csgrs 0.20.1

Constructive solid geometry (CSG) on meshes using BSP trees in Rust
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
use crate::float_types::Real;
use crate::mesh::Mesh;
use crate::mesh::polygon::Polygon;
use crate::mesh::vertex::Vertex;
use crate::sketch::Sketch;

use geo::CoordsIter;
use nalgebra::{Point3, Vector3};
use std::fmt::Debug;

#[cfg(any(feature = "stl-io", feature = "dxf-io"))]
use core2::io::Cursor;

#[cfg(feature = "stl-io")]
use stl_io;

impl<S: Clone + Debug + Send + Sync> Mesh<S> {
    /// Export to ASCII STL
    /// Convert this Mesh to an **ASCII STL** string with the given `name`.
    ///
    /// ```rust
    /// # use csgrs::mesh::Mesh;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let mesh  = Mesh::<()>::cube(1.0, None);
    /// let bytes = mesh.to_stl_ascii("my_solid");
    /// std::fs::write("stl/my_solid.stl", bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_stl_ascii(&self, name: &str) -> String {
        let mut out = String::new();
        out.push_str(&format!("solid {name}\n"));

        // Write out all *3D* polygons
        for poly in &self.polygons {
            // Ensure the polygon is tessellated, since STL is triangle-based.
            let triangles = poly.triangulate();
            // A typical STL uses the face normal; we can take the polygon's plane normal:
            let normal = poly.plane.normal().normalize();
            for tri in triangles {
                out.push_str(&format!(
                    "  facet normal {:.6} {:.6} {:.6}\n",
                    normal.x, normal.y, normal.z
                ));
                out.push_str("    outer loop\n");
                for vertex in &tri {
                    out.push_str(&format!(
                        "      vertex {:.6} {:.6} {:.6}\n",
                        vertex.pos.x, vertex.pos.y, vertex.pos.z
                    ));
                }
                out.push_str("    endloop\n");
                out.push_str("  endfacet\n");
            }
        }

        out.push_str(&format!("endsolid {name}\n"));
        out
    }

    /// Export to BINARY STL (returns `Vec<u8>`)
    ///
    /// Convert this Mesh to a **binary STL** byte vector with the given `name`.
    ///
    /// The resulting `Vec<u8>` can then be written to a file or handled in memory:
    ///
    /// ```rust
    /// # use csgrs::mesh::Mesh;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let object = Mesh::<()>::cube(1.0, None);
    /// let bytes  = object.to_stl_binary("my_solid")?;
    /// std::fs::write("stl/my_solid.stl", bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "stl-io")]
    pub fn to_stl_binary(&self, _name: &str) -> std::io::Result<Vec<u8>> {
        use core2::io::Cursor;
        use stl_io::{Normal, Triangle, Vertex, write_stl};

        let mut triangles = Vec::new();

        // Triangulate all 3D polygons in self.polygons
        for poly in &self.polygons {
            let normal = poly.plane.normal().normalize();
            // Convert polygon to triangles
            let tri_list = poly.triangulate();
            #[allow(clippy::unnecessary_cast)]
            for tri in tri_list {
                triangles.push(Triangle {
                    normal: Normal::new([normal.x as f32, normal.y as f32, normal.z as f32]),
                    vertices: [
                        Vertex::new([
                            tri[0].pos.x as f32,
                            tri[0].pos.y as f32,
                            tri[0].pos.z as f32,
                        ]),
                        Vertex::new([
                            tri[1].pos.x as f32,
                            tri[1].pos.y as f32,
                            tri[1].pos.z as f32,
                        ]),
                        Vertex::new([
                            tri[2].pos.x as f32,
                            tri[2].pos.y as f32,
                            tri[2].pos.z as f32,
                        ]),
                    ],
                });
            }
        }

        // Encode into a binary STL buffer
        let mut cursor = Cursor::new(Vec::new());
        write_stl(&mut cursor, triangles.iter())?;
        Ok(cursor.into_inner())
    }

    /// Create a Mesh object from STL data using 'stl_io'.
    #[cfg(feature = "stl-io")]
    pub fn from_stl(stl_data: &[u8], metadata: Option<S>) -> Result<Mesh<S>, std::io::Error> {
        // Create an in-memory cursor from the STL data
        let mut cursor = Cursor::new(stl_data);

        // Create an STL reader from the cursor
        let stl_reader = stl_io::create_stl_reader(&mut cursor)?;

        let mut polygons = Vec::new();

        for tri_result in stl_reader {
            // Handle potential errors from the STL reader
            let tri = tri_result?;

            // Construct vertices and a polygon
            let vertices = vec![
                Vertex::new(
                    Point3::new(
                        tri.vertices[0][0] as Real,
                        tri.vertices[0][1] as Real,
                        tri.vertices[0][2] as Real,
                    ),
                    Vector3::new(
                        tri.normal[0] as Real,
                        tri.normal[1] as Real,
                        tri.normal[2] as Real,
                    ),
                ),
                Vertex::new(
                    Point3::new(
                        tri.vertices[1][0] as Real,
                        tri.vertices[1][1] as Real,
                        tri.vertices[1][2] as Real,
                    ),
                    Vector3::new(
                        tri.normal[0] as Real,
                        tri.normal[1] as Real,
                        tri.normal[2] as Real,
                    ),
                ),
                Vertex::new(
                    Point3::new(
                        tri.vertices[2][0] as Real,
                        tri.vertices[2][1] as Real,
                        tri.vertices[2][2] as Real,
                    ),
                    Vector3::new(
                        tri.normal[0] as Real,
                        tri.normal[1] as Real,
                        tri.normal[2] as Real,
                    ),
                ),
            ];
            polygons.push(Polygon::new(vertices, metadata.clone()));
        }

        Ok(Mesh::from_polygons(&polygons, metadata))
    }
}

impl<S: Clone + Debug + Send + Sync> Sketch<S> {
    /// Export to ASCII STL
    /// Convert this Sketch to an **ASCII STL** string with the given 'name'.
    ///
    /// ```
    /// # use csgrs::sketch::Sketch;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let sketch: Sketch<()> = Sketch::square(2.0, None);
    /// let bytes = sketch.to_stl_ascii("my_sketch");
    /// std::fs::write("stl/my_sketch.stl", bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_stl_ascii(&self, name: &str) -> String {
        let mut out = String::new();
        out.push_str(&format!("solid {name}\n"));

        // Write out all *2D* geometry from `self.geometry`
        // We only handle Polygon and MultiPolygon.  We tessellate in XY, set z=0.
        for geom in &self.geometry {
            match geom {
                geo::Geometry::Polygon(poly2d) => {
                    // Outer ring (in CCW for a typical "positive" polygon)
                    let outer = poly2d
                        .exterior()
                        .coords_iter()
                        .map(|c| [c.x, c.y])
                        .collect::<Vec<[Real; 2]>>();

                    // Collect holes
                    let holes_vec = poly2d
                        .interiors()
                        .iter()
                        .map(|ring| ring.coords_iter().map(|c| [c.x, c.y]).collect::<Vec<_>>())
                        .collect::<Vec<_>>();
                    let hole_refs = holes_vec
                        .iter()
                        .map(|hole_coords| &hole_coords[..])
                        .collect::<Vec<_>>();

                    // Triangulate with our existing helper:
                    let triangles_2d = Sketch::<()>::triangulate_2d(&outer, &hole_refs);

                    // Write each tri as a facet in ASCII STL, with a normal of (0,0,1)
                    for tri in triangles_2d {
                        out.push_str("  facet normal 0.000000 0.000000 1.000000\n");
                        out.push_str("    outer loop\n");
                        for pt in &tri {
                            out.push_str(&format!(
                                "      vertex {:.6} {:.6} {:.6}\n",
                                pt.x, pt.y, pt.z
                            ));
                        }
                        out.push_str("    endloop\n");
                        out.push_str("  endfacet\n");
                    }
                },

                geo::Geometry::MultiPolygon(mp) => {
                    // Each polygon inside the MultiPolygon
                    for poly2d in &mp.0 {
                        let outer = poly2d
                            .exterior()
                            .coords_iter()
                            .map(|c| [c.x, c.y])
                            .collect::<Vec<[Real; 2]>>();

                        // Holes
                        let holes_vec = poly2d
                            .interiors()
                            .iter()
                            .map(|ring| {
                                ring.coords_iter().map(|c| [c.x, c.y]).collect::<Vec<_>>()
                            })
                            .collect::<Vec<_>>();
                        let hole_refs = holes_vec
                            .iter()
                            .map(|hole_coords| &hole_coords[..])
                            .collect::<Vec<_>>();

                        let triangles_2d = Sketch::<()>::triangulate_2d(&outer, &hole_refs);

                        for tri in triangles_2d {
                            out.push_str("  facet normal 0.000000 0.000000 1.000000\n");
                            out.push_str("    outer loop\n");
                            for pt in &tri {
                                out.push_str(&format!(
                                    "      vertex {:.6} {:.6} {:.6}\n",
                                    pt.x, pt.y, pt.z
                                ));
                            }
                            out.push_str("    endloop\n");
                            out.push_str("  endfacet\n");
                        }
                    }
                },

                // Skip all other geometry types (LineString, Point, etc.)
                // You can optionally handle them if you like, or ignore them.
                _ => {},
            }
        }

        out.push_str(&format!("endsolid {name}\n"));
        out
    }

    /// Export to BINARY STL (returns `Vec<u8>`)
    ///
    /// Convert this Sketch to a **binary STL** byte vector with the given 'name'.
    ///
    /// The resulting `Vec<u8>` can then be written to a file or handled in memory:
    ///
    /// ```rust
    /// # use csgrs::sketch::Sketch;
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// let object = Sketch::<()>::square(1.0, None);
    /// let bytes  = object.to_stl_binary("my_sketch")?;
    /// std::fs::write("stl/my_sketch.stl", bytes)?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "stl-io")]
    pub fn to_stl_binary(&self, _name: &str) -> std::io::Result<Vec<u8>> {
        use core2::io::Cursor;
        use stl_io::{Normal, Triangle, Vertex, write_stl};

        let mut triangles = Vec::new();

        // Triangulate any 2D geometry from self.geometry (Polygon, MultiPolygon).
        // We treat these as lying in the XY plane, at Z=0, with a default normal of +Z.
        for geom in &self.geometry {
            match geom {
                geo::Geometry::Polygon(poly2d) => {
                    // Gather outer ring as [x,y]
                    let outer: Vec<[Real; 2]> =
                        poly2d.exterior().coords_iter().map(|c| [c.x, c.y]).collect();

                    // Gather holes
                    let holes_vec: Vec<Vec<[Real; 2]>> = poly2d
                        .interiors()
                        .iter()
                        .map(|ring| ring.coords_iter().map(|c| [c.x, c.y]).collect())
                        .collect();

                    // Convert each hole to a slice-reference for triangulation
                    let hole_refs: Vec<&[[Real; 2]]> =
                        holes_vec.iter().map(|h| &h[..]).collect();

                    // Triangulate using our geo-based helper
                    let tri_2d = Sketch::<()>::triangulate_2d(&outer, &hole_refs);

                    // Each triangle is in XY, so normal = (0,0,1)
                    #[allow(clippy::unnecessary_cast)]
                    for tri_pts in tri_2d {
                        triangles.push(Triangle {
                            normal: Normal::new([0.0, 0.0, 1.0]),
                            vertices: [
                                Vertex::new([
                                    tri_pts[0].x as f32,
                                    tri_pts[0].y as f32,
                                    tri_pts[0].z as f32,
                                ]),
                                Vertex::new([
                                    tri_pts[1].x as f32,
                                    tri_pts[1].y as f32,
                                    tri_pts[1].z as f32,
                                ]),
                                Vertex::new([
                                    tri_pts[2].x as f32,
                                    tri_pts[2].y as f32,
                                    tri_pts[2].z as f32,
                                ]),
                            ],
                        });
                    }
                },

                geo::Geometry::MultiPolygon(mpoly) => {
                    // Same approach, but each Polygon in the MultiPolygon
                    for poly2d in &mpoly.0 {
                        let outer: Vec<[Real; 2]> =
                            poly2d.exterior().coords_iter().map(|c| [c.x, c.y]).collect();

                        let holes_vec: Vec<Vec<[Real; 2]>> = poly2d
                            .interiors()
                            .iter()
                            .map(|ring| ring.coords_iter().map(|c| [c.x, c.y]).collect())
                            .collect();

                        let hole_refs: Vec<&[[Real; 2]]> =
                            holes_vec.iter().map(|h| &h[..]).collect();
                        let tri_2d = Sketch::<()>::triangulate_2d(&outer, &hole_refs);

                        #[allow(clippy::unnecessary_cast)]
                        for tri_pts in tri_2d {
                            triangles.push(Triangle {
                                normal: Normal::new([0.0, 0.0, 1.0]),
                                vertices: [
                                    Vertex::new([
                                        tri_pts[0].x as f32,
                                        tri_pts[0].y as f32,
                                        tri_pts[0].z as f32,
                                    ]),
                                    Vertex::new([
                                        tri_pts[1].x as f32,
                                        tri_pts[1].y as f32,
                                        tri_pts[1].z as f32,
                                    ]),
                                    Vertex::new([
                                        tri_pts[2].x as f32,
                                        tri_pts[2].y as f32,
                                        tri_pts[2].z as f32,
                                    ]),
                                ],
                            });
                        }
                    }
                },

                // Skip other geometry types: lines, points, etc.
                _ => {},
            }
        }

        //
        // (C) Encode into a binary STL buffer
        //
        let mut cursor = Cursor::new(Vec::new());
        write_stl(&mut cursor, triangles.iter())?;
        Ok(cursor.into_inner())
    }
}