1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4pub(super) struct RimPiece {
6 pub(super) window: [f64; 2],
8 pub(super) edge_id: u64,
9}
10
11pub fn blend_smooth_chain(
17 solid: &BrepSolid,
18 seed_edge_id: u64,
19 radius: f64,
20 chamfer: bool,
21 name: Option<&str>,
22) -> Result<BrepSolid, KernelRefusal> {
23 let _operation = crate::blend::BlendOperation::enter();
26 if !(radius > 0.0) || !radius.is_finite() {
27 return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
28 }
29 let chain = collect_smooth_chain(solid, seed_edge_id)?;
30 if chain.segments.len() < 2 {
31 return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
32 }
33 let pairs: Vec<[u64; 2]> = chain.segments.iter().map(|segment| [segment.first.face.id, segment.second.face.id]).collect();
35 let _sides = crate::blend::setback::chain_sides(&pairs)?;
36 if chain.closed {
37 blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
38 } else {
39 blend_open_smooth_chain(solid, &chain, radius, chamfer, name)
40 }
41}
42
43pub fn blend_smooth_chain_if_closed(
50 solid: &BrepSolid,
51 seed_edge_id: u64,
52 radius: f64,
53 chamfer: bool,
54 name: Option<&str>,
55) -> Result<BrepSolid, KernelRefusal> {
56 let _operation = crate::blend::BlendOperation::enter();
59 if !(radius > 0.0) || !radius.is_finite() {
60 return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
61 }
62 let chain = collect_smooth_chain(solid, seed_edge_id)?;
63 if chain.segments.len() < 2 {
64 return Err(KernelRefusal::internal(KernelStage::Refine, "chain_single_segment", "blend: chain collapsed to a single segment"));
65 }
66 let pairs: Vec<[u64; 2]> = chain.segments.iter().map(|segment| [segment.first.face.id, segment.second.face.id]).collect();
68 let _sides = crate::blend::setback::chain_sides(&pairs)?;
69 if !chain.closed {
70 return Err(
71 KernelRefusal::unsupported(KernelStage::Classify, "open_tangent_chain", "blend: the edge is one arc of an OPEN tangent chain; the unselected \
72 continuation is capped, not blended"),
73 );
74 }
75 blend_closed_smooth_chain(solid, &chain.segments, radius, chamfer, name)
76}
77
78fn blend_closed_smooth_chain(
95 solid: &BrepSolid,
96 segments: &[ChainSegment<'_>],
97 radius: f64,
98 chamfer: bool,
99 name: Option<&str>,
100) -> Result<BrepSolid, KernelRefusal> {
101 let mode = std::env::var("BREP_CHAIN_LADDER_MEMO");
102 let (memo_on, verify) = match mode.as_deref() {
103 Ok("0") => (false, false),
104 Ok("verify") => (true, true),
105 _ => (true, false),
106 };
107 if !memo_on || crate::blend::setback::sides().is_some() {
109 return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
110 }
111 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
112 let signed = if chain_ladder_signed_key_on() {
121 let mut signs = Vec::with_capacity(segments.len());
122 for segment in segments {
123 match crate::blend::stations::signed_radii(
124 segment.edge,
125 segment.first.face,
126 segment.first.coedge,
127 segment.second.face,
128 segment.second.coedge,
129 radius,
130 ) {
131 Ok(pair) => signs.push(pair),
132 Err(_) => return blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name),
134 }
135 }
136 Some(signs)
137 } else {
138 None
139 };
140 let key = ladder_memo_key(segments, radius, chamfer, bar, signed.as_deref());
141 let cached = LADDER_MEMO.with(|memo| memo.borrow().iter().find(|(stored, _)| *stored == key).map(|(_, refusal)| refusal.clone()));
142 crate::blend::carve::carve_trace(format_args!(
143 "blend chain ladder memo: {} for segments {:?}",
144 if cached.is_some() { "hit" } else { "miss" },
145 segments
146 .iter()
147 .map(|segment| (segment.edge.id, segment.forward, segment.first.face.id, segment.second.face.id))
148 .collect::<Vec<_>>()
149 ));
150 if let (Some(refusal), false) = (&cached, verify) {
151 crate::blend::record_count("count.chain_ladder_memo.hit", 1);
152 return Err(refusal.clone());
153 }
154 let result = blend_closed_smooth_chain_unmemoized(solid, segments, radius, chamfer, name);
155 if let Some(refusal) = cached {
156 let same = matches!(&result, Err(again) if *again == refusal && format!("{again:?}") == format!("{refusal:?}"));
157 assert!(same, "chain ladder memo mismatch: cached {refusal:?}, recomputed {:?}", result.as_ref().err());
158 crate::blend::record_count("count.chain_ladder_memo.verified", 1);
159 return result;
160 }
161 if let Err(refusal) = &result {
162 if matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == "chain_ladder_top") {
163 LADDER_MEMO.with(|memo| {
164 let mut memo = memo.borrow_mut();
165 if memo.len() >= LADDER_MEMO_CAPACITY {
166 memo.remove(0);
167 }
168 memo.push((key, refusal.clone()));
169 });
170 }
171 }
172 result
173}
174
175fn chain_ladder_signed_key_on() -> bool {
179 switch!("BREP_CHAIN_LADDER_SIGNED_KEY", true)
180}
181
182fn chain_ladder_rotation_key_on() -> bool {
186 switch!("BREP_CHAIN_LADDER_ROTATION_KEY", true)
187}
188
189const LADDER_MEMO_CAPACITY: usize = 32;
191
192thread_local! {
193 static LADDER_MEMO: std::cell::RefCell<Vec<(Vec<u64>, KernelRefusal)>> = const { std::cell::RefCell::new(Vec::new()) };
195}
196
197fn ladder_memo_key(segments: &[ChainSegment<'_>], radius: f64, chamfer: bool, bar: f64, signed: Option<&[(f64, f64)]>) -> Vec<u64> {
199 fn curve(key: &mut Vec<u64>, curve: &NurbsCurve) {
200 key.extend([curve.degree as u64, curve.knots.len() as u64, curve.control_points.len() as u64]);
201 key.extend(curve.knots.iter().map(|knot| knot.to_bits()));
202 for point in &curve.control_points {
203 key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
204 }
205 }
206 fn face(key: &mut Vec<u64>, face: &FaceRecord, loops: bool) {
207 let surface = &face.surface;
208 key.extend([face.id, face.same_sense as u64, surface.degree_u as u64, surface.degree_v as u64]);
209 key.extend([surface.knots_u.len() as u64, surface.knots_v.len() as u64, surface.control_points.len() as u64]);
210 key.extend(surface.knots_u.iter().chain(&surface.knots_v).map(|knot| knot.to_bits()));
211 for row in &surface.control_points {
212 key.push(row.len() as u64);
213 for point in row {
214 key.extend([point.x.to_bits(), point.y.to_bits(), point.z.to_bits(), point.w.to_bits()]);
215 }
216 }
217 if !loops {
218 return;
219 }
220 key.push(face.loops.len() as u64);
221 for loop_record in &face.loops {
222 key.extend([loop_record.id, loop_record.coedges.len() as u64]);
223 for coedge in &loop_record.coedges {
224 key.extend([coedge.id, coedge.edge_id, coedge.forward as u64]);
225 curve(key, &coedge.pcurve);
226 }
227 }
228 }
229 let mut key = vec![
230 radius.to_bits(),
231 chamfer as u64,
232 bar.to_bits(),
233 crate::blend::station_refinement_on() as u64,
234 crate::blend::chain_arc_stations_on() as u64,
235 wall_verdict_on() as u64,
236 local_continue_on() as u64,
237 segments.len() as u64,
238 signed.is_some() as u64,
239 ];
240 let start = if chain_ladder_rotation_key_on() {
245 key.push(1);
246 segments.iter().enumerate().min_by_key(|(_, segment)| segment.edge.id).map_or(0, |(index, _)| index)
247 } else {
248 0
249 };
250 for index in (0..segments.len()).map(|offset| (start + offset) % segments.len()) {
251 let segment = &segments[index];
252 if let Some((rho1, rho2)) = signed.and_then(|signs| signs.get(index)) {
253 key.extend([rho1.to_bits(), rho2.to_bits()]);
254 }
255 let edge = segment.edge;
256 key.extend([edge.id, edge.start_vertex_id, edge.end_vertex_id, edge.t0.to_bits(), edge.t1.to_bits(), segment.forward as u64]);
257 curve(&mut key, &edge.curve);
258 for mate in [&segment.first, &segment.second] {
259 key.extend([mate.coedge.id, mate.coedge.edge_id, mate.coedge.forward as u64, mate.loop_index as u64, mate.rho.to_bits()]);
260 curve(&mut key, &mate.coedge.pcurve);
261 face(&mut key, mate.face, signed.is_none());
262 }
263 }
264 key
265}
266fn blend_closed_smooth_chain_unmemoized(
279 solid: &BrepSolid,
280 segments: &[ChainSegment<'_>],
281 radius: f64,
282 chamfer: bool,
283 name: Option<&str>,
284) -> Result<BrepSolid, KernelRefusal> {
285 let bar = crate::blend::setback::chain_bar(solid, crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit);
286 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
289 let mut trend: Vec<(usize, f64)> = Vec::new();
291 let first = loop {
292 let per_segment = budget.rung;
293 let rung = build_closed_smooth_chain(
294 solid,
295 segments,
296 radius,
297 chamfer,
298 name,
299 &budget,
300 FoldPolicy::Refuse,
301 bar,
302 );
303 match rung {
304 Ok(Rung::TooCoarse { deviation }) => {
305 crate::blend::carve::carve_trace(format_args!(
306 "blend chain: {} leaves the rails \
307 {deviation:.6e} from the rolling ball, against {bar:.3e}",
308 budget.describe()
309 ));
310 trend.push((per_segment, deviation));
311 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
312 let (best_rung, best, listing) = ladder_trend(&trend);
313 return Err(KernelRefusal::non_convergence(KernelStage::Refine, "chain_ladder_top", format!(
314 "blend: the chain's ladder reached its top, {per_segment} stations per segment, \
315 and no rung passed — its best, {best_rung} stations per segment, left this \
316 collar's fitted rails {best:.6e} from the rolling ball's own contacts against \
317 a bar of {bar:.3e} (rung by rung: {listing}), so there is no wall accurate \
318 enough to build"
319 )));
320 }
321 budget = budget.doubled();
322 }
323 Ok(Rung::StationFailed(failure)) => {
328 crate::blend::carve::carve_trace(format_args!(
329 "blend chain: {per_segment} stations per segment: segment {} position {} \
330 (t {:.9}) continued from position {} (t {:.9}, seed {:?}) did not converge: {}",
331 failure.segment, failure.position, failure.t, failure.from_position,
332 failure.from_t, failure.seed_uv, failure.error
333 ));
334 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
335 break Err(failure.error);
336 }
337 budget = budget.doubled();
338 }
339 other => break other,
340 }
341 };
342 if let Err(error) = &first {
343 crate::blend::carve::carve_trace(format_args!(
344 "blend chain: the march at {} refused: {error}", budget.describe()
345 ));
346 }
347 match first {
348 Ok(Rung::Built(built)) => Ok(built),
349 Ok(Rung::TooCoarse { .. }) | Ok(Rung::StationFailed(_)) => {
350 Err(KernelRefusal::internal(KernelStage::Refine, "chain_ladder_rung", "blend: the chain ladder left an accuracy rung unhandled"))
351 }
352 Err(error) if crate::blend::fold::is_rail_fold(&error) => Err(error),
358 Err(error) if crate::blend::is_wall_fold(&error) && !chamfer => {
361 carve_ladder(solid, segments, radius, name, bar)
362 .map_err(|carve_error| {
370 if crate::blend::is_wall_fold(&carve_error) {
371 carve_error
372 } else {
373 crate::blend::fold::wall_fold_refusal(
374 Vec::new(),
375 format!(
376 "{} {} fits this edge: the wall folds, and the fold band could not \
377 be carved — {carve_error}",
378 crate::blend::WALL_FOLDS,
379 radius.abs()
380 ),
381 )
382 }
383 })
384 }
385 Err(error) => Err(error),
386 }
387}
388
389fn carve_ladder(
399 solid: &BrepSolid,
400 segments: &[ChainSegment<'_>],
401 radius: f64,
402 name: Option<&str>,
403 bar: f64,
404) -> Result<BrepSolid, KernelRefusal> {
405 let mut budget = ChainBudget::for_chain(segments, CHAIN_PER_SEGMENT)?;
406 loop {
407 let per_segment = budget.rung;
408 match build_closed_smooth_chain(
409 solid,
410 segments,
411 radius,
412 false,
413 name,
414 &budget,
415 FoldPolicy::Carve,
416 bar,
417 )? {
418 Rung::Built(built) => {
419 crate::blend::carve::carve_trace(format_args!(
420 "blend carve: {} is the first rung inside \
421 {bar:.3e}",
422 budget.describe()
423 ));
424 return Ok(built);
425 }
426 Rung::StationFailed(failure) => return Err(failure.error),
429 Rung::TooCoarse { deviation } => {
430 crate::blend::carve::carve_trace(format_args!(
431 "blend carve: {} leaves the rails \
432 {deviation:.6e} from the rolling ball, against {bar:.3e}",
433 budget.describe()
434 ));
435 if budget.largest() * 2 > CHAIN_CARVE_MAX_PER_SEGMENT {
436 return Err(crate::blend::fold::wall_fold_refusal(
437 Vec::new(),
438 format!(
439 "{} {} fits this edge: the wall folds, and at {per_segment} stations \
440 per segment — the top of the carve's ladder — its fitted rails are \
441 still {deviation:.6e} from the rolling ball's own contacts against a \
442 bar of {bar:.3e}, so there is no wall accurate enough to carve",
443 crate::blend::WALL_FOLDS,
444 radius.abs()
445 ),
446 ));
447 }
448 budget = budget.doubled();
449 }
450 }
451 }
452}
453
454enum Rung {
457 Built(BrepSolid),
458 TooCoarse { deviation: f64 },
459 StationFailed(ChainStationFailure),
462}
463
464fn rail_deviation(
488 samples: &[ChainSample],
489 cr: &NurbsCurve,
490 cs: &NurbsCurve,
491 fit_low: f64,
492 fit_range: f64,
493 budget: &ChainBudget,
494 bar: f64,
495) -> Result<(f64, Vec<usize>), KernelRefusal> {
496 let mut order: Vec<usize> = (0..samples.len())
500 .filter(|&index| (0..=budget.count(samples[index].segment) as isize).contains(&samples[index].position))
501 .collect();
502 order.sort_by(|&a, &b| {
503 let (a, b) = (&samples[a], &samples[b]);
504 a.segment.cmp(&b.segment).then(a.position.cmp(&b.position)).then(a.offset.total_cmp(&b.offset))
505 });
506 let next_of: std::collections::HashMap<usize, f64> = order
507 .windows(2)
508 .filter(|pair| samples[pair[0]].segment == samples[pair[1]].segment)
509 .map(|pair| (pair[0], samples[pair[1]].parameter))
510 .collect();
511 let mut failing = Vec::new();
512 let closest = closest_on_rail;
513 let mut worst: f64 = 0.0;
514 let mut per_segment_worst: Vec<(f64, isize, f64, f64, Vec3, Vec3)> = Vec::new();
517 for &index in &order {
518 let sample = &samples[index];
519 let Some([p1, p2]) = sample.midpoint else {
520 continue;
521 };
522 let Some(&next) = next_of.get(&index) else {
523 continue;
524 };
525 let global = (0.5 * (sample.parameter + next)).rem_euclid(1.0);
526 let seed = (global - fit_low) / fit_range;
527 let reach = (next - sample.parameter).abs() / fit_range;
528 let (miss1, miss2) = (closest(cr, p1, seed, reach)?, closest(cs, p2, seed, reach)?);
529 worst = worst.max(miss1).max(miss2);
530 if miss1.max(miss2) > bar {
531 failing.push(index);
532 }
533 if per_segment_worst.len() <= sample.segment {
534 per_segment_worst.resize(
535 sample.segment + 1,
536 (0.0, 0, 0.0, 0.0, Vec3::default(), Vec3::default()),
537 );
538 }
539 if miss1.max(miss2) >= per_segment_worst[sample.segment].0 {
540 per_segment_worst[sample.segment] = (miss1.max(miss2), sample.position, miss1, miss2, p1, p2);
541 }
542 }
543 for (segment, (miss, position, miss1, miss2, p1, p2)) in per_segment_worst.iter().enumerate() {
544 crate::blend::carve::carve_trace(format_args!(
545 " rail miss segment {segment}: worst {miss:.6e} after station {position} \
546 (cr {miss1:.6e} at ({:.6}, {:.6}, {:.6}), cs {miss2:.6e} at ({:.6}, {:.6}, {:.6}))",
547 p1.x, p1.y, p1.z, p2.x, p2.y, p2.z
548 ));
549 }
550 Ok((worst, failing))
551}
552
553const PIECE_TRACK_CEILING: usize = 4096;
557
558fn closest_on_rail(curve: &NurbsCurve, target: Vec3, seed: f64, reach: f64) -> Result<f64, KernelRefusal> {
561 let [low, high] = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
562 let (u, _) = crate::projection::curve_foot_newton(curve, target, seed, [low, high],
563 crate::projection::CurveFootPolicy {
564 domain: crate::projection::FootDomain::Clamp,
565 iterations: 40,
566 slope_guard: -1.0, step_limit: reach,
568 parameter_tolerance: 1e-15,
569 mode: crate::projection::FootMode::Backtracked,
570 }).or_refuse(KernelStage::Refine, "curve_foot_newton")?;
571 Ok(curve.derivatives_extended(u, 0).or_refuse(KernelStage::Refine, "derivatives_extended")?[0].sub(target).length())
572}
573
574pub(super) const LOCAL_RAIL_STENCIL: usize = 16;
577
578fn rail_pair_miss(cr_miss: f64, cs_miss: f64) -> Option<f64> {
582 (cr_miss.is_finite() && cs_miss.is_finite()).then(|| cr_miss.max(cs_miss))
583}
584
585#[allow(clippy::too_many_arguments)]
591pub(super) fn dense_rail_misses(
592 contacts: &crate::blend::chain::DenseContacts,
593 samples: &[ChainSample],
594 cr: &NurbsCurve,
595 cs: &NurbsCurve,
596 low: f64,
597 range: f64,
598 wrap: bool,
599) -> Result<(Vec<(usize, f64)>, Vec<usize>), KernelRefusal> {
600 let mut readable = Vec::with_capacity(contacts.solved.len());
601 let mut unreadable = Vec::new();
602 for (left, next, fraction, p1, p2) in &contacts.solved {
603 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
604 let global = from + fraction * (to - from);
608 let global = if wrap { global.rem_euclid(1.0) } else { global };
609 let seed = (global - low) / range;
610 let reach = (to - from).abs() / range;
611 let cr_miss = closest_on_rail(cr, *p1, seed, reach).unwrap_or(f64::NAN);
614 let cs_miss = closest_on_rail(cs, *p2, seed, reach).unwrap_or(f64::NAN);
615 match rail_pair_miss(cr_miss, cs_miss) {
616 Some(miss) => readable.push((*left, miss)),
617 None => unreadable.push(*left),
618 }
619 }
620 Ok((readable, unreadable))
621}
622
623pub(super) fn combine_rail_verdict(
629 halfway: (f64, Vec<usize>),
630 dense: &[(usize, f64)],
631 unsolved: &[usize],
632 bar: f64,
633) -> (f64, Vec<usize>) {
634 let (mut worst, mut failing) = halfway;
635 for &(left, miss) in dense {
636 if !miss.is_finite() {
637 failing.push(left);
638 continue;
639 }
640 if miss > bar {
641 failing.push(left);
642 }
643 worst = worst.max(miss);
644 }
645 failing.extend_from_slice(unsolved);
646 failing.sort_unstable();
647 failing.dedup();
648 (worst, failing)
649}
650
651pub(super) fn model_rounds_limit() -> usize {
658 REFINE_ROUNDS
659}
660
661pub(super) fn model_request_on() -> bool {
662 wall_verdict_on()
663}
664
665
666pub(super) fn wall_verdict_on() -> bool {
669 true
670}
671
672
673
674
675
676pub(super) const WALL_SECTION_PROBES: usize = 8;
679
680pub(in crate::blend) fn sweep_residual(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<f64> {
701 let j = locate_foot(p, nodes, j, radius)?;
702 sweep_residual_on(p, nodes, (j - 1).min(nodes.len() - 4), j, radius)
703}
704
705const FOOT_TRAVEL: usize = 4;
708
709fn locate_foot(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<usize> {
719 locate_foot_read(p, nodes, j, radius).map(|(node, _)| node)
720}
721
722fn locate_foot_read(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(usize, f64)> {
725 locate_foot_read_prepared(p, nodes, j, radius, None)
726}
727
728fn locate_foot_read_prepared(p: Vec3, nodes: &[Vec3], j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Option<(usize, f64)> {
729 let n = nodes.len();
730 if n < 4 || j == 0 || j + 1 >= n {
731 return None;
732 }
733 let mut tried: Vec<usize> = Vec::new();
734 let mut at = j;
735 loop {
736 let base = (at - 1).min(n - 4);
737 match stencil_solve_prepared(p, nodes, base, at, radius, prepared) {
738 Solve::Read(distance) => return Some((at, distance)),
739 Solve::Unread => return None,
740 Solve::Window(s) => {
741 tried.push(at);
742 let next = (base as f64 + s).round();
743 let next = if next.is_finite() { next.clamp(1.0, (n - 2) as f64) as usize } else { at };
744 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
745 wall_decline(|| format!(
746 "foot search from node {j} of {n}: tried {tried:?}, next {next} ({})",
747 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
748 ));
749 return None;
750 }
751 at = next;
752 }
753 }
754 }
755}
756
757fn sweep_residual_on(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Option<f64> {
760 match stencil_solve(p, nodes, base, j, radius) {
761 Solve::Read(distance) => Some(distance),
762 Solve::Window(_) | Solve::Unread => None,
763 }
764}
765
766enum Solve {
769 Read(f64),
770 Window(f64),
771 Unread,
772}
773
774thread_local! {
775 static WALL_DECLINES: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
780}
781
782fn wall_decline(reason: impl FnOnce() -> String) {
783 WALL_DECLINES.with(|log| {
784 if let Some(lines) = log.borrow_mut().as_mut() {
785 lines.push(reason());
786 }
787 });
788}
789
790pub(in crate::blend) fn declared_wall_probe_why(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Result<(f64, f64), String> {
798 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
799 let read = declared_wall_probe(p, fine, jf, radius);
800 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
801 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
802}
803
804fn stencil_solve(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64) -> Solve {
805 stencil_solve_prepared(p, nodes, base, j, radius, None)
806}
807
808fn stencil_solve_prepared(p: Vec3, nodes: &[Vec3], base: usize, j: usize, radius: f64, prepared: Option<&StencilPreparation>) -> Solve {
809 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
810 let n = nodes.len();
811 if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || !radius.is_finite() || !finite(p) || !prepared.map_or_else(|| wall_nodes_finite(nodes), |cache| cache.finite) {
812 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: unreadable input"));
813 return Solve::Unread;
814 }
815 let [p0, d1, d2, d3] = prepared.map_or_else(|| wall_coefficients(nodes, base), |cache| cache.coefficients(nodes, base));
816 let curve = |s: f64| -> (Vec3, Vec3, Vec3) {
817 let c = p0.add(d1.scale(s)).add(d2.scale(s * (s - 1.0))).add(d3.scale(s * (s - 1.0) * (s - 2.0)));
818 let c1 = d1.add(d2.scale(2.0 * s - 1.0)).add(d3.scale(3.0 * s * s - 6.0 * s + 2.0));
819 let c2 = d2.scale(2.0).add(d3.scale(6.0 * s - 6.0));
820 (c, c1, c2)
821 };
822 let start = j as f64 - base as f64;
823 let initial = prepared.and_then(|cache| cache.start(base, j, &curve));
824 let point_length = p.length();
825 let mut s = start;
826 let mut converged = false;
827 let mut converged_point = None;
828 for iteration in 0..50 {
829 let state = if iteration == 0 { initial.unwrap_or_else(|| WallStart::new(curve(s))) }
830 else { WallStart::new(curve(s)) };
831 let (c, c1, c2) = state.curve;
832 let w = c.sub(p);
833 let (g, slope) = (w.dot(c1), state.tangent_squared + w.dot(c2));
834 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
835 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at s {s}"));
836 return Solve::Unread;
837 }
838 let stationary = g.abs() <= 16.0 * f64::EPSILON * (point_length + state.point_length) * state.tangent_length;
851 if stationary {
852 converged = true;
853 converged_point = Some(c);
854 break;
855 }
856 let step = g / slope;
857 let before = s;
858 s -= step;
859 if !((s - start).abs() <= 1.0) {
860 wall_decline(|| {
861 let (c, c1, _) = curve(s);
864 let g_after = c.sub(p).dot(c1);
865 let stationary_after = g_after.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length();
866 format!(
867 "stencil {n} nodes base {base} j {j}: window exit s {before} -> {s} (start {start}, |s - start| - 1 = {:e}), \
868 g {g:e} -> {g_after:e}, stationary at the overshot s: {stationary_after}",
869 (s - start).abs() - 1.0
870 )
871 });
872 return if s.is_finite() { Solve::Window(s) } else { Solve::Unread };
873 }
874 if step.abs() <= 1e-14 * (1.0 + s.abs()) {
875 converged = true;
876 break;
877 }
878 }
879 if !converged {
880 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: no convergence in 50 steps, s {s}"));
881 return Solve::Unread;
882 }
883 let distance = converged_point.unwrap_or_else(|| curve(s).0).sub(p).length() - radius;
884 if distance.is_finite() {
885 Solve::Read(distance)
886 } else {
887 wall_decline(|| format!("stencil {n} nodes base {base} j {j}: non-finite distance at s {s}"));
888 Solve::Unread
889 }
890}
891
892pub(in crate::blend) fn wall_probe_reading(p: Vec3, nodes: &[Vec3], j: usize, radius: f64) -> Option<(f64, f64)> {
901 let n = nodes.len();
902 if n < 5 || j == 0 || j + 1 >= n {
903 return None;
904 }
905 let j = locate_foot(p, nodes, j, radius)?;
906 let first = (j - 1).min(n - 4);
907 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
908 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
909 let a = sweep_residual_on(p, nodes, first, j, radius)?;
910 let b = sweep_residual_on(p, nodes, second, j, radius)?;
911 Some((a.abs().max(b.abs()), (a - b).abs()))
912}
913
914fn wall_solve_reuse_on() -> bool {
927 switch!(live "BREP_WALL_SOLVE_REUSE", true)
928}
929
930pub(in crate::blend) fn declared_wall_probe(p: Vec3, fine: &[Vec3], jf: usize, radius: f64) -> Option<(f64, f64)> {
931 declared_wall_probe_with(p, fine, jf, radius, wall_solve_reuse_on())
932}
933
934fn declared_wall_probe_with(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool) -> Option<(f64, f64)> {
935 declared_wall_probe_prepared(p, fine, jf, radius, reuse, None)
936}
937
938fn declared_wall_probe_prepared(p: Vec3, fine: &[Vec3], jf: usize, radius: f64, reuse: bool, prepared: Option<&PreparedWall<'_>>) -> Option<(f64, f64)> {
939 if jf % 2 != 0 || fine.len() < 9 || fine.len() % 2 == 0 {
940 wall_decline(|| format!("declared reader: node {jf} of {} not an even node of an odd fine set", fine.len()));
941 return None;
942 }
943 let (reading, spread, at_fine) = if reuse {
944 let read = (|| {
945 let n = fine.len();
946 let (j, a) = locate_foot_read_prepared(p, fine, jf, radius, prepared.map(|c| &c.fine_stencils))?;
947 let first = (j - 1).min(n - 4);
948 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
949 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
950 let b = match stencil_solve_prepared(p, fine, second, j, radius, prepared.map(|c| &c.fine_stencils)) {
951 Solve::Read(distance) => distance,
952 _ => return None,
953 };
954 Some((a.abs().max(b.abs()), (a - b).abs(), a))
955 })();
956 let Some(read) = read else {
957 wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
958 return None;
959 };
960 read
961 } else {
962 let Some((reading, spread)) = wall_probe_reading(p, fine, jf, radius) else {
963 wall_decline(|| format!("FINE two-stencil reading at node {jf} of {}", fine.len()));
964 return None;
965 };
966 let Some(at_fine) = sweep_residual(p, fine, jf, radius) else {
967 wall_decline(|| format!("FINE sweep at node {jf} of {}", fine.len()));
968 return None;
969 };
970 (reading, spread, at_fine)
971 };
972 let coarse_owned;
973 let coarse = match prepared {
974 Some(cache) => cache.coarse.as_slice(),
975 None => { coarse_owned = wall_coarse(fine); &coarse_owned }
976 };
977 let at_coarse = if reuse {
978 locate_foot_read_prepared(p, coarse, jf / 2, radius, prepared.map(|c| &c.coarse_stencils)).map(|(_, distance)| distance)
979 } else {
980 sweep_residual(p, coarse, jf / 2, radius)
981 };
982 let Some(at_coarse) = at_coarse else {
983 wall_decline(|| format!("COARSE sweep at node {} of {}", jf / 2, coarse.len()));
984 return None;
985 };
986 let uncertainty = spread.max((at_fine - at_coarse).abs());
987 uncertainty.is_finite().then_some((reading, uncertainty))
988}
989
990pub(in crate::blend) fn centre_path_node(fine: &[Vec3], fraction: f64) -> Option<usize> {
1006 let n = fine.len();
1007 if n < 7 || !(fraction.is_finite()) {
1008 return None;
1009 }
1010 let mut cumulative = Vec::with_capacity(n);
1011 cumulative.push(0.0_f64);
1012 for pair in fine.windows(2) {
1013 let step = pair[1].sub(pair[0]).length();
1014 cumulative.push(cumulative.last().copied().unwrap_or(0.0) + step);
1015 }
1016 let total = *cumulative.last()?;
1017 if !(total.is_finite() && total > 0.0) {
1018 return None;
1019 }
1020 let target = fraction.clamp(0.0, 1.0) * total;
1021 let nearest = (0..n).min_by(|&a, &b| (cumulative[a] - target).abs().total_cmp(&(cumulative[b] - target).abs()))?;
1022 let even = 2 * ((nearest as f64 / 2.0).round() as usize);
1023 Some(even.clamp(2, (n - 3) & !1))
1024}
1025
1026pub(in crate::blend) fn declared_wall_probe_located_why(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Result<(f64, f64), String> {
1033 let first = match declared_wall_probe_why(p, fine, jf, radius) {
1034 Ok(read) => return Ok(read),
1035 Err(why) => why,
1036 };
1037 match centre_path_node(fine, fraction) {
1038 Some(located) if located != jf => declared_wall_probe_why(p, fine, located, radius)
1039 .map_err(|again| format!("{first} -- and from centre-path node {located}: {again}")),
1040 _ => Err(first),
1041 }
1042}
1043
1044pub(in crate::blend) fn declared_wall_probe_located(p: Vec3, fine: &[Vec3], jf: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
1046 match declared_wall_probe(p, fine, jf, radius) {
1047 Some(read) => Some(read),
1048 None => match centre_path_node(fine, fraction) {
1049 Some(located) if located != jf => declared_wall_probe(p, fine, located, radius),
1050 _ => None,
1051 },
1052 }
1053}
1054
1055pub(in crate::blend) fn declared_wall_probe_at_why(p: Vec3, fine: &[Vec3], ts: &[f64], jf: usize, radius: f64) -> Result<(f64, f64), String> {
1067 if jf % 2 != 0
1068 || fine.len() < 9
1069 || fine.len() % 2 == 0
1070 || ts.len() != fine.len()
1071 || !ts.iter().all(|t| t.is_finite())
1072 || !ts.windows(2).all(|pair| pair[1] > pair[0])
1073 {
1074 return Err(format!("native-abscissa reader: node {jf} of {} with {} finite, strictly increasing abscissae required", fine.len(), ts.len()));
1075 }
1076 let previous = WALL_DECLINES.with(|log| log.replace(Some(Vec::new())));
1077 let read = (|| -> Option<(f64, f64)> {
1078 let (reading, spread) = wall_probe_reading_at(p, fine, ts, jf, radius).or_else(|| {
1079 wall_decline(|| format!("FINE two-stencil reading (native abscissae) at node {jf} of {}", fine.len()));
1080 None
1081 })?;
1082 let at_fine = sweep_residual_at(p, fine, ts, jf, radius).or_else(|| {
1083 wall_decline(|| format!("FINE sweep (native abscissae) at node {jf} of {}", fine.len()));
1084 None
1085 })?;
1086 let coarse: Vec<Vec3> = fine.iter().step_by(2).copied().collect();
1087 let coarse_ts: Vec<f64> = ts.iter().step_by(2).copied().collect();
1088 let at_coarse = sweep_residual_at(p, &coarse, &coarse_ts, jf / 2, radius).or_else(|| {
1089 wall_decline(|| format!("COARSE sweep (native abscissae) at node {} of {}", jf / 2, coarse.len()));
1090 None
1091 })?;
1092 let uncertainty = spread.max((at_fine - at_coarse).abs());
1093 uncertainty.is_finite().then_some((reading, uncertainty))
1094 })();
1095 let lines = WALL_DECLINES.with(|log| log.replace(previous)).unwrap_or_default();
1096 read.ok_or_else(|| if lines.is_empty() { "declined (no inner cause recorded)".to_string() } else { lines.join(" <- ") })
1097}
1098
1099fn wall_probe_reading_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<(f64, f64)> {
1100 let n = nodes.len();
1101 if n < 5 || j == 0 || j + 1 >= n {
1102 return None;
1103 }
1104 let j = locate_foot_at(p, nodes, ts, j, radius)?;
1105 let first = (j - 1).min(n - 4);
1106 let second = if j >= 2 { (j - 2).min(n - 4) } else { j.min(n - 4) };
1107 let second = if second == first { if first >= 1 { first - 1 } else { first + 1 } } else { second };
1108 let a = match stencil_solve_at(p, nodes, ts, first, j, radius) { Solve::Read(distance) => distance, _ => return None };
1109 let b = match stencil_solve_at(p, nodes, ts, second, j, radius) { Solve::Read(distance) => distance, _ => return None };
1110 Some((a.abs().max(b.abs()), (a - b).abs()))
1111}
1112
1113fn sweep_residual_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<f64> {
1114 let j = locate_foot_at(p, nodes, ts, j, radius)?;
1115 match stencil_solve_at(p, nodes, ts, (j - 1).min(nodes.len() - 4), j, radius) {
1116 Solve::Read(distance) => Some(distance),
1117 Solve::Window(_) | Solve::Unread => None,
1118 }
1119}
1120
1121fn locate_foot_at(p: Vec3, nodes: &[Vec3], ts: &[f64], j: usize, radius: f64) -> Option<usize> {
1125 let n = nodes.len();
1126 if n < 4 || j == 0 || j + 1 >= n {
1127 return None;
1128 }
1129 let mut tried: Vec<usize> = Vec::new();
1130 let mut at = j;
1131 loop {
1132 let base = (at - 1).min(n - 4);
1133 match stencil_solve_at(p, nodes, ts, base, at, radius) {
1134 Solve::Read(_) => return Some(at),
1135 Solve::Unread => return None,
1136 Solve::Window(t) => {
1137 tried.push(at);
1138 let nearest = (0..n).min_by(|&a, &b| (ts[a] - t).abs().total_cmp(&(ts[b] - t).abs())).unwrap_or(at);
1139 let next = if t.is_finite() { nearest.clamp(1, n - 2) } else { at };
1140 if tried.contains(&next) || next.abs_diff(j) > FOOT_TRAVEL {
1141 wall_decline(|| format!(
1142 "foot search (native abscissae) from node {j} of {n}: tried {tried:?}, next {next} ({})",
1143 if tried.contains(&next) { "already tried" } else { "beyond FOOT_TRAVEL" }
1144 ));
1145 return None;
1146 }
1147 at = next;
1148 }
1149 }
1150 }
1151}
1152
1153fn stencil_solve_at(p: Vec3, nodes: &[Vec3], ts: &[f64], base: usize, j: usize, radius: f64) -> Solve {
1158 let finite = |v: Vec3| v.x.is_finite() && v.y.is_finite() && v.z.is_finite();
1159 let n = nodes.len();
1160 if n < 4 || j == 0 || j + 1 >= n || base + 4 > n || ts.len() != n || !radius.is_finite() || !finite(p) || !nodes.iter().all(|&c| finite(c)) {
1161 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: unreadable input"));
1162 return Solve::Unread;
1163 }
1164 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
1165 let [t0, t1, t2, t3] = [ts[base], ts[base + 1], ts[base + 2], ts[base + 3]];
1166 let d1 = p1.sub(p0).scale(1.0 / (t1 - t0));
1167 let d12 = p2.sub(p1).scale(1.0 / (t2 - t1));
1168 let d23 = p3.sub(p2).scale(1.0 / (t3 - t2));
1169 let d2 = d12.sub(d1).scale(1.0 / (t2 - t0));
1170 let d123 = d23.sub(d12).scale(1.0 / (t3 - t1));
1171 let d3 = d123.sub(d2).scale(1.0 / (t3 - t0));
1172 let curve = |t: f64| -> (Vec3, Vec3, Vec3) {
1173 let (a, b, c) = (t - t0, t - t1, t - t2);
1174 let point = p0.add(d1.scale(a)).add(d2.scale(a * b)).add(d3.scale(a * b * c));
1175 let first = d1.add(d2.scale(a + b)).add(d3.scale(b * c + a * c + a * b));
1176 let second = d2.scale(2.0).add(d3.scale(2.0 * (a + b + c)));
1177 (point, first, second)
1178 };
1179 let (low, high) = (ts[j - 1], ts[j + 1]);
1180 let start = ts[j];
1181 let mut t = start;
1182 let mut converged = false;
1183 for _ in 0..50 {
1184 let (c, c1, c2) = curve(t);
1185 let w = c.sub(p);
1186 let (g, slope) = (w.dot(c1), c1.dot(c1) + w.dot(c2));
1187 if !(g.is_finite() && slope.is_finite()) || slope == 0.0 {
1188 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: slope {slope:e} g {g:e} at t {t}"));
1189 return Solve::Unread;
1190 }
1191 if g.abs() <= 16.0 * f64::EPSILON * (p.length() + c.length()) * c1.length() {
1192 converged = true;
1193 break;
1194 }
1195 let step = g / slope;
1196 let before = t;
1197 t -= step;
1198 if !(t >= low && t <= high) {
1199 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: window exit t {before} -> {t} (window [{low}, {high}])"));
1200 return if t.is_finite() { Solve::Window(t) } else { Solve::Unread };
1201 }
1202 let node = 0.5 * (high - low);
1207 if (step / node).abs() <= 1e-14 * (1.0 + ((t - t0) / node).abs()) {
1208 converged = true;
1209 break;
1210 }
1211 }
1212 if !converged {
1213 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: no convergence in 50 steps, t {t}"));
1214 return Solve::Unread;
1215 }
1216 let distance = curve(t).0.sub(p).length() - radius;
1217 if distance.is_finite() {
1218 Solve::Read(distance)
1219 } else {
1220 wall_decline(|| format!("native stencil {n} nodes base {base} j {j}: non-finite distance at t {t}"));
1221 Solve::Unread
1222 }
1223}
1224
1225pub(in crate::blend) fn wall_model_missing(readings: &[(usize, f64, f64, f64)], model: f64) -> Vec<usize> {
1230 readings.iter().filter(|&&(_, declared, _, _)| !(declared <= model)).map(|&(left, _, _, _)| left).collect()
1231}
1232
1233#[allow(clippy::too_many_arguments)]
1243pub(super) fn wall_interior_misses(
1244 contacts: &crate::blend::chain::DenseContacts,
1245 samples: &[ChainSample],
1246 surface: &crate::NurbsSurface,
1247 low: f64,
1248 range: f64,
1249 radius: f64,
1250 subdivisions: usize,
1251 probes: usize,
1252 wrap: bool,
1253) -> (Vec<(usize, f64, f64, f64)>, Vec<usize>) {
1254 use std::collections::BTreeMap;
1255 let mut nodes: BTreeMap<usize, (usize, Vec<Option<Vec3>>)> = BTreeMap::new();
1258 for (index, (left, next, fraction, _, _)) in contacts.solved.iter().enumerate() {
1259 let entry = nodes.entry(*left).or_insert_with(|| {
1260 let mut row = vec![None; subdivisions + 1];
1261 row[0] = Some(samples[*left].station.center);
1262 row[subdivisions] = Some(samples[*next].station.center);
1263 (*next, row)
1264 });
1265 let step = (fraction * subdivisions as f64).round() as usize;
1266 if (1..subdivisions).contains(&step) {
1267 entry.1[step] = contacts.centers.get(index).copied().flatten();
1268 }
1269 }
1270 let mut readable = Vec::new();
1271 let mut unreadable: Vec<usize> = contacts.unsolved_at.clone();
1272 for (&left, (next, row)) in &nodes {
1273 let Some(centres) = row.iter().copied().collect::<Option<Vec<Vec3>>>() else {
1274 unreadable.push(left);
1275 continue;
1276 };
1277 let (from, to) = (samples[left].parameter, samples[*next].parameter);
1278 let (mut declared, mut worst, mut spread) = (0.0_f64, 0.0_f64, 0.0_f64);
1279 let mut read = true;
1280 let prepared = PreparedWall::for_interval(¢res);
1281 'probes: for step in (2..subdivisions).step_by(2) {
1282 let global = from + (step as f64 / subdivisions as f64) * (to - from);
1283 let global = if wrap { global.rem_euclid(1.0) } else { global };
1284 let u = (global - low) / range;
1285 for k in 1..probes {
1286 let v = k as f64 / probes as f64;
1287 let reading = surface.evaluate(u, v).ok().and_then(|p| {
1288 match &prepared {
1289 Some(cache) => cache.read(p, step, step as f64 / subdivisions as f64, radius),
1290 None => declared_wall_probe_located(p, ¢res, step, step as f64 / subdivisions as f64, radius),
1291 }
1292 });
1293 match reading {
1294 Some((distance, gap)) => {
1295 declared = declared.max(distance + gap);
1296 worst = worst.max(distance);
1297 spread = spread.max(gap);
1298 }
1299 None => {
1300 read = false;
1301 break 'probes;
1302 }
1303 }
1304 }
1305 }
1306 if read {
1307 readable.push((left, declared, worst, spread));
1308 } else {
1309 unreadable.push(left);
1310 }
1311 }
1312 unreadable.sort_unstable();
1313 unreadable.dedup();
1314 (readable, unreadable)
1315}
1316
1317
1318fn build_closed_smooth_chain(
1319 solid: &BrepSolid,
1320 segments: &[ChainSegment<'_>],
1321 radius: f64,
1322 chamfer: bool,
1323 name: Option<&str>,
1324 budget: &ChainBudget,
1325 fold: FoldPolicy,
1326 bar: f64,
1327) -> Result<Rung, KernelRefusal> {
1328 let samples = match march_chain_typed(segments, radius, false, budget, fold) {
1329 Ok(samples) => samples,
1330 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1331 Err(ChainMarchError::Incoherent(failure)) => return Err(failure.error),
1334 Err(ChainMarchError::Other(error)) => return Err(error),
1335 };
1336 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(0));
1337 build_closed_chain_from_samples(solid, segments, radius, chamfer, name, budget, fold, bar, samples, 0)
1338}
1339
1340
1341thread_local! {
1342 static CHAIN_DEEPEST_ROUND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1346}
1347
1348fn local_continue_on() -> bool {
1354 switch!(live "BREP_CHAIN_LOCAL_CONTINUE", false)
1355}
1356
1357const LOCAL_CONTINUE_MAX_ROUNDS: usize = 4 * REFINE_ROUNDS;
1359
1360const LOCAL_CONTINUE_STALL_ROUNDS: usize = 3;
1362
1363thread_local! {
1364 static CHAIN_LOCAL_BEST: std::cell::Cell<(f64, usize)> = const { std::cell::Cell::new((f64::INFINITY, 0)) };
1366}
1367
1368fn local_rounds_spent(round: usize, deviation: f64) -> bool {
1374 if round == 0 {
1375 CHAIN_LOCAL_BEST.with(|best| best.set((f64::INFINITY, 0)));
1376 return false;
1377 }
1378 let (_, best_round) = CHAIN_LOCAL_BEST.with(|best| {
1379 let (reading, at) = best.get();
1380 if deviation < reading {
1381 best.set((deviation, round));
1382 (deviation, round)
1383 } else {
1384 (reading, at)
1385 }
1386 });
1387 round >= LOCAL_CONTINUE_MAX_ROUNDS || round - best_round >= LOCAL_CONTINUE_STALL_ROUNDS
1388}
1389#[allow(clippy::too_many_arguments)]
1400fn build_closed_chain_from_samples(
1401 solid: &BrepSolid,
1402 segments: &[ChainSegment<'_>],
1403 radius: f64,
1404 chamfer: bool,
1405 name: Option<&str>,
1406 budget: &ChainBudget,
1407 fold: FoldPolicy,
1408 bar: f64,
1409 mut samples: Vec<ChainSample>,
1410 round: usize,
1411) -> Result<Rung, KernelRefusal> {
1412 let per_segment = budget.rung;
1415 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round)));
1416
1417 let mut global: Vec<(f64, &ChainSample)> = samples
1419 .iter()
1420 .filter(|sample| (0..budget.count(sample.segment) as isize).contains(&sample.position))
1421 .map(|sample| (sample.parameter.rem_euclid(1.0), sample))
1422 .collect();
1423 global.sort_by(|a, b| a.0.total_cmp(&b.0));
1424 let count = global.len();
1425 let degree = FIT_DEGREE;
1426 let mut extended_params = Vec::new();
1427 let mut samples_cr = Vec::new();
1428 let mut samples_mid = Vec::new();
1429 let mut samples_cs = Vec::new();
1430 let mut push = |station: &Station, parameter: f64| {
1431 extended_params.push(parameter);
1432 samples_cr.push(Vec4::from_point(station.p1, 1.0));
1433 samples_cs.push(Vec4::from_point(station.p2, 1.0));
1434 samples_mid.push(Vec4 {
1435 x: station.apex.x * station.weight,
1436 y: station.apex.y * station.weight,
1437 z: station.apex.z * station.weight,
1438 w: station.weight,
1439 });
1440 };
1441 for offset in (1..=degree).rev() {
1442 let (parameter, sample) = &global[count - offset];
1443 push(&sample.station, parameter - 1.0);
1444 }
1445 for (parameter, sample) in &global {
1446 push(&sample.station, *parameter);
1447 }
1448 push(&global[0].1.station, global[0].0 + 1.0);
1451 for offset in 1..=degree {
1452 let (parameter, sample) = &global[offset];
1453 push(&sample.station, parameter + 1.0);
1454 }
1455 let low = extended_params[0];
1456 let high = *extended_params.last().unwrap();
1457 let range = high - low;
1458 let normalized: Vec<f64> = extended_params
1459 .iter()
1460 .map(|parameter| (parameter - low) / range)
1461 .collect();
1462 let seam_low = (0.0 - low) / range;
1463 let seam_high = (1.0 - low) / range;
1464 let fit_row = |row: &[Vec4]| -> Result<NurbsCurve, KernelRefusal> {
1465 let curve = fit::interpolate_homogeneous(row, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1466 let (_, tail) = curve.split(seam_low).or_refuse(KernelStage::Refine, "split")?;
1467 let (middle, _) = tail.split(seam_high).or_refuse(KernelStage::Refine, "split")?;
1468 Ok(middle)
1469 };
1470 let cr = fit_row(&samples_cr)?;
1471 let cs = fit_row(&samples_cs)?;
1472 let mid = if chamfer {
1473 None
1474 } else {
1475 Some(fit_row(&samples_mid)?)
1476 };
1477 let u_domain = cr.domain().or_refuse(KernelStage::Refine, "domain")?;
1478 let surface = crate::blend::rows::surface_from_rows(degree, &cr, &cs, mid.as_ref(), true)?;
1479
1480 let (halfway, halfway_failing) = rail_deviation(&samples, &cr, &cs, low, range, budget, bar)?;
1493 let stencil = if round > 0 {
1505 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, LOCAL_RAIL_STENCIL)?)
1506 } else {
1507 None
1508 };
1509 let wall_stencil = if !chamfer && wall_verdict_on() {
1514 Some(crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, 2 * LOCAL_RAIL_STENCIL)?)
1515 } else {
1516 None
1517 };
1518 let (mut deviation, mut failing, _stencil_reads) = if round > 0 {
1519 let contacts = stencil.as_ref().expect("the local path solves the stencil");
1520 let (dense, unreadable) = dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?;
1521 let reads = dense.len() + unreadable.len() + contacts.unsolved;
1522 let failed_to_read: Vec<usize> = contacts.unsolved_at.iter().chain(&unreadable).copied().collect();
1523 let verdict = combine_rail_verdict((halfway, halfway_failing), &dense, &failed_to_read, bar);
1524 crate::blend::carve::carve_trace(format_args!(
1525 "blend chain local rails: rung {per_segment} round {round}: stencil verdict {:.9e} (halfway {halfway:.9e}), \
1526 {} failing interval(s), {} unsolved contact(s)",
1527 verdict.0, verdict.1.len(), contacts.unsolved
1528 ));
1529 (verdict.0, verdict.1, reads)
1530 } else {
1531 (halfway, halfway_failing, 0)
1532 };
1533 let mut _wall_worst = 0.0_f64;
1539 let mut _wall_spread = 0.0_f64;
1540 let mut wall_readings: Vec<(usize, f64, f64, f64)> = Vec::new();
1541 if let Some(contacts) = wall_stencil.as_ref() {
1542 let (wall, unreadable) =
1543 wall_interior_misses(contacts, &samples, &surface, low, range, radius, 2 * LOCAL_RAIL_STENCIL, WALL_SECTION_PROBES, true);
1544 wall_readings = wall.clone();
1545 for &(left, declared, _, uncertainty) in &wall {
1547 if declared > bar {
1548 failing.push(left);
1549 }
1550 _wall_worst = _wall_worst.max(declared);
1551 _wall_spread = _wall_spread.max(uncertainty);
1552 }
1553 failing.extend_from_slice(&unreadable);
1554 failing.sort_unstable();
1555 failing.dedup();
1556 deviation = deviation.max(_wall_worst);
1557 crate::blend::carve::carve_trace(format_args!(
1558 "blend chain wall: rung {per_segment} round {round}: wall interior worst {_wall_worst:.9e} over {} \
1559 interval(s), {} unreadable, bar {bar:.3e}",
1560 wall.len(),
1561 unreadable.len()
1562 ));
1563 }
1564 if deviation > bar || !failing.is_empty() {
1565 let in_segment = |segment: usize| {
1566 samples
1567 .iter()
1568 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1569 .count()
1570 };
1571 let within_ceiling = (0..segments.len()).all(|segment| {
1572 in_segment(segment) + failing.iter().filter(|&&index| samples[index].segment == segment).count()
1573 <= CHAIN_CARVE_MAX_PER_SEGMENT
1574 });
1575 crate::blend::carve::carve_trace(format_args!(
1576 "blend chain local rails: rung {per_segment} round {round} stations {} failing {} \
1577 worst {deviation:.9e} bar {bar:.9e} ceiling {}",
1578 samples.len(),
1579 failing.len(),
1580 if within_ceiling { "ok" } else { "reached" }
1581 ));
1582 let rounds_spent = if local_continue_on() {
1584 local_rounds_spent(round, deviation)
1585 } else {
1586 round >= REFINE_ROUNDS
1587 };
1588 if fold != FoldPolicy::Refuse || rounds_spent || !within_ceiling {
1590 return Ok(Rung::TooCoarse { deviation });
1591 }
1592 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1594 match insert_chain_stations(segments, radius, budget, &mut samples, &failing) {
1595 Ok(()) => {}
1596 Err(ChainMarchError::Station(failure)) => return Ok(Rung::StationFailed(failure)),
1597 Err(ChainMarchError::Incoherent(failure)) => {
1601 crate::blend::carve::carve_trace(format_args!(
1602 "blend chain local rails: rung {per_segment} round {round}: segment {} station \
1603 at t {:.9} does not reach its retained right neighbour: {}",
1604 failure.segment, failure.t, failure.error
1605 ));
1606 return Ok(Rung::TooCoarse { deviation });
1607 }
1608 Err(ChainMarchError::Other(error)) => return Err(error),
1609 }
1610 assign_chain_parameters(&mut samples, segments.len(), budget, false);
1611 return build_closed_chain_from_samples(
1612 solid, segments, radius, chamfer, name, budget, fold, bar, samples, round + 1,
1613 );
1614 }
1615 crate::blend::carve::carve_trace(format_args!(
1616 "blend chain: {per_segment} stations per segment leaves the rails {deviation:.6e} \
1617 from the rolling ball, inside {bar:.3e}"
1618 ));
1619 let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
1633 let stations_now = (0..segments.len())
1634 .map(|segment| {
1635 samples
1636 .iter()
1637 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1638 .count()
1639 })
1640 .max()
1641 .unwrap_or(0);
1642 let mut unmet: Option<(f64, crate::BudgetReason)> = None;
1643 let mut request_detail: Option<String> = None;
1647 let mut request_component = crate::MeasuredComponent::Wall;
1648 let mut request_unread = 0usize;
1649 if !chamfer && fold == FoldPolicy::Refuse && model_request_on() {
1650 let wall_missing = wall_model_missing(&wall_readings, model);
1651 let (rail_dense, rail_unread) = match wall_stencil.as_ref() {
1659 Some(contacts) => dense_rail_misses(contacts, &samples, &cr, &cs, low, range, true)?,
1660 None => (Vec::new(), Vec::new()),
1661 };
1662 let rail_over: std::collections::BTreeSet<usize> =
1664 rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(left, _)| left).collect();
1665 let rail_unread_intervals: std::collections::BTreeSet<usize> = rail_unread.iter().copied().collect();
1666 let rail_missing: Vec<usize> = rail_over.union(&rail_unread_intervals).copied().collect();
1667 let mut missing: Vec<usize> = wall_missing.iter().chain(&rail_missing).copied().collect();
1668 missing.sort_unstable();
1669 missing.dedup();
1670 if !missing.is_empty() {
1671 let wall_short = wall_readings
1673 .iter()
1674 .filter(|reading| wall_missing.contains(&reading.0))
1675 .map(|&(_, declared, _, _)| declared)
1676 .fold(0.0_f64, f64::max);
1677 let rail_short = rail_dense.iter().filter(|&&(_, miss)| !(miss <= model)).map(|&(_, miss)| miss).fold(0.0_f64, f64::max);
1678 let short = wall_short.max(rail_short);
1679 request_component = if rail_short > wall_short { crate::MeasuredComponent::Rails } else { crate::MeasuredComponent::Wall };
1680 request_unread = rail_unread_intervals.len();
1681 request_detail = Some(format!(
1682 "short of {model:.3e}: rails {rail_short:.3e} off the exact contacts over {} interval(s) ({} unread), \
1683 wall {wall_short:.3e} over {} interval(s)",
1684 rail_over.len(),
1685 rail_unread_intervals.len(),
1686 wall_missing.len()
1687 ));
1688 let within_ceiling = (0..segments.len()).all(|segment| {
1689 let present = samples
1690 .iter()
1691 .filter(|sample| sample.segment == segment && (0..budget.count(segment) as isize).contains(&sample.position))
1692 .count();
1693 present + missing.iter().filter(|&&index| samples[index].segment == segment).count()
1694 <= CHAIN_CARVE_MAX_PER_SEGMENT
1695 });
1696 crate::blend::carve::carve_trace(format_args!(
1697 "blend chain wall model: rung {per_segment} round {round}: {} interval(s) short of {model:.3e} \
1698 (worst reading + spread {short:.3e}), ceiling {}",
1699 missing.len(),
1700 if within_ceiling { "ok" } else { "reached" }
1701 ));
1702 unmet = if round >= model_rounds_limit() {
1703 Some((short, crate::BudgetReason::RoundsSpent))
1704 } else if !within_ceiling {
1705 Some((short, crate::BudgetReason::StationCeiling))
1706 } else {
1707 let mut refined = samples.clone();
1708 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1710 match insert_chain_stations(segments, radius, budget, &mut refined, &missing) {
1711 Ok(()) => {
1712 assign_chain_parameters(&mut refined, segments.len(), budget, false);
1713 match build_closed_chain_from_samples(
1714 solid, segments, radius, chamfer, name, budget, fold, bar, refined, round + 1,
1715 ) {
1716 Ok(Rung::Built(built)) => return Ok(Rung::Built(built)),
1717 _ => Some((short, crate::BudgetReason::Rejected)),
1718 }
1719 }
1720 Err(_) => {
1721 CHAIN_DEEPEST_ROUND.with(|deepest| deepest.set(deepest.get().max(round + 1)));
1723 Some((short, crate::BudgetReason::Incoherent))
1724 }
1725 }
1726 };
1727 }
1728 }
1729 if let Some(subdivisions) = std::env::var("BREP_DEBUG_CHAIN_DENSE_RAILS").ok().and_then(|value| value.parse::<usize>().ok()) {
1734 let contacts = crate::blend::chain::chain_dense_contacts(segments, radius, budget, &samples, subdivisions.max(2))?;
1735 let mut worst = (0.0_f64, 0usize, 0isize, 0.0_f64);
1736 let mut unreadable = 0usize;
1737 for (left, next, fraction, p1, p2) in &contacts.solved {
1738 let (from, to) = (samples[*left].parameter, samples[*next].parameter);
1739 let global = (from + fraction * (to - from)).rem_euclid(1.0);
1740 let seed = (global - low) / range;
1741 let reach = (to - from).abs() / range;
1742 match rail_pair_miss(closest_on_rail(&cr, *p1, seed, reach).unwrap_or(f64::NAN), closest_on_rail(&cs, *p2, seed, reach).unwrap_or(f64::NAN)) {
1743 Some(miss) if miss > worst.0 => worst = (miss, samples[*left].segment, samples[*left].position, *fraction),
1744 Some(_) => {}
1745 None => unreadable += 1,
1746 }
1747 }
1748 eprintln!(
1749 "blend chain dense rails: rung {per_segment} round {round}: {} contacts at {subdivisions} per interval, \
1750 worst {:.9e} (halfway reading {halfway:.9e}, bar {bar:.3e}) at segment {} position {} fraction {:.4}; {} unsolved, {unreadable} unreadable",
1751 contacts.solved.len(), worst.0, worst.1, worst.2, worst.3, contacts.unsolved
1752 );
1753 }
1754 let crease = if fold == FoldPolicy::Carve {
1755 let bar = crate::KernelTolerances::for_solid(solid, 1e-7).pcurve_consistency;
1765 let Some(carved) = crate::blend::carve::trace_wall_crease(&surface, radius.abs())? else {
1766 return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", format!(
1767 "blend carve: the wall re-marched at {per_segment} stations per segment carries no fold to carve, but the march at {CHAIN_PER_SEGMENT} refused one"
1768 )));
1769 };
1770 Some(crate::blend::carve::fit_crease(&surface, &carved, bar)?)
1771 } else {
1772 None
1773 };
1774
1775 let single_face = |side: usize| -> bool {
1779 let first_id = segments[0].mate(side).face.id;
1780 segments
1781 .iter()
1782 .all(|segment| segment.mate(side).face.id == first_id)
1783 };
1784 let mut whole_pcurves: [Option<NurbsCurve>; 2] = [None, None];
1785 for side in 0..2 {
1786 if !single_face(side) {
1787 continue;
1788 }
1789 let mut row = Vec::new();
1790 let select = |station: &Station| -> [f64; 2] {
1791 if side == 0 {
1792 station.uv1
1793 } else {
1794 station.uv2
1795 }
1796 };
1797 let mut push_uv = |station: &Station| {
1798 let uv = select(station);
1799 row.push(Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0));
1800 };
1801 for offset in (1..=degree).rev() {
1802 push_uv(&global[count - offset].1.station);
1803 }
1804 for (_, sample) in &global {
1805 push_uv(&sample.station);
1806 }
1807 push_uv(&global[0].1.station);
1808 for offset in 1..=degree {
1809 push_uv(&global[offset].1.station);
1810 }
1811 whole_pcurves[side] = Some(fit_row(&row)?);
1812 }
1813
1814 let mut pcurves1 = Vec::with_capacity(segments.len());
1817 let mut pcurves2 = Vec::with_capacity(segments.len());
1818 for segment in 0..segments.len() {
1819 let mut window: Vec<&ChainSample> = samples
1820 .iter()
1821 .filter(|sample| sample.segment == segment)
1822 .collect();
1823 window.sort_by(|a, b| a.parameter.total_cmp(&b.parameter));
1824 let params: Vec<f64> = window.iter().map(|sample| sample.parameter).collect();
1825 let low = params[0];
1826 let high = *params.last().unwrap();
1827 let normalized: Vec<f64> = params
1828 .iter()
1829 .map(|parameter| (parameter - low) / (high - low))
1830 .collect();
1831 let fit_uv = |select: &dyn Fn(&Station) -> [f64; 2]| -> Result<NurbsCurve, KernelRefusal> {
1832 let points: Vec<Vec4> = window
1833 .iter()
1834 .map(|sample| {
1835 let uv = select(&sample.station);
1836 Vec4::from_point(Vec3::new(uv[0], uv[1], 0.0), 1.0)
1837 })
1838 .collect();
1839 let curve = fit::interpolate_homogeneous(&points, degree, &normalized).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?;
1840 Ok(curve)
1844 };
1845 pcurves1.push((low, high, fit_uv(&|station| station.uv1)?));
1846 pcurves2.push((low, high, fit_uv(&|station| station.uv2)?));
1847 }
1848
1849 let wall_surface = unmet.as_ref().map(|_| surface.clone());
1850 let built = chain_surgery(
1851 solid,
1852 segments,
1853 ChainRows {
1854 surface,
1855 cr,
1856 cs,
1857 u_domain,
1858 fit_low: low,
1859 fit_range: range,
1860 pcurves1,
1861 pcurves2,
1862 whole_pcurves,
1863 crease,
1864 },
1865 name,
1866 )?;
1867 if let (Some((residual, reason)), Some(surface)) = (unmet, wall_surface) {
1868 crate::blend::record_wall_model_report(crate::blend::WallModelReport {
1869 name: name.map(str::to_string),
1870 surface,
1871 request: model,
1872 residual,
1873 detail: request_detail,
1874 budget: crate::ApproximationBudget {
1875 reason,
1876 rounds_used: CHAIN_DEEPEST_ROUND.with(|deepest| deepest.get()).max(round),
1879 rounds_limit: model_rounds_limit(),
1880 stations: stations_now,
1881 station_limit: CHAIN_CARVE_MAX_PER_SEGMENT,
1882 mechanism: crate::BudgetMechanism::LocalRounds,
1883 measured_component: request_component,
1884 unread: request_unread,
1885 },
1886 });
1887 }
1888 Ok(Rung::Built(built))
1889}
1890
1891pub(super) struct ChainRows {
1892 pub(super) surface: NurbsSurface,
1893 pub(super) cr: NurbsCurve,
1894 pub(super) cs: NurbsCurve,
1895 pub(super) u_domain: [f64; 2],
1896 pub(super) fit_low: f64,
1900 pub(super) fit_range: f64,
1901 pub(super) pcurves1: Vec<(f64, f64, NurbsCurve)>,
1904 pub(super) pcurves2: Vec<(f64, f64, NurbsCurve)>,
1905 pub(super) whole_pcurves: [Option<NurbsCurve>; 2],
1907 pub(super) crease: Option<crate::blend::carve::CarvedCrease>,
1910}
1911
1912impl ChainRows {
1913 pub(super) fn to_global(&self, fit_parameter: f64) -> f64 {
1914 self.fit_low + fit_parameter * self.fit_range
1915 }
1916}
1917
1918pub(super) fn pcurve_portion(fitted: &(f64, f64, NurbsCurve), a: f64, b: f64) -> Result<NurbsCurve, KernelRefusal> {
1922 let (low, high, curve) = fitted;
1923 let to_local = |value: f64| {
1926 let mut best = value;
1927 for candidate in [value, value + 1.0, value - 1.0] {
1928 if candidate >= low - 1e-9 && candidate <= high + 1e-9 {
1929 best = candidate;
1930 break;
1931 }
1932 }
1933 ((best - low) / (high - low)).clamp(0.0, 1.0)
1934 };
1935 let mut local_a = to_local(a);
1936 let mut local_b = to_local(b);
1937 if local_a > local_b {
1938 std::mem::swap(&mut local_a, &mut local_b);
1939 }
1940 let epsilon = 1e-9;
1941 let (_, tail) = if local_a > epsilon {
1942 curve.split(local_a).or_refuse(KernelStage::Refine, "split")?
1943 } else {
1944 (curve.clone(), curve.clone())
1945 };
1946 let tail = if local_a > epsilon {
1947 tail
1948 } else {
1949 curve.clone()
1950 };
1951 let portion = if local_b < 1.0 - epsilon {
1952 tail.split(local_b).or_refuse(KernelStage::Refine, "split")?.0
1953 } else {
1954 tail
1955 };
1956 Ok(portion)
1957}
1958
1959pub(super) fn cross_edge_at(
1965 solid: &BrepSolid,
1966 face_before: &FaceRecord,
1967 loop_before: usize,
1968 face_after: &FaceRecord,
1969 loop_after: usize,
1970 vertex: u64,
1971 before_edge: u64,
1972 after_edge: u64,
1973) -> Result<Option<u64>, KernelRefusal> {
1974 let mut found: Option<u64> = None;
1975 let mut consider = |face: &FaceRecord, loop_index: usize| -> Result<(), KernelRefusal> {
1976 for coedge in &face.loops[loop_index].coedges {
1977 if coedge.edge_id == before_edge || coedge.edge_id == after_edge {
1978 continue;
1979 }
1980 let edge = solid
1981 .edges
1982 .iter()
1983 .find(|edge| edge.id == coedge.edge_id)
1984 .ok_or(KernelRefusal::internal(KernelStage::Refine, "missing_edge", "blend: loop references missing edge"))?;
1985 if edge.start_vertex_id == vertex || edge.end_vertex_id == vertex {
1986 if found.is_some() && found != Some(edge.id) {
1987 return Err(KernelRefusal::unsupported(KernelStage::Classify, "chain_cross_edges", "blend: multiple cross edges at a chain vertex"));
1988 }
1989 found = Some(edge.id);
1990 }
1991 }
1992 Ok(())
1993 };
1994 consider(face_before, loop_before)?;
1995 if !(face_after.id == face_before.id && loop_after == loop_before) {
1996 consider(face_after, loop_after)?;
1997 }
1998 Ok(found)
1999}
2000
2001fn nearest_seam_image(value: f64, low: f64, high: f64) -> f64 {
2004 let period = high - low;
2005 low + ((value - low) / period).round() * period
2006}
2007
2008pub(in crate::blend) fn project_piece_pcurve(
2026 piece: &NurbsCurve,
2027 surface: &NurbsSurface,
2028 start_is_crossing: bool,
2029 end_is_crossing: bool,
2030) -> Result<NurbsCurve, KernelRefusal> {
2031 project_piece_pcurve_from(piece, surface, start_is_crossing, end_is_crossing, None)
2032}
2033
2034
2035pub(in crate::blend) fn pcurve_guide<'a>(old: &'a NurbsCurve, surface: &NurbsSurface) -> Result<impl Fn(f64) -> Option<[f64; 2]> + 'a, KernelRefusal> {
2040 let [o0, o1] = old.domain().or_refuse(KernelStage::Refine, "domain")?;
2041 let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2042 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2043 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2044 let into = move |value: f64, closed: bool, low: f64, high: f64| {
2045 if closed && high > low {
2046 low + (value - low).rem_euclid(high - low)
2047 } else {
2048 value.clamp(low, high)
2049 }
2050 };
2051 Ok(move |fraction: f64| {
2052 let uv = old.evaluate(o0 + (o1 - o0) * fraction).ok()?;
2053 let seed = [into(uv.x, closed_u, u0, u1), into(uv.y, closed_v, v0, v1)];
2054 seed.iter().all(|value| value.is_finite()).then_some(seed)
2055 })
2056}
2057
2058pub(in crate::blend) fn project_piece_pcurve_from(
2068 piece: &NurbsCurve,
2069 surface: &NurbsSurface,
2070 start_is_crossing: bool,
2071 end_is_crossing: bool,
2072 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2073) -> Result<NurbsCurve, KernelRefusal> {
2074 project_piece_pcurve_within(piece, surface, start_is_crossing, end_is_crossing, guide, &[])
2075}
2076
2077pub(crate) const CHAIN_PCURVE_FLOOR_WHAT: &str = "chain_pcurve_floor";
2083
2084pub(in crate::blend) fn project_piece_pcurve_within(
2085 piece: &NurbsCurve,
2086 surface: &NurbsSurface,
2087 start_is_crossing: bool,
2088 end_is_crossing: bool,
2089 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2090 refine_near: &[f64],
2091) -> Result<NurbsCurve, KernelRefusal> {
2092 project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, false)
2093}
2094
2095pub(in crate::blend) fn project_piece_pcurve_within_knot_retry(
2106 piece: &NurbsCurve,
2107 surface: &NurbsSurface,
2108 start_is_crossing: bool,
2109 end_is_crossing: bool,
2110 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2111 refine_near: &[f64],
2112) -> Result<NurbsCurve, KernelRefusal> {
2113 match project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, false) {
2114 Err(uniform) if matches!(&uniform.class, crate::RefusalClass::NonConvergence { what } if what == CHAIN_PCURVE_FLOOR_WHAT) => {
2115 project_piece_pcurve_track(piece, surface, start_is_crossing, end_is_crossing, guide, refine_near, true).map_err(|_| uniform)
2116 }
2117 other => other,
2118 }
2119}
2120
2121#[allow(clippy::too_many_arguments)]
2125fn project_piece_pcurve_track(
2126 piece: &NurbsCurve,
2127 surface: &NurbsSurface,
2128 start_is_crossing: bool,
2129 end_is_crossing: bool,
2130 guide: Option<&dyn Fn(f64) -> Option<[f64; 2]>>,
2131 refine_near: &[f64],
2132 knot_aware: bool,
2133) -> Result<NurbsCurve, KernelRefusal> {
2134 let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
2135 let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
2136 let (_, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
2137 let period = u1 - u0;
2138 let period_v = v1 - v0;
2139 let [d0, d1] = piece.domain().or_refuse(KernelStage::Refine, "domain")?;
2140 let ceiling = if knot_aware { 2 * PIECE_TRACK_CEILING } else { PIECE_TRACK_CEILING };
2150 let uniform = (8 * piece.control_points.len()).clamp(96, PIECE_TRACK_CEILING);
2151 let mut fractions: Vec<f64> = (0..=uniform).map(|section| section as f64 / uniform as f64).collect();
2152 if knot_aware {
2153 let span = d1 - d0;
2156 let mut knots: Vec<f64> = piece.knots.iter().copied().filter(|knot| *knot > d0 && *knot < d1).map(|knot| (knot - d0) / span).collect();
2157 knots.dedup();
2158 fractions.extend(knots);
2159 fractions.sort_by(|a, b| a.total_cmp(b));
2160 fractions.dedup_by(|b, a| (*b - *a).abs() <= 1e-6 / uniform as f64);
2161 }
2162 let dense = fractions.len() - 1;
2163 crate::blend::record_count("count.track.piece_samples", dense as u64 + 1);
2164 let mut proj_u = Vec::with_capacity(dense + 1);
2165 let mut proj_v = Vec::with_capacity(dense + 1);
2166 let mut point3 = Vec::with_capacity(dense + 1);
2167 let mut params = Vec::with_capacity(dense + 1);
2168 let mut previous_u: Option<f64> = None;
2169 let mut previous_foot: Option<[f64; 2]> = None;
2174 let mut feet: Vec<[f64; 2]> = Vec::with_capacity(dense + 1);
2175 let project_timer = crate::blend::BlendTimer::start("timing.track.project_ms");
2176 for section in 0..=dense {
2177 let fraction = fractions[section];
2178 let t = if knot_aware { d0 + (d1 - d0) * fraction } else { d0 + (d1 - d0) * section as f64 / dense as f64 };
2182 let point = piece.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
2183 let guide = guide.filter(|_| {
2184 true
2185 });
2186 let seeds: Vec<[f64; 2]> = guide.and_then(|guide| guide(fraction)).into_iter().chain(previous_foot).collect();
2191 let mut projection: Option<crate::projection::SurfaceProjection> = None;
2192 for seed in &seeds {
2193 let found = crate::projection::project_point_to_surface_from_seed(surface, point, *seed).or_refuse(KernelStage::Refine, "project_point_to_surface_from_seed")?;
2194 if projection.as_ref().map_or(true, |known| found.distance < known.distance) {
2195 projection = Some(found);
2196 }
2197 }
2198 let projection = match projection {
2199 Some(projection) => projection,
2200 None => crate::project_point_to_surface(surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?,
2201 };
2202 previous_foot = Some([projection.u, projection.v]);
2203 feet.push([projection.u, projection.v]);
2204 let mut u = projection.u;
2205 if let Some(previous) = previous_u {
2206 while u - previous > period * 0.5 {
2207 u -= period;
2208 }
2209 while previous - u > period * 0.5 {
2210 u += period;
2211 }
2212 }
2213 previous_u = Some(u);
2214 proj_u.push(u);
2215 proj_v.push(projection.v);
2216 point3.push(point);
2217 params.push(fraction);
2218 }
2219 project_timer.stop();
2220 if closed_v {
2227 for index in 2..=dense {
2228 while proj_v[index] - proj_v[index - 1] > period_v * 0.5 {
2229 proj_v[index] -= period_v;
2230 }
2231 while proj_v[index - 1] - proj_v[index] > period_v * 0.5 {
2232 proj_v[index] += period_v;
2233 }
2234 }
2235 while proj_v[0] - proj_v[1] > period_v * 0.5 {
2236 proj_v[0] -= period_v;
2237 }
2238 while proj_v[1] - proj_v[0] > period_v * 0.5 {
2239 proj_v[0] += period_v;
2240 }
2241 }
2242 let mean_u: f64 = proj_u[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2245 let seam_u = if mean_u - u0 > u1 - mean_u { u1 } else { u0 };
2246 let pinned = |index: usize,
2255 neighbour: usize,
2256 proj_u: &[f64],
2257 proj_v: &[f64]|
2258 -> Result<(f64, f64), KernelRefusal> {
2259 let point = point3[index];
2260 let u_error = surface
2261 .evaluate(seam_u, proj_v[index]).or_refuse(KernelStage::Refine, "evaluate")?
2262 .sub(point)
2263 .length();
2264 if closed_v {
2265 let seam_v = nearest_seam_image(proj_v[neighbour], v0, v1);
2266 let v_error = surface
2267 .evaluate(proj_u[index], seam_v).or_refuse(KernelStage::Refine, "evaluate")?
2268 .sub(point)
2269 .length();
2270 if v_error < u_error {
2271 return Ok((proj_u[index], seam_v));
2272 }
2273 }
2274 Ok((seam_u, proj_v[index]))
2275 };
2276 if start_is_crossing {
2277 let (u, v) = pinned(0, 1, &proj_u, &proj_v)?;
2278 proj_u[0] = u;
2279 proj_v[0] = v;
2280 }
2281 if end_is_crossing {
2282 let (u, v) = pinned(dense, dense - 1, &proj_u, &proj_v)?;
2283 proj_u[dense] = u;
2284 proj_v[dense] = v;
2285 }
2286 let mut shift = 0.0;
2287 while mean_u + shift > u1 + 1e-9 {
2288 shift -= period;
2289 }
2290 while mean_u + shift < u0 - 1e-9 {
2291 shift += period;
2292 }
2293 for u in proj_u.iter_mut() {
2294 *u += shift;
2295 }
2296 if closed_v {
2297 let mean_v: f64 = proj_v[1..dense].iter().sum::<f64>() / (dense - 1) as f64;
2298 let mut shift_v = 0.0;
2299 while mean_v + shift_v > v1 + 1e-9 {
2300 shift_v -= period_v;
2301 }
2302 while mean_v + shift_v < v0 - 1e-9 {
2303 shift_v += period_v;
2304 }
2305 for v in proj_v.iter_mut() {
2306 *v += shift_v;
2307 }
2308 }
2309 let tolerance = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
2324 let at = |fraction: f64| piece.evaluate(d0 + (d1 - d0) * fraction);
2331 let mut track = crate::blend::track_fit::Track {
2332 fractions: params,
2333 uv: proj_u.iter().zip(&proj_v).map(|(u, v)| [*u, *v]).collect(),
2334 feet,
2335 breaks: Vec::new(),
2336 };
2337 let breaks = crate::blend::track_fit::curve_breaks(piece, d0, d1, true);
2338 let polish_timer = crate::blend::BlendTimer::start("timing.track.polish_ms");
2339 crate::blend::track_fit::polish_track(surface, &at, &mut track)?;
2340 polish_timer.stop();
2341 let crossings_timer = crate::blend::BlendTimer::start("timing.track.crossings_ms");
2342 crate::blend::track_fit::insert_knot_crossings(surface, &at, &mut track, &breaks)?;
2343 crossings_timer.stop();
2344 crate::blend::record_count("count.track.breaks", track.breaks.len() as u64);
2345 for &fraction in refine_near {
2346 for _ in 0..2 {
2347 let Some(index) = track.fractions.windows(2).position(|pair| pair[0] <= fraction && fraction <= pair[1]) else { break };
2348 if crate::blend::track_fit::refine_track_intervals(surface, &at, &mut track, &[index], ceiling)?.is_none() {
2349 break;
2350 }
2351 }
2352 }
2353 let fit_timer = crate::blend::BlendTimer::start("timing.track.fit_local_ms");
2360 let (fit, inserted) = crate::blend::track_fit::fit_track_locally(
2361 surface,
2362 &mut track,
2363 &at,
2364 tolerance,
2365 REFINE_ROUNDS,
2366 ceiling,
2367 )?;
2368 fit_timer.stop();
2369 crate::blend::record_count("count.track.fit_sections", fit.sections as u64);
2370 crate::blend::record_count("count.track.local_inserted", inserted as u64);
2371 if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2372 eprintln!("TRACK_FIT closed-chain piece: {inserted} sample(s) inserted locally");
2373 eprintln!(
2374 "TRACK_FIT closed-chain piece: miss {:.3e} at {} samples of {} ({} breaks), on floor {}",
2375 fit.miss,
2376 fit.samples,
2377 track.fractions.len(),
2378 track.breaks.len(),
2379 fit.on_floor
2380 );
2381 if let Some(worst) = fit.worst {
2386 let parameter = d0 + (d1 - d0) * worst.fraction;
2387 let spans: Vec<[f64; 2]> = piece.knots.windows(2)
2388 .filter(|pair| pair[1] > pair[0] && pair[1] > d0 && pair[0] < d1)
2389 .map(|pair| [pair[0], pair[1]]).collect();
2390 let mean = (d1 - d0) / spans.len().max(1) as f64;
2391 let span = spans.iter().position(|pair| parameter >= pair[0] && parameter <= pair[1]);
2392 let width = span.map(|index| spans[index][1] - spans[index][0]);
2393 eprintln!(
2394 "TRACK_FIT closed-chain worst: fraction {:.9} parameter {:.9} (pinned start {start_is_crossing}, pinned end {end_is_crossing}) \
2395 knot span {:?} of {} width {:?} vs mean {:.3e}; dense bracket [{:.9}, {:.9}] (interval {})",
2396 worst.fraction, parameter, span, spans.len(), width, mean,
2397 worst.bracket[0], worst.bracket[1], worst.interval
2398 );
2399 }
2400 }
2401 if !fit.on_floor {
2408 if std::env::var("BREP_DEBUG_TRACK_FIT").is_ok() {
2409 for (label, t) in [("start", d0), ("end", d1)] {
2412 if let Ok(point) = piece.evaluate(t) {
2413 let standoff = crate::project_point_to_surface(surface, point).map(|p| p.distance).unwrap_or(f64::NAN);
2414 eprintln!(
2415 "TRACK_FIT closed-chain piece {label} ({:.9}, {:.9}, {:.9}) stands {standoff:.3e} off the carrier",
2416 point.x, point.y, point.z
2417 );
2418 }
2419 }
2420 }
2421 return Err(KernelRefusal::non_convergence(KernelStage::Refine, CHAIN_PCURVE_FLOOR_WHAT, format!(
2422 "{} a closed chain's support piece misses its pcurve by {:.3e} at {} samples, \
2423 against a floor of {tolerance:.1e}",
2424 crate::blend::PCURVE_OFF_FLOOR,
2425 fit.miss,
2426 fit.samples
2427 )));
2428 }
2429 Ok(fit.curve)
2430}
2431
2432
2433
2434pub(in crate::blend) struct PreparedWall<'a> {
2437 fine: &'a [Vec3],
2438 coarse: Vec<Vec3>,
2439 fine_stencils: StencilPreparation,
2440 coarse_stencils: StencilPreparation,
2441}
2442
2443#[derive(Clone, Copy)]
2444struct WallStart {
2445 curve: (Vec3, Vec3, Vec3),
2446 point_length: f64,
2447 tangent_length: f64,
2448 tangent_squared: f64,
2449}
2450impl WallStart {
2451 fn new(curve: (Vec3, Vec3, Vec3)) -> Self {
2452 Self { point_length: curve.0.length(), tangent_length: curve.1.length(),
2453 tangent_squared: curve.1.dot(curve.1), curve }
2454 }
2455}
2456
2457struct StencilPreparation {
2458 finite: bool,
2459 coefficients: std::cell::RefCell<Vec<Option<[Vec3; 4]>>>,
2460 starts: std::cell::RefCell<Vec<[Option<WallStart>; 2]>>,
2463}
2464impl StencilPreparation {
2465 fn new(nodes: &[Vec3]) -> Self {
2466 Self { finite: wall_nodes_finite(nodes), coefficients: std::cell::RefCell::new(vec![None; nodes.len().saturating_sub(3)]),
2467 starts: std::cell::RefCell::new(vec![[None; 2]; nodes.len().saturating_sub(3)]) }
2468 }
2469 fn start(&self, base: usize, j: usize, curve: &impl Fn(f64) -> (Vec3, Vec3, Vec3)) -> Option<WallStart> {
2470 let offset = j.checked_sub(base)?;
2471 if !(1..=2).contains(&offset) { return None; }
2472 let mut entries = self.starts.borrow_mut();
2473 Some(*entries.get_mut(base)?[offset-1].get_or_insert_with(|| WallStart::new(curve(offset as f64))))
2474 }
2475 fn coefficients(&self, nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2476 let mut entries = self.coefficients.borrow_mut();
2477 *entries[base].get_or_insert_with(|| wall_coefficients(nodes, base))
2478 }
2479}
2480
2481fn wall_nodes_finite(nodes: &[Vec3]) -> bool {
2482 nodes.iter().all(|c| c.x.is_finite() && c.y.is_finite() && c.z.is_finite())
2483}
2484
2485fn wall_coefficients(nodes: &[Vec3], base: usize) -> [Vec3; 4] {
2486 let [p0, p1, p2, p3] = [nodes[base], nodes[base + 1], nodes[base + 2], nodes[base + 3]];
2488 let d1 = p1.sub(p0);
2489 let d2 = p2.sub(p1.scale(2.0)).add(p0).scale(0.5);
2490 let d3 = p3.sub(p2.scale(3.0)).add(p1.scale(3.0)).sub(p0).scale(1.0 / 6.0);
2491 [p0, d1, d2, d3]
2492}
2493
2494fn wall_coarse(fine: &[Vec3]) -> Vec<Vec3> {
2495 fine.iter().step_by(2).copied().collect()
2496}
2497
2498fn wall_preparation_on() -> bool {
2499 switch!(live "BREP_WALL_PREPARE", true)
2500}
2501
2502impl<'a> PreparedWall<'a> {
2503 pub(in crate::blend) fn for_interval(fine: &'a [Vec3]) -> Option<Self> {
2504 (wall_preparation_on() && wall_solve_reuse_on()).then(|| Self::new(fine))
2505 }
2506 fn new(fine: &'a [Vec3]) -> Self {
2507 let coarse = wall_coarse(fine);
2508 let fine_stencils = StencilPreparation::new(fine);
2509 let coarse_stencils = StencilPreparation::new(&coarse);
2510 Self { fine, coarse, fine_stencils, coarse_stencils }
2511 }
2512 pub(in crate::blend) fn read(&self, p: Vec3, j: usize, fraction: f64, radius: f64) -> Option<(f64, f64)> {
2513 let read = |at| declared_wall_probe_prepared(p, self.fine, at, radius, true, Some(self));
2514 match read(j) {
2515 Some(read) => Some(read),
2516 None => match centre_path_node(self.fine, fraction) {
2517 Some(located) if located != j => read(located),
2518 _ => None,
2519 },
2520 }
2521 }
2522}