geom#
Deterministic modelling kernel: meshes from primitives, profiles and operations, with checks -- crate root lib/geom/src/lib.rs
geom -- the modelling kernel of the game engine (docs/GEOM.md, GAME.md stage G7g): indexed triangle meshes
built from primitives, profiles and operations, checked, the same bits on every target
Mesh positions, normals, UV (f64), indices and points (the topology: a hard edge does not
open a surface, touching parts stay apart); transformed, translated, rotated (degrees,
exact at multiples of 90), scaled, mirrored, flipped, merge, array, radial, weld; flat,
smooth (angle threshold), uv_box (box projection in metres); bounds, area, volume,
fingerprint; check() -> Report
build cuboid, cylinder, cone, sphere, torus, stairs, arch (standing on y = 0, centred over
the origin), extrude (front-view profile along Z), prism (floor plan up along Y), sweep
(profile along a path, mitred corners, rotation-minimising frames), lathe (profile about Y)
poly 2D profiles: area, cleaning, triangulation (ear clipping), rect, circle, arc, rounded_rect
Solid convex cells as brushes: from_convex, union, difference, intersection (exact decisions:
points are where three planes meet, sides are signs of determinants), to_mesh (closed,
corners rounded once at the end), bevel (chamfer or round edges and corners)
exact expansions (Shewchuk), orient2d, the side of a plane at a meeting of three planes,
the correctly rounded quotient
region plane regions with holes (JD21): union, intersection, difference, xor and the
decomposition of an overlay (Visio's Fragment) of contour sets, non-zero or even-odd,
open polylines as cutters; every output edge marks the input edge it lies on;
decided by snap rounding on an integer grid (exact, the same bits everywhere)
Report closed, manifold, outward, degenerate triangles, normals, bounds, area, volume, Euler
characteristic, components; json()
math Vec3, Aabb, Affine in f64; sqrt correctly rounded, sin / cos / atan2 from rt's portable
math, sin_cos_deg exact at multiples of 90 degrees
Metres, right-handed, Y up, faces counter-clockwise from outside (render3d, lib/physics, glTF). A script
describes a model (apps/modeltool binds JFScript), this crate does the geometry: it has a plain Rust API and
knows no script. Deterministic: only + - * / and correctly rounded square roots in f64, trigonometry from
rt's portable math, sorting with unique keys, no unordered containers, no threads, so the same calls give the
same mesh bits on every target (the checksum of apps/modeltool). Error texts are German, like JFScript's: they
end up in front of whoever wrote the script.
geom crate root#
/// The most triangles a mesh may have (2^24): a limit against runaway parameters, far above a game model.
MAX_TRIANGLES: usize = 1 << 24
/// The most segments of a round primitive, a lathe or stairs.
MAX_SEGMENTS: usize = 4096
/// The most copies of an array.
MAX_COPIES: usize = 100_000
enum ErrorWhy an operation made no mesh; the text (German) says what to change.Param(String)-- a parameter out of range: a length not above 0, a segment count, an arch that does not fitProfile(String)-- a profile with too few points, no area, crossing edges or one that cannot be triangulatedPath(String)-- a path with too few points or one that turns back on itselfTooBig(String)-- more triangles, points or copies than the limits allowInvalid(String)-- arrays of a mesh that do not fit together (from_triangles, validate)
impl Error
fn message(&self) -> &strthe text
geom/src/build.rs#
Source: lib/geom/src/build.rs
build -- the generators: primitives (box, cylinder, cone, sphere, torus, stairs, arch) and the operations
that make solids from profiles (extrude, prism, sweep along a path, lathe). Every one gives a closed
mesh whose faces point outward, with normals and box-projected UV in metres. Every primitive stands on
the ground: its lowest point at y = 0, centred over the origin (the rule a script relies on to stack
parts); profiles are counter-clockwise or not, the generators turn them as needed.
/// the threshold in degrees for the normals of extrusions, sweeps and lathes: edges sharper than it stay hard
DEFAULT_SMOOTH_DEG: f64 = 30.0
fn cuboid(w: f64, h: f64, d: f64) -> Result<Mesh, Error>A boxwxhxd(x, y, z) standing on y = 0, centred over the origin: 8 corners, 12 triangles, flat normals (24 vertices), box UV in metres.fn cylinder(r: f64, h: f64, n: usize) -> Result<Mesh, Error>A cylinder of radiusrand heighthon y = 0 about the Y axis,nsegments: smooth sides, flat caps.fn cone(r: f64, h: f64, n: usize, top: f64) -> Result<Mesh, Error>A cone (or withtop> 0 a frustum) of base radiusr, top radiustopand heighthon y = 0 about the Y axis,nsegments.fn sphere(r: f64, n: usize, stacks: usize) -> Result<Mesh, Error>A UV sphere of radiusrresting on y = 0 (centre at y = r),nsegments around andstacksfrom pole to pole, smooth (flat where a step is 85 degrees or more).fn torus(major: f64, minor: f64, n: usize, sides: usize) -> Result<Mesh, Error>A torus lying flat on y = 0 about the Y axis:majorfrom the axis to the middle of the tube, tube radiusminor(less thanmajor),nsegments around the axis andsidesaround the tube, smooth (flat where a step is 85 degrees or more).fn stairs(w: f64, h: f64, d: f64, steps: usize) -> Result<Mesh, Error>Stairswwide (x),hhigh andddeep (z) withstepssteps on y = 0, centred over the origin: the first riser at the front (z = d / 2), rising towards the back, a solid block under the steps. Flat.fn arch(w: f64, h: f64, d: f64, thickness: f64, n: usize) -> Result<Mesh, Error>An archwwide (x),hhigh andddeep (z) on y = 0, centred over the origin: two piersthicknessthick, the opening below a half circle ofnsegments,thicknessof material over its crown. The opening isw - 2 thicknesswide and needs room for the half circle.fn extrude(profile: &[[f64; 2]], depth: f64) -> Result<Mesh, Error>The profile (x, y; the front view) extrudeddepthalong Z, centred on z = 0: the front cap at z = depth / 2. Smooth up to [DEFAULT_SMOOTH_DEG].fn prism(footprint: &[[f64; 2]], height: f64) -> Result<Mesh, Error>The footprint (x, z; the top view) raisedheightalong Y from y = 0: walls from a floor plan.fn sweep(profile: &[[f64; 2]], path: &[Vec3], closed: bool, smooth_deg: f64) -> Result<Mesh, Error>The profile swept along a path of points. The profile's x runs to the right of the path, y up (the world's Y where the path is not vertical; for a vertical path x is X and y is Z), seen looking along the path; frames turn with the path without twisting (rotation-minimising), corners are mitred, the ends capped. A closed path joins its last point to the first (no caps; a twist the loop leaves is spread over its segments). Smooth up tosmooth_degdegrees (0: flat).fn lathe(profile: &[[f64; 2]], n: usize, smooth_deg: f64) -> Result<Mesh, Error>The profile (radius, height) turned about the Y axis innsegments: a solid of revolution. The profile is a closed polygon in the half plane radius >= 0; edges on the axis make no faces, points on it become poles, so a profile from the axis around to the axis gives a solid without a hole (a column, a vase), one away from the axis a ring. Smooth up tosmooth_degdegrees (0: flat).
geom/src/check.rs#
Source: lib/geom/src/check.rs
check -- what a model must be, measured: closed and manifold (every edge between exactly two triangles,
one fan around every point), consistently wound with the faces outward (positive volume per closed
part), normals that agree with the faces, no degenerate triangles; bounds, area, volume, counts. The
topology is the mesh's points (Mesh::points), so hard edges and UV seams do not open a mesh and parts
that only touch are not counted as non-manifold. The report is plain data and JSON for tools
(apps/modeltool).
/// A triangle counts as degenerate when two corners are one point or its height above the longest edge is
/// below this fraction of that edge (collinear corners, slivers no renderer shows)
DEGENERATE_RATIO: f64 = 1e-9
/// A stored normal counts as wrong when its length is off 1 by more than this, or when it points away from
/// its triangle's face (a dot product of 0 or less)
NORMAL_TOLERANCE: f64 = 1e-6
struct ReportThe checks of a mesh (see [Mesh::check]). Counts of problems are 0 for a good mesh.vertices: usize-- vertices of the meshtriangles: usize-- triangles of the meshpoints: usize-- points of the topology (Mesh::points)edges: usize-- distinct edges between pointsbounds: Option<Aabb>-- the bounds in metres (None for an empty mesh)area: f64-- square metresvolume: f64-- cubic metres, signed (outward faces: positive); meaningful when closedcomponents: usize-- parts connected across edgeseuler: i64-- V - E + F summed over the components (2 per closed part without a hole, 0 for a torus)open_edges: usize-- edges with one triangle: the mesh has a hole therenonmanifold_edges: usize-- edges with more than two trianglesflipped_edges: usize-- edges whose two triangles run the same way: one of them is turnednonmanifold_points: usize-- points whose triangles form more than one fan (two parts touching at a point)inverted_components: usize-- closed components with a negative volume: inside outdegenerate: usize-- triangles without area (see [DEGENERATE_RATIO])bad_normals: usize-- vertex normals that are not unit length or point away from their face (see [NORMAL_TOLERANCE])problem_at: Option<Vec3>-- where the first problem lies, for a message: the middle of the first open, non-manifold or flipped edge, else a pinched point, else the middle of the first degenerate triangle, else a vertex with a wrong normal; None when there is none of these
impl Report
fn closed(&self) -> boolclosed and manifold: no open, non-manifold or flipped edges, no pinched pointsfn outward(&self) -> boolfaces point outward: consistently wound (no flipped edges) and no closed part inside outfn ok(&self) -> boolevery check passed: closed, outward, no degenerate triangles, good normalsfn size(&self) -> Vec3width, height, depth in metres (0 for an empty mesh)fn json(&self) -> Stringthe report as one JSON object, keys in a fixed order, numbers rounded to 1e-9 (metres: a nanometre)fn fnum(v: f64) -> Stringa number for JSON: rounded to 9 decimals, without trailing zeros, -0 as 0, NaN and infinities as null
impl Mesh
fn check(&self) -> ReportMeasure the mesh: counts, bounds, area, volume and the topology checks of [Report].
geom/src/csg.rs#
Source: lib/geom/src/csg.rs
csg -- Boolean operations on convex solids, as brushes in a map editor (docs/GEOM.md, "Boolesche
Operationen"): a Solid is a set of convex cells that do not overlap, each the intersection of half-spaces
whose planes it shares with the other cells; union, difference and intersection split cells by planes and
give such a set again, so results can be combined further. to_mesh gives the boundary: the faces of the
cells less where two cells touch, as one closed mesh.
Exact where it decides: a point is where three planes meet, never rounded while the operation runs, and
which side of a plane it lies on is the sign of a 4 x 4 determinant of plane coefficients (exact.rs: f64
with an error bound, exact expansions near 0). So splitting a cell, cutting a face and finding where
faces of neighbouring cells meet always agree with each other, also for points exactly on a plane (the
usual case: a window flush with a wall, boxes touching). Only the output is rounded: every corner to the
f64 nearest the exact point (equal points, equal bits), the faces triangulated with exact orientation
tests on those coordinates. The planes themselves come from the input meshes in f64; planes closer than
WELD_RATIO of the extent count as one (also between the operands), so faces that are meant to lie in one
plane do, and features smaller than that (where several planes almost meet in one point: the tip of a
cone, the rings of a sphere) fall together into one point of the output.
/// Planes closer than this fraction of the extent count as one, output points closer than it fall together.
WELD_RATIO: f64 = 1e-9
/// the most cells a solid may have (a limit against runaway splitting)
MAX_CELLS: usize = 20_000
/// the most planes of one cell: a cell costs the square of its planes (a bevel of 64 segments made some 33 000,
/// a sphere of 256 x 128 faces as many: minutes; a sphere of 64 x 32 has about 2000)
MAX_PLANES: usize = 4096
struct PlaneA plane n . x + w = 0, n a unit vector pointing out of the solid: inside is n . x + w < 0.n: Vec3-- the outward normal, unit lengthw: f64-- the offset: n . x + w = 0 on the plane
impl Plane
fn eval(&self, p: Vec3) -> f64the signed distance ofp(positive outside)fn flipped(&self) -> Planethe same plane facing the other wayfn transformed(&self, a: &Affine) -> Planethe plane mapped bya(normal by the normal matrix, kept pointing outward)struct SolidA solid as convex cells that do not overlap (brushes): each cell is a list of planes whose inside it is. Made from a convex mesh ([Solid::from_convex]) or by union, difference and intersection; [Solid::to_mesh] gives its surface.
impl Solid
fn from_convex(m: &Mesh) -> Result<Solid, Error>The solid of a convex closed mesh: one cell whose planes are the mesh's faces (triangles in one plane within [WELD_RATIO] of the extent are one face). Err when the mesh is not closed, inside out, flat or not convex (a corner in front of a face by more than the tolerance).fn cell_count(&self) -> usizethe number of cells (convex pieces)fn plane_count(&self) -> usizethe number of planes the cells usefn is_empty(&self) -> boolwhether it has no cell (nothing left)fn cells(&self) -> Vec<Vec<Plane>>the planes of each cell (each pointing out of its cell)fn bounds(&self) -> Aabbthe box around the operands it came from (at least the solid's own)fn transformed(&self, a: &Affine) -> Solidthe solid mapped bya(planes and bounds; cells that shared a plane still do)fn union(&self, o: &Solid) -> Result<Solid, Error>Everything in this solid or ino.fn difference(&self, o: &Solid) -> Result<Solid, Error>What is in this solid but not ino.fn intersection(&self, o: &Solid) -> Result<Solid, Error>What is in both.fn to_mesh(&self, smooth_deg: f64) -> Result<Mesh, Error>The surface as one closed mesh with normals smooth up tosmooth_degdegrees (0: flat) and box UV in metres. Err for an empty solid.
impl Solid
fn bevel(&self, radius: f64, segments: usize, only: Option<Axis>) -> Result<(Solid, Mesh), Error>The solid with its edges and corners bevelled, and its surface ([bevel]):segments1 chamfers (a flat face along each edge, a triangle at each corner of three faces), more round them with that many faces per quarter turn (an edge turning by another angle gets proportionally many, at least one), the faces cut back byradiusat right angles.only: just the edges along that axis, the corners stay. Only for one convex cell.fn union(meshes: &[&Mesh]) -> Result<Mesh, Error>The union of convex closed meshes as one mesh, normals smooth up to 30 degrees.fn difference(a: &Mesh, minus: &[&Mesh]) -> Result<Mesh, Error>The convex closed meshaless each ofminus, as one mesh, normals smooth up to 30 degrees.fn intersection(meshes: &[&Mesh]) -> Result<Mesh, Error>The intersection of convex closed meshes as one mesh, normals smooth up to 30 degrees.fn bevel(m: &Mesh, radius: f64, segments: usize, only: Option<Axis>) -> Result<Mesh, Error>A convex closed mesh with its edges and corners bevelled ([Solid::bevel]); the flat faces keep flat normals, the rounded ones get normals across the arcs (where an arc meets a face, the face's normal: no seam, no shading across the face).
geom/src/exact.rs#
Source: lib/geom/src/exact.rs
exact -- arithmetic without rounding error for the decisions of the Boolean operations (docs/GEOM.md,
"Boolesche Operationen"): expansions after Shewchuk (a number as a sum of f64 components that do not overlap,
smallest first; sums and products of them are exact), the orientation of three points in the plane, the
side of a plane at the point where three other planes meet, and the f64 nearest to a quotient of two
expansions. Only + - * on f64 (never a fused multiply-add: Rust does not contract a * b + c), so the same
bits and the same answers on every target. Each predicate first computes in f64 and decides there when the
result is farther from 0 than its error bound; only near 0 (and exactly at 0) it computes exactly.
struct Exp(pub Vec<f64>)An exact number: f64 components that do not overlap, smallest magnitude first, no zeros (an empty list is 0).
impl Exp
fn zero() -> Exp0fn of(a: f64) -> Expone f64fn product(a: f64, b: f64) -> Expa * b, exactfn diff(a: f64, b: f64) -> Expa - b, exactfn sign(&self) -> i32-1, 0 or 1: the sign of the largest componentfn estimate(&self) -> f64the components summed in f64, smallest first: close to the value (after compress within an ulp)fn add_f64(&self, b: f64) -> Expself + b, exact (Shewchuk's Grow-Expansion with zero elimination)fn add(&self, o: &Exp) -> Expself + o, exact: o's components grown in one by one (correct for any two expansions that do not overlap)fn neg(&self) -> Exp-selffn sub(&self, o: &Exp) -> Expself - o, exactfn scale(&self, b: f64) -> Expself * b, exact (Shewchuk's Scale-Expansion with zero elimination)fn mul(&self, o: &Exp) -> Expself * o, exact: the sum of self scaled by each component of ofn compress(&self) -> Expthe same value in as few components as possible (Shewchuk's Compress): the largest component is then the value rounded to within an ulpfn orient2d(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> i32The orientation of a, b, c in the plane: 1 counter-clockwise (c left of a -> b), -1 clockwise, 0 on one line -- exact: the f64 determinant decides when it is clearly away from 0, else the exact one.fn orient2d_exact(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> i32orient2d without the f64 shortcuttype Pl = [f64; 4]a plane n . x + w = 0 as [nx, ny, nz, w]; its inside is where n . x + w < 0struct MeetThe point where three planes meet, as the cofactors x~ of the 3 x 4 matrix of their rows: for any plane p, det[p1; p2; p3; p] = p . x~, and x~ = det3(normals) * (x, y, z, 1). Exact (expansions) on request, always in f64 with error bounds for the shortcut.approx: [f64; 4]-- the cofactors in f64perm: [f64; 4]-- the permanents (the same sums of products, every term positive): the scale of each cofactor's errorexact: Option<[Exp; 4]>-- the exact cofactors, compressed (computed the first time a decision needs them)
impl Meet
fn new(p: &Pl, q: &Pl, r: &Pl) -> Meetwhere planes p, q, r meet (x~ in f64; exact later on request)fn exact(&mut self, p: &Pl, q: &Pl, r: &Pl) -> &[Exp; 4]the exact cofactors (computed once)fn w_sign(&mut self, p: &Pl, q: &Pl, r: &Pl) -> i32the sign of x~_w = det3 of the three normals: 0 when the planes do not meet in one pointfn dot_sign(&mut self, s: &Pl, p: &Pl, q: &Pl, r: &Pl) -> i32The sign of p . x~ (det[p1; p2; p3; s]): with w_sign, the side of plane s at the point (exact).fn point(&mut self, p: &Pl, q: &Pl, r: &Pl) -> [f64; 3]the point's coordinates, each the f64 nearest to the exact quotient (ties to even): equal points give equal bits however their planes were chosenfn div_round(n: &Exp, d: &Exp) -> f64The f64 nearest to n / d (ties to even), d not 0: an estimate, moved by ulps until n / d lies between two neighbours, then the side of their midpoint decides (2n against (lo + hi) d, exact).
geom/src/math.rs#
Source: lib/geom/src/math.rs
math -- the vectors and affine maps of the crate, in f64, with operations that give the same bits on every
target: + - * / and a correctly rounded square root, never a fused multiply-add (Rust does not contract
a * b + c on its own); sin, cos and atan2 from rt's portable math (docs/ARM64.md, ARM2), the same code on
every target. Angles of the modelling API are degrees: a multiple of 90 degrees turns exactly (sin and cos
are 0 and +-1 there), so a box turned by 90 degrees keeps exact corners and copies of a radial array in
four meet without a gap. The same scheme as lib/physics' math (docs/PHYSICS.md, "Bitgleich").
fn sqrt(x: f64) -> f64The square root, correctly rounded (IEEE 754), so the same bits on every target, NaN included:rt::fx::sqrtd, the processor's instruction where rt has it (sqrtsdon x86-64,fsqrton ARM64), elsewhere (the browser, the x86-64 Android emulator) [sqrt_portable]. A negative argument gives NaN, -0.0 gives -0.0.fn sqrt_portable(x: f64) -> f64The correctly rounded square root from f64 operations and one 64 x 64 bit product (rt::fx::sqrt_portable, tested against the processor in apps/physicstest): Newton's method gives an estimate within a few units in the last place, the integer test (R - 1/2)^2 < X <= (R + 1/2)^2 on the significand picks the right neighbour. Equal tosqrtsdfor every input, NaN included. Public for the tests.fn sin(x: f64) -> f64sin ofx(radians), the same bits on every target (within half an ulp)fn cos(x: f64) -> f64cos ofx(radians), the same bits on every targetfn atan2(y: f64, x: f64) -> f64atan2(y, x) in radians, the same bits on every target
/// The largest angle in degrees [`sin_cos_deg`] takes (beyond it NaN): far more than any modelling needs, and
/// small enough that the reduction stays exact.
MAX_DEGREES: f64 = 1e12
fn sin_cos_deg(deg: f64) -> (f64, f64)(sin, cos) of an angle in degrees, the same bits on every target and exact at every multiple of 90 degrees (0 and +-1): the angle is reduced exactly to the nearest multiple of 90 and a rest of at most 45 degrees, whose sine and cosine come from rt's portable math. NaN for a NaN angle or one beyond [MAX_DEGREES].fn floor(x: f64) -> f64the largest integer not abovexfor |x| < 2^62 (the crate's reductions; larger ones as they are), the same on every targetfn abs(x: f64) -> f64|x| (the sign bit cleared)fn angle_deg(a: Vec3, b: Vec3) -> f64the angle between two directions in degrees, 0 ..= 180 (atan2 of the cross product's length and the dot product: accurate at 0 and 180 too); 0 when one of them is zerofn min(a: f64, b: f64) -> f64the smaller of two numbers (bwhen they are equal or one is NaN)fn max(a: f64, b: f64) -> f64the larger of two numbers (bwhen they are equal or one is NaN)fn unsign_zero(x: f64) -> f64xwith -0.0 turned into +0.0 (the same bits for the same point; welding and hashing compare bits)struct Vec3A point or a direction in metres,f64; right-handed, Y up (render3d's and lib/physics' convention).x: f64-- metres (or a direction's component)y: f64-- metres, upz: f64-- metres, towards the viewer of the front view
impl Vec3
const ZERO: Vec3 = Vec3::new(0.0, 0.0, 0.0)(0, 0, 0)const X: Vec3 = Vec3::new(1.0, 0.0, 0.0)the unit vector along Xconst Y: Vec3 = Vec3::new(0.0, 1.0, 0.0)the unit vector along Y (up)const Z: Vec3 = Vec3::new(0.0, 0.0, 1.0)the unit vector along Z (towards the front view's camera)const fn new(x: f64, y: f64, z: f64) -> Vec3(x, y, z)fn dot(self, o: Vec3) -> f64the dot product, summed x, y, z in this orderfn cross(self, o: Vec3) -> Vec3the cross product (right-handed)fn length_sq(self) -> f64the squared lengthfn length(self) -> f64the length (correctly rounded root)fn try_normalize(self) -> Option<Vec3>the unit vector in this direction, None for a zero (or not finite) vectorfn normalize_or_zero(self) -> Vec3the unit vector in this direction; a zero vector stays zerofn min(self, o: Vec3) -> Vec3the smaller coordinates of bothfn max(self, o: Vec3) -> Vec3the larger coordinates of bothfn is_finite(self) -> boolwhether every coordinate is finitefn unsigned_zeros(self) -> Vec3the same point with -0.0 coordinates as +0.0fn key(self) -> [u64; 3]the bits of the coordinates with -0.0 as +0.0: equal for equal points (the key of welding)fn to_f32(self) -> [f32; 3]the coordinates as f32 (render3d, glTF)fn get(self, axis: Axis) -> f64the coordinate along an axisenum Axisone of the three axes (mirror planes, rotations, the dominant axis of a normal)X-- left to rightY-- upZ-- back to front
struct AabbAn axis-aligned box in metres (the bounds of a mesh).min: Vec3-- the smallest coordinatesmax: Vec3-- the largest coordinates
impl Aabb
fn point(p: Vec3) -> Aabbthe box around one pointfn grow(&mut self, p: Vec3)the box grown to holdpfn union(self, o: Aabb) -> Aabbthe box around bothfn size(&self) -> Vec3width, height, depth (max - min)fn center(&self) -> Vec3the middlestruct AffineAn affine map p -> m p + t in f64: rotations, scales, mirrors and moves of the modelling operations.mholds rows.m: [[f64; 3]; 3]-- the linear part, rowst: Vec3-- the move after it
impl Affine
const IDENTITY: Affine = Affine { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, ...the map that changes nothingfn translation(t: Vec3) -> Affinea move bytfn scale(s: Vec3) -> Affinea scale along the axes (a negative factor mirrors)fn mirror(axis: Axis) -> Affinethe mirror at the plane through the origin acrossaxis(x -> -x for Axis::X)fn rotation(axis: Axis, deg: f64) -> Affinea rotation bydegdegrees about an axis through the origin, counter-clockwise when the axis points at the viewer (right-handed); exact at multiples of 90 degreesfn rotation_about(axis: Vec3, deg: f64) -> Option<Affine>a rotation bydegdegrees about the directionaxis(any length) through the origin, right-handed (Rodrigues); None for a zero axisfn then_after(&self, first: &Affine) -> Affineselfafterfirst: p -> self(first(p))fn apply(&self, p: Vec3) -> Vec3m p + t, with -0.0 coordinates as +0.0fn apply_vector(&self, v: Vec3) -> Vec3m v (a direction: without the move)fn determinant(&self) -> f64the determinant of the linear part (negative: the map mirrors, faces must turn)fn normal_matrix(&self) -> [[f64; 3]; 3]the map of normals: the inverse transposed linear part up to a positive factor (the cofactor matrix, times the determinant's sign), so that a normal maps to a normal pointing the same way outfn is_finite(&self) -> boolwhether every number is finitefn is_similarity(&self) -> boolwhether the linear part keeps angles: a rotation, a mirror or a uniform scale (m^T m = s^2 I to 1e-12), so normals can simply be turned with it
geom/src/mesh.rs#
Source: lib/geom/src/mesh.rs
mesh -- the indexed triangle mesh of the crate and the operations that keep its topology: moves,
rotations, scales, mirrors, arrays, merging, turning the faces; bounds, area, volume; the fingerprint of
its bits. Normals and UV are in normals.rs, the checks in check.rs.
struct MeshAn indexed triangle mesh in metres: one normal and one UV per position, three indices per triangle, counter-clockwise seen from outside (render3d's and glTF's convention), and the topology: each vertex belongs to a point of the surface (points). A hard edge or a UV seam is two vertices of one point, as a GPU needs it; normals and the checks follow the points, so such a split does not open the mesh, while two parts that only touch (the pieces of a wall) stay two closed parts. [Mesh::weld] joins the points of vertices at the same place (a half and its mirror image).positions: Vec<Vec3>-- metresnormals: Vec<Vec3>-- unit vectors, one per position (zero until a normal operation ran on a raw mesh)uvs: Vec<[f64; 2]>-- texture coordinates, one per position; the box projection gives metres (normals.rs)points: Vec<u32>-- the point of each vertex, numbered 0 .. point count without gapsindices: Vec<u32>-- three per triangle
impl Mesh
fn new() -> Meshan empty meshfn from_triangles(positions: Vec<Vec3>, indices: Vec<u32>) -> Result<Mesh, Error>a mesh of positions and triangles, every vertex its own point, normals and UV zero (a raw mesh: the generators share vertices where the surface is connected and give it to [Mesh::smooth] or [Mesh::flat]); Err for an index count that is no multiple of 3, an index out of range or a position that is not finitefn validate(&self) -> Result<(), Error>whether the arrays fit together: as many normals, UV and points as positions, points numbered without gaps, whole triangles, indices in range, every number finite, at most [MAX_TRIANGLES]fn vertex_count(&self) -> usizethe number of vertices (positions)fn point_count(&self) -> usizethe number of points (vertices joined by the topology)fn triangle_count(&self) -> usizethe number of trianglesfn triangle(&self, t: usize) -> [u32; 3]the three indices of triangletfn corners(&self, t: usize) -> [Vec3; 3]the three corners of triangletfn bounds(&self) -> Option<Aabb>the box around every position, None for a mesh without positionsfn area(&self) -> f64the surface area in square metres: the triangles' areas summed in orderfn volume(&self) -> f64the signed volume in cubic metres (divergence theorem, relative to the middle of the bounds for accuracy): positive for a closed mesh whose faces point outward, meaningless for an open onefn transformed(&self, a: &Affine) -> MeshThe mesh mapped bya: positions moved; a map that keeps angles (rotation, mirror, uniform scale) turns the normals with it, any other (a scale that differs per axis) computes them again from the mapped faces within the same smoothing groups, so hard edges stay hard and smooth ones smooth; a map that mirrors (negative determinant) turns the triangles, so faces keep pointing outward. UV stay (call [Mesh::uv_box] again for metres in the new place).fn translated(&self, v: Vec3) -> Meshmoved by (x, y, z) metresfn rotated(&self, axis: Axis, deg: f64) -> Meshturned bydegdegrees about an axis through the origin (right-handed; exact at multiples of 90)fn scaled(&self, s: Vec3) -> Meshscaled along the axes about the origin (a negative factor mirrors; faces are turned to stay outward)fn mirrored(&self, axis: Axis) -> Meshmirrored at the plane through the origin acrossaxis(x -> -x for Axis::X), faces turned so they point outwardfn flipped(&self) -> Meshthe triangles turned the other way (normals negated): inside outfn append(&mut self, o: &Mesh)appendo(its indices and points shifted: its points stay its own)fn merge(meshes: &[&Mesh]) -> Result<Mesh, Error>the meshes as one, in order (each keeps its own vertices and points: parts that touch stay apart in the topology; [Mesh::weld] joins them)fn array(&self, count: usize, step: Vec3) -> Result<Mesh, Error>countcopies, copy i moved by i *step(copy 0 where the mesh is), as one meshfn radial(&self, count: usize, step_deg: f64) -> Result<Mesh, Error>countcopies about the Y axis through the origin, copy i turned by i *step_degdegrees (counter- clockwise seen from above), as one mesh; 360 / count for a full circlefn positions_f32(&self) -> Vec<[f32; 3]>the positions as f32 (render3d's MeshData, glTF)fn normals_f32(&self) -> Vec<[f32; 3]>the normals as f32fn uvs_f32(&self) -> Vec<[f32; 2]>the UV as f32fn fingerprint(&self) -> u64FNV-1a (64 bits) over the bits of every position, normal, UV and index in order: equal for equal meshes on every target (the determinism checksums, cache checks)fn weld(&self, tolerance: f64) -> MeshThe points of vertices at the same place joined: at the bit-equal position (-0.0 = +0.0) fortolerance0, else withintolerancemetres on every axis (and through chains of such pairs). Positions stay; only the topology changes, so a half and its mirror image merged and welded are one closed surface. Points are numbered again in the order of their first vertex.struct Fnv(pub u64)FNV-1a over 64-bit words, the hash of [Mesh::fingerprint] (public for checksums over several meshes and numbers)
impl Fnv
fn new() -> Fnvthe offset basisfn u(&mut self, v: u64)fold the 8 bytes of a word in, little-endianfn f(&mut self, v: f64)fold a number's bits infn v(&mut self, v: Vec3)fold a vector's bits in, x, y, z
geom/src/normals.rs#
Source: lib/geom/src/normals.rs
normals -- vertex normals and texture coordinates: flat (each triangle its own normal), smooth with an
angle threshold (the triangles around a point share a normal across every edge flatter than the
threshold, split at sharper ones), and UV by box projection in metres. Each rebuilds the vertices from
the triangles' corners: corners with the same position, normal and UV become one vertex, in the order of
their first corner, so the result is the same on every target.
impl Mesh
fn flat(&self) -> MeshFlat normals: every corner gets the normal of its triangle (hard edges everywhere).fn smooth(&self, max_angle_deg: f64) -> MeshSmooth normals with an angle threshold in degrees: around each point the triangles that meet across an edge whose faces differ by at mostmax_angle_degshare one normal (their normals weighted by the corner angles), split at sharper edges, open edges and edges of more than two triangles. Edges are those of the points (Mesh::points), so a hard edge split before can become smooth again; parts that only touch are never smoothed together. 0 gives flat normals except across exactly flat edges, 180 smooths every manifold edge.fn uv_box(&self, metres_per_unit: f64) -> MeshUV by box projection in world scale: each triangle is projected along the axis its normal points most along (ties: Y, then X), so one UV unit ismetres_per_unitmetres on every face, without mirrored textures: +X faces (u, v) = (-z, y), -X (z, y), +Y (x, -z), -Y (x, z), +Z (x, y), -Z (-x, y). Normals stay; vertices split where the projection changes.
geom/src/poly.rs#
Source: lib/geom/src/poly.rs
poly -- 2D profiles: signed area, orientation, cleaning, triangulation by ear clipping, and the profiles
the modelling API offers (rectangle, circle, rounded rectangle, arc). A profile is a simple polygon
(no self-intersections, no holes) as a list of points; the closing edge from the last point to the
first is implied.
/// the most points a profile or path may have
MAX_PROFILE_POINTS: usize = 65_536
fn signed_area2(p: &[[f64; 2]]) -> f64twice the signed area (shoelace): positive counter-clockwise (x right, y up)fn area(p: &[[f64; 2]]) -> f64the signed area in square metres: positive counter-clockwise
/// Points of a profile or path closer than this fraction of its extent count as one (a script's
/// arithmetic, `(y + r) - r`, leaves such near-duplicates; they would make triangles without area).
MERGE_RATIO: f64 = 1e-9
fn clean(p: &[[f64; 2]], what: &str) -> Result<Vec<[f64; 2]>, Error>the profile checked and cleaned: finite numbers, consecutive points closer than [MERGE_RATIO] of its extent merged (the first one stays) and so a repeated first point at the end, at least 3 points with an area;whatnames it in the messagefn ccw(mut p: Vec<[f64; 2]>) -> Vec<[f64; 2]>the profile counter-clockwise (reversed if it ran clockwise)fn check_simple(p: &[[f64; 2]], what: &str) -> Result<(), Error>Err when two edges of the profile cross (it must be simple); O(n^2), profiles are smallfn triangulate(p: &[[f64; 2]]) -> Result<Vec<[u32; 3]>, Error>Triangles of a simple counter-clockwise polygon by ear clipping: n - 2 triangles over its own points, counter-clockwise, none without area (a point on a straight run is never the tip of an ear, so it stays on the boundary and the walls next to a cap meet it). Err when no ear is left (a self-intersecting or degenerate polygon). Deterministic: the first ear from where the last one was cut.fn rect(w: f64, h: f64) -> Vec<[f64; 2]>a rectanglewxhcentred on the origin, counter-clockwise from the lower left cornerfn circle(r: f64, n: usize) -> Vec<[f64; 2]>a regular polygon ofncorners on a circle of radiusrabout the origin, counter-clockwise from (r, 0); exact at the axes when n is a multiple of 4fn arc(r: f64, from_deg: f64, to_deg: f64, n: usize) -> Vec<[f64; 2]>points on an arc of radiusrabout the origin fromfrom_degtoto_deg(counter-clockwise for to > from),nsegments, both ends included (n + 1 points): an open polyline for profiles and pathsfn rounded_rect(w: f64, h: f64, r: f64, n: usize) -> Vec<[f64; 2]>a rectanglewxhcentred on the origin with corners rounded by radiusr(at most half the shorter side),nsegments per corner, counter-clockwise
geom/src/region.rs#
Source: lib/geom/src/region.rs
region -- Boolean operations on plane regions (docs/GEOM.md, "Ebene Regionen"): sets given as contours
(outer contours and holes, nested to any depth, several operands, filled by a rule: non-zero or
even-odd), union, intersection, difference, exclusive or, and the decomposition of their overlay into
its faces with the operands that cover each one (Visio's "Fragment", the polygons of a map made from
overlapping areas). Open polylines go in as cutters: they split the faces of a decomposition.
boolean(operands, op, rule) -> Vec<Contour> the result's boundary: outer contours
counter-clockwise, holes clockwise
decompose(operands, rule) -> Vec<Piece> every covered face with its operands
union / intersection / difference / xor shorthands; area(contours)
Operand { contours, open }, Contour { points, marks }, Mark { operand, contour, edge, reversed }
Every output edge carries a Mark: the input edge it lies on (operand, contour, the edge from point i to
point i + 1, and whether it runs against it). A caller that flattened curves into polylines
(diagram_core: the arcs of a shape) finds its curves again by these marks. Consecutive output edges
with the same mark are one edge (the vertex between them is gone).
How it decides (snap rounding to an integer grid, exact integer arithmetic):
* The input is put on a grid: the box around all points is 2^30 steps across its longer side (the
coordinate minus the box's corner times a power of two, rounded to the nearest step), so every point
becomes a pair of integers below 2^30. Points closer than a step (10^-9 of the extent) are one.
* Snap rounding (Hobby; Guibas and Marimont): every endpoint and every point where two segments cross
makes a "hot pixel", the unit square around the grid point it rounds to; every segment is bent
through the centre of each hot pixel it passes through, in order. The result has no crossings: its
segments meet at their ends or lie on each other. Done again on its own output until nothing changes
(iterated snap rounding, Halperin and Packer), which also splits a segment where a vertex lies on it.
All tests are signs of determinants and comparisons of fractions in i128: exact, the same answer on
every target, and no case is special (touching in a point or along an edge, identical operands, a
hole on its outer contour, an operand overlapping itself). Only crossing points move, by at most
half a step; input points come back with their own f64 bits.
* The overlay: equal segments become one edge that keeps, per operand, how much the winding number
grows from its right to its left (+1 for an edge of a counter-clockwise contour). Edges that change
nothing (an operand's edge drawn there and back) are left out. Around each vertex the edges are
sorted by angle (exactly: half-plane, then cross product) and the faces traced as cycles; a cycle with
positive area is a face, the one with area <= 0 of each connected part is its outside. Which face
holds a part is found by a ray down from just left of its lowest-leftmost vertex: the first edge it
meets, compared as exact fractions. Winding numbers spread from the face around a part across its
edges.
* A face is inside an operand when its winding number is not 0 (non-zero) or odd (even-odd). The result
of an operation is its boundary: the edges with a different answer left and right, traced so that each
contour turns as sharply as it can where two pieces touch (two squares corner to corner stay two
contours).
Deterministic like the rest of geom: integers and + - * on f64, sorting with unique keys, no unordered
containers, no threads. Limits against runaway input: MAX_EDGES input edges, MAX_HOT crossings.
/// The input's box is 2^GRID_BITS steps across its longer side (a step is 10^-9 of the extent).
GRID_BITS: i32 = 30
/// the most input edges (all operands together)
MAX_EDGES: usize = 1 << 20
/// the most points where edges cross
MAX_HOT: usize = 1 << 22
enum FillRulehow contours fill: where the winding number is not 0, or where it is oddNonZeroEvenOdd
enum BoolOpthe Boolean operationsUnion-- in any operandIntersection-- in every operandDifference-- in the first and in none of the othersXor-- in an odd number of operands
struct OperandAn operand: closed contours (the last point joins the first; outer contours and holes in any order and direction, the fill rule decides) or,open, polylines that only cut (decompose).contours: Vec<Vec<[f64; 2]>>open: bool
impl Operand
fn closed(contours: Vec<Vec<[f64; 2]>>) -> Operandan area from closed contoursfn open(polylines: Vec<Vec<[f64; 2]>>) -> Operandcutters from open polylinesstruct MarkWhere an output edge comes from: the input edge from pointedgeto pointedge + 1(the closing edge of a closed contour has the index of its last point) of contourcontourof operandoperand;reversed: the output runs against it. Where input edges lie on each other, the smallest of them.operand: u32contour: u32edge: u32reversed: bool
struct ContourAn output contour: closed,marks[i]the mark of the edge frompoints[i]to the next point.points: Vec<[f64; 2]>marks: Vec<Mark>
impl Contour
fn area(&self) -> f64the signed area (shoelace about the first point, so that far coordinates do not cancel): positive for an outer contour, negative for a holefn is_hole(&self) -> boolwhether it runs clockwise (a hole)struct PieceA face of a decomposition: the operands that cover it (indices, rising) and its boundary (an outer contour, counter-clockwise, and its holes, clockwise).cover: Vec<u32>contours: Vec<Contour>
fn area(contours: &[Contour]) -> f64the sum of the signed areas of contours (the area of a result)fn union(operands: &[Operand], rule: FillRule) -> Result<Vec<Contour>, Error>union of the closed operandsfn intersection(operands: &[Operand], rule: FillRule) -> Result<Vec<Contour>, Error>intersection of the closed operandsfn difference(operands: &[Operand], rule: FillRule) -> Result<Vec<Contour>, Error>the first closed operand without the othersfn xor(operands: &[Operand], rule: FillRule) -> Result<Vec<Contour>, Error>what an odd number of closed operands coverfn boolean(operands: &[Operand], op: BoolOp, rule: FillRule) -> Result<Vec<Contour>, Error>The boundary of a Boolean operation on the closed operands (open ones do not take part): outer contours counter-clockwise, holes clockwise, none crossing another (they may touch in a point). Empty when nothing is left.fn decompose(operands: &[Operand], rule: FillRule) -> Result<Vec<Piece>, Error>The faces of the overlay that at least one closed operand covers, each with the operands covering it (byrule) and its boundary. Neighbouring faces with the same cover are one piece unless a cutter (an open operand) runs between them. Pieces in a fixed order (the order their edges were found).