All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.casperix.math.axis_aligned.float64.Box2d.kt Maven / Gradle / Ivy

package ru.casperix.math.axis_aligned.float64
import ru.casperix.math.axis_aligned.Box
import ru.casperix.math.axis_aligned.int32.Box2i
import ru.casperix.math.vector.float64.Vector2d
import kotlinx.serialization.Serializable

@Serializable
data class Box2d(override val min: Vector2d, override val max: Vector2d) : Box {
	override val center: Vector2d get() = (max + min) * 0.5
	override val dimension: Vector2d get() = max - min
	override val volume: Double get() = dimension.x * dimension.y


	init {
		if (!min.isFinite() || !max.isFinite()) throw Error("Box is invalid ($min => $max)")
		if (!min.lessOrEq(max)) throw Error("$min > $max mst be valid for $Box2d");
	}

	override fun isInside(point: Vector2d): Boolean {
		return min.x <= point.x && point.x <= max.x && min.y <= point.y && point.y <= max.y
	}

	fun toBox2i(): Box2i? {
		try {
			return Box2i(min.toVector2i(), max.toVector2i())
		} catch (t: Throwable) {
			return null
		}
	}

	override fun toString(): String {
		return "Box2d(min=${min}; max=${max})"
	}

	fun grow(value: Double): Box2d {
		return Box2d(min - Vector2d(value), max + Vector2d(value))
	}

	companion object {
		fun createOrNull(min: Vector2d, max: Vector2d): Box2d? {
			if (!min.lessOrEq(max)) return null
			return Box2d(min, max)
		}

		fun byCorners(A: Vector2d, B: Vector2d): Box2d {
			val min = A.lower(B)
			val max = A.upper(B)
			return Box2d(min, max)
		}

		fun byRadius(center: Vector2d, radius: Vector2d): Box2d {
			return Box2d(center - radius, center + radius)
		}

		fun byDimension(start: Vector2d, dimension: Vector2d): Box2d {
			return Box2d(start, start + dimension)
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy