#! Contains `hull`, a convex polyhedron: its corners; its faces, each a convex #! polygon of its corners, counterclockwise as it's seen from outside, its #! normal facing out; and its edges, each between two faces. It's made as a box, #! as a triangle, flat, with a face each way, or around places, as the least #! hull holding them, each of its faces as many of their triangles as lie in one #! plane. import std::containers; import std::math; import malunal::linear; module malunal::physics3d; #! The most corners a hull has. pub const max_hull_points: u32 = 32; # The most faces and edges a hull of so many corners has, as Euler's formula # bounds them: 2V - 4 faces and 3V - 6 edges, each edge a corner of two faces. const max_hull_faces: u32 = 60; const max_hull_edges: u32 = 90; # Faces whose normals are nearer one another than this are one face. const coplanar: f32 = 0.9999; #! A convex polyhedron, about the origin of its body, as plain data, so a shape #! holding one is copied whole. pub struct hull { var _count: u32; var _faces: u32; var _edges: u32; var _points: vec3[32]; var _normals: vec3[60]; var _first: u8[60]; # Of each face, where its corners begin in `_corners`. var _sizes: u8[60]; # Of each face, how many corners. var _corners: u8[180]; # Each face's corners, counterclockwise from outside. var _ends: u8[180]; # Each edge's two corners. var _sides: u8[180]; # Each edge's two faces. var _center: vec3; } #! A box reaching so far each way from its middle, about a place, turned by a #! rotation. pub def hull::box(half: vec3, center: vec3 = vec3::zero, turn: quat = quat::identity): hull { var made := hull{ _count = 8, _faces = 6 }; val m := mat3::rotation(turn); # Corner `i` is on the high side of x where bit 0 is set, of y where bit 1 # is, and of z where bit 2 is. for i in 0..8u { val corner := vec3{ (i & 1) != 0 ? half.x : -half.x, (i & 2) != 0 ? half.y : -half.y, (i & 4) != 0 ? half.z : -half.z }; made._points[i] = center + m * corner; } val loops: u8[24] = [1, 3, 7, 5, 0, 4, 6, 2, 2, 6, 7, 3, 0, 1, 5, 4, 4, 5, 7, 6, 0, 2, 3, 1]; for i in 0..24u { made._corners[i] = loops[i]; } for f in 0..6u { made._first[f] = (f * 4) as u8; made._sizes[f] = 4; } made.finish(); return made; } #! A triangle of three places, flat: a face each way, the first facing where #! they turn counterclockwise, and three edges, each between the two faces. pub def hull::triangle(a: vec3, b: vec3, c: vec3): hull { var made := hull{ _count = 3, _faces = 2 }; made._points[0] = a; made._points[1] = b; made._points[2] = c; val loops: u8[6] = [0, 1, 2, 0, 2, 1]; for i in 0..6u { made._corners[i] = loops[i]; } made._first[1] = 3; made._sizes[0] = 3; made._sizes[1] = 3; made.finish(); return made; } # A triangle of the hull being made, by its corners' indices among the places. struct building { var a: u32; var b: u32; var c: u32; var normal: vec3; var offset: f32; var alive: bool; } def building_of(places: span, a: u32, b: u32, c: u32): building { val normal := (places[b] - places[a]).cross(places[c] - places[a]).normalized(); return building{ a = a, b = b, c = c, normal = normal, offset = normal.dot(places[a]), alive = true }; } # A place, and how far it is from the middle of the first four corners, by # which the furthest are put on first. struct by_reach { var reach: f32; var index: u32; } def further(x: &by_reach, y: &by_reach): bool { return x.reach > y.reach; } #! The least convex hull holding places: what's within it, or on its faces, #! left out. Nothing where the places hold no volume, or their hull has more #! than `max_hull_points` corners. pub def hull::of(places: span): maybe { return nothing{} if places.length < 4; # How near a place is to a face to be taken as on it, of the places' size. var low := places[0]; var high := places[0]; for i in 1..places.length { low = low.min(places[i]); high = high.max(places[i]); } val reach := low.abs().max(high.abs()); val near := (reach.x + reach.y + reach.z) * 4e-6 + tiny; # The first four corners: the place furthest left, the one furthest from # it, the one furthest from the line of those, and the one furthest from # the plane of the three. var i0: u32 = 0; for i in 1..places.length { if places[i].x < places[i0 as u64].x { i0 = i as u32; } } var i1 := i0; var best: f32 = 0; for i in 0..places.length { val d := (places[i] - places[i0 as u64]).length; if d > best { best = d; i1 = i as u32; } } return nothing{} if best <= near; val along := (places[i1 as u64] - places[i0 as u64]).normalized(); var i2 := i0; best = 0; for i in 0..places.length { val d := (places[i] - places[i0 as u64]).cross(along).length; if d > best { best = d; i2 = i as u32; } } return nothing{} if best <= near; val facing := (places[i1 as u64] - places[i0 as u64]).cross(places[i2 as u64] - places[i0 as u64]).normalized(); var i3 := i0; best = 0; var side: f32 = 0; for i in 0..places.length { val d := facing.dot(places[i] - places[i0 as u64]); if math::abs(d) > best { best = math::abs(d); side = d; i3 = i as u32; } } return nothing{} if best <= near; # The first face faces away from the fourth corner. var a := i0; var b := i1; var c := i2; if side > 0 { b = i2; c = i1; } var faces := vector::::new(); faces.append(building_of(places, a, b, c)); faces.append(building_of(places, a, i3, b)); faces.append(building_of(places, b, i3, c)); faces.append(building_of(places, c, i3, a)); # The rest, the furthest from the middle first, each outside the hull so # far replacing the faces it sees with faces from their horizon to it. val middle := (places[i0 as u64] + places[i1 as u64] + places[i2 as u64] + places[i3 as u64]) * 0.25; var order := vector::::new(); for i in 0..places.length { order.append(by_reach{ reach = (places[i] - middle).length_squared, index = i as u32 }); } order.sort_by(further); var seen := vector::::new(); for k in 0..order.length { val p := order[k].index; val place := places[p as u64]; # The directed edges of the faces it sees. seen.clear(); for f in 0..faces.length { continue if !faces[f].alive || faces[f].normal.dot(place) - faces[f].offset <= near; faces[f].alive = false; seen.append(edge_key(faces[f].a, faces[f].b)); seen.append(edge_key(faces[f].b, faces[f].c)); seen.append(edge_key(faces[f].c, faces[f].a)); } continue if seen.empty; # An edge seen one way only is on the horizon. val count := seen.length; for e in 0..count { val key := seen[e]; val from := (key >> 32) as u32; val to := (key & 0xFFFFFFFF) as u32; var shared := false; for o in 0..count { if seen[o] == edge_key(to, from) { shared = true; break; } } if !shared { faces.append(building_of(places, from, to, p)); } } } return hull::of_triangles(places, faces.span); } def edge_key(from: u32, to: u32): u64 { return ((from as u64) << 32) | to as u64; } # The hull of the triangles left: those in one plane made one face, the # corners they use numbered from 0. def hull::of_triangles(places: span, faces: span): maybe { # Which triangle lies across each directed edge. var across := dict::::new(); var alive := vector::::new(); for f in 0..faces.length { continue if !faces[f].alive; alive.append(f); across.set(edge_key(faces[f].a, faces[f].b), f); across.set(edge_key(faces[f].b, faces[f].c), f); across.set(edge_key(faces[f].c, faces[f].a), f); } # Each triangle's face: those reached from it across edges, facing as it # does. var group := vector::::new(); for f in 0..faces.length { group.append(-1); } var made := hull{}; var numbered := dict::::new(); var corners: u32 = 0; var pending := vector::::new(); var edges := vector::::new(); var ring := dict::::new(); for k in 0..alive.length { val seed := alive[k]; # A triangle of no area takes the face of one beside it. continue if group[seed] >= 0 || faces[seed].normal.length_squared < 0.25; return nothing{} if made._faces >= max_hull_faces; val face := made._faces; val normal := faces[seed].normal; group[seed] = face as i64; pending.clear(); pending.append(seed); edges.clear(); while !pending.empty { val t := pending[pending.length - 1]; pending.truncate(); val keys: u64[3] = [edge_key(faces[t].a, faces[t].b), edge_key(faces[t].b, faces[t].c), edge_key(faces[t].c, faces[t].a)]; for e in 0..3u { edges.append(keys[e]); val reverse := edge_key((keys[e] & 0xFFFFFFFF) as u32, (keys[e] >> 32) as u32); if across.get(&reverse) is some(&other) { val o: u64 = other; if group[o] < 0 && (faces[o].normal.dot(normal) > coplanar || faces[o].normal.length_squared < 0.25) { group[o] = face as i64; pending.append(o); } } } } # The face's boundary: its triangles' edges whose reverse isn't among # them, walked from one to the next. ring.clear(); var start: u32 = 0; var length: u32 = 0; for e in 0..edges.length { val from := (edges[e] >> 32) as u32; val to := (edges[e] & 0xFFFFFFFF) as u32; var inner := false; for o in 0..edges.length { if edges[o] == edge_key(to, from) { inner = true; break; } } if !inner { ring.set(from, to); start = from; length++; } } val first := made.corner_total(); return nothing{} if first + length > max_hull_edges * 2; var at := start; var walked: u32 = 0; var newell := vec3::zero; while walked < length { if numbered.get(&at) is none { return nothing{} if corners >= max_hull_points; made._points[corners] = places[at as u64]; numbered.set(at, corners); corners++; } if numbered.get(&at) is some(&n) { val number: u32 = n; made._corners[first + walked] = number as u8; } var next := at; if ring.get(&at) is some(&n) { next = n; } else { return nothing{}; } newell = newell + places[at as u64].cross(places[next as u64]); at = next; walked++; break if at == start; } return nothing{} if walked != length || walked < 3; made._first[face] = first as u8; made._sizes[face] = walked as u8; made._normals[face] = newell.normalized(); made._faces++; } made._count = corners; return nothing{} if !made.find_edges(); made.find_center(); return made; } # How many corners its faces have in all. def hull::corner_total(&this): u32 { var total: u32 = 0; for f in 0..this._faces { total += this._sizes[f] as u32; } return total; } # Finds its normals, edges, and middle, of its corners and faces. def hull::finish(&mut this): void { for f in 0..this._faces { var newell := vec3::zero; for k in 0..this.face_size(f) { newell = newell + this.point(this.corner(f, k)).cross(this.point(this.corner(f, (k + 1) % this.face_size(f)))); } this._normals[f] = newell.normalized(); } _ = this.find_edges(); this.find_center(); } # Finds its edges, each once, and the two faces either side, of its faces' # corners: an edge from a lesser corner to a greater in one face, and back in # the other. Gives false where one isn't, as a hull with a hole. def hull::find_edges(&mut this): bool { this._edges = 0; for f in 0..this._faces { val size := this.face_size(f); for k in 0..size { val from := this.corner(f, k); val to := this.corner(f, (k + 1) % size); continue if from > to; return false if this._edges >= max_hull_edges; val e := this._edges; this._ends[e * 2] = from as u8; this._ends[e * 2 + 1] = to as u8; this._sides[e * 2] = f as u8; this._sides[e * 2 + 1] = 0xFF; this._edges++; } } for f in 0..this._faces { val size := this.face_size(f); for k in 0..size { val from := this.corner(f, k); val to := this.corner(f, (k + 1) % size); continue if from < to; for e in 0..this._edges { if this._ends[e * 2] as u32 == to && this._ends[e * 2 + 1] as u32 == from { this._sides[e * 2 + 1] = f as u8; break; } } } } for e in 0..this._edges { return false if this._sides[e * 2 + 1] == 0xFF; } return true; } def hull::find_center(&mut this): void { var sum := vec3::zero; for i in 0..this._count { sum = sum + this._points[i]; } this._center = sum * (1 / this._count as f32); } #! How many corners it has. pub val hull::count: u32 { get => this._count; } #! A corner. pub def hull::point(&this, i: u32): vec3 { return this._points[i]; } #! How many faces it has. pub val hull::faces: u32 { get => this._faces; } #! A face's normal, facing out. pub def hull::normal(&this, face: u32): vec3 { return this._normals[face]; } #! How many corners a face has. pub def hull::face_size(&this, face: u32): u32 { return this._sizes[face] as u32; } #! Which corner is a face's `k`th, counterclockwise from outside. pub def hull::corner(&this, face: u32, k: u32): u32 { return this._corners[this._first[face] as u32 + k] as u32; } #! How far its plane is along a face's normal from the origin. pub def hull::offset(&this, face: u32): f32 { return this._normals[face].dot(this.point(this.corner(face, 0))); } #! How many edges it has. pub val hull::edges: u32 { get => this._edges; } #! An edge's corners, the lesser first. pub def hull::edge(&this, e: u32): u32[2] { return [this._ends[e * 2] as u32, this._ends[e * 2 + 1] as u32]; } #! The faces either side of an edge. pub def hull::edge_faces(&this, e: u32): u32[2] { return [this._sides[e * 2] as u32, this._sides[e * 2 + 1] as u32]; } #! The middle of its corners, which is within it. pub val hull::center: vec3 { get => this._center; } #! Whether it's flat, of two faces, as a triangle is. pub val hull::is_flat: bool { get => this._faces == 2; } #! The corner furthest along a direction. pub def hull::support(&this, direction: vec3): u32 { var found: u32 = 0; var most := this._points[0].dot(direction); for i in 1..this._count { val d := this._points[i].dot(direction); if d > most { most = d; found = i; } } return found; } #! The hull scaled along each axis, as a transform scales what it holds: its #! normals turned as the faces they're of are. pub def hull::scaled(&this, by: vec3): hull { var made: hull = this; for i in 0..this._count { made._points[i] = this._points[i] * by; } for f in 0..this._faces { made._normals[f] = (this._normals[f] / by).normalized(); } made._center = this._center * by; return made; } #! The hull moved and turned as a pose places it. pub def hull::moved(&this, by: pose): hull { var made: hull = this; val m := mat3::rotation(by.turn); for i in 0..this._count { made._points[i] = by.at + m * this._points[i]; } for f in 0..this._faces { made._normals[f] = m * this._normals[f]; } made._center = by.at + m * this._center; return made; }