1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
use super::*;
pub(super) fn chain_surgery(
solid: &BrepSolid,
segments: &[ChainSegment<'_>],
rows: ChainRows,
name: Option<&str>,
) -> Result<BrepSolid, String> {
let mut result = solid.clone();
let mut take_id = crate::blend::edge::fresh_id_source(solid);
let [u_start, u_end] = rows.u_domain;
// ---- side descriptors -------------------------------------------
// For each side, group consecutive segments by face; a junction
// between different faces needs a spoke edge; a side whose every
// segment shares one face has no crossings at all.
struct SideJunction {
/// Junction index (between segment j-1 and j, cyclic).
junction: usize,
spoke_edge_id: u64,
crossing_support: f64,
crossing_spoke: f64,
vertex_id: u64,
}
struct SidePlan {
junctions: Vec<SideJunction>,
}
let chain_vertex_at = |junction: usize| -> u64 {
// Junction j sits between segment j-1 and segment j (cyclic);
// it is segment j's chain-entry vertex.
let segment = &segments[junction % segments.len()];
if segment.forward {
segment.edge.start_vertex_id
} else {
segment.edge.end_vertex_id
}
};
let mut plans = Vec::new();
// Tracks whether any junction below needed a looser-than-1e-7 spoke
// crossing; if so the finished solid is validated before it is handed back.
let mut crossings = SpokeCrossings::default();
// A side "needs seam surgery" when any of its junctions is a carrier
// SEAM (the mate face is the same across the junction, i.e. a closed
// cylinder/cone/sphere whose seam the chain crosses) rather than a
// face-change SPOKE. Those sides rebuild their mate loops run-by-run.
let mut side_has_seam = [false, false];
for side in 0..2 {
let support = if side == 0 { &rows.cr } else { &rows.cs };
let mut junctions = Vec::new();
for junction in 0..segments.len() {
let before = &segments[(junction + segments.len() - 1) % segments.len()];
let after = &segments[junction];
let before_mate = before.mate(side);
let after_mate = after.mate(side);
let (face_before, loop_before) = (before_mate.face, before_mate.loop_index);
let (face_after, loop_after) = (after_mate.face, after_mate.loop_index);
let vertex = chain_vertex_at(junction);
let Some(spoke) = cross_edge_at(
solid,
face_before,
loop_before,
face_after,
loop_after,
vertex,
before.edge.id,
after.edge.id,
)?
else {
// Same face and no seam here: the chain flows through.
continue;
};
if face_before.id == face_after.id {
side_has_seam[side] = true;
}
let spoke_record = solid
.edges
.iter()
.find(|edge| edge.id == spoke)
.ok_or("blend: chain spoke edge missing")?;
let vertex_point = result
.vertices
.iter()
.find(|candidate| candidate.id == vertex)
.map(|candidate| candidate.point)
.unwrap_or_default();
let Some((crossing_support, crossing_spoke, escalated)) =
spoke_crossing(solid, support, spoke_record, vertex_point)?
else {
return Err("blend: support does not cross a chain spoke".into());
};
crossings.note(escalated);
junctions.push(SideJunction {
junction,
spoke_edge_id: spoke,
crossing_support,
crossing_spoke,
vertex_id: vertex,
});
}
plans.push(SidePlan { junctions });
}
// ---- support edges: split at crossings and the seam --------------
// Crossing vertices first.
let mut side_edges: Vec<Vec<RimPiece>> = Vec::new();
let mut seam_vertices = [0u64; 2];
// Crossing (cut) vertices per side — used by the seam-aware run rebuild
// to pin piece pcurves onto the carrier meridian.
let mut side_crossing_vertices: Vec<Vec<u64>> = Vec::new();
for (side, plan) in plans.iter().enumerate() {
let support = if side == 0 { &rows.cr } else { &rows.cs };
let seam_point = support.evaluate(u_start)?;
let seam_vertex = take_id();
result.vertices.push(VertexRecord {
id: seam_vertex,
point: seam_point,
});
seam_vertices[side] = seam_vertex;
// Sorted crossing parameters with their new vertices.
let mut cuts: Vec<(f64, u64, usize)> = Vec::new();
let mut crossing_vertices = Vec::new();
for junction in &plan.junctions {
let vertex = take_id();
result.vertices.push(VertexRecord {
id: vertex,
point: support.evaluate(junction.crossing_support)?,
});
crossing_vertices.push(vertex);
cuts.push((junction.crossing_support, vertex, junction.junction));
}
side_crossing_vertices.push(crossing_vertices);
cuts.sort_by(|a, b| a.0.total_cmp(&b.0));
// Pieces between consecutive cut parameters (wrapping through the
// seam): [seam..c0], [c0..c1], ..., [ck..seam-end].
let mut pieces = Vec::new();
let mut boundaries = vec![(u_start, seam_vertex)];
boundaries.extend(
cuts.iter()
.map(|(parameter, vertex, _)| (*parameter, *vertex)),
);
boundaries.push((u_end, seam_vertex));
for window in boundaries.windows(2) {
let (a, vertex_a) = window[0];
let (b, vertex_b) = window[1];
if b - a <= 1e-9 {
return Err("blend: degenerate support piece between crossings".into());
}
let piece_curve = {
let (_, tail) = if a > u_start + 1e-12 {
support.split(a)?
} else {
(support.clone(), support.clone())
};
let tail = if a > u_start + 1e-12 {
tail
} else {
support.clone()
};
if b < u_end - 1e-12 {
tail.split(b)?.0
} else {
tail
}
};
let edge_id = take_id();
let [piece_t0, piece_t1] = piece_curve.domain()?;
result.edges.push(EdgeRecord {
id: edge_id,
curve: piece_curve,
t0: piece_t0,
t1: piece_t1,
start_vertex_id: vertex_a,
end_vertex_id: vertex_b,
degenerate: false,
name: None,
});
pieces.push(RimPiece {
face_id: 0,
loop_index: 0,
window: [a, b],
edge_id,
});
}
side_edges.push(pieces);
}
// Blend seam edge between the two rim seam vertices.
let seam_curve = rows.surface.iso_curve_u(u_start)?;
let [seam_t0, seam_t1] = seam_curve.domain()?;
let blend_seam_id = take_id();
result.edges.push(EdgeRecord {
id: blend_seam_id,
curve: seam_curve,
t0: seam_t0,
t1: seam_t1,
start_vertex_id: seam_vertices[0],
end_vertex_id: seam_vertices[1],
degenerate: false,
name: None,
});
// ---- trim spokes -------------------------------------------------
for (side, plan) in plans.iter().enumerate() {
for junction in &plan.junctions {
// The crossing vertex created for this junction.
let vertex = side_edges[side]
.iter()
.find_map(|piece| {
(piece.window[0] - junction.crossing_support)
.abs()
.le(&1e-12)
.then(|| {
result
.edges
.iter()
.find(|edge| edge.id == piece.edge_id)
.map(|edge| edge.start_vertex_id)
})
})
.flatten()
.ok_or("blend: crossing vertex lost")?;
trim_edge_at(
&mut result,
junction.spoke_edge_id,
junction.crossing_spoke,
junction.vertex_id,
vertex,
)?;
}
}
// ---- replace chain coedges in the mate faces ---------------------
// For each side, each face's run of chain coedges is replaced by its
// support pieces (in loop-traversal order and sense).
let mut side_use_forward = [true, true];
for side in 0..2 {
// Map each piece window to the segment(s) it covers, and thus the
// face. A piece's midpoint parameter falls inside exactly one
// segment's window unless the side has no crossings (single face).
let pieces = &side_edges[side];
let face_info = |segment: &ChainSegment| {
let mate = segment.mate(side);
(mate.face.id, mate.loop_index, mate.coedge.id)
};
if side_has_seam[side] {
// Seam-carrier mate(s): one closed carrier's loop holds the
// chain coedges in MULTIPLE runs split by its OWN seam edges
// (which we already trimmed to the support crossings). Rebuild
// each mate loop run-by-run, projecting each support piece onto
// the carrier so the pcurve never wraps the seam.
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
let fitted = if side == 0 {
&rows.pcurves1
} else {
&rows.pcurves2
};
let segment_mid = |index: usize| -> f64 {
let (low, high, _) = &fitted[index];
(low + high) * 0.5
};
let piece_segment = |piece: &RimPiece| -> usize {
let midpoint = rows.to_global((piece.window[0] + piece.window[1]) * 0.5);
let mut best = (0usize, f64::INFINITY);
for segment_index in 0..segments.len() {
let sm = segment_mid(segment_index);
let distance = (sm - midpoint)
.abs()
.min((sm - midpoint + 1.0).abs())
.min((sm - midpoint - 1.0).abs());
if distance < best.1 {
best = (segment_index, distance);
}
}
best.0
};
let crossing_set: HashSet<u64> = side_crossing_vertices[side].iter().copied().collect();
// Distinct mate faces on this side (usually a single carrier).
let mut faces: Vec<(u64, usize)> = Vec::new();
for segment in segments {
let (face_id, loop_index, _) = face_info(segment);
if !faces.iter().any(|(id, _)| *id == face_id) {
faces.push((face_id, loop_index));
}
}
for (face_id, loop_index) in faces {
// Which chain segments live in this face, keyed by edge id.
let mut edge_to_segment: HashMap<u64, usize> = HashMap::default();
for (segment_index, segment) in segments.iter().enumerate() {
if face_info(segment).0 == face_id {
edge_to_segment.insert(segment.edge.id, segment_index);
}
}
let surface = {
let face = result
.shells
.iter()
.flat_map(|shell| &shell.faces)
.find(|face| face.id == face_id)
.ok_or("blend: mate face lost during chain surgery")?;
face.surface.clone()
};
let loop_coedges = {
let face = result
.shells
.iter()
.flat_map(|shell| &shell.faces)
.find(|face| face.id == face_id)
.unwrap();
face.loops[loop_index].coedges.clone()
};
let count = loop_coedges.len();
let is_chain =
|coedge: &CoedgeRecord| edge_to_segment.contains_key(&coedge.edge_id);
// Rotate so index 0 is a NON-chain coedge (a carrier seam)
// — then no run of chain coedges wraps the coedge vector.
// If a face carries no seam edge of its own (a plain face on
// a mixed side), its chain coedges form a single whole-loop
// run; anchoring at 0 is then fine.
let rotation = (0..count)
.find(|&i| !is_chain(&loop_coedges[i]))
.unwrap_or(0);
let rotated: Vec<CoedgeRecord> = (0..count)
.map(|i| loop_coedges[(i + rotation) % count].clone())
.collect();
// The face's loop winds +chain or −chain (constant per face).
let chain_forward = {
let first_chain = rotated.iter().find(|coedge| is_chain(coedge)).unwrap();
let segment_index = edge_to_segment[&first_chain.edge_id];
first_chain.forward == segments[segment_index].forward
};
side_use_forward[side] = chain_forward;
let mut new_coedges: Vec<CoedgeRecord> = Vec::new();
let mut position = 0;
while position < count {
if !is_chain(&rotated[position]) {
new_coedges.push(rotated[position].clone());
position += 1;
continue;
}
// A maximal run of chain coedges (bounded by carrier
// seams); gather the segments it covers.
let mut run_segments: HashSet<usize> = HashSet::default();
while position < count && is_chain(&rotated[position]) {
run_segments.insert(edge_to_segment[&rotated[position].edge_id]);
position += 1;
}
// The support pieces covering those segments, +param.
let mut run_pieces: Vec<&RimPiece> = pieces
.iter()
.filter(|piece| run_segments.contains(&piece_segment(piece)))
.collect();
run_pieces.sort_by(|a, b| a.window[0].total_cmp(&b.window[0]));
// A run spanning the blend seam owns both the first and
// the last piece — rotate them contiguous.
if run_pieces.len() > 1
&& (run_pieces[0].window[0] - u_start).abs() < 1e-9
&& (run_pieces[run_pieces.len() - 1].window[1] - u_end).abs() < 1e-9
{
let shift = run_pieces.len() - 1;
run_pieces.rotate_left(shift);
}
if !chain_forward {
run_pieces.reverse();
}
for piece in run_pieces {
let (curve, start_vertex, end_vertex) = {
let edge = result
.edges
.iter()
.find(|edge| edge.id == piece.edge_id)
.ok_or("blend: support piece edge lost")?;
(edge.curve.clone(), edge.start_vertex_id, edge.end_vertex_id)
};
let base = project_piece_pcurve(
&curve,
&surface,
crossing_set.contains(&start_vertex),
crossing_set.contains(&end_vertex),
)?;
new_coedges.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: chain_forward,
pcurve: if chain_forward {
base
} else {
base.reversed()?
},
});
}
}
let face = result
.shells
.iter_mut()
.flat_map(|shell| &mut shell.faces)
.find(|face| face.id == face_id)
.ok_or("blend: mate face lost during chain surgery")?;
face.loops[loop_index].coedges = new_coedges;
}
continue;
}
// Global window of each segment from the in-segment samples: use
// the pcurve fit windows (low..high include overshoot; the
// in-segment span is [low + overshoot, high - overshoot], but for
// piece assignment the crossing parameters already delimit
// exactly — assign by nearest segment midpoint.
let fitted = if side == 0 {
&rows.pcurves1
} else {
&rows.pcurves2
};
let segment_mid = |index: usize| -> f64 {
let (low, high, _) = &fitted[index];
(low + high) * 0.5
};
// Group pieces per face.
use rustc_hash::FxHashMap as HashMap;
let mut per_face: HashMap<u64, Vec<usize>> = HashMap::default();
for (piece_index, piece) in pieces.iter().enumerate() {
let midpoint = rows.to_global((piece.window[0] + piece.window[1]) * 0.5);
let mut best = (0usize, f64::INFINITY);
for (segment_index, _) in segments.iter().enumerate() {
let distance = (segment_mid(segment_index) - midpoint).abs();
let wrapped = (segment_mid(segment_index) - midpoint + 1.0).abs();
let wrapped2 = (segment_mid(segment_index) - midpoint - 1.0).abs();
let distance = distance.min(wrapped).min(wrapped2);
if distance < best.1 {
best = (segment_index, distance);
}
}
let (face_id, ..) = face_info(&segments[best.0]);
per_face.entry(face_id).or_default().push(piece_index);
}
for (face_id, piece_indices) in per_face {
// The run of chain coedges in this face's loop.
let (loop_index, coedge_ids): (usize, Vec<u64>) = {
let mut loop_index = None;
let mut ids = Vec::new();
for segment in segments {
let (candidate_face, candidate_loop, coedge_id) = face_info(segment);
if candidate_face == face_id {
loop_index = Some(candidate_loop);
ids.push(coedge_id);
}
}
(loop_index.ok_or("blend: face lost its chain coedges")?, ids)
};
let face = result
.shells
.iter_mut()
.flat_map(|shell| &mut shell.faces)
.find(|face| face.id == face_id)
.ok_or("blend: mate face lost during chain surgery")?;
let loop_record = &mut face.loops[loop_index];
let positions: Vec<usize> = loop_record
.coedges
.iter()
.enumerate()
.filter(|(_, coedge)| coedge_ids.contains(&coedge.id))
.map(|(position, _)| position)
.collect();
if positions.is_empty() {
return Err("blend: chain coedges missing from mate loop".into());
}
let old_forward = loop_record.coedges[positions[0]].forward;
// Sense: the support pieces run in chain direction; whether
// the loop traverses them forward mirrors the old coedges
// relative to their segments' chain direction.
let chain_forward = {
let segment = segments
.iter()
.find(|segment| face_info(segment).0 == face_id)
.unwrap();
let (.., coedge_id) = face_info(segment);
let old = loop_record
.coedges
.iter()
.find(|coedge| coedge.id == coedge_id)
.unwrap();
old.forward == segment.forward
};
// Build the replacement coedges: pieces sorted by window in
// chain direction, oriented to the loop traversal.
let mut ordered: Vec<&RimPiece> =
piece_indices.iter().map(|index| &pieces[*index]).collect();
ordered.sort_by(|a, b| a.window[0].total_cmp(&b.window[0]));
// Wrap: if the face owns both the first and last pieces (its
// run spans the seam), rotate so the sequence is contiguous
// in traversal: [.., last piece, first piece, ..].
if ordered.len() > 1
&& (ordered[0].window[0] - u_start).abs() < 1e-12
&& (ordered[ordered.len() - 1].window[1] - u_end).abs() < 1e-12
{
let rotation = ordered.len() - 1;
ordered.rotate_left(rotation);
}
if !chain_forward {
ordered.reverse();
}
let mut replacements = Vec::new();
for piece in ordered {
if let Some(whole) = &rows.whole_pcurves[side] {
// Rows-space fit: split directly at the piece window.
let [w0, w1] = piece.window;
let epsilon = 1e-9;
let portion = {
let (_, tail) = if w0 > u_start + epsilon {
whole.split(w0)?
} else {
(whole.clone(), whole.clone())
};
let tail = if w0 > u_start + epsilon {
tail
} else {
whole.clone()
};
if w1 < u_end - epsilon {
tail.split(w1)?.0
} else {
tail
}
};
replacements.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: chain_forward,
pcurve: if chain_forward {
portion
} else {
portion.reversed()?
},
});
continue;
}
let global_window = [
rows.to_global(piece.window[0]),
rows.to_global(piece.window[1]),
];
let pcurve = pcurve_portion(
fitted
.iter()
.enumerate()
.min_by(|(a, _), (b, _)| {
let mid = (global_window[0] + global_window[1]) * 0.5;
let da = (segment_mid(*a) - mid)
.abs()
.min((segment_mid(*a) - mid + 1.0).abs())
.min((segment_mid(*a) - mid - 1.0).abs());
let db = (segment_mid(*b) - mid)
.abs()
.min((segment_mid(*b) - mid + 1.0).abs())
.min((segment_mid(*b) - mid - 1.0).abs());
da.total_cmp(&db)
})
.map(|(_, fitted)| fitted)
.unwrap(),
global_window[0],
global_window[1],
)?;
replacements.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: chain_forward,
pcurve: if chain_forward {
pcurve
} else {
pcurve.reversed()?
},
});
}
let _ = old_forward;
side_use_forward[side] = chain_forward;
// Splice: replace the run (positions may be non-contiguous
// only through the loop's own wrap; handle the contiguous
// rotation) with the replacement sequence.
let first_position = positions[0];
let mut kept: Vec<CoedgeRecord> = Vec::new();
for (position, coedge) in loop_record.coedges.iter().enumerate() {
if !positions.contains(&position) {
kept.push(coedge.clone());
} else if position == first_position {
for replacement in &replacements {
kept.push(replacement.clone());
}
}
}
loop_record.coedges = kept;
}
}
// ---- blend face ---------------------------------------------------
// The blend's use of every support piece must OPPOSE the mate side's
// use (manifold pairing); the loop winding follows, and same_sense
// follows the winding (loops run CCW around the face normal).
let v0_forward = !side_use_forward[0];
if side_use_forward[1] != v0_forward {
return Err("blend: chain sides have inconsistent orientations".into());
}
let same_sense = v0_forward;
let loop_id = take_id();
let mut coedges = Vec::new();
if v0_forward {
for piece in &side_edges[0] {
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: true,
pcurve: crate::sweep_topology::parameter_line(
piece.window[0],
0.0,
piece.window[1],
0.0,
)?,
});
}
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: blend_seam_id,
forward: true,
pcurve: crate::sweep_topology::parameter_line(u_end, 0.0, u_end, 1.0)?,
});
for piece in side_edges[1].iter().rev() {
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: false,
pcurve: crate::sweep_topology::parameter_line(
piece.window[1],
1.0,
piece.window[0],
1.0,
)?,
});
}
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: blend_seam_id,
forward: false,
pcurve: crate::sweep_topology::parameter_line(u_start, 1.0, u_start, 0.0)?,
});
} else {
// Mirror winding: v=1 side forward, v=0 side reversed.
for piece in &side_edges[1] {
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: true,
pcurve: crate::sweep_topology::parameter_line(
piece.window[0],
1.0,
piece.window[1],
1.0,
)?,
});
}
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: blend_seam_id,
forward: false,
pcurve: crate::sweep_topology::parameter_line(u_end, 1.0, u_end, 0.0)?,
});
for piece in side_edges[0].iter().rev() {
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: piece.edge_id,
forward: false,
pcurve: crate::sweep_topology::parameter_line(
piece.window[1],
0.0,
piece.window[0],
0.0,
)?,
});
}
coedges.push(CoedgeRecord {
id: take_id(),
edge_id: blend_seam_id,
forward: true,
pcurve: crate::sweep_topology::parameter_line(u_start, 0.0, u_start, 1.0)?,
});
}
let mut loops = vec![LoopRecord {
id: loop_id,
coedges,
}];
// The CARVED lens: an INNER loop of two coedges on ONE new edge — the
// crease — both of them this face's own. That is the slit pattern the
// torus mate's v-seam already carries, and it is what a crease IS: the two
// sheets of the wall are one surface, so the curve where they meet has one
// edge and two coedges rather than two faces' worth. The lens between them
// is the part of the swept envelope inside the swept ball volume, and
// dropping it is what makes the wall the blend.
if let Some(crease) = rows.crease {
let start_vertex = take_id();
let end_vertex = take_id();
let crease_edge = take_id();
result.vertices.push(VertexRecord {
id: start_vertex,
point: crease.start,
});
result.vertices.push(VertexRecord {
id: end_vertex,
point: crease.end,
});
let [crease_t0, crease_t1] = crease.curve.domain()?;
result.edges.push(EdgeRecord {
id: crease_edge,
curve: crease.curve,
t0: crease_t0,
t1: crease_t1,
start_vertex_id: start_vertex,
end_vertex_id: end_vertex,
degenerate: false,
name: name.map(|value| format!("{value}:CREASE")),
});
// WINDING: an inner loop runs against the outer one. Measured from the
// two loops themselves rather than assumed from a convention, so the
// hole is a hole whichever way the outer loop was wound (this surgery
// winds it two ways already — see `v0_forward` above).
let outer = signed_area(&loops[0].coedges)?;
let forward_first = signed_area(&[
CoedgeRecord {
id: 0,
edge_id: crease_edge,
forward: true,
pcurve: crease.first.clone(),
},
CoedgeRecord {
id: 0,
edge_id: crease_edge,
forward: false,
pcurve: crease.second.reversed()?,
},
])?;
let coedges = if outer * forward_first < 0.0 {
vec![
CoedgeRecord {
id: take_id(),
edge_id: crease_edge,
forward: true,
pcurve: crease.first,
},
CoedgeRecord {
id: take_id(),
edge_id: crease_edge,
forward: false,
pcurve: crease.second.reversed()?,
},
]
} else {
vec![
CoedgeRecord {
id: take_id(),
edge_id: crease_edge,
forward: true,
pcurve: crease.second,
},
CoedgeRecord {
id: take_id(),
edge_id: crease_edge,
forward: false,
pcurve: crease.first.reversed()?,
},
]
};
loops.push(LoopRecord {
id: take_id(),
coedges,
});
}
let blend_face = FaceRecord {
id: take_id(),
surface: rows.surface,
same_sense,
loops,
name: name.map(|value| value.to_string()),
};
let shell_index = result
.shells
.iter()
.position(|shell| {
shell
.faces
.iter()
.any(|face| face.id == segments[0].first.face.id)
})
.ok_or("blend: mate shell lost during chain surgery")?;
result.shells[shell_index].faces.push(blend_face);
// ---- drop the chain edges and orphaned vertices -------------------
let chain_edge_ids: Vec<u64> = segments.iter().map(|segment| segment.edge.id).collect();
result
.edges
.retain(|candidate| !chain_edge_ids.contains(&candidate.id));
let old_vertices: Vec<u64> = (0..segments.len()).map(chain_vertex_at).collect();
for vertex in old_vertices {
let still_used = result.edges.iter().any(|candidate| {
candidate.start_vertex_id == vertex || candidate.end_vertex_id == vertex
});
if !still_used {
result.vertices.retain(|candidate| candidate.id != vertex);
}
}
crossings.gate(result)
}
/// Signed area of a loop in the face's own (u, v), from its pcurves.
///
/// The sign is all that is used: an inner loop must run AGAINST its outer one,
/// and reading both off the same sampler makes that true by measurement rather
/// than by a convention this surgery would otherwise have to restate (it winds
/// the outer loop two different ways already).
fn signed_area(coedges: &[CoedgeRecord]) -> Result<f64, String> {
const SAMPLES: usize = 24;
let mut twice_area = 0.0;
for coedge in coedges {
let [t0, t1] = coedge.pcurve.domain()?;
let mut previous: Option<crate::Vec3> = None;
for index in 0..=SAMPLES {
let t = t0 + (t1 - t0) * index as f64 / SAMPLES as f64;
let point = coedge.pcurve.evaluate(t)?;
if let Some(before) = previous {
twice_area += before.x * point.y - point.x * before.y;
}
previous = Some(point);
}
}
Ok(0.5 * twice_area)
}