gmac_rs 0.2.0

Blazingly fast geometry manipulation and creation library
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
use crate::{
    core::selection::select_nodes_in_plane_direction,
    io::{
        obj::{read_obj, write_obj},
        stl::{read_stl, write_stl, StlFormat},
    },
};
use crate::error::Result;

/// Represents a standard 3D mesh.
/// A `Mesh` consists of nodes representing points in 3D space,
/// and cells which are triangles connecting these points.
///
/// # Example
/// ```
/// # use some_module::Mesh;
/// let nodes = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
/// let cells = vec![[0, 1, 2]];
/// let mesh = Mesh::new(nodes, cells);
/// ```
#[derive(Default, Debug, Clone)]
pub struct Mesh {
    pub nodes: Vec<[f64; 3]>,
    pub cells: Vec<[usize; 3]>,
}

impl Mesh {
    /// Constructs a new `Mesh`.
    ///
    /// # Arguments
    /// * `nodes`: Nodes of the mesh.
    /// * `cells`: Faces of the mesh.
    pub fn new(nodes: Vec<[f64; 3]>, cells: Vec<[usize; 3]>) -> Self {
        Mesh { nodes, cells }
    }

    /// Reads a mesh from an ASCII STL file using `read_stl`.
    /// See `read_stl`
    pub fn from_stl(filename: &str) -> Result<Self> {
        let (nodes, cells) = read_stl(filename)?;
        Ok(Mesh::new(nodes, cells))
    }

    /// Reads a mesh from an OBJ file using `read_obj`.
    /// See `read_obj`
    pub fn from_obj(filename: &str) -> Result<Self> {
        let (nodes, cells) = read_obj(filename)?;
        Ok(Mesh::new(nodes, cells))
    }

    /// Writes the mesh to an STL file.
    /// See `write_stl`
    pub fn write_stl(
        &self,
        filename: Option<&str>,
        format: Option<StlFormat>,
    ) -> Result<()> {
        write_stl(&self.nodes, &self.cells, filename, format)
    }

    /// Writes the mesh to an OBJ file.
    /// See `write_obj`
    pub fn write_obj(&self, filename: Option<&str>) -> Result<()> {
        write_obj(&self.nodes, &self.cells, filename)
    }

    /// Get nodes that make up cell triangles.
    /// See `get_mesh_triangles`
    pub fn triangles(&self) -> Vec<[[f64; 3]; 3]> {
        get_mesh_triangles(&self.nodes, &self.cells)
    }

    /// Get cell normals.
    /// See `get_mesh_cell_normals`
    pub fn cell_normals(&self) -> Vec<[f64; 3]> {
        get_mesh_cell_normals(&self.nodes, &self.cells)
    }

    /// Get nodes that are interpolated onto a slicing plane.
    /// See `find_node_intersections_with_plane`
    pub fn slice(&self, origin: [f64; 3], normal: [f64; 3]) -> Option<Vec<[f64; 3]>> {
        find_mesh_intersections_with_plane(&self.nodes, &self.cells, origin, normal)
    }

    /// Get mesh in direction of plane.
    /// See `clip_mesh_from_plane`
    pub fn clip(&self, origin: [f64; 3], normal: [f64; 3]) -> Mesh {
        let (new_nodes, new_cells) =
            clip_mesh_from_plane(&self.nodes, &self.cells, origin, normal);
        Mesh::new(new_nodes, new_cells)
    }
}

/// Returns the coordinates of the vertices for a single cell.
///
/// # Arguments
/// * `nodes`: Nodes of the mesh.
/// * `cell`: Cell id.
///
/// # Returns
/// A triangle in the form `[[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]]`.
fn get_triangle(nodes: &[[f64; 3]], cell: &[usize; 3]) -> [[f64; 3]; 3] {
    [nodes[cell[0]], nodes[cell[1]], nodes[cell[2]]]
}

/// Returns the coordinates of the vertices for each cell in the mesh.
///
/// # Arguments
/// * `nodes`: Nodes of the mesh.
/// * `cells`: Cells of the mesh.
///
/// # Returns
/// A `Vec<[[f64; 3]; 3]>` where each element represents a triangle.
pub fn get_mesh_triangles(
    nodes: &[[f64; 3]],
    cells: &[[usize; 3]],
) -> Vec<[[f64; 3]; 3]> {
    cells.iter().map(|cell| get_triangle(nodes, cell)).collect()
}

/// Computes and returns the normals for each cell in the mesh.
/// The normal for each cell is computed using the right-hand rule.
///
/// # Arguments
/// * `nodes`: Nodes of the mesh.
/// * `cells`: Cells of the mesh.
///
/// # Returns
/// A `Vec<[f64; 3]>` where each element is a normal corresponding to a cell.
pub fn get_mesh_cell_normals(nodes: &[[f64; 3]], cells: &[[usize; 3]]) -> Vec<[f64; 3]> {
    cells
        .iter()
        .map(|cell| {
            let a = nodes[cell[0]];
            let b = nodes[cell[1]];
            let c = nodes[cell[2]];

            // Calculate vectors ab and ac
            let ab = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
            let ac = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];

            // Calculate the cross product of ab and ac to get the normal
            let normal = [
                ab[1] * ac[2] - ab[2] * ac[1],
                ab[2] * ac[0] - ab[0] * ac[2],
                ab[0] * ac[1] - ab[1] * ac[0],
            ];

            // Normalize the normal vector
            let length =
                (normal[0].powi(2) + normal[1].powi(2) + normal[2].powi(2)).sqrt();
            [normal[0] / length, normal[1] / length, normal[2] / length]
        })
        .collect()
}

/// Finds the intersection points of a mesh with a slicing plane.
///
/// # Arguments
/// * `nodes`: Nodes of the mesh.
/// * `cells`: Cells of the mesh.
/// * `origin`: A 3D point `[x, y, z]` representing a point through which the
///             slice plane passes.
/// * `normal`: A 3D vector `[x, y, z]` representing the normal to the slice plane.
///
/// # Returns
/// Returns a `Vec<[f64; 3]>` containing the intersection points of the mesh with
/// the slice plane.
/// Each intersection point is represented as a 3D point `[x, y, z]`.
///
/// # Example
/// ```
/// # Example usage
/// let nodes = vec![
///     [0.0, 0.0, 0.0],
///     [1.0, 0.0, 0.0],
///     [0.0, 1.0, 0.0],
///     [0.0, 0.0, 1.0],
/// ];
/// let cells = vec![[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]];
/// let mesh = Mesh { nodes, cells };
///
/// let origin = [0.5, 0.5, 0.5];
/// let normal = [0.0, 0.0, 1.0];
///
/// let result = find_intersections_with_slice_plane(mesh, origin, normal);
/// ```
pub fn find_mesh_intersections_with_plane(
    nodes: &[[f64; 3]],
    cells: &[[usize; 3]],
    origin: [f64; 3],
    normal: [f64; 3],
) -> Option<Vec<[f64; 3]>> {
    let d = origin
        .iter()
        .zip(normal.iter())
        .map(|(o, n)| o * n)
        .sum::<f64>();
    let triangles = get_mesh_triangles(nodes, cells);

    // This is an arbitrary size for initial preallocation; you might have a better estimate
    let mut intersections: Vec<[f64; 3]> = Vec::with_capacity(2 * triangles.len());

    for [a, b, c] in triangles {
        let mut edge_intersections: Vec<[f64; 3]> = Vec::with_capacity(2);

        for &[point1, point2] in &[[a, b], [b, c], [c, a]] {
            let [x1, y1, z1] = point1;
            let [x2, y2, z2] = point2;

            let t = (d - normal
                .iter()
                .zip(point1.iter())
                .map(|(n, p)| n * p)
                .sum::<f64>())
                / normal
                    .iter()
                    .zip(point2.iter())
                    .zip(point1.iter())
                    .map(|((n, p2), p1)| n * (p2 - p1))
                    .sum::<f64>();

            if (0.0..=1.0).contains(&t) {
                let x = x1 + (x2 - x1) * t;
                let y = y1 + (y2 - y1) * t;
                let z = z1 + (z2 - z1) * t;
                edge_intersections.push([x, y, z]);
            }
        }

        if edge_intersections.len() == 2 {
            intersections.push(edge_intersections[0]);
            intersections.push(edge_intersections[1]);
        }
    }

    if intersections.is_empty() {
        None
    } else {
        Some(intersections)
    }
}

/// Clips the mesh with a given slicing plane, keeping only the elements and nodes that
/// lie in the direction of the plane's normal.
///
/// # Arguments
/// * `origin`: A 3D point `[x, y, z]` representing a point through which the
///             slice plane passes.
/// * `normal`: A 3D vector `[x, y, z]` representing the normal to the slice plane.
///
/// # Returns
/// Returns a new `Mesh` object containing only the nodes and cells (triangles)
/// that are on the "positive" side of the slicing plane, i.e., in the direction
/// of the plane's normal.
pub fn clip_mesh_from_plane(
    nodes: &[[f64; 3]],
    cells: &[[usize; 3]],
    origin: [f64; 3],
    normal: [f64; 3],
) -> (Vec<[f64; 3]>, Vec<[usize; 3]>) {
    // Get the indices of nodes that lie in the direction of the plane's normal
    let selected_node_indices = select_nodes_in_plane_direction(nodes, origin, normal);

    // Create a new list of nodes using the selected indices
    let new_nodes = selected_node_indices
        .iter()
        .map(|&i| nodes[i])
        .collect::<Vec<[f64; 3]>>();

    // Create a new list of cells (elements) using only the selected nodes and reindexing them
    let new_cells = cells
        .iter()
        .filter_map(|cell| {
            if cell.iter().all(|&i| selected_node_indices.contains(&i)) {
                Some([
                    selected_node_indices
                        .iter()
                        .position(|&x| x == cell[0])
                        .unwrap(),
                    selected_node_indices
                        .iter()
                        .position(|&x| x == cell[1])
                        .unwrap(),
                    selected_node_indices
                        .iter()
                        .position(|&x| x == cell[2])
                        .unwrap(),
                ])
            } else {
                None
            }
        })
        .collect::<Vec<[usize; 3]>>();

    // Create a new Mesh using the selected nodes and cells
    (new_nodes, new_cells)
}

#[cfg(test)]
mod tests {
    use super::*;
    const EPSILON: f64 = 1e-9;

    #[test]
    fn test_get_triangles() {
        let nodes = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
        ];
        let cells = vec![[0, 1, 2], [0, 2, 3]];
        let triangles = get_mesh_triangles(&nodes, &cells);

        let expected_triangles = vec![
            [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
            [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
        ];

        assert_eq!(triangles, expected_triangles)
    }

    #[test]
    fn test_get_face_normals() {
        let nodes = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
        ];
        let cells = vec![[0, 1, 2], [0, 2, 3]];
        let normals = get_mesh_cell_normals(&nodes, &cells);

        let expected_normals = vec![[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]];

        assert_eq!(normals, expected_normals)
    }

    #[test]
    fn test_slice_mesh_with_plane() {
        // A simple tetrahedron for slicing
        let nodes = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.5, 1.0, 0.0],
            [0.5, 0.5, 1.0],
        ];
        let cells = vec![[0, 1, 2], [0, 1, 3], [1, 2, 3], [0, 2, 3]];
        let mesh = Mesh::new(nodes, cells);

        // A plane that cuts horizontally through the tetrahedron
        let origin = [0.0, 0.0, 0.5];
        let normal = [0.0, 0.0, 1.0];

        let intersections = mesh
            .slice(origin, normal)
            .expect("Should find intersections");

        // The slice of a tetrahedron is a triangle, which is 3 line segments (6 points).
        assert_eq!(
            intersections.len(),
            6,
            "Slice should produce 3 line segments"
        );
        // All intersection points should have a z-coordinate of 0.5
        for point in intersections {
            assert!((point[2] - 0.5).abs() < EPSILON);
        }
    }

    #[test]
    fn test_slice_mesh_no_intersection() {
        let nodes = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
        let cells = vec![[0, 1, 2]];
        let mesh = Mesh::new(nodes, cells);

        // A plane far away from the triangle
        let origin = [0.0, 0.0, 10.0];
        let normal = [0.0, 0.0, 1.0];

        let result = mesh.slice(origin, normal);
        assert!(result.is_none(), "Should not find any intersections");
    }

    #[test]
    fn test_clip_mesh_from_plane() {
        // A 2x1x1 block centered at the origin
        let nodes = vec![
            [-1., -0.5, -0.5],
            [-1., -0.5, 0.5],
            [-1., 0.5, -0.5],
            [-1., 0.5, 0.5],
            [1., -0.5, -0.5],
            [1., -0.5, 0.5],
            [1., 0.5, -0.5],
            [1., 0.5, 0.5],
        ];
        let cells = vec![
            [0, 1, 3],
            [0, 3, 2],
            [4, 7, 5],
            [4, 6, 7],
            [0, 4, 5],
            [0, 5, 1],
            [2, 3, 7],
            [2, 7, 6],
            [0, 6, 4],
            [0, 2, 6],
            [1, 5, 7],
            [1, 7, 3],
        ];
        let mesh = Mesh::new(nodes, cells);

        // A plane that cuts the block in half at x=0
        let origin = [0.0, 0.0, 0.0];
        let normal = [1.0, 0.0, 0.0]; // Keep the +X side

        let new_mesh = mesh.clip(origin, normal);

        // Should keep the 4 nodes on the +X side
        assert_eq!(new_mesh.nodes.len(), 4);
        // Those 4 nodes should form a single quad face (2 triangles)
        assert_eq!(new_mesh.cells.len(), 2);

        // Verify all kept nodes have a positive or zero x-coordinate
        for node in new_mesh.nodes {
            assert!(node[0] >= -EPSILON);
        }
    }
}