vcad 0.1.0

Parametric CAD in Rust — CSG modeling with multi-format export
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
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
#![warn(missing_docs)]

//! vcad — Parametric CAD in Rust
//!
//! CSG modeling with multi-format export (STL, glTF, USD, DXF).
//!
//! # Example
//!
//! ```rust,no_run
//! use vcad::{centered_cube, Part};
//!
//! let cube = centered_cube("block", 20.0, 10.0, 5.0);
//! let hole = Part::cylinder("hole", 3.0, 10.0, 32).translate(0.0, 0.0, -2.5);
//! let result = cube.difference(&hole);
//! result.write_stl("block_with_hole.stl").unwrap();
//! ```

use manifold_rs::{Manifold, Mesh};
use nalgebra::Vector3;
use std::f64::consts::PI;
use thiserror::Error;

pub mod export;
pub mod step;

pub use export::{Material, Materials};

/// Errors returned by CAD operations.
#[derive(Error, Debug)]
pub enum CadError {
    /// An I/O error occurred during export.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// The geometry is empty (no vertices or triangles).
    #[error("Empty geometry")]
    EmptyGeometry,
}

/// A named part with geometry.
///
/// Parts are the primary building block in vcad. Create primitives with
/// [`Part::cube`], [`Part::cylinder`], [`Part::sphere`], etc., then combine
/// them with CSG operations ([`Part::union`], [`Part::difference`],
/// [`Part::intersection`]) or the operator shorthands (`+`, `-`, `&`).
pub struct Part {
    /// Human-readable name for this part (used in export filenames and scene graphs).
    pub name: String,
    manifold: Manifold,
}

impl Part {
    /// Create a new part with a name
    pub fn new(name: impl Into<String>, manifold: Manifold) -> Self {
        Self {
            name: name.into(),
            manifold,
        }
    }

    /// Create an empty part
    pub fn empty(name: impl Into<String>) -> Self {
        Self::new(name, Manifold::empty())
    }

    /// Create a cube/box centered at origin
    pub fn cube(name: impl Into<String>, x: f64, y: f64, z: f64) -> Self {
        let manifold = Manifold::cube(x, y, z);
        Self::new(name, manifold)
    }

    /// Create a cylinder along Z axis, centered at origin
    pub fn cylinder(name: impl Into<String>, radius: f64, height: f64, segments: u32) -> Self {
        let manifold = Manifold::cylinder(radius, radius, height, segments);
        Self::new(name, manifold)
    }

    /// Create a cone/tapered cylinder
    pub fn cone(
        name: impl Into<String>,
        radius_bottom: f64,
        radius_top: f64,
        height: f64,
        segments: u32,
    ) -> Self {
        let manifold = Manifold::cylinder(radius_bottom, radius_top, height, segments);
        Self::new(name, manifold)
    }

    /// Create a sphere centered at origin
    pub fn sphere(name: impl Into<String>, radius: f64, segments: u32) -> Self {
        let manifold = Manifold::sphere(radius, segments);
        Self::new(name, manifold)
    }

    /// Boolean difference (self - other)
    pub fn difference(&self, other: &Part) -> Self {
        Self::new(
            format!("{}-diff", self.name),
            self.manifold.difference(&other.manifold),
        )
    }

    /// Boolean union (self + other)
    pub fn union(&self, other: &Part) -> Self {
        Self::new(
            format!("{}-union", self.name),
            self.manifold.union(&other.manifold),
        )
    }

    /// Boolean intersection
    pub fn intersection(&self, other: &Part) -> Self {
        Self::new(
            format!("{}-intersect", self.name),
            self.manifold.intersection(&other.manifold),
        )
    }

    /// Translate the part
    pub fn translate(&self, x: f64, y: f64, z: f64) -> Self {
        Self::new(self.name.clone(), self.manifold.translate(x, y, z))
    }

    /// Translate by vector
    pub fn translate_vec(&self, v: Vector3<f64>) -> Self {
        self.translate(v.x, v.y, v.z)
    }

    /// Rotate the part (angles in degrees)
    pub fn rotate(&self, x_deg: f64, y_deg: f64, z_deg: f64) -> Self {
        Self::new(self.name.clone(), self.manifold.rotate(x_deg, y_deg, z_deg))
    }

    /// Scale the part
    pub fn scale(&self, x: f64, y: f64, z: f64) -> Self {
        Self::new(self.name.clone(), self.manifold.scale(x, y, z))
    }

    /// Uniform scale
    pub fn scale_uniform(&self, s: f64) -> Self {
        self.scale(s, s, s)
    }

    /// Check if geometry is empty
    pub fn is_empty(&self) -> bool {
        self.manifold.is_empty()
    }

    /// Get the mesh representation
    pub fn to_mesh(&self) -> Mesh {
        self.manifold.to_mesh()
    }

    /// Export to binary STL bytes (delegates to [`export::stl::to_stl_bytes`])
    pub fn to_stl(&self) -> Result<Vec<u8>, CadError> {
        export::stl::to_stl_bytes(self)
    }

    /// Write STL to file (delegates to [`export::stl::export_stl`])
    pub fn write_stl(&self, path: impl AsRef<std::path::Path>) -> Result<(), CadError> {
        export::stl::export_stl(self, path)
    }
}

/// Helper to create a centered cube (manifold cubes are corner-aligned by default)
pub fn centered_cube(name: impl Into<String>, x: f64, y: f64, z: f64) -> Part {
    Part::cube(name, x, y, z).translate(-x / 2.0, -y / 2.0, -z / 2.0)
}

/// Helper to create a centered cylinder
pub fn centered_cylinder(name: impl Into<String>, radius: f64, height: f64, segments: u32) -> Part {
    Part::cylinder(name, radius, height, segments).translate(0.0, 0.0, -height / 2.0)
}

/// Create a counterbore hole (through hole + larger shallow hole for bolt head)
pub fn counterbore_hole(
    through_diameter: f64,
    counterbore_diameter: f64,
    counterbore_depth: f64,
    total_depth: f64,
    segments: u32,
) -> Part {
    let through = Part::cylinder("through", through_diameter / 2.0, total_depth, segments);
    let counterbore = Part::cylinder(
        "counterbore",
        counterbore_diameter / 2.0,
        counterbore_depth,
        segments,
    )
    .translate(0.0, 0.0, total_depth - counterbore_depth);
    through.union(&counterbore)
}

/// Create a bolt pattern (circle of holes)
pub fn bolt_pattern(
    num_holes: usize,
    bolt_circle_diameter: f64,
    hole_diameter: f64,
    depth: f64,
    segments: u32,
) -> Part {
    let radius = bolt_circle_diameter / 2.0;
    let mut result = Part::empty("bolt_pattern");

    for i in 0..num_holes {
        let angle = 2.0 * PI * (i as f64) / (num_holes as f64);
        let x = radius * angle.cos();
        let y = radius * angle.sin();
        let hole =
            Part::cylinder("hole", hole_diameter / 2.0, depth, segments).translate(x, y, 0.0);
        result = result.union(&hole);
    }

    result
}

// =============================================================================
// Operator overloads for ergonomic CSG
// =============================================================================

/// Union: `&a + &b`
impl std::ops::Add for &Part {
    type Output = Part;
    fn add(self, rhs: &Part) -> Part {
        self.union(rhs)
    }
}

/// Union: `a + b`
impl std::ops::Add for Part {
    type Output = Part;
    fn add(self, rhs: Part) -> Part {
        self.union(&rhs)
    }
}

/// Difference: `&a - &b`
impl std::ops::Sub for &Part {
    type Output = Part;
    fn sub(self, rhs: &Part) -> Part {
        self.difference(rhs)
    }
}

/// Difference: `a - b`
impl std::ops::Sub for Part {
    type Output = Part;
    fn sub(self, rhs: Part) -> Part {
        self.difference(&rhs)
    }
}

/// Intersection: `&a & &b`
impl std::ops::BitAnd for &Part {
    type Output = Part;
    fn bitand(self, rhs: &Part) -> Part {
        self.intersection(rhs)
    }
}

/// Intersection: `a & b`
impl std::ops::BitAnd for Part {
    type Output = Part;
    fn bitand(self, rhs: Part) -> Part {
        self.intersection(&rhs)
    }
}

// =============================================================================
// Mesh inspection
// =============================================================================

impl Part {
    /// Signed volume of the mesh (uses the divergence theorem).
    ///
    /// Returns a positive value for well-formed manifold meshes.
    pub fn volume(&self) -> f64 {
        let mesh = self.manifold.to_mesh();
        let verts = mesh.vertices();
        let indices = mesh.indices();
        let mut vol = 0.0;
        for tri in indices.chunks(3) {
            let (i0, i1, i2) = (
                tri[0] as usize * 3,
                tri[1] as usize * 3,
                tri[2] as usize * 3,
            );
            let v0 = [verts[i0] as f64, verts[i0 + 1] as f64, verts[i0 + 2] as f64];
            let v1 = [verts[i1] as f64, verts[i1 + 1] as f64, verts[i1 + 2] as f64];
            let v2 = [verts[i2] as f64, verts[i2 + 1] as f64, verts[i2 + 2] as f64];
            // Signed volume of tetrahedron formed with origin
            vol += v0[0] * (v1[1] * v2[2] - v2[1] * v1[2])
                - v1[0] * (v0[1] * v2[2] - v2[1] * v0[2])
                + v2[0] * (v0[1] * v1[2] - v1[1] * v0[2]);
        }
        (vol / 6.0).abs()
    }

    /// Total surface area of the mesh.
    pub fn surface_area(&self) -> f64 {
        let mesh = self.manifold.to_mesh();
        let verts = mesh.vertices();
        let indices = mesh.indices();
        let mut area = 0.0;
        for tri in indices.chunks(3) {
            let (i0, i1, i2) = (
                tri[0] as usize * 3,
                tri[1] as usize * 3,
                tri[2] as usize * 3,
            );
            let v0 = Vector3::new(verts[i0] as f64, verts[i0 + 1] as f64, verts[i0 + 2] as f64);
            let v1 = Vector3::new(verts[i1] as f64, verts[i1 + 1] as f64, verts[i1 + 2] as f64);
            let v2 = Vector3::new(verts[i2] as f64, verts[i2 + 1] as f64, verts[i2 + 2] as f64);
            area += (v1 - v0).cross(&(v2 - v0)).norm() / 2.0;
        }
        area
    }

    /// Axis-aligned bounding box as `(min, max)`.
    pub fn bounding_box(&self) -> ([f64; 3], [f64; 3]) {
        let mesh = self.manifold.to_mesh();
        let verts = mesh.vertices();
        let mut min = [f64::MAX; 3];
        let mut max = [f64::MIN; 3];
        for chunk in verts.chunks(3) {
            for i in 0..3 {
                let v = chunk[i] as f64;
                if v < min[i] {
                    min[i] = v;
                }
                if v > max[i] {
                    max[i] = v;
                }
            }
        }
        (min, max)
    }

    /// Geometric centroid (volume-weighted center of mass assuming uniform density).
    pub fn center_of_mass(&self) -> [f64; 3] {
        let mesh = self.manifold.to_mesh();
        let verts = mesh.vertices();
        let indices = mesh.indices();
        let mut cx = 0.0;
        let mut cy = 0.0;
        let mut cz = 0.0;
        let mut total_vol = 0.0;
        for tri in indices.chunks(3) {
            let (i0, i1, i2) = (
                tri[0] as usize * 3,
                tri[1] as usize * 3,
                tri[2] as usize * 3,
            );
            let v0 = [verts[i0] as f64, verts[i0 + 1] as f64, verts[i0 + 2] as f64];
            let v1 = [verts[i1] as f64, verts[i1 + 1] as f64, verts[i1 + 2] as f64];
            let v2 = [verts[i2] as f64, verts[i2 + 1] as f64, verts[i2 + 2] as f64];
            let vol = v0[0] * (v1[1] * v2[2] - v2[1] * v1[2])
                - v1[0] * (v0[1] * v2[2] - v2[1] * v0[2])
                + v2[0] * (v0[1] * v1[2] - v1[1] * v0[2]);
            total_vol += vol;
            cx += vol * (v0[0] + v1[0] + v2[0]);
            cy += vol * (v0[1] + v1[1] + v2[1]);
            cz += vol * (v0[2] + v1[2] + v2[2]);
        }
        if total_vol.abs() < 1e-15 {
            return [0.0; 3];
        }
        let s = 1.0 / (4.0 * total_vol);
        [cx * s, cy * s, cz * s]
    }

    /// Number of triangles in the mesh.
    pub fn num_triangles(&self) -> usize {
        let mesh = self.manifold.to_mesh();
        mesh.indices().len() / 3
    }
}

// =============================================================================
// Mirror and pattern transforms
// =============================================================================

impl Part {
    /// Mirror across the YZ plane (negate X).
    pub fn mirror_x(&self) -> Part {
        self.scale(-1.0, 1.0, 1.0)
    }

    /// Mirror across the XZ plane (negate Y).
    pub fn mirror_y(&self) -> Part {
        self.scale(1.0, -1.0, 1.0)
    }

    /// Mirror across the XY plane (negate Z).
    pub fn mirror_z(&self) -> Part {
        self.scale(1.0, 1.0, -1.0)
    }

    /// Union of `count` copies spaced by `(dx, dy, dz)`.
    ///
    /// The first copy is at the original position; each subsequent copy
    /// is offset by an additional `(dx, dy, dz)`.
    pub fn linear_pattern(&self, dx: f64, dy: f64, dz: f64, count: usize) -> Part {
        let mut result = self.translate(0.0, 0.0, 0.0); // clone
        for i in 1..count {
            let n = i as f64;
            result = result.union(&self.translate(dx * n, dy * n, dz * n));
        }
        result
    }

    /// Union of `count` copies rotated evenly around the Z axis.
    ///
    /// Each copy is rotated by `360° / count` increments. An optional
    /// `radius` translates each copy outward along X before rotating.
    pub fn circular_pattern(&self, radius: f64, count: usize) -> Part {
        let mut result = Part::empty("circular_pattern");
        for i in 0..count {
            let angle = 360.0 * (i as f64) / (count as f64);
            let copy = self.translate(radius, 0.0, 0.0).rotate(0.0, 0.0, angle);
            result = result.union(&copy);
        }
        result
    }
}

// =============================================================================
// Scene (multi-part assembly with materials)
// =============================================================================

/// A scene node containing a part with its material assignment.
pub struct SceneNode {
    /// The geometry for this node.
    pub part: Part,
    /// Key into the [`Materials`] database for this node's material.
    pub material_key: String,
}

impl SceneNode {
    /// Create a new scene node with a part and material key.
    pub fn new(part: Part, material_key: impl Into<String>) -> Self {
        Self {
            part,
            material_key: material_key.into(),
        }
    }
}

/// A scene containing multiple parts with different materials
///
/// Unlike Part.union() which merges geometry into a single mesh,
/// Scene preserves individual parts for multi-material rendering.
pub struct Scene {
    /// Name of the scene (used as root node name in exports).
    pub name: String,
    /// Ordered list of parts with their material assignments.
    pub nodes: Vec<SceneNode>,
}

impl Scene {
    /// Create a new empty scene.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            nodes: Vec::new(),
        }
    }

    /// Add a part with its material key
    pub fn add(&mut self, part: Part, material_key: impl Into<String>) {
        self.nodes.push(SceneNode::new(part, material_key));
    }

    /// Add a part with default material
    pub fn add_default(&mut self, part: Part) {
        self.nodes.push(SceneNode::new(part, "default"));
    }

    /// Get total number of nodes
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Check if scene is empty
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cube_creation() {
        let cube = Part::cube("test", 10.0, 10.0, 10.0);
        assert!(!cube.is_empty());
    }

    #[test]
    fn test_cylinder_creation() {
        let cyl = Part::cylinder("test", 5.0, 10.0, 32);
        assert!(!cyl.is_empty());
    }

    #[test]
    fn test_difference() {
        let cube = Part::cube("cube", 10.0, 10.0, 10.0);
        let hole = Part::cylinder("hole", 3.0, 15.0, 32).translate(5.0, 5.0, -1.0);
        let result = cube.difference(&hole);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_operator_overloads() {
        let a = Part::cube("a", 10.0, 10.0, 10.0);
        let b = Part::cube("b", 10.0, 10.0, 10.0).translate(5.0, 0.0, 0.0);

        // Owned operators
        let union = Part::cube("a", 10.0, 10.0, 10.0) + Part::cube("b", 10.0, 10.0, 10.0);
        assert!(!union.is_empty());

        let diff = Part::cube("a", 10.0, 10.0, 10.0)
            - Part::cube("b", 5.0, 5.0, 5.0).translate(2.5, 2.5, 2.5);
        assert!(!diff.is_empty());

        let isect = Part::cube("a", 10.0, 10.0, 10.0)
            & Part::cube("b", 10.0, 10.0, 10.0).translate(5.0, 5.0, 5.0);
        assert!(!isect.is_empty());

        // Reference operators
        let union_ref = &a + &b;
        assert!(!union_ref.is_empty());

        let diff_ref = &a - &b;
        assert!(!diff_ref.is_empty());

        let isect_ref = &a & &b;
        assert!(!isect_ref.is_empty());
    }

    #[test]
    fn test_volume() {
        let cube = Part::cube("cube", 10.0, 10.0, 10.0);
        let vol = cube.volume();
        assert!((vol - 1000.0).abs() < 1.0, "expected ~1000, got {vol}");
    }

    #[test]
    fn test_surface_area() {
        let cube = Part::cube("cube", 10.0, 10.0, 10.0);
        let area = cube.surface_area();
        assert!((area - 600.0).abs() < 1.0, "expected ~600, got {area}");
    }

    #[test]
    fn test_bounding_box() {
        let cube = Part::cube("cube", 10.0, 20.0, 30.0);
        let (min, max) = cube.bounding_box();
        assert!((max[0] - min[0] - 10.0).abs() < 0.01);
        assert!((max[1] - min[1] - 20.0).abs() < 0.01);
        assert!((max[2] - min[2] - 30.0).abs() < 0.01);
    }

    #[test]
    fn test_center_of_mass() {
        // Cube at origin should have centroid at (5,5,5) since manifold cubes are corner-aligned
        let cube = Part::cube("cube", 10.0, 10.0, 10.0);
        let com = cube.center_of_mass();
        assert!((com[0] - 5.0).abs() < 0.1, "cx: {}", com[0]);
        assert!((com[1] - 5.0).abs() < 0.1, "cy: {}", com[1]);
        assert!((com[2] - 5.0).abs() < 0.1, "cz: {}", com[2]);
    }

    #[test]
    fn test_num_triangles() {
        let cube = Part::cube("cube", 10.0, 10.0, 10.0);
        assert!(
            cube.num_triangles() >= 12,
            "cube should have at least 12 triangles"
        );
    }

    #[test]
    fn test_mirror() {
        let cube = Part::cube("cube", 10.0, 10.0, 10.0).translate(5.0, 0.0, 0.0);
        let mirrored = cube.mirror_x();
        let (min, _max) = mirrored.bounding_box();
        // Original is at x=[5,15], mirrored should be at x=[-15,-5]
        assert!(
            min[0] < 0.0,
            "mirrored min x should be negative: {}",
            min[0]
        );
    }

    #[test]
    fn test_linear_pattern() {
        let cube = Part::cube("cube", 5.0, 5.0, 5.0);
        let pattern = cube.linear_pattern(10.0, 0.0, 0.0, 3);
        let (min, max) = pattern.bounding_box();
        // 3 copies at x=0, x=10, x=20 each 5 wide → spans 0..25
        assert!((max[0] - min[0] - 25.0).abs() < 0.1);
    }

    #[test]
    fn test_circular_pattern() {
        let cube = Part::cube("cube", 2.0, 2.0, 2.0);
        let pattern = cube.circular_pattern(10.0, 4);
        assert!(!pattern.is_empty());
        // Should span roughly -12..12 in both X and Y
        let (min, max) = pattern.bounding_box();
        assert!(max[0] > 10.0);
        assert!(min[0] < -10.0 + 2.0); // at least close to -10
    }
}