commonMain.ru.casperix.math.geometry.Quad.kt Maven / Gradle / Ivy
package ru.casperix.math.geometry
import ru.casperix.math.vector.float32.Vector2f
import ru.casperix.math.vector.float32.Vector3f
import ru.casperix.math.vector.float64.Vector2d
import ru.casperix.math.vector.float64.Vector3d
import ru.casperix.math.vector.int32.Vector2i
import ru.casperix.math.vector.int32.Vector3i
import kotlinx.serialization.Serializable
/*
* 1/----/2
* / /
* 0/----/3
*/
@Serializable
data class Quad(val v0: Point, val v1: Point, val v2: Point, val v3: Point) :
Polygon {
override fun convert(converter: (Point) -> TargetPoint): Quad {
return Quad(
converter(v0),
converter(v1),
converter(v2),
converter(v3)
)
}
fun getFace(index: Int): Triangle {
return when (index) {
0 -> Triangle(v0, v1, v2) // -x
1 -> Triangle(v2, v3, v0) // +x
else -> throw Error("Invalid index")
}
}
override fun getVertexAmount(): Int {
return 4
}
override fun getVertex(index: Int): Point {
return when (index) {
0 -> v0
1 -> v1
2 -> v2
3 -> v3
else -> throw Error("Invalid index")
}
}
override fun getEdge(index: Int): Line {
return when (index) {
0 -> Line(v0, v1)
1 -> Line(v1, v2)
2 -> Line(v2, v3)
3 -> Line(v3, v0)
else -> throw Error("Expected index in range 0 - 3. Actual: $index")
}
}
override fun getEdgeAmount(): Int {
return 4
}
override fun getEdgeList(): List> {
return (0 until getEdgeAmount()).map {
getEdge(it)
}
}
companion object {
fun from(list: List): Quad? {
if (list.size != 4) return null
return Quad(list[0], list[1], list[2], list[3])
}
}
}
typealias Quad3f = Quad
typealias Quad2f = Quad
typealias Quad3d = Quad
typealias Quad2d = Quad
typealias Quad3i = Quad
typealias Quad2i = Quad
fun Quad2i.addDimension(value: Int): Quad3i {
return convert { it.addDimension(value) }
}
fun Quad2i.toQuad2d(): Quad2d {
return convert { it.toVector2d() }
}
fun Quad2i.toQuad2f(): Quad2f {
return convert { it.toVector2f() }
}
fun Quad3i.toQuad3d(): Quad3d {
return convert { it.toVector3d() }
}
fun Quad3d.toQuad3i(): Quad3i {
return convert { it.toVector3i() }
}
fun Quad3i.toQuad3f(): Quad3f {
return convert { it.toVector3f() }
}
//fun Quad3f.toQuad3i():Quad3i {
// return convert { it.toVector3i() }
//}
fun Quad3d.scale(scale: Double): Quad3d {
val center = (v0 + v1 + v2 + v3) / 4.0
return Quad3d(
center + (v0 - center) * scale,
center + (v1 - center) * scale,
center + (v2 - center) * scale,
center + (v3 - center) * scale
)
}
fun Quad2f.grow(value: Float): Quad2f {
if (value == 0f) {
return this
}
val e0 = (v1 - v0).normalize()
val e1 = (v2 - v1).normalize()
val e2 = (v3 - v2).normalize()
val e3 = (v0 - v3).normalize()
return Quad2f(
v0 - (e0 - e3) * value,
v1 - (e1 - e0) * value,
v2 - (e2 - e1) * value,
v3 - (e3 - e2) * value,
)
}