diff --git a/crates/geom/src/brep/history.rs b/crates/geom/src/brep/history.rs index b098fc09c..95533c276 100644 --- a/crates/geom/src/brep/history.rs +++ b/crates/geom/src/brep/history.rs @@ -119,7 +119,8 @@ pub enum EdgeOrigin { } /// A result edge: the result faces it separates and what it came from (empty when it is new -/// and lies between faces new to the operation). +/// and lies between faces new to the operation, or between two pieces of one face: a split +/// line). #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct EdgeProv { pub faces: Vec, diff --git a/crates/geom/src/fill_iso.rs b/crates/geom/src/fill_iso.rs index 6d7be3c40..c318d50c0 100644 --- a/crates/geom/src/fill_iso.rs +++ b/crates/geom/src/fill_iso.rs @@ -44,10 +44,16 @@ //! formulation ([`crate::linkage`]): at stations along an edge, the iso-parameter curve `c` //! of the fill leaving across it (σ growing into the fill) must have its height above the //! neighbour vanish to order n: -//! - order 1: `n·c′ = 0` (`n` the neighbour's normal), with weak rows `w·c′ = s`, `t·c′ = 0` -//! (`w` the neighbour's leave direction, `t = n × w` along the edge, `s` how fast the Coons -//! start leaves along `w`) that keep the fill leaving into itself, about as fast; they act -//! in the tangent plane only, so they never pull against the G1 row; +//! - order 1: `n·c′ = 0` (`n` the neighbour's normal), with weak rows `w·c′ = s`, `t·c′ = a` +//! (`w` the neighbour's leave direction, `t = n × w` along the edge) that keep the fill +//! leaving into itself, about as fast: `(a, s)` is the Coons start's own cross derivative +//! `d` turned about the edge into the neighbour's tangent plane (`a = t·d`, `s` the length of +//! the rest of `d`). The Coons start is compatible at every corner (its cross derivative there +//! is the tangent of the side it meets, as any tensor patch's must be: the two share the +//! corner's next control point), so the target is too wherever that side lies in the +//! neighbour's tangent plane; a target that is not (`t·c′ = 0` up to the corner) is a +//! contradiction the least squares can only fold the corner's spans over. They act in the +//! tangent plane only, so they never pull against the G1 row; //! - order k = 2 … n: `n·c⁽ᵏ⁾ = k!·[σᵏ] Σ_m H_m(x(σ))/m!` ([`crate::linkage::Jet::targets`]): //! the normal curvature (G2), its rate of change (G3) and that rate's (G4) are the //! neighbour's, in the fill's own leave direction. The right-hand side reads `c′ … c⁽ᵏ⁻¹⁾` @@ -813,7 +819,10 @@ struct Station { tilt: f64, held: bool, clear: bool, + /// The weak rows' target for the cross derivative `c′` ([`stations`]): `w·c′ = speed`, + /// `t·c′ = slide`. speed: f64, + slide: f64, } impl Station { @@ -1180,13 +1189,28 @@ fn stations( let ask = Asked::near(asked, [(corners.get(k).copied(), f), (corners.get((k + 1) % n).copied(), 1.0 - f)]); let clear = f > CORNER_SHARE && f < 1.0 - CORNER_SHARE && ask.full == asked; let (uv, (du, dv, sign)) = station_on(side, t); - // How fast the Coons start leaves into the leave direction: it blends the sides - // across, so it leaves as fast as the opposite sides lie apart; the side's own speed - // where it does not leave into the patch at all. - let along = p.eval(uv[0], uv[1], dv, du).map(|d| d.len()).unwrap_or(0.0); - let speed = p.eval(uv[0], uv[1], du, dv).map(|d| (d * sign).dot(c.leave)).ok().filter(|x| *x > 0.0).unwrap_or(along); + // The Coons start's cross derivative turned about the edge into the neighbour's + // tangent plane: its part along the edge kept, the rest laid along the leave + // direction at its own length. At a corner it is the next side's tangent, which the + // patch's cross derivative is there whatever its inside (module docs). + let d = p.eval(uv[0], uv[1], du, dv)? * sign; + let slide = d.dot(c.normal.cross(c.leave)); + let speed = (d.dot(d) - slide * slide).max(0.0).sqrt(); let tilt = edges.get(k).and_then(|e| e.tangent(param)).map_or(0.0, |d| d.dot(c.normal).abs().clamp(0.0, 1.0).asin()); - out.push(Station { patch, side, t, across: c, order: ask.order(), full: ask.full, fade: ask.fade, tilt, held: ask.held, clear, speed }); + out.push(Station { + patch, + side, + t, + across: c, + order: ask.order(), + full: ask.full, + fade: ask.fade, + tilt, + held: ask.held, + clear, + speed, + slide, + }); } } Ok(out) @@ -1296,7 +1320,7 @@ fn knot_line_rows(quilt: &Quilt, angle_tol: f64) -> SplineResult> { } /// A station's rows (module docs), linearised about the patch as it stands: -/// - G1: `n·c′ = 0`, and the weak Hermite rows `w·c′ = s`, `t·c′ = 0` in the neighbour's tangent +/// - G1: `n·c′ = 0`, and the weak Hermite rows `w·c′ = s`, `t·c′ = a` in the neighbour's tangent /// plane only (`t = n × w`), so they never pull against the G1 row; /// - orders k = 2 … n: `n·c⁽ᵏ⁾ = T_k(x₁ … x_{k−1})` ([`crate::linkage::Jet::linearised`]) by /// Newton's method: `T_k` is replaced by its tangent at the last solution's `x⁰`, so the row is @@ -1318,7 +1342,7 @@ fn linkage_rows(rows: &mut Vec, patch: &Patch, s: &Station, span: f64) -> S .collect::>()?; let Some(first) = derivative.first() else { return Ok(()) }; rows.push(Row { terms: along(s.patch, first, n), value: 0.0, weight: 1.0 }); - for (dir, value) in [(w, s.speed), (t, 0.0)] { + for (dir, value) in [(w, s.speed), (t, s.slide)] { rows.push(Row { terms: along(s.patch, first, dir), value, weight: HERMITE_WEIGHT }); } let Some(jet) = s.across.jet else { return Ok(()) }; diff --git a/crates/geom/src/fill_iso_tests.rs b/crates/geom/src/fill_iso_tests.rs index 04ac77f6e..618870c56 100644 --- a/crates/geom/src/fill_iso_tests.rs +++ b/crates/geom/src/fill_iso_tests.rs @@ -217,3 +217,65 @@ fn a_rational_patch_s_derivatives_are_its_differences() { assert!(exact.dist(differences) < 1e-5 * exact.len().max(1.0), "∂({du}, {dv}): {exact:?} vs {differences:?}"); } } + +/// The four quarter arcs of the circle of radius `r` about z at height `z`, on their NURBS form. +fn circle_quarters(z: f64, r: f64) -> Vec { + let f = frame(Vec3::Z * z, Vec3::X, Vec3::Y); + let q = std::f64::consts::FRAC_PI_2; + (0..4).map(|k| arc(f.clone(), r, [k as f64 * q, (k + 1) as f64 * q], false)).collect() +} + +/// Neighbours given by a normal and a leave direction at each point of the loop. +fn beside_by<'a>( + edges: &'a [IsoEdge], + frame_at: impl Fn(Vec3) -> (Vec3, Vec3) + 'a, +) -> impl FnMut(usize, &[f64]) -> Result>, String> + 'a { + move |k, ts| { + ts.iter() + .map(|t| { + let p = eval_edge_h(&edges[k], *t).map_err(|e| e.to_string())?.project().ok_or("a point at infinity")?; + let (normal, leave) = frame_at(p); + Ok(Some(Across { leave, normal, bend: None, jet: None })) + }) + .collect() + } +} + +/// Whether any patch of the fill folds (its normal reverses between neighbouring samples). +fn any_fold(fill: &IsoFill) -> bool { + fill.patches.iter().any(|p| { + let s = SurfaceEval::new(&Surface::RationalSpline { + u_knots: p.surface.knots()[0].clone(), + v_knots: p.surface.knots()[1].clone(), + homogeneous: (0..p.surface.count()[0]) + .map(|i| (0..p.surface.count()[1]).map(|j| p.surface.point(i, j)).map(|h| [h.x, h.y, h.z, h.w]).collect()) + .collect(), + }) + .unwrap(); + let n = 48; + let normal = |i: usize, j: usize| { + let (_, su, sv) = s.derivs(i as f64 / n as f64, j as f64 / n as f64).unwrap(); + su.cross(sv).normalized() + }; + (0..=n).any(|i| { + (0..=n).any(|j| { + let Some(a) = normal(i, j) else { return false }; + [(i + 1, j), (i, j + 1)].iter().any(|&(k, l)| k <= n && l <= n && normal(k, l).is_some_and(|b| a.dot(b) <= 0.0)) + }) + }) + }) +} + +/// A tube's end: the circle in four quarter arcs, G1 to the tube's wall (its normal radial, the +/// wall going on upwards). Every corner of the loop is a smooth vertex, where the cross derivative +/// of one side is the next side's tangent, along the edge itself. +#[test] +fn a_tube_end_capped_g1_holds_the_wall_and_does_not_fold() { + let edges = circle_quarters(30.0, 10.0); + let radial = |p: Vec3| (Vec3::new(p.x, p.y, 0.0).normalized().unwrap(), Vec3::Z); + let s = IsoSpec { tol: 2e-5, ..spec() }; + let fill = iso_fill(&edges, &mut beside_by(&edges, radial), &s).unwrap(); + eprintln!("tube end g1: {} patches, {:?}", fill.patches.len(), fill.achieved); + assert!(fill.achieved.normal_excess <= s.angle_tol); + assert!(!any_fold(&fill), "the cap folds"); +} diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 8dfbb96c4..b87478d02 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -827,12 +827,23 @@ fn smlib_tapered(plane: &Plane, region: &Region2, from: f64, to: f64, foot: f64, return Err(KernelError::Invalid("a tapered extrusion needs a taper".into())); }; let holes: Vec = joined.holes.iter().map(|h| section(h, from, -taper)).collect::>()?; + // A loop's section `at` as it is there: a line the offset swallows is gone, its neighbours + // meeting where it was (its wall closes on the way; whether that wall is built is the + // draft's to say). + let shape = |l: &NumberedLoop, at: f64, taper: f64| -> Result { + let ccw = l.oriented(false); + if at == 0.0 || taper == 0.0 { + return Ok(ccw); + } + let segs: Vec = offset_loop(&ccw.lp, at * taper.tan())?.into_iter().flatten().collect(); + Ok(NumberedLoop { lp: Loop2 { segs }, from: ccw.from }) + }; // The sections where the walls are farthest moved, the two ends: each hole stays inside the // outer loop and clear of the other holes there (the walls are planes, cones and their like, // which move monotonically in between). for at in [from, to] { - let o = section(&joined.outer, at, taper)?; - let hs: Vec = joined.holes.iter().map(|h| section(h, at, -taper)).collect::>()?; + let o = shape(&joined.outer, at, taper)?; + let hs: Vec = joined.holes.iter().map(|h| shape(h, at, -taper)).collect::>()?; let pts = |l: &NumberedLoop| l.lp.segs.iter().flat_map(|s| s.polyline(1e-3)).collect::>(); // Apart: no point of either inside the other. let apart = |a: &NumberedLoop, b: &NumberedLoop| !pts(a).iter().any(|p| b.lp.contains(*p)) && !pts(b).iter().any(|p| a.lp.contains(*p)); diff --git a/crates/render/src/raytrace/dielectric.rs b/crates/render/src/raytrace/dielectric.rs index f5c61b856..21a23478f 100644 --- a/crates/render/src/raytrace/dielectric.rs +++ b/crates/render/src/raytrace/dielectric.rs @@ -104,8 +104,13 @@ pub enum Certificate { ClosedBox(Bounds), } -/// A strict geometric subset, never a trusted mesh.closed flag. Only twelve -/// outward corner triangles, two complementary halves per box face, qualify. +/// Most triangles a closed box's boundary may come in (its mesh is read in full, sorting its +/// edges). +pub const MAX_BOX_TRIANGLES: usize = 1 << 16; + +/// A strict geometric subset, never a trusted mesh.closed flag. A thin sheet is one or two +/// coplanar triangles; a closed box is a mesh that is exactly the boundary of an axis-aligned +/// box, in however many triangles ([`certify_box`]). pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result { let body = scene.meshes.get(input.body_index).ok_or(TraceError::InvalidInput("dielectric body ordinal"))?; if body.name != input.body_name { @@ -113,70 +118,105 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result 36 { - return Err(TraceError::InvalidInput("unsupported dielectric boundary tessellation")); + let unsupported = TraceError::InvalidInput("unsupported dielectric boundary tessellation"); + if closed { + if !(12..=MAX_BOX_TRIANGLES).contains(&mesh.triangles.len()) { + return Err(unsupported); + } + return certify_box(mesh); } - let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); - let mut hi = -lo; - let mut tris = [None; 12]; + if !(1..=2).contains(&mesh.triangles.len()) || mesh.positions.len() > 36 { + return Err(unsupported); + } + let mut tris = [None; 2]; for (slot, indices) in tris.iter_mut().zip(&mesh.triangles) { - let mut vertices = [Vec3::ZERO; 3]; - for (v, index) in vertices.iter_mut().zip(indices) { - *v = *mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("dielectric vertex index"))?; - lo = lo.min(*v); - hi = hi.max(*v); - } - let triangle = Triangle::new(vertices)?; - if triangle.geometric_normal().is_none() { - return Err(TraceError::InvalidInput("degenerate dielectric boundary")); - } + let triangle = triangle(mesh, indices)?; *slot = Some(triangle); } - if !closed { - let first = tris.first().copied().flatten().ok_or(TraceError::InvalidInput("empty thin sheet"))?; - let normal = first.geometric_normal().ok_or(TraceError::InvalidInput("thin sheet normal"))?; - let [anchor, _, _] = first.vertices(); - for triangle in tris.into_iter().flatten() { - if triangle.geometric_normal() != Some(normal) || triangle.vertices().into_iter().any(|p| (p - anchor).dot(normal) != 0.0) { - return Err(TraceError::InvalidInput("thin sheet must be one planar consistently wound surface")); + let first = tris.first().copied().flatten().ok_or(TraceError::InvalidInput("empty thin sheet"))?; + let normal = first.geometric_normal().ok_or(TraceError::InvalidInput("thin sheet normal"))?; + let [anchor, _, _] = first.vertices(); + for triangle in tris.into_iter().flatten() { + if triangle.geometric_normal() != Some(normal) || triangle.vertices().into_iter().any(|p| (p - anchor).dot(normal) != 0.0) { + return Err(TraceError::InvalidInput("thin sheet must be one planar consistently wound surface")); + } + } + if let Some(second) = tris.get(1).copied().flatten() { + let first = first.vertices(); + let second = second.vertices(); + let mut shared = [Vec3::ZERO; 2]; + let mut shared_count = 0usize; + let mut other_first = None; + let mut other_second = None; + for p in first { + if second.contains(&p) { + *shared.get_mut(shared_count).ok_or(TraceError::InvalidInput("duplicate thin sheet triangle"))? = p; + shared_count += 1; + } else { + other_first = Some(p); } } - if let Some(second) = tris.get(1).copied().flatten() { - let first = first.vertices(); - let second = second.vertices(); - let mut shared = [Vec3::ZERO; 2]; - let mut shared_count = 0usize; - let mut other_first = None; - let mut other_second = None; - for p in first { - if second.contains(&p) { - *shared.get_mut(shared_count).ok_or(TraceError::InvalidInput("duplicate thin sheet triangle"))? = p; - shared_count += 1; - } else { - other_first = Some(p); - } - } - for p in second { - if !first.contains(&p) { - other_second = Some(p); - } - } - let [a, b] = shared; - let c = other_first.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; - let d = other_second.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; - if shared_count != 2 || (b - a).cross(c - a).dot(normal) * (b - a).cross(d - a).dot(normal) >= 0.0 { - return Err(TraceError::InvalidInput("thin sheet triangles overlap or have no unique shared edge")); + for p in second { + if !first.contains(&p) { + other_second = Some(p); } } - return Ok(Certificate::ThinSheet); + let [a, b] = shared; + let c = other_first.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; + let d = other_second.ok_or(TraceError::InvalidInput("thin sheet shared edge"))?; + if shared_count != 2 || (b - a).cross(c - a).dot(normal) * (b - a).cross(d - a).dot(normal) >= 0.0 { + return Err(TraceError::InvalidInput("thin sheet triangles overlap or have no unique shared edge")); + } + } + Ok(Certificate::ThinSheet) +} + +/// The mesh's triangle with these indices, refused where it is degenerate. +fn triangle(mesh: &solidcraft_geom::Mesh, indices: &[u32; 3]) -> Result { + let mut vertices = [Vec3::ZERO; 3]; + for (v, index) in vertices.iter_mut().zip(indices) { + *v = *mesh.positions.get(*index as usize).ok_or(TraceError::InvalidInput("dielectric vertex index"))?; + } + let triangle = Triangle::new(vertices)?; + if triangle.geometric_normal().is_none() { + return Err(TraceError::InvalidInput("degenerate dielectric boundary")); + } + Ok(triangle) +} + +/// A closed box: `mesh` is exactly the boundary of the axis-aligned box its points span, each +/// point of that boundary covered once, by exact tests on the mesh's coordinates: +/// - every triangle lies in the plane of one of the box's faces (its three corners on it, its +/// normal exactly that axis), facing out of the box; +/// - the triangles make a closed, consistently oriented surface: each edge, between two points +/// given by their exact coordinates, is run once each way. +/// +/// Such a surface is a 2-cycle on the box's boundary, a sphere, so it covers every point of the +/// boundary the same number of times k, with every triangle facing out (k ≥ 1), and its area is +/// k times the boundary's. k is 1 when the triangles' area is under 1.5 times the boundary's. +/// The count of triangles is no part of it: a face may come in any tiling. +fn certify_box(mesh: &solidcraft_geom::Mesh) -> Result { + let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY); + let mut hi = -lo; + let mut tris = Vec::new(); + tris.try_reserve_exact(mesh.triangles.len()).map_err(|_| TraceError::AllocationFailed)?; + for indices in &mesh.triangles { + let triangle = triangle(mesh, indices)?; + for v in triangle.vertices() { + lo = lo.min(v); + hi = hi.max(v); + } + tris.push(triangle); } if lo.x >= hi.x || lo.y >= hi.y || lo.z >= hi.z { return Err(TraceError::InvalidInput("closed box needs positive extents")); } let bounds = Bounds::new(lo, hi)?; - let mut masks = [[0u8; 2]; 6]; - let mut counts = [0usize; 6]; - for triangle in tris.into_iter().flatten() { + let mut edges: Vec<([u64; 3], [u64; 3])> = Vec::new(); + edges.try_reserve_exact(tris.len() * 3).map_err(|_| TraceError::AllocationFailed)?; + let key = |p: Vec3| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]; + let mut area = 0.0; + for triangle in &tris { let vertices = triangle.vertices(); let n = triangle.geometric_normal().ok_or(TraceError::InvalidInput("box normal"))?; let axis = if n.x.abs() == 1.0 { @@ -190,41 +230,23 @@ pub fn certify(scene: &ProductScene, input: &DielectricOptions) -> Result 0.0; let plane = super::component(if positive { hi } else { lo }, axis); - let face = axis * 2 + usize::from(positive); - let mut mask = 0u8; - for p in vertices { - if super::component(p, axis) != plane { - return Err(TraceError::InvalidInput("box winding or face plane")); - } - let mut corner = 0; - for (bit, a) in [(0, (axis + 1) % 3), (1, (axis + 2) % 3)] { - let value = super::component(p, a); - if value == super::component(hi, a) { - corner |= 1 << bit; - } else if value != super::component(lo, a) { - return Err(TraceError::InvalidInput("box vertex is not a corner")); - } - } - mask |= 1 << corner; + if vertices.iter().any(|p| super::component(*p, axis) != plane) { + return Err(TraceError::InvalidInput("box winding or face plane")); } - let count = counts.get_mut(face).ok_or(TraceError::Internal("box face count"))?; - let target = masks.get_mut(face).and_then(|pair| pair.get_mut(*count)).ok_or(TraceError::InvalidInput("too many box face triangles"))?; - *target = mask; - *count += 1; + let [a, b, c] = vertices; + area += (b - a).cross(c - a).len() * 0.5; + edges.extend([(key(a), key(b)), (key(b), key(c)), (key(c), key(a))]); } - for (count, [a, b]) in counts.into_iter().zip(masks) { - // Three distinct corners each; missing corners must be opposite. Thus - // both triangles share a diagonal and tile, rather than overlap. - let missing_a = (!a) & 15; - let missing_b = (!b) & 15; - if count != 2 - || a.count_ones() != 3 - || b.count_ones() != 3 - || (a | b) != 15 - || !matches!((missing_a, missing_b), (1, 8) | (8, 1) | (2, 4) | (4, 2)) - { - return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); - } + // Each edge run once each way: sorted, every directed edge is there once and so is its + // reverse. + edges.sort_unstable(); + if edges.windows(2).any(|w| w[0] == w[1]) || edges.iter().any(|(a, b)| edges.binary_search(&(*b, *a)).is_err()) { + return Err(TraceError::InvalidInput("incomplete or ambiguous closed box face")); + } + let size = hi - lo; + let boundary = 2.0 * (size.x * size.y + size.y * size.z + size.z * size.x); + if !(area < 1.5 * boundary) { + return Err(TraceError::InvalidInput("closed box boundary covered more than once")); } Ok(Certificate::ClosedBox(bounds)) } diff --git a/crates/render/src/raytrace/dielectric_tests.rs b/crates/render/src/raytrace/dielectric_tests.rs index e2bc981b2..30fd12737 100644 --- a/crates/render/src/raytrace/dielectric_tests.rs +++ b/crates/render/src/raytrace/dielectric_tests.rs @@ -128,6 +128,31 @@ fn closed_box_certification_requires_complete_outward_boundary() { assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); } +/// A box's boundary in more triangles than two a face (its top fanned from a point in its +/// middle, as a mesher with interior points makes it) is the same box; the fan's middle off the +/// face's plane, or a face covered twice, is not. +#[test] +fn closed_box_certification_takes_any_tiling_of_the_faces() { + let fanned = |middle: Vec3| { + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.positions.push(middle); + mesh.triangles.retain(|t| *t != [4, 5, 7] && *t != [4, 7, 6]); + mesh.triangles.extend([[8, 4, 5], [8, 5, 7], [8, 7, 6], [8, 6, 4]]); + body + }; + let Ok(Certificate::ClosedBox(bounds)) = certify(&scene(fanned(Vec3::new(1.0, -3.0, 2.0))), &input(DielectricBoundary::ClosedBox)) else { + panic!("a fanned top is still the box") + }; + assert_eq!((bounds.min(), bounds.max()), (Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 2.0))); + assert!(certify(&scene(fanned(Vec3::new(1.0, -3.0, 2.0 - 1e-9))), &input(DielectricBoundary::ClosedBox)).is_err()); + // The top once more, split along its other diagonal: covered twice. + let mut body = box_body(2.0); + let mesh = Arc::make_mut(&mut body.mesh); + mesh.triangles.extend([[4, 5, 6], [5, 7, 6]]); + assert!(certify(&scene(body), &input(DielectricBoundary::ClosedBox)).is_err()); +} + #[test] fn captured_occurrence_identity_and_unsupported_boundary_are_refused() { let scene = scene(box_body(2.0)); diff --git a/crates/smlib/src/history.rs b/crates/smlib/src/history.rs index b88b54d12..e2eedc164 100644 --- a/crates/smlib/src/history.rs +++ b/crates/smlib/src/history.rs @@ -178,10 +178,11 @@ impl Raw { } }; let origins = if e.origins.is_empty() { - // New: where its two faces meet, each side what that face came from. + // New: where its two faces meet, each side what that face came from. Between two + // pieces of one face (a split line) nothing met: it comes from nothing. let side = |f: usize| faces.get(f).and_then(|p| Side::new(p.origins.iter().copied())); match bounds.as_slice() { - [a, b] => side(*a).zip(side(*b)).map(|(a, b)| EdgeOrigin::meet(a, b)).into_iter().collect(), + [a, b] => side(*a).zip(side(*b)).filter(|(a, b)| a != b).map(|(a, b)| EdgeOrigin::meet(a, b)).into_iter().collect(), _ => Vec::new(), } } else { diff --git a/crates/smlib/src/history/tests.rs b/crates/smlib/src/history/tests.rs index 6fdc4b994..7282aa61d 100644 --- a/crates/smlib/src/history/tests.rs +++ b/crates/smlib/src/history/tests.rs @@ -55,6 +55,17 @@ fn new_edges_are_where_their_faces_meet() { h.check_counts((3, 3), &[(3, 8), (5, 4)]).unwrap(); } +/// A face split in two (a split line across operand 0's face 0): the new edge lies between two +/// pieces of one face, where nothing met, so it comes from nothing. +#[test] +fn a_split_line_comes_from_nothing() { + let raw = Raw::decode(&[1, 2, 1, 2, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0]).unwrap(); + let h = raw.history(&[Order::default()], &Order::default()).unwrap(); + assert_eq!(h.faces.iter().map(|f| (f.origins.clone(), f.change)).collect::>(), vec![(vec![face(0, 0)], Change::Split); 2]); + assert_eq!(h.edges[0].faces, vec![0, 1]); + assert!(h.edges[0].origins.is_empty(), "{:?}", h.edges[0].origins); +} + #[test] fn renumbers_into_canonical_order() { let raw = Raw::decode(RECORDS).unwrap();