BREP_kernel 0.2.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
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
use super::*;

#[derive(Clone)]
struct SectionFrame {
    normal: Vec3,
    centroid: Vec3,
    samples: Vec<Vec3>,
    planar: bool,
}

pub(super) fn closed_points(curves: &[NurbsCurve], tolerance: f64) -> Result<Vec<Vec3>, String> {
    if curves.len() < 2 {
        return Err("loftSolid: a section needs at least 2 curves".into());
    }
    let mut points = Vec::with_capacity(curves.len());
    for (index, curve) in curves.iter().enumerate() {
        let [start, end] = curve.domain()?;
        let next = &curves[(index + 1) % curves.len()];
        let next_start = next.domain()?[0];
        if curve
            .evaluate(end)?
            .sub(next.evaluate(next_start)?)
            .length()
            > tolerance
        {
            return Err(format!("loftSolid: section is open at curve {index}"));
        }
        points.push(curve.evaluate(start)?);
    }
    Ok(points)
}

fn section_frame(curves: &[NurbsCurve], tolerance: f64) -> Result<SectionFrame, String> {
    let mut samples = Vec::new();
    for curve in curves {
        let [start, end] = curve.domain()?;
        for index in 0..16 {
            samples.push(curve.evaluate(start + (end - start) * index as f64 / 16.0)?);
        }
    }
    let mut normal = Vec3::default();
    let mut centroid = Vec3::default();
    for index in 0..samples.len() {
        let point = samples[index];
        let next = samples[(index + 1) % samples.len()];
        normal.x += (point.y - next.y) * (point.z + next.z);
        normal.y += (point.z - next.z) * (point.x + next.x);
        normal.z += (point.x - next.x) * (point.y + next.y);
        centroid = centroid.add(point);
    }
    normal = normal.normalized()?;
    centroid = centroid.scale(1.0 / samples.len() as f64);
    let planar = samples
        .iter()
        .all(|point| point.sub(samples[0]).dot(normal).abs() <= tolerance * 100.0);
    Ok(SectionFrame {
        normal,
        centroid,
        samples,
        planar,
    })
}

fn reverse_section(curves: &[NurbsCurve]) -> Result<Vec<NurbsCurve>, String> {
    curves.iter().rev().map(NurbsCurve::reversed).collect()
}

fn cap_face(
    curves: &[NurbsCurve],
    edge_ids: &[u64],
    frame: &SectionFrame,
    axis: Vec3,
    outward: bool,
    next_id: &mut u64,
) -> Result<FaceRecord, String> {
    let normal = if frame.normal.dot(axis) >= 0.0 {
        frame.normal
    } else {
        frame.normal.scale(-1.0)
    };
    let x_axis = normal.perpendicular()?;
    let y_axis = normal.cross(x_axis).normalized()?;
    let (mut min_x, mut min_y) = (f64::INFINITY, f64::INFINITY);
    let (mut max_x, mut max_y) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
    for point in &frame.samples {
        let delta = point.sub(frame.centroid);
        min_x = min_x.min(delta.dot(x_axis));
        max_x = max_x.max(delta.dot(x_axis));
        min_y = min_y.min(delta.dot(y_axis));
        max_y = max_y.max(delta.dot(y_axis));
    }
    let padding = (max_x - min_x).max(max_y - min_y) * 0.05 + 1e-6;
    let origin = frame
        .centroid
        .add(x_axis.scale(min_x - padding))
        .add(y_axis.scale(min_y - padding));
    let surface = make_plane(
        origin,
        x_axis,
        y_axis,
        max_x - min_x + 2.0 * padding,
        max_y - min_y + 2.0 * padding,
    )?;
    let mut coedges = Vec::with_capacity(curves.len());
    if outward {
        for (index, curve) in curves.iter().enumerate() {
            coedges.push(CoedgeRecord {
                id: *next_id,
                edge_id: edge_ids[index],
                forward: true,
                pcurve: curve_to_plane_parameters(curve, origin, x_axis, y_axis)?,
            });
            *next_id += 1;
        }
    } else {
        for index in (0..curves.len()).rev() {
            coedges.push(CoedgeRecord {
                id: *next_id,
                edge_id: edge_ids[index],
                forward: false,
                pcurve: curve_to_plane_parameters(&curves[index], origin, x_axis, y_axis)?
                    .reversed()?,
            });
            *next_id += 1;
        }
    }
    let loop_id = *next_id;
    *next_id += 1;
    let face_id = *next_id;
    *next_id += 1;
    Ok(FaceRecord {
        id: face_id,
        surface,
        same_sense: outward,
        loops: vec![LoopRecord {
            id: loop_id,
            coedges,
        }],
        name: None,
    })
}

pub fn loft_profile_brep(input_sections: &[Vec<NurbsCurve>]) -> Result<BrepSolid, String> {
    loft_profile_brep_core(input_sections, None)
}

/// §5.8 loft with END TANGENCY: the skin leaves the first section along
/// `start_direction` and arrives at the last along `end_direction` (unit
/// directions; each interpolation column scales them by its own chord length,
/// the standard magnitude that keeps the v-parametrization well conditioned).
/// Exact by construction — the column interpolant reproduces the prescribed
/// end derivatives.
pub fn loft_profile_brep_tangent(
    input_sections: &[Vec<NurbsCurve>],
    start_direction: Vec3,
    end_direction: Vec3,
) -> Result<BrepSolid, String> {
    let start = start_direction
        .normalized()
        .map_err(|_| "loftSolid: start tangent must be a nonzero direction".to_string())?;
    let end = end_direction
        .normalized()
        .map_err(|_| "loftSolid: end tangent must be a nonzero direction".to_string())?;
    loft_profile_brep_core(input_sections, Some((start, end)))
}

fn loft_profile_brep_core(
    input_sections: &[Vec<NurbsCurve>],
    end_tangents: Option<(Vec3, Vec3)>,
) -> Result<BrepSolid, String> {
    let tolerance = 1e-6;
    let section_count = input_sections.len();
    if section_count < 2 {
        return Err("loftSolid: need at least 2 sections".into());
    }
    let mut sections = input_sections.to_vec();
    let curve_count = sections[0].len();
    if sections.iter().any(|section| section.len() != curve_count) {
        return Err("loftSolid: sections must have the same curve count".into());
    }
    for section in &sections {
        closed_points(section, tolerance)?;
    }
    for curve_index in 0..curve_count {
        let reference = &sections[0][curve_index];
        for (section_index, section) in sections.iter().enumerate().skip(1) {
            let curve = &section[curve_index];
            if curve.degree != reference.degree
                || curve.control_points.len() != reference.control_points.len()
            {
                return Err(format!(
                    "loftSolid: section {section_index} curve {curve_index} incompatible with section 0"
                ));
            }
            if curve.knots.len() != reference.knots.len()
                || curve
                    .knots
                    .iter()
                    .zip(&reference.knots)
                    .any(|(a, b)| (a - b).abs() > 1e-9)
            {
                return Err(format!(
                    "loftSolid: section {section_index} curve {curve_index} has different knots"
                ));
            }
            if curve
                .control_points
                .iter()
                .zip(&reference.control_points)
                .any(|(a, b)| (a.w - b.w).abs() > 1e-9)
            {
                return Err(format!(
                    "loftSolid: section {section_index} curve {curve_index} has different weights"
                ));
            }
        }
    }

    let first_frame = section_frame(&sections[0], tolerance)?;
    let last_frame = section_frame(&sections[section_count - 1], tolerance)?;
    if !first_frame.planar || !last_frame.planar {
        return Err("loftSolid: end sections must be planar".into());
    }
    let axis = last_frame
        .centroid
        .sub(first_frame.centroid)
        .normalized()
        .map_err(|_| "loftSolid: end sections coincide".to_string())?;
    let first_normal = if first_frame.normal.dot(axis) >= 0.0 {
        first_frame.normal
    } else {
        first_frame.normal.scale(-1.0)
    };
    if first_normal.dot(axis).abs() < 0.1 {
        return Err("loftSolid: loft direction nearly parallel to end section plane".into());
    }
    let x_axis = first_normal.perpendicular()?;
    let y_axis = first_normal.cross(x_axis).normalized()?;
    let reversed_winding = profile_area(&sections[0], first_frame.centroid, x_axis, y_axis)? < 0.0;
    if reversed_winding {
        sections = sections
            .iter()
            .map(|section| reverse_section(section))
            .collect::<Result<_, _>>()?;
    }

    let mut parameters = vec![0.0; section_count];
    let mut accumulated = vec![0.0; section_count];
    let mut columns = 0usize;
    for curve_index in 0..curve_count {
        for control_index in 0..sections[0][curve_index].control_points.len() {
            let mut total = 0.0;
            let mut chords = vec![0.0; section_count];
            for section_index in 1..section_count {
                let previous = sections[section_index - 1][curve_index].control_points
                    [control_index]
                    .point()?;
                let current =
                    sections[section_index][curve_index].control_points[control_index].point()?;
                total += current.sub(previous).length();
                chords[section_index] = total;
            }
            if total <= tolerance {
                continue;
            }
            for section_index in 0..section_count {
                accumulated[section_index] += chords[section_index] / total;
            }
            columns += 1;
        }
    }
    if columns == 0 {
        return Err("loftSolid: sections coincide".into());
    }
    for index in 0..section_count {
        parameters[index] = accumulated[index] / columns as f64;
    }
    parameters[0] = 0.0;
    parameters[section_count - 1] = 1.0;
    if parameters.windows(2).any(|pair| pair[1] <= pair[0] + 1e-9) {
        return Err("loftSolid: sections are not strictly ordered".into());
    }
    // Tangent lofts always interpolate cubically — the end-derivative rows
    // need the two extra control points even for a 2-section Hermite loft.
    let degree_v = if end_tangents.is_some() {
        3
    } else {
        3usize.min(section_count - 1)
    };
    let mut skins = Vec::with_capacity(curve_count);
    for curve_index in 0..curve_count {
        let reference = &sections[0][curve_index];
        let mut grid = Vec::with_capacity(reference.control_points.len());
        let mut knots_v = Vec::new();
        for control_index in 0..reference.control_points.len() {
            let points = sections
                .iter()
                .map(|section| section[curve_index].control_points[control_index].point())
                .collect::<Result<Vec<_>, _>>()?;
            let interpolated = match end_tangents {
                None => interpolate_curve(&points, degree_v, &parameters)?,
                Some((start_direction, end_direction)) => {
                    let chord: f64 = points
                        .windows(2)
                        .map(|pair| pair[1].sub(pair[0]).length())
                        .sum();
                    // A column whose stations coincide still needs a usable
                    // tangent magnitude; fall back to the section spacing.
                    let magnitude = if chord > tolerance { chord } else { 1.0 };
                    crate::interpolate_curve_with_end_tangents(
                        &points,
                        &parameters,
                        start_direction.scale(magnitude),
                        end_direction.scale(magnitude),
                    )?
                }
            };
            knots_v = interpolated.knots.clone();
            let weight = reference.control_points[control_index].w;
            grid.push(
                interpolated
                    .control_points
                    .iter()
                    .map(|point| Vec4::from_point(point.point().unwrap(), weight))
                    .collect(),
            );
        }
        skins.push(NurbsSurface::new(
            reference.degree,
            degree_v,
            reference.knots.clone(),
            knots_v,
            grid,
        )?);
    }

    let bottom = &sections[0];
    let top = &sections[section_count - 1];
    let bottom_points = closed_points(bottom, tolerance)?;
    let top_points = closed_points(top, tolerance)?;
    let mut vertices = Vec::with_capacity(2 * curve_count);
    for (index, point) in bottom_points.iter().chain(&top_points).enumerate() {
        vertices.push(VertexRecord {
            id: index as u64 + 1,
            point: *point,
        });
    }
    let mut edges = Vec::with_capacity(3 * curve_count);
    let mut bottom_edge_ids = Vec::new();
    let mut top_edge_ids = Vec::new();
    let mut vertical_edge_ids = Vec::new();
    for index in 0..curve_count {
        let [start, end] = bottom[index].domain()?;
        let bottom_id = 10 + index as u64;
        let top_id = 10 + curve_count as u64 + index as u64;
        let vertical_id = 10 + 2 * curve_count as u64 + index as u64;
        bottom_edge_ids.push(bottom_id);
        top_edge_ids.push(top_id);
        vertical_edge_ids.push(vertical_id);
        edges.push(EdgeRecord {
            id: bottom_id,
            curve: bottom[index].clone(),
            t0: start,
            t1: end,
            start_vertex_id: index as u64 + 1,
            end_vertex_id: ((index + 1) % curve_count) as u64 + 1,
            degenerate: false,
            name: None,
        });
        edges.push(EdgeRecord {
            id: top_id,
            curve: top[index].clone(),
            t0: start,
            t1: end,
            start_vertex_id: (curve_count + index) as u64 + 1,
            end_vertex_id: (curve_count + (index + 1) % curve_count) as u64 + 1,
            degenerate: false,
            name: None,
        });
        let vertical = skins[index].iso_curve_u(start)?;
        let [v_start, v_end] = vertical.domain()?;
        edges.push(EdgeRecord {
            id: vertical_id,
            curve: vertical,
            t0: v_start,
            t1: v_end,
            start_vertex_id: index as u64 + 1,
            end_vertex_id: (curve_count + index) as u64 + 1,
            degenerate: false,
            name: None,
        });
    }

    let mut next_id = 1000u64;
    let mut faces = Vec::with_capacity(curve_count + 2);
    for index in 0..curve_count {
        let [start, end] = bottom[index].domain()?;
        let coedges = vec![
            CoedgeRecord {
                id: next_id,
                edge_id: bottom_edge_ids[index],
                forward: true,
                pcurve: parameter_line(start, 0.0, end, 0.0)?,
            },
            CoedgeRecord {
                id: next_id + 1,
                edge_id: vertical_edge_ids[(index + 1) % curve_count],
                forward: true,
                pcurve: parameter_line(end, 0.0, end, 1.0)?,
            },
            CoedgeRecord {
                id: next_id + 2,
                edge_id: top_edge_ids[index],
                forward: false,
                pcurve: parameter_line(end, 1.0, start, 1.0)?,
            },
            CoedgeRecord {
                id: next_id + 3,
                edge_id: vertical_edge_ids[index],
                forward: false,
                pcurve: parameter_line(start, 1.0, start, 0.0)?,
            },
        ];
        next_id += 4;
        let loop_id = next_id;
        next_id += 1;
        let face_id = next_id;
        next_id += 1;
        faces.push(FaceRecord {
            id: face_id,
            surface: skins[index].clone(),
            same_sense: true,
            loops: vec![LoopRecord {
                id: loop_id,
                coedges,
            }],
            name: None,
        });
    }
    if reversed_winding {
        // The winding normalization reversed the section curve order above.
        // Callers stamp side-face names by INPUT-curve order (the extrude
        // and revolve wall-naming permutation, loft edition) — emit side
        // faces in input order.
        faces.reverse();
    }
    faces.push(cap_face(
        bottom,
        &bottom_edge_ids,
        &first_frame,
        axis,
        false,
        &mut next_id,
    )?);
    faces.push(cap_face(
        top,
        &top_edge_ids,
        &last_frame,
        axis,
        true,
        &mut next_id,
    )?);
    let solid = BrepSolid {
        id: next_id + 1,
        vertices,
        edges,
        shells: vec![ShellRecord { id: next_id, faces }],
        genus: 0,
    };
    let issues = solid.validate();
    if issues.is_empty() {
        Ok(solid)
    } else {
        Err(format!(
            "Rust loft builder produced invalid topology: {issues:?}"
        ))
    }
}