diff --git a/apps/solidcraft-cli/src/main.rs b/apps/solidcraft-cli/src/main.rs index 531380d0a..d9cd5a7bb 100644 --- a/apps/solidcraft-cli/src/main.rs +++ b/apps/solidcraft-cli/src/main.rs @@ -9,7 +9,7 @@ //! solidcraft-cli bench-assistant --connect 127.0.0.1:PORT [--token T] --base-url URL --model NAME [--tasks 1,2,5] [--repeat N] //! [--timeout-s 300] [--json out.json] [--markdown out.md] //! the standard Assistant model test (#4851) on a running app -//! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] +//! solidcraft-cli snapshot [--in design|part.step] --out shot.png [--width W] [--height H] [--view iso|front|top|…|NAME | --camera JSON] [--no-grid] [--no-axes] [--quality LEVEL] //! [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] //! solidcraft-cli exec [json-params] run one command on an empty design //! solidcraft-cli commands the command registry as JSON @@ -71,7 +71,7 @@ const USAGE_BENCH_AGENT: &str = " solidcraft-cli bench-agent [--scale F] [--sav /// `bench-assistant`'s lines in the usage. const USAGE_BENCH_ASSISTANT: &str = " solidcraft-cli bench-assistant --connect 127.0.0.1:PORT [--token T] --base-url URL --model NAME [--tasks 1,2,5] [--repeat N] [--timeout-s 300] [--json out.json] [--markdown out.md]\n"; /// `snapshot`'s lines in the usage. -const USAGE_SNAPSHOT: &str = " solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]\n [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27]\n solidcraft-cli snapshot --in --out shot.png ...\n (as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error;\n --view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save;\n --camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md);\n --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture;\n --body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside\n it shows) and color #rrggbb, either or both, once per body;\n --tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body\n is visible inside the material it meets; a later --body overrides it;\n --section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world\n coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON)\n"; +const USAGE_SNAPSHOT: &str = " solidcraft-cli snapshot [--in design.solidcraft|part.step] --out shot.png [--width W] [--height H] [--view NAME | --camera JSON] [--no-grid] [--no-axes]\n [--body NAME:opacity=0.3,color=#rrggbb]... [--tool NAME]... [--section z=27] [--quality coarse|normal|fine|ultra]\n solidcraft-cli snapshot --in --out shot.png ...\n (as with run, --in starts from a design and the script runs on top of it; an option snapshot doesn't take is an error;\n --view: iso, front, back, top, bottom, left, right, or the name of a view saved in the design with view.save;\n --camera: {target: [x,y,z], yaw, pitch, distance, fov?} in mm and radians, as the MCP screenshot takes it (docs/mcp.md);\n --no-grid and --no-axes leave the ground grid (on Z 0) and the origin's axes out of the picture;\n --body: how one body is drawn, as appearance.assign takes it: opacity 0-1 (below 1 is see-through, so what is inside\n it shows) and color #rrggbb, either or both, once per body;\n --tool: draw this body solid in the tool colour and every other body see-through, so a cut's or a join's tool body\n is visible inside the material it meets; a later --body overrides it;\n --section: cut the model as inspect.section does, so the inside shows: z=27 (the plane through that world\n coordinate, keeping the smaller side), add ,flip to keep the other side, or XY, XZ, YZ, or its own JSON;\n --quality: the display quality the bodies are meshed at, as the app's setting (default normal))\n"; /// `render`'s lines in the usage. const USAGE_RENDER: &str = " solidcraft-cli render --out image.png [--setup NAME] [--width W] [--height H] [--transparent] [--overwrite] [--timeout SECONDS]\n [--progressive] [--samples N] [--max-depth N] [--seed N] [--exposure EV] [--lighting FILE.json] [--environment FILE.json] [--tone-map reinhard|aces_fitted]\n"; /// `exec`'s lines in the usage. @@ -569,7 +569,7 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { known_args( "snapshot", args, - &["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section"], + &["--in", "--out", "--width", "--height", "--view", "--camera", "--body", "--tool", "--section", "--quality"], &["--no-grid", "--no-axes"], true, )?; @@ -582,6 +582,16 @@ fn cmd_snapshot(args: &[String]) -> Result<(), String> { Some(x) => x.parse().ok().filter(|n| (16..=8192).contains(n)).ok_or_else(|| format!("{name} must be 16 to 8192 pixels, not `{x}`")), }; let (w, h) = (size("--width", 1280)?, size("--height", 800)?); + // The display quality the bodies are meshed at, as the app's Display Quality setting: set + // before the design opens, so every display plan is made at it. + if let Some(q) = flag(args, "--quality") { + use solidcraft_engine::doc::display_quality::{DisplayQuality, set_current}; + let level = DisplayQuality::parse(q).ok_or_else(|| { + let ids: Vec<&str> = DisplayQuality::ALL.iter().map(|q| q.id()).collect(); + format!("--quality must be one of {}, not `{q}`", ids.join(", ")) + })?; + set_current(level); + } let mut s = open(flag(args, "--in"), positional(args))?; // How the bodies are drawn and where the model is cut, through the commands the app's // Appearance dialog and Section Analysis run (`preview`). diff --git a/crates/geom/src/brep/geometry.rs b/crates/geom/src/brep/geometry.rs index 6c0b92fc3..3d6f4e007 100644 --- a/crates/geom/src/brep/geometry.rs +++ b/crates/geom/src/brep/geometry.rs @@ -166,11 +166,17 @@ impl Brep { ends.push(if u.forward { [uv[0], uv[2]] } else { [uv[2], uv[0]] }); } // Each use continues the one before it (the last closes the loop), except - // along a direction that collapses there (a pole). + // along a direction that collapses there (a pole): at the vertex where + // they meet, to within the vertex's tolerance. for (position, pair) in ends.iter().enumerate() { let before = ends.get(position.checked_sub(1).unwrap_or(ends.len().saturating_sub(1))); let (Some([_, end]), [start, _]) = (before, pair) else { continue }; - let pole = surface.pole(*start); + let reach = edges + .get(position) + .and_then(|u| self.edges.get(u.edge as usize).map(|e| e.vertices[if u.forward { 0 } else { 1 }])) + .and_then(|v| self.vertices.get(v as usize)) + .map_or(0.0, |v| v.tolerance); + let pole = surface.pole_within(*start, reach); for d in 0..2 { let (Some(Some(p)), Some(false)) = (period.get(d), pole.get(d)) else { continue }; let gap = (start[d] - end[d]).abs(); diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs index 7fdd21d72..aa623ce21 100644 --- a/crates/kernel/src/step_in/tests.rs +++ b/crates/kernel/src/step_in/tests.rs @@ -2039,3 +2039,60 @@ fn spline_edges_off_their_plane_by_less_than_the_file_states_get_their_closed_fo let m = measure(&imp.bodies[0].body).unwrap(); assert!(rel(m.area, 900.0) < 1e-6, "{}", m.area); } + +/// A spherical triangle (radius 0.5) whose edge runs from the equator over the sphere's pole to +/// a vertex 1.8° past it, as a corner ball meets its rounds (Poppy Humanoid writes one): on the +/// sphere's parameters the pole is a line where that edge's pcurve would jump half a turn. The +/// edge is split at the pole, and the face reads with its area by the spherical excess. +#[test] +fn an_edge_over_a_spheres_pole_is_split_there() { + let r = 0.5f64; + let over = (91.8f64).to_radians(); + let a = [r, 0.0, 0.0]; + let b = [0.0, r, 0.0]; + let p = [r * over.cos(), 0.0, r * over.sin()]; + let f = |x: f64| format!("{x:.17E}"); + let pt = |id: u64, q: [f64; 3]| format!("#{id}=CARTESIAN_POINT('',({},{},{}));\n", f(q[0]), f(q[1]), f(q[2])); + let dir = |id: u64, q: [f64; 3]| format!("#{id}=DIRECTION('',({},{},{}));\n", f(q[0]), f(q[1]), f(q[2])); + let mut t = String::from(HEAD); + t += &pt(1, [0.0; 3]); + t += &dir(2, [0.0, 0.0, 1.0]); + t += &dir(3, [1.0, 0.0, 0.0]); + t += "#4=AXIS2_PLACEMENT_3D('',#1,#2,#3);\n#5=SPHERICAL_SURFACE('',#4,0.5);\n"; + t += &pt(10, a); + t += &pt(11, b); + t += &pt(12, p); + t += "#13=VERTEX_POINT('',#10);\n#14=VERTEX_POINT('',#11);\n#15=VERTEX_POINT('',#12);\n"; + // A to P in the x–z plane over the pole (normal −y, from x towards z); P to B (normal P × B, + // from P); B to A on the equator (normal −z, from y towards x). + let n = |u: [f64; 3], v: [f64; 3]| { + let c = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let l = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); + [c[0] / l, c[1] / l, c[2] / l] + }; + let unit = |u: [f64; 3]| [u[0] / r, u[1] / r, u[2] / r]; + t += &dir(20, [0.0, -1.0, 0.0]); + t += "#21=AXIS2_PLACEMENT_3D('',#1,#20,#3);\n#22=CIRCLE('',#21,0.5);\n#23=EDGE_CURVE('',#13,#15,#22,.T.);\n"; + t += &dir(30, n(p, b)); + t += &dir(31, unit(p)); + t += "#32=AXIS2_PLACEMENT_3D('',#1,#30,#31);\n#33=CIRCLE('',#32,0.5);\n#34=EDGE_CURVE('',#15,#14,#33,.T.);\n"; + t += &dir(40, [0.0, 0.0, -1.0]); + t += &dir(41, [0.0, 1.0, 0.0]); + t += "#42=AXIS2_PLACEMENT_3D('',#1,#40,#41);\n#43=CIRCLE('',#42,0.5);\n#44=EDGE_CURVE('',#14,#13,#43,.T.);\n"; + // Counter-clockwise seen from outside: A, B, P, so every edge the other way round. + t += "#50=ORIENTED_EDGE('',*,*,#44,.F.);\n#51=ORIENTED_EDGE('',*,*,#34,.F.);\n#52=ORIENTED_EDGE('',*,*,#23,.F.);\n"; + t += "#53=EDGE_LOOP('',(#50,#51,#52));\n#54=FACE_OUTER_BOUND('',#53,.T.);\n#55=ADVANCED_FACE('',(#54),#5,.T.);\n"; + t += "#60=OPEN_SHELL('',(#55));\n#61=SHELL_BASED_SURFACE_MODEL('Ball corner',(#60));\n#62=MANIFOLD_SURFACE_SHAPE_REPRESENTATION('',(#61),#70);\n"; + t += &context(70, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"); + t += TAIL; + let imp = step_import(&t).unwrap(); + assert_eq!(imp.bodies.len(), 1, "{:?}", imp.warnings); + assert!(imp.warnings.iter().any(|w| w.contains("1 edges split where they pass through a face's pole")), "{:?}", imp.warnings); + // The spherical excess of the unit vectors' triangle, tan(E/2) = |a·(b×c)| / (1 + a·b + b·c + c·a). + let (ua, ub, up) = (unit(a), unit(b), unit(p)); + let dot = |u: [f64; 3], v: [f64; 3]| u[0] * v[0] + u[1] * v[1] + u[2] * v[2]; + let triple = dot(ua, n(ub, up)) * (1.0 - dot(ub, up).powi(2)).sqrt(); + let excess = 2.0 * triple.abs().atan2(1.0 + dot(ua, ub) + dot(ub, up) + dot(up, ua)); + let m = measure(&imp.bodies[0].body).unwrap(); + assert!(rel(m.area, excess * r * r) < 1e-3, "{} vs {}", m.area, excess * r * r); +} diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs index cc1720804..08d9b192f 100644 --- a/crates/kernel/src/tess/mod.rs +++ b/crates/kernel/src/tess/mod.rs @@ -192,12 +192,13 @@ pub(crate) fn plan(b: &brep::Brep, tol: f64, turn: Option) -> Result }; let mut boundaries: Vec = crate::par::map("face boundaries", &indexed, curved >= PARALLEL_FACES, |&fi| face_boundary(fi, &nodes)).into_iter().collect::>()?; - untangle(b, &evals, &edge_faces, &mut nodes, &mut boundaries, &face_boundary)?; + let tangled = untangle(b, &evals, &edge_faces, &mut nodes, &mut boundaries, &face_boundary)?; let planned = crate::par::map("face tessellation", &indexed, curved >= PARALLEL_FACES, |&fi| { let (Some(face), Some(eval), Some(size), Some(fb)) = (faces.get(fi), evals.get(fi), sizes.get(fi), boundaries.get(fi)) else { return Err(unsupported(format!("face {fi}: missing"))); }; - let (fp, stats) = plan_or_fill(fi, kind(face.parameters()), eval, &fb.loops, &rules, *size)?; + let refused = tangled.iter().find(|(f, _)| *f == fi).map(|(_, why)| why.as_str()); + let (fp, stats) = plan_or_fill(fi, kind(face.parameters()), eval, &fb.loops, &rules, *size, refused)?; let fwd = forward.get(fi).copied().unwrap_or(true); let fp = FacePlan { flip: !fwd, triangles: if fwd { fp.triangles } else { fp.triangles.into_iter().map(|[a, b, c]| [a, c, b]).collect() }, ..fp }; @@ -356,7 +357,7 @@ fn untangle( nodes: &mut [edges::Nodes], boundaries: &mut [Boundary], face_boundary: &(dyn Fn(usize, &[edges::Nodes]) -> Result + Sync), -) -> Result<()> { +) -> Result> { let crossing = |fi: usize, fb: &Boundary| -> Vec<(u32, u32)> { let Some(s) = evals.get(fi) else { return Vec::new() }; tangle::crossing(s, &fb.loops).into_iter().filter_map(|(l, k)| fb.segments.get(l)?.get(k).copied()).collect() @@ -370,15 +371,21 @@ fn untangle( .collect::>()?; let mut tangled: Vec<(usize, Vec<(u32, u32)>)> = found.into_iter().enumerate().filter(|(_, c)| !c.is_empty()).collect(); for round in 0..=MAX_UNTANGLE { - let Some((fi, first)) = tangled.first() else { return Ok(()) }; + if tangled.is_empty() { + return Ok(Vec::new()); + } if round == MAX_UNTANGLE { - let mut es: Vec = first.iter().map(|(e, _)| *e).collect(); - es.sort_unstable(); - es.dedup(); - let kind = b.faces.get(*fi).map_or("?", |f| kind(&f.surface)); - return Err(unsupported(format!( - "face {fi} ({kind}): boundary crosses itself: edges {es:?} run closer together than their chords can follow after {MAX_UNTANGLE} halvings" - ))); + // Each face still crossing, with why: planned leniently, and named (`plan_or_fill`). + return Ok(tangled + .iter() + .map(|(fi, c)| { + let mut es: Vec = c.iter().map(|(e, _)| *e).collect(); + es.sort_unstable(); + es.dedup(); + let kind = b.faces.get(*fi).map_or("?", |f| kind(&f.surface)); + (*fi, format!("face {fi} ({kind}): boundary crosses itself: edges {es:?} run closer together than their chords can follow after {MAX_UNTANGLE} halvings")) + }) + .collect()); } let mut split: Vec<(u32, u32)> = tangled.iter().flat_map(|(_, c)| c.iter().copied()).collect(); split.sort_unstable(); @@ -405,7 +412,7 @@ fn untangle( } } } - Ok(()) + Ok(Vec::new()) } /// Bounded work for the facet angle: a face whose boundary would get more than @@ -626,7 +633,9 @@ fn holes_beside_outer(dom: &uv::Domain, loops: &mut [seam::Loop]) { /// One face, planned by [`plan_face`]; a face it refuses because its loops cross in (u, v) is /// planned once more leniently (see [`Lenient`]) and named in the stats with the first refusal, /// so the defect upstream is still reported. When the lenient fill refuses too, the first -/// refusal is the error. +/// refusal is the error. `refused`: a face whose boundary still crosses itself after +/// [`untangle`] (two edges meeting tangentially at a cusp, whose chords cross however often +/// they are halved), filled leniently straight away with that reason. fn plan_or_fill( fi: usize, kind: &str, @@ -634,9 +643,14 @@ fn plan_or_fill( loops: &[seam::Loop], rules: &size::Rules, size: (f64, [f64; 2]), + refused: Option<&str>, ) -> Result<(FacePlan, PlanStats)> { let mut stats = PlanStats::default(); - match plan_face(fi, kind, s, loops, rules, size, &mut stats, Lenient::No) { + let strict = match refused { + Some(why) => Err(unsupported(why.to_string())), + None => plan_face(fi, kind, s, loops, rules, size, &mut stats, Lenient::No), + }; + match strict { Ok(fp) => Ok((fp, stats)), Err(first) => { let mut stats = PlanStats::default(); diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs index c67e34090..5ee223aaa 100644 --- a/crates/kernel/src/tess/tests.rs +++ b/crates/kernel/src/tess/tests.rs @@ -743,7 +743,7 @@ fn a_curved_face_crossing_itself_is_filled_on_its_surface() { fn a_face_filled_leniently_is_named_in_the_stats() { let (s, l, rules) = a_face_crossing_itself(); let size = size::face_size(&s, &uv::domain(&s), &rules); - let Ok((fp, stats)) = plan_or_fill(7, "spline", &s, std::slice::from_ref(&l), &rules, size) else { panic!("filled leniently") }; + let Ok((fp, stats)) = plan_or_fill(7, "spline", &s, std::slice::from_ref(&l), &rules, size, None) else { panic!("filled leniently") }; assert!(!fp.triangles.is_empty()); assert_eq!((stats.planar, stats.structured, stats.delaunay), (0, 0, 0)); let [lenient] = stats.lenient.as_slice() else { panic!("one lenient face: {:?}", stats.lenient) }; @@ -751,6 +751,22 @@ fn a_face_filled_leniently_is_named_in_the_stats() { assert!(lenient.reason.contains("face 7 (spline)"), "{}", lenient.reason); } +/// A face whose boundary still crosses itself after untangling (two edges leaving a vertex +/// tangentially: their chords cross however often they are halved, as on one of Poppy +/// Humanoid's faces) is filled leniently straight away with that reason, and named: the body's +/// other faces are planned as usual instead of the whole body failing with it. +#[test] +fn a_face_untangling_cannot_resolve_is_filled_leniently_and_named() { + let (s, l, rules) = a_face_crossing_itself(); + let size = size::face_size(&s, &uv::domain(&s), &rules); + let why = "face 7 (spline): boundary crosses itself: edges [1, 2] run closer together than their chords can follow"; + let Ok((fp, stats)) = plan_or_fill(7, "spline", &s, std::slice::from_ref(&l), &rules, size, Some(why)) else { panic!("filled leniently") }; + assert!(!fp.triangles.is_empty()); + let [lenient] = stats.lenient.as_slice() else { panic!("one lenient face: {:?}", stats.lenient) }; + assert_eq!(lenient.face, 7); + assert!(lenient.reason.contains(why), "{}", lenient.reason); +} + #[test] fn a_face_bounded_by_two_short_arcs_keeps_an_area_to_mesh() { // A lens on z = 0 between two radius-1000 circles crossing at (±10, 0), in a record whose diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rs index 4d1b9f1a3..bcf6eb465 100644 --- a/crates/step/src/topology.rs +++ b/crates/step/src/topology.rs @@ -458,10 +458,23 @@ impl<'b, 'a> Builder<'b, 'a> { /// and the edge's tolerance covers it. A spline face's gaps are measured on the pcurves its /// kernel makes (`raise_edges`): an iterative nearest point may settle elsewhere on it. fn measure_edges(&mut self, surface: &BSurface, edge_loops: &[Vec<(u32, bool)>]) -> R<()> { + // Only where the nearest point is in closed form: on a spline the search may settle on + // another part of the surface, or on its boundary for a point a hair past it, and report a + // gap the edge does not have (2.9 mm on Poppy Humanoid's leg shells, whose edges lie within + // 0.003 mm), widening tolerances past what SMLib takes. A spline face's gaps are measured + // on the pcurves its kernel makes (`raise_edges`). + if !matches!( + surface, + BSurface::Plane { .. } + | BSurface::PlaneThrough { .. } + | BSurface::Cylinder { .. } + | BSurface::Cone { .. } + | BSurface::Sphere { .. } + | BSurface::Torus { .. } + ) { + return Ok(()); + } let on = SurfaceEval::new(surface).map_err(|m| m.to_string())?; - // One search grid for all of the face's points, each searched from the whole grid: a - // nearest point carried on as the next one's start can settle on another part of a - // closed spline. let starts = solidcraft_geom::tess::uv::Starts::default(); for l in edge_loops { for &(e, _) in l { @@ -794,6 +807,10 @@ impl<'b, 'a> Builder<'b, 'a> { fn finish(mut self, item: u64, name: String, shells: Vec>, kind: Kind) -> R { let _span = solidcraft_profile::span("import", "step.solid_record"); let mut notes = Vec::new(); + let at_poles = self.split_at_poles()?; + if at_poles > 0 { + notes.push(format!("{at_poles} edges split where they pass through a face's pole")); + } let seams = self.add_seams()?; if seams > 0 { notes.push(format!("{seams} seam edges added to faces that wind around their surface")); diff --git a/crates/step/src/topology/seams.rs b/crates/step/src/topology/seams.rs index ef2afae54..46dd4f9b3 100644 --- a/crates/step/src/topology/seams.rs +++ b/crates/step/src/topology/seams.rs @@ -207,6 +207,69 @@ impl Builder<'_, '_> { Ok(added) } + /// Split every edge that passes through a pole of a face it bounds (a sphere's, a revolved + /// face's on its axis) inside its interval: a great circle from the equator over the pole to a + /// vertex just past it. On the face's parameters the pole is a line, along which the edge's + /// pcurve would have to jump half a turn; split there, the jump is at a vertex on the pole, + /// where a loop may run along the pole's line. Returns how many edges were split. + pub(super) fn split_at_poles(&mut self) -> R { + let mut splits = 0; + for fi in 0..self.faces.len() { + let Some(face) = self.faces.get(fi) else { continue }; + let Some(ax) = axis(&face.surface) else { continue }; + let poles: Vec = ax.poles.iter().flatten().copied().collect(); + if poles.is_empty() { + continue; + } + let mut edges: Vec = + face.loops.iter().filter_map(|l| if let LoopB::Edges(es) = l { Some(es) } else { None }).flatten().map(|u| u.0).collect(); + edges.sort_unstable(); + edges.dedup(); + for e in edges { + for pole in &poles { + let Some(t) = self.through_at(e, *pole)? else { continue }; + splits += 1; + if splits > MAX_SPLITS { + return Err(format!("more than {MAX_SPLITS} edges split at poles")); + } + let v = self.split_edge(e, t)?; + // The new vertex is the pole, as the face's parameters have it. + if let Some(x) = self.vertices.get_mut(v as usize) { + let gap = Vec3::from(x.point).dist(*pole); + x.point = arr(*pole); + x.tolerance = x.tolerance.max(1.5 * gap); + } + } + } + } + Ok(splits) + } + + /// Where edge `e` passes through `pole` inside its interval (within the tolerance, away from + /// its ends), if it does: its nearest point to the pole, refined by golden-section search. + fn through_at(&self, e: u32, pole: Vec3) -> R> { + let edge = self.edges.get(e as usize).ok_or("edge reference")?; + let c = CurveEval::new(&edge.curve).map_err(|m| m.to_string())?; + let [lo, hi] = edge.interval; + let reach = self.tol.max(edge.tolerance); + let d = |t: f64| c.point(t).map_or(f64::INFINITY, |p| p.dist(pole)); + let step = (hi - lo) / SAMPLES as f64; + let k = (0..=SAMPLES).min_by(|&i, &j| d(lo + step * i as f64).total_cmp(&d(lo + step * j as f64))).unwrap_or(0); + let (mut a, mut b) = (lo + step * k.saturating_sub(1) as f64, (lo + step * (k + 1) as f64).min(hi)); + let g = 0.5 * (5f64.sqrt() - 1.0); + for _ in 0..100 { + let (x, y) = (b - g * (b - a), a + g * (b - a)); + if d(x) < d(y) { + b = y; + } else { + a = x; + } + } + let t = 0.5 * (a + b); + let ends = [lo, hi].map(|s| c.point(s).map_or(0.0, |p| p.dist(pole))); + Ok((d(t) <= reach && ends.iter().all(|x| *x > reach) && t > lo && t < hi).then_some(t)) + } + /// Turns (in u, in v) a loop makes around a periodic surface. fn winding(&self, eval: &SurfaceEval, es: &[(u32, bool)], periods: [Option; 2]) -> R<[i64; 2]> { let mut last: Option<[f64; 2]> = None;