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
//! OBJ file format support for Mesh objects
//!
//! This module provides import and export functionality for Wavefront OBJ files,
//! a widely-supported 3D file format used by many modeling and rendering applications.
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;
use std::io::{BufRead, Write};
impl<S: Clone + Debug + Send + Sync> Mesh<S> {
/// Export this Mesh to OBJ format as a string
///
/// Creates a Wavefront OBJ file containing:
/// 1. All 3D polygons from `self.polygons` (tessellated to triangles)
/// 2. Any 2D geometry from `self.geometry` (extruded/projected to 3D)
///
/// # Arguments
/// * `object_name` - Name for the object in the OBJ file
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let obj_content = csg.to_obj("my_cube");
/// println!("{}", obj_content);
/// ```
pub fn to_obj(&self, object_name: &str) -> String {
let mut obj_content = String::new();
// OBJ header
obj_content.push_str("# Generated by csgrs library\n");
obj_content.push_str(&format!("# Object: {object_name}\n"));
obj_content.push_str("# https://github.com/timschmidt/csgrs\n\n");
obj_content.push_str(&format!("o {object_name}\n\n"));
let mut vertices = Vec::new();
let mut normals = Vec::new();
let mut faces = Vec::new();
// Process 3D polygons
for poly in &self.polygons {
// Tessellate polygon to triangles
let triangles = poly.triangulate();
let normal = poly.plane.normal().normalize();
for triangle in triangles {
let mut face_indices = Vec::new();
let normal_idx = add_unique_normal(&mut normals, normal);
for vertex in triangle {
let vertex_idx = add_unique_vertex(&mut vertices, vertex.pos);
face_indices.push((vertex_idx, normal_idx));
}
if face_indices.len() == 3 {
faces.push(face_indices);
}
}
}
// Write vertices
for vertex in &vertices {
obj_content.push_str(&format!(
"v {:.6} {:.6} {:.6}\n",
vertex.x, vertex.y, vertex.z
));
}
obj_content.push('\n');
// Write normals
for normal in &normals {
obj_content.push_str(&format!(
"vn {:.6} {:.6} {:.6}\n",
normal.x, normal.y, normal.z
));
}
obj_content.push('\n');
// Write faces (1-indexed in OBJ format)
for face in &faces {
#[allow(clippy::single_char_add_str)]
obj_content.push_str("f");
for (vertex_idx, normal_idx) in face {
obj_content.push_str(&format!(" {}//{}", vertex_idx + 1, normal_idx + 1));
}
obj_content.push('\n');
}
obj_content
}
/// Export this Mesh to an OBJ file
///
/// # Arguments
/// * `writer` - Where to write the OBJ data
/// * `object_name` - Name for the object in the OBJ file
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// use std::fs::File;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let mut file = File::create("stl/output.obj")?;
/// csg.write_obj(&mut file, "my_cube")?;
/// # Ok(())
/// # }
/// ```
pub fn write_obj<W: Write>(
&self,
writer: &mut W,
object_name: &str,
) -> std::io::Result<()> {
let obj_content = self.to_obj(object_name);
writer.write_all(obj_content.as_bytes())
}
/// Import a Mesh from OBJ file data
///
/// # Arguments
/// * `reader` - Source of OBJ data
/// * `metadata` - Optional metadata to attach to all polygons
///
/// # Example
/// ```no_run
/// use csgrs::mesh::Mesh;
/// use std::fs::File;
/// use std::io::BufReader;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let file = File::open("input.obj")?;
/// let reader = BufReader::new(file);
/// let csg: Mesh<()> = Mesh::from_obj(reader, None)?;
/// # Ok(())
/// # }
/// ```
pub fn from_obj<R: BufRead>(reader: R, metadata: Option<S>) -> std::io::Result<Mesh<S>> {
let mut vertices = Vec::new();
let mut normals = Vec::new();
let mut polygons = Vec::new();
for line_result in reader.lines() {
let line = line_result?;
let line = line.trim();
// Skip comments and empty lines
if line.is_empty() || line.starts_with('#') {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.is_empty() {
continue;
}
match parts[0] {
"v" => {
// Vertex: v x y z
if parts.len() >= 4 {
let x: Real = parts[1].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid vertex x coordinate: {e}"),
)
})?;
let y: Real = parts[2].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid vertex y coordinate: {e}"),
)
})?;
let z: Real = parts[3].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid vertex z coordinate: {e}"),
)
})?;
vertices.push(Point3::new(x, y, z));
}
},
"vn" => {
// Normal: vn x y z
if parts.len() >= 4 {
let x: Real = parts[1].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid normal x coordinate: {e}"),
)
})?;
let y: Real = parts[2].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid normal y coordinate: {e}"),
)
})?;
let z: Real = parts[3].parse().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid normal z coordinate: {e}"),
)
})?;
normals.push(Vector3::new(x, y, z));
}
},
"f" => {
// Face: f v1//n1 v2//n2 v3//n3 or f v1/vt1/n1 v2/vt2/n2 v3/vt3/n3
if parts.len() >= 4 {
let face_vertices =
Self::parse_obj_face(&parts[1..], &vertices, &normals)?;
if face_vertices.len() >= 3 {
// Convert to triangles if more than 3 vertices
for i in 1..face_vertices.len() - 1 {
let triangle = vec![
face_vertices[0].clone(),
face_vertices[i].clone(),
face_vertices[i + 1].clone(),
];
polygons.push(Polygon::new(triangle, metadata.clone()));
}
}
}
},
_ => {
// Ignore other OBJ elements (materials, groups, etc.)
},
}
}
Ok(Mesh::from_polygons(&polygons, metadata))
}
// Helper function to parse OBJ face definitions
fn parse_obj_face(
face_parts: &[&str],
vertices: &[Point3<Real>],
normals: &[Vector3<Real>],
) -> std::io::Result<Vec<Vertex>> {
let mut face_vertices = Vec::new();
for part in face_parts {
// Parse face element: vertex_idx[/texture_idx][/normal_idx]
let indices: Vec<&str> = part.split('/').collect();
// Get vertex index (1-based in OBJ, convert to 0-based)
let vertex_idx: usize = indices[0].parse::<usize>().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid vertex index: {e}"),
)
})? - 1;
if vertex_idx >= vertices.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Vertex index {} out of range", vertex_idx + 1),
));
}
let position = vertices[vertex_idx];
// Get normal (if available)
let normal = if indices.len() >= 3 && !indices[2].is_empty() {
let normal_idx: usize = indices[2].parse::<usize>().map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Invalid normal index: {e}"),
)
})? - 1;
if normal_idx >= normals.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("Normal index {} out of range", normal_idx + 1),
));
}
normals[normal_idx]
} else {
// Calculate normal from face if not provided
Vector3::new(0.0, 0.0, 1.0) // Default up vector
};
face_vertices.push(Vertex::new(position, normal));
}
Ok(face_vertices)
}
}
impl<S: Clone + Debug + Send + Sync> Sketch<S> {
/// Export this Mesh to OBJ format as a string
///
/// Creates a Wavefront OBJ file containing:
/// 1. All 3D polygons from `self.polygons` (tessellated to triangles)
/// 2. Any 2D geometry from `self.geometry` (extruded/projected to 3D)
///
/// # Arguments
/// * `object_name` - Name for the object in the OBJ file
///
/// # Example
/// ```
/// use csgrs::mesh::Mesh;
/// let csg: Mesh<()> = Mesh::cube(10.0, None);
/// let obj_content = csg.to_obj("my_cube");
/// println!("{}", obj_content);
/// ```
pub fn to_obj(&self, object_name: &str) -> String {
let mut obj_content = String::new();
// OBJ header
obj_content.push_str("# Generated by csgrs library\n");
obj_content.push_str(&format!("# Object: {object_name}\n"));
obj_content.push_str("# https://github.com/timschmidt/csgrs\n\n");
obj_content.push_str(&format!("o {object_name}\n\n"));
let mut vertices = Vec::new();
let mut normals = Vec::new();
let mut faces = Vec::new();
// Process 2D geometry (project to XY plane at Z=0)
for geom in &self.geometry.0 {
match geom {
geo::Geometry::Polygon(poly2d) => {
self.add_2d_polygon_to_obj(
poly2d,
&mut vertices,
&mut normals,
&mut faces,
);
},
geo::Geometry::MultiPolygon(mp) => {
for poly2d in &mp.0 {
self.add_2d_polygon_to_obj(
poly2d,
&mut vertices,
&mut normals,
&mut faces,
);
}
},
_ => {}, // Skip other geometry types
}
}
// Write vertices
for vertex in &vertices {
obj_content.push_str(&format!(
"v {:.6} {:.6} {:.6}\n",
vertex.x, vertex.y, vertex.z
));
}
obj_content.push('\n');
// Write normals
for normal in &normals {
obj_content.push_str(&format!(
"vn {:.6} {:.6} {:.6}\n",
normal.x, normal.y, normal.z
));
}
obj_content.push('\n');
// Write faces (1-indexed in OBJ format)
for face in &faces {
#[allow(clippy::single_char_add_str)]
obj_content.push_str("f");
for (vertex_idx, normal_idx) in face {
obj_content.push_str(&format!(" {}//{}", vertex_idx + 1, normal_idx + 1));
}
obj_content.push('\n');
}
obj_content
}
// Helper function to add 2D polygon to OBJ data
fn add_2d_polygon_to_obj(
&self,
poly2d: &geo::Polygon<Real>,
vertices: &mut Vec<Point3<Real>>,
normals: &mut Vec<Vector3<Real>>,
faces: &mut Vec<Vec<(usize, usize)>>,
) {
// Get the exterior ring
let exterior: Vec<[Real; 2]> =
poly2d.exterior().coords_iter().map(|c| [c.x, c.y]).collect();
// Get holes
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();
// Tessellate the 2D polygon
let triangles_2d = Self::triangulate_2d(&exterior, &hole_refs);
// Add triangles with normal pointing up (positive Z)
let normal = Vector3::new(0.0, 0.0, 1.0);
let normal_idx = add_unique_normal(normals, normal);
for triangle in triangles_2d {
let mut face_indices = Vec::new();
for point in triangle {
let vertex_3d = Point3::new(point.x, point.y, point.z);
let vertex_idx = add_unique_vertex(vertices, vertex_3d);
face_indices.push((vertex_idx, normal_idx));
}
if face_indices.len() == 3 {
faces.push(face_indices);
}
}
}
}
// Helper function to add unique vertex and return its index
fn add_unique_vertex(vertices: &mut Vec<Point3<Real>>, vertex: Point3<Real>) -> usize {
const EPSILON: Real = 1e-6;
// Check if vertex already exists (within tolerance)
for (i, existing) in vertices.iter().enumerate() {
if (existing.coords - vertex.coords).norm() < EPSILON {
return i;
}
}
// Add new vertex
vertices.push(vertex);
vertices.len() - 1
}
// Helper function to add unique normal and return its index
fn add_unique_normal(normals: &mut Vec<Vector3<Real>>, normal: Vector3<Real>) -> usize {
const EPSILON: Real = 1e-6;
// Check if normal already exists (within tolerance)
for (i, existing) in normals.iter().enumerate() {
if (existing - normal).norm() < EPSILON {
return i;
}
}
// Add new normal
normals.push(normal);
normals.len() - 1
}