Skip to content

Commit

Permalink
Add method to reflect vertex along a plane
Browse files Browse the repository at this point in the history
  • Loading branch information
zilmarinen committed Aug 30, 2024
1 parent c004f95 commit 1d5ba3a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 19 deletions.
16 changes: 1 addition & 15 deletions Sources/Polygon+CSG.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,7 @@ public extension Polygon {
/// - Parameter plane: The ``Plane`` against which the vertices are to be reflected.
/// - Returns: A ``Polygon`` representing the reflected vertices.
func reflect(along plane: Plane) -> Self {
mapVertices {
let p = $0.position.project(onto: plane)
let d = $0.position - p

//https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector
//𝑟=𝑑−2(𝑑⋅𝑛)𝑛
let n = plane.normal - 2.0 * plane.normal.dot($0.normal) * $0.normal

return Vertex(
p - d,
n,
$0.texcoord,
$0.color
)
}.inverted()
mapVertices { $0.reflect(along: plane) }.inverted()
}
}

Expand Down
19 changes: 19 additions & 0 deletions Sources/Vertex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,25 @@ public extension Vertex {
vertex.color = color ?? .white
return vertex
}

/// Reflects the vertex along a plane.
/// - Parameter plane: The ``Plane`` against which the vertices are to be reflected.
/// - Returns: A ``Vertex`` representing the reflected vertex.
func reflect(along plane: Plane) -> Self {
let p = position.project(onto: plane)
let d = position - p

// https://math.stackexchange.com/questions/13261/how-to-get-a-reflection-vector
// 𝑟=𝑑−2(𝑑⋅𝑛)𝑛
let n = plane.normal - 2.0 * plane.normal.dot(normal) * normal

return Self(
p - d,
n,
texcoord,
color
)
}
}

extension Vertex {
Expand Down
7 changes: 3 additions & 4 deletions Tests/MeshTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -361,23 +361,22 @@ class MeshTests: XCTestCase {
// MARK: Reflection

func testQuadReflectionAlongPlane() {

let quad = Polygon(unchecked: [
Vertex(Vector(-0.5, 1.0, 0.5), .unitY, Vector(0.0, 1.0), .black),
Vertex(Vector(0.5, 1.0, 0.5), .unitY, Vector(1.0, 1.0), .black),
Vertex(Vector(0.5, 1.0, -0.5), .unitY, Vector(1.0, 0.0), .white),
Vertex(Vector(-0.5, 1.0, -0.5), .unitY, Vector(0.0, 0.0), .white),
])

let expected = Polygon(unchecked: [
Vertex(Vector(-0.5, -1.0, -0.5), -.unitY, Vector(0.0, 0.0), .white),
Vertex(Vector(0.5, -1.0, -0.5), -.unitY, Vector(1.0, 0.0), .white),
Vertex(Vector(0.5, -1.0, 0.5), -.unitY, Vector(1.0, 1.0), .black),
Vertex(Vector(-0.5, -1.0, 0.5), -.unitY, Vector(0.0, 1.0), .black),
])

let reflection = quad.reflect(along: .xz)

XCTAssertEqual(reflection.plane.normal, -.unitY)
XCTAssertEqual(reflection.vertices, expected.vertices)
}
Expand Down

0 comments on commit 1d5ba3a

Please sign in to comment.