Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXGraph/Tests/ORIXGraphTests/SurfaceTests.swift3// Description: Surface meshes (counts, normals, holes, no triangle across a pole), contours, inspection, camera projection and depth sorting.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9@testable import ORIXGraph1011private func triangles(_ m: SurfaceMesh) -> [(Point3, Point3, Point3)] {12 (0..<m.triangleCount).map { (m.vertices[Int(m.indices[3 * $0])], m.vertices[Int(m.indices[3 * $0 + 1])], m.vertices[Int(m.indices[3 * $0 + 2])]) }13}1415@Suite struct Surfaces {16 @Test func paraboloid() {17 let m = SurfacePlotter.mesh(fn2("x^2 + y^2"), x: -5...5, y: -5...5)18 #expect(m.columns == 60 && m.rows == 60)19 #expect(m.vertices.count == 61 * 61 && m.normals.count == 61 * 61 && m.colorParameters.count == 61 * 61)20 #expect(m.triangleCount == 2 * 60 * 60 && m.indices.count == 6 * 60 * 60 && m.droppedTriangles == 0)21 #expect(m.zMin == 0 && m.zMax == 50 && m.isComplete && m.notices.isEmpty)22 #expect(m.valid.allSatisfy { $0 } && !m.clipped.contains(true))23 #expect(m.indices.allSatisfy { Int($0) < m.vertices.count })24 // heights are exact, the normals are unit vectors pointing up25 #expect(m.vertices.allSatisfy { abs($0.z - ($0.x * $0.x + $0.y * $0.y)) < 1e-12 })26 #expect(m.normals.allSatisfy { abs($0.length - 1) < 1e-12 && $0.z > 0 })27 let origin = m.vertexIndex(30, 30)28 #expect(m.vertices[origin] == Point3(0, 0, 0))29 #expect(abs(m.normals[origin].x) < 1e-9 && abs(m.normals[origin].y) < 1e-9 && abs(m.normals[origin].z - 1) < 1e-12)30 // the normal is (−2x, −2y, 1) normalised31 let v = m.vertices[m.vertexIndex(45, 12)], n = m.normals[m.vertexIndex(45, 12)]32 let expected = Point3(-2 * v.x, -2 * v.y, 1).normalized33 #expect(abs(n.x - expected.x) < 1e-7 && abs(n.y - expected.y) < 1e-7 && abs(n.z - expected.z) < 1e-7)34 #expect(m.colorParameters[origin] == 0 && m.colorParameters[0] == 1)35 #expect(m.colorParameters.allSatisfy { $0 >= 0 && $0 <= 1 })36 // triangles are counter-clockwise seen from above37 #expect(triangles(m).allSatisfy { ($0.1.x - $0.0.x) * ($0.2.y - $0.0.y) - ($0.1.y - $0.0.y) * ($0.2.x - $0.0.x) > 0 })38 // grid normals agree with the precise ones to first order39 let coarse = SurfacePlotter.mesh(fn2("x^2 + y^2"), x: -5...5, y: -5...5, options: SurfaceOptions(columns: 20, rows: 30, preciseNormals: false))40 #expect(coarse.vertices.count == 21 * 31 && coarse.triangleCount == 1200)41 #expect(abs(coarse.normals[coarse.vertexIndex(10, 15)].z - 1) < 1e-12)42 }4344 @Test(arguments: [60, 61])45 func poleAtTheOriginIsNotBridged(_ n: Int) {46 // n = 60 puts a vertex exactly on the pole (undefined), n = 61 does not.47 let m = SurfacePlotter.mesh(fn2("1/(x^2 + y^2)"), x: -2...2, y: -2...2, options: SurfaceOptions(columns: n, rows: n))48 #expect(m.droppedTriangles > 0 && m.triangleCount + m.droppedTriangles == 2 * n * n)49 // the scale is not blown up by the pole50 #expect(m.zMax < 10 && m.zMin >= 0.124)51 #expect(m.vertices.allSatisfy { $0.z.isFinite && $0.z <= m.zMax && $0.z >= m.zMin })52 // no triangle covers the origin53 for (a, b, c) in triangles(m) {54 let d1 = a.x * b.y - a.y * b.x, d2 = b.x * c.y - b.y * c.x, d3 = c.x * a.y - c.y * a.x55 #expect(!((d1 > 0 && d2 > 0 && d3 > 0) || (d1 < 0 && d2 < 0 && d3 < 0)))56 }57 #expect(m.notices.contains { $0.kind == .info })58 }5960 @Test(arguments: [60, 61])61 func poleLineIsNotBridged(_ n: Int) {62 let f = fn2("1/x + 0*y")63 let m = SurfacePlotter.mesh(f, x: -2...2, y: -2...2, options: SurfaceOptions(columns: n, rows: n))64 #expect(m.triangleCount > n * n)65 // no triangle has vertices on both sides of x = 0, and none touches it66 for (a, b, c) in triangles(m) {67 let xs = [a.x, b.x, c.x]68 #expect(xs.allSatisfy { $0 > 0 } || xs.allSatisfy { $0 < 0 })69 // and no kept triangle joins the clipped top to the clipped bottom70 #expect(!(max(a.z, b.z, c.z) == m.zMax && min(a.z, b.z, c.z) == m.zMin))71 }72 #expect(m.zMax < 20 && m.zMin > -20)73 if n == 61 { #expect(m.notices.contains { $0.kind == .rejectedFalseContour }) }74 }7576 @Test func jumpSurfaceIsNotBridged() {77 let m = SurfacePlotter.mesh(fn2("floor(x) + 0*y"), x: -2.05...1.95, y: -2...2, options: SurfaceOptions(columns: 40, rows: 10))78 for (a, b, c) in triangles(m) { #expect(a.z == b.z && b.z == c.z) } // only flat treads, no risers79 #expect(m.droppedTriangles > 0)80 }8182 @Test func hemisphereHasAHoleOutsideTheDisc() {83 let m = SurfacePlotter.mesh(fn2("sqrt(1 - x^2 - y^2)"), x: -2...2, y: -2...2)84 #expect(m.valid.contains(false) && m.valid.contains(true))85 for (i, v) in m.vertices.enumerated() {86 let r2 = v.x * v.x + v.y * v.y87 if abs(r2 - 1) > 1e-9 { #expect(m.valid[i] == (r2 < 1)) } // lattice points exactly on the rim may round either way88 }89 for (a, b, c) in triangles(m) {90 for p in [a, b, c] {91 #expect(p.x * p.x + p.y * p.y <= 1 + 1e-12)92 #expect(abs(p.x * p.x + p.y * p.y + p.z * p.z - 1) < 1e-12)93 }94 }95 #expect(m.triangleCount > 500 && m.triangleCount < 2 * 60 * 60 / 3)96 #expect(m.zMin >= 0 && m.zMax <= 1)97 let nowhere = SurfacePlotter.mesh(fn2("sqrt(-1 - x^2 - y^2)"), x: -1...1, y: -1...1)98 #expect(nowhere.triangleCount == 0 && nowhere.vertices.count == 61 * 61 && nowhere.vertices.allSatisfy { $0.z == 0 })99 }100101 @Test func fixedRangeAndNormalisation() {102 let m = SurfacePlotter.mesh(fn2("x * y"), x: 0...4, y: -1...1, options: SurfaceOptions(columns: 8, rows: 8, zRange: -2...2))103 #expect(m.zMin == -2 && m.zMax == 2 && m.clipped.contains(true))104 #expect(m.vertices.allSatisfy { $0.z >= -2 && $0.z <= 2 })105 let u = m.normalized()106 #expect(u.vertices.allSatisfy { abs($0.x) <= 1 + 1e-12 && abs($0.y) <= 1 + 1e-12 && abs($0.z) <= 1 + 1e-12 })107 #expect(u.vertices[0] == Point3(-1, -1, 0) && u.vertices[u.vertexIndex(8, 8)].x == 1)108 #expect(u.normals.allSatisfy { abs($0.length - 1) < 1e-12 })109 #expect(u.indices == m.indices)110 }111112 @Test func inspection() {113 let f = fn2("x^2 * y + sin(y)")114 let s = SurfacePlotter.inspect(f, x: 2, y: 1, scale: 10)115 #expect(abs(s.z! - (4 + sin(1))) < 1e-12)116 #expect(abs(s.gradient!.x - 4) < 1e-7 && abs(s.gradient!.y - (4 + cos(1))) < 1e-7)117 #expect(abs(s.normal!.length - 1) < 1e-12 && s.normal!.z > 0)118 let u = SurfacePlotter.inspect(fn2("1/(x^2 + y^2)"), x: 0, y: 0)119 #expect(u.z == nil && u.gradient == nil && u.normal == nil)120 }121122 @Test func contourLines() {123 let lines = SurfacePlotter.contours(fn2("x^2 + y^2"), levels: [1, 4, 9, 100], x: -5...5, y: -5...5)124 #expect(lines.map(\.level) == [1, 4, 9, 100])125 for line in lines.prefix(3) {126 #expect(line.polylines.count == 1 && line.polylines[0].isClosed && line.reliable)127 #expect(line.polylines[0].points.allSatisfy { abs(($0.x * $0.x + $0.y * $0.y).squareRoot() - line.level.squareRoot()) < 1e-3 })128 }129 #expect(lines[3].polylines.isEmpty)130 // contours of a surface with a pole do not include the pole line131 let pole = SurfacePlotter.contours(fn2("1/x + y"), levels: [0], x: -3.01...3, y: -3...3)132 #expect(pole[0].polylines.count == 2)133 #expect(pole[0].polylines.allSatisfy { l in l.points.allSatisfy { abs(1 / $0.x + $0.y) < 0.2 * (1 + $0.y * $0.y) } })134 let levels = SurfacePlotter.niceLevels(zMin: 0, zMax: 50, count: 10)135 #expect(levels == [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50])136 }137138 @Test func parametricSphere() {139 let m = SurfacePlotter.parametricMesh({ u, v in Point3(cos(u) * sin(v), sin(u) * sin(v), cos(v)) }, u: 0...(2 * .pi), v: 0.2...(Double.pi - 0.2), columns: 24, rows: 12)140 #expect(m.vertices.count == 25 * 13 && m.triangleCount == 2 * 24 * 12)141 #expect(m.vertices.allSatisfy { abs($0.length - 1) < 1e-12 })142 // normals are radial (up to orientation)143 #expect(zip(m.vertices, m.normals).allSatisfy { abs(abs($0.dot($1)) - 1) < 0.02 })144 }145}146147@Suite struct Camera {148 @Test func projectionOfKnownPoints() {149 let cam = Camera3D(yaw: 0, pitch: 0, distance: 5, target: .zero, fieldOfView: .pi / 2)150 #expect(abs(cam.position.x - 5) < 1e-12 && abs(cam.position.y) < 1e-12 && abs(cam.position.z) < 1e-12)151 // the target is in the middle of the screen, 5 units away152 let centre = cam.project(.zero, width: 800, height: 600)!153 #expect(abs(centre.screen.x - 400) < 1e-9 && abs(centre.screen.y - 300) < 1e-9 && abs(centre.depth - 5) < 1e-12)154 // z is up: a point above the target appears above the centre; with a 90° field of view, tan = 1 at the edge:155 // a point at height h and distance d projects h/d of the half-height away156 let up = cam.project(Point3(0, 0, 1), width: 800, height: 600)!157 #expect(abs(up.screen.x - 400) < 1e-9 && abs(up.screen.y - (300 - 300.0 / 5)) < 1e-9)158 // looking from +x towards the origin, +y is to the right159 let right = cam.project(Point3(0, 1, 0), width: 800, height: 600)!160 #expect(abs(right.screen.y - 300) < 1e-9 && abs(right.screen.x - (400 + 300.0 / 5)) < 1e-9)161 // nearer points have a smaller depth and look bigger162 let near = cam.project(Point3(2, 0, 1), width: 800, height: 600)!163 #expect(abs(near.depth - 3) < 1e-12 && abs(near.screen.y - (300 - 300.0 / 3)) < 1e-9)164 // behind the camera: not projected165 #expect(cam.project(Point3(6, 0, 0), width: 800, height: 600) == nil)166 }167168 @Test func matrices() {169 let cam = Camera3D(yaw: 0.7, pitch: 0.4, distance: 6, target: Point3(1, 2, 3))170 let view = cam.viewMatrix171 // the view matrix sends the eye to the origin and the target down the −z axis172 let eye = Camera3D.transform(view, cam.position)173 #expect(abs(eye.x) < 1e-12 && abs(eye.y) < 1e-12 && abs(eye.z) < 1e-12 && eye.w == 1)174 let target = Camera3D.transform(view, cam.target)175 #expect(abs(target.x) < 1e-12 && abs(target.y) < 1e-12 && abs(target.z + 6) < 1e-12)176 // rotation part is orthonormal177 for c in 0..<3 {178 let column = Point3(view[c * 4], view[c * 4 + 1], view[c * 4 + 2])179 #expect(abs(column.length - 1) < 1e-12)180 }181 let vp = cam.viewProjectionMatrix(aspect: 4.0 / 3)182 #expect(vp.count == 16 && vp == Camera3D.multiply(cam.projectionMatrix(aspect: 4.0 / 3), view))183 // near and far planes map to −1 and +1184 let p = cam.projectionMatrix(aspect: 1)185 let n = Camera3D.transform(p, Point3(0, 0, -cam.near)), f = Camera3D.transform(p, Point3(0, 0, -cam.far))186 #expect(abs(n.z / n.w + 1) < 1e-9 && abs(f.z / f.w - 1) < 1e-9)187 let identity: [Double] = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]188 #expect(Camera3D.multiply(identity, view) == view)189 }190191 @Test func orbitAndZoom() {192 let cam = Camera3D()193 #expect(abs(cam.orbited(yawBy: 0.3, pitchBy: 0).yaw - (cam.yaw + 0.3)) < 1e-12)194 #expect(cam.orbited(yawBy: 0, pitchBy: 10).pitch < .pi / 2) // never over the pole195 #expect(cam.orbited(yawBy: 0, pitchBy: -10).pitch > -.pi / 2)196 #expect(abs(cam.zoomed(by: 2).distance - cam.distance / 2) < 1e-12)197 #expect(cam.zoomed(by: 0).distance == cam.distance && cam.zoomed(by: .nan).distance == cam.distance)198 #expect(abs((cam.position - cam.target).length - cam.distance) < 1e-12)199 // looking straight down still gives a usable matrix200 let top = Camera3D(yaw: 0, pitch: .pi / 2)201 let finite = top.viewMatrix.allSatisfy { $0.isFinite }202 #expect(finite)203 #expect(top.project(.zero, width: 100, height: 100) != nil)204 }205206 @Test func painterOrderIsFarToNear() {207 let mesh = SurfacePlotter.mesh(fn2("sin(x) * cos(y)"), x: -3...3, y: -3...3, options: SurfaceOptions(columns: 24, rows: 24)).normalized()208 let cam = Camera3D()209 let projected = PainterRenderer.project(mesh, camera: cam, width: 800, height: 600)210 #expect(projected.count == mesh.triangleCount)211 #expect(zip(projected, projected.dropFirst()).allSatisfy { $0.depth >= $1.depth })212 #expect(projected.allSatisfy { $0.shade >= 0.25 && $0.shade <= 1 && $0.colorParameter >= 0 && $0.colorParameter <= 1 })213 // the whole unit cube is in front of the default camera and on screen214 func onScreen(_ p: Point2) -> Bool { p.x > 0 && p.x < 800 && p.y > 0 && p.y < 600 }215 #expect(projected.allSatisfy { onScreen($0.a) && onScreen($0.b) && onScreen($0.c) })216 let order = PainterRenderer.depthOrder(mesh, camera: cam)217 #expect(order.count == mesh.triangleCount && Set(order).count == order.count)218 // first drawn is farther from the eye than last drawn219 func centroidDistance(_ t: Int) -> Double {220 let a = mesh.vertices[Int(mesh.indices[3 * t])], b = mesh.vertices[Int(mesh.indices[3 * t + 1])], c = mesh.vertices[Int(mesh.indices[3 * t + 2])]221 return (((a + b + c) * (1.0 / 3)) - cam.position).dot(cam.forward)222 }223 #expect(centroidDistance(order.first!) > centroidDistance(order.last!))224 let firstDepth: Double = centroidDistance(order[0])225 #expect(abs(firstDepth - projected[0].depth) < 0.05)226 }227}228