-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathcsg.rs
More file actions
1220 lines (1058 loc) · 42.5 KB
/
csg.rs
File metadata and controls
1220 lines (1058 loc) · 42.5 KB
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::bsp::Node;
use crate::float_types::parry3d::{
bounding_volume::Aabb,
query::{Ray, RayCast},
shape::{Shape, SharedShape, TriMesh, Triangle},
};
use crate::float_types::rapier3d::prelude::*;
use crate::float_types::{EPSILON, Real};
use crate::plane::Plane;
use crate::polygon::Polygon;
use crate::vertex::Vertex;
use geo::{
AffineOps, AffineTransform, BooleanOps, BoundingRect, Coord, CoordsIter, Geometry,
GeometryCollection, LineString, MultiPolygon, Orient, Polygon as GeoPolygon, Rect,
orient::Direction,
};
use nalgebra::{
Isometry3, Matrix3, Matrix4, Point3, Quaternion, Rotation3, Translation3, Unit, Vector3,
};
use std::fmt::Debug;
use std::sync::OnceLock;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
/// The main CSG solid structure. Contains a list of 3D polygons, 2D polylines, and some metadata.
#[derive(Debug, Clone)]
pub struct CSG<S: Clone = ()> {
/// 3D polygons for volumetric shapes
pub polygons: Vec<Polygon<S>>,
/// 2D geometry
pub geometry: GeometryCollection<Real>,
/// Lazily calculated AABB that spans `polygons` **and** any 2‑D geometry.
pub bounding_box: OnceLock<Aabb>,
/// Metadata
pub metadata: Option<S>,
}
impl<S: Clone + Debug + Send + Sync> Default for CSG<S> {
fn default() -> Self {
Self::new()
}
}
impl<S: Clone + Debug + Send + Sync> CSG<S> {
/// Create an empty CSG
pub fn new() -> Self {
CSG {
polygons: Vec::new(),
geometry: GeometryCollection::default(),
bounding_box: OnceLock::new(),
metadata: None,
}
}
/// Helper to collect all vertices from the CSG.
#[cfg(not(feature = "parallel"))]
pub fn vertices(&self) -> Vec<Vertex> {
self.polygons
.iter()
.flat_map(|p| p.vertices.clone())
.collect()
}
/// Parallel helper to collect all vertices from the CSG.
#[cfg(feature = "parallel")]
pub fn vertices(&self) -> Vec<Vertex> {
self.polygons
.par_iter()
.flat_map(|p| p.vertices.clone())
.collect()
}
/// Build a CSG from an existing polygon list
pub fn from_polygons(polygons: &[Polygon<S>]) -> Self {
let mut csg = CSG::new();
csg.polygons = polygons.to_vec();
csg
}
/// Convert internal polylines into polygons and return along with any existing internal polygons.
pub fn to_polygons(&self) -> Vec<Polygon<S>> {
/// Helper function to convert a geo::Polygon into one or more Polygon<S> entries.
fn process_polygon<S>(
poly2d: &geo::Polygon<Real>,
all_polygons: &mut Vec<Polygon<S>>,
metadata: &Option<S>,
) where
S: Clone + Send + Sync,
{
// 1. Convert the outer ring to 3D.
let mut outer_vertices_3d = Vec::new();
for c in poly2d.exterior().coords_iter() {
outer_vertices_3d.push(Vertex::new(Point3::new(c.x, c.y, 0.0), Vector3::z()));
}
if outer_vertices_3d.len() >= 3 {
all_polygons.push(Polygon::new(outer_vertices_3d, metadata.clone()));
}
// 2. Convert interior rings (holes), if needed as separate polygons.
for ring in poly2d.interiors() {
let mut hole_vertices_3d = Vec::new();
for c in ring.coords_iter() {
hole_vertices_3d
.push(Vertex::new(Point3::new(c.x, c.y, 0.0), Vector3::z()));
}
if hole_vertices_3d.len() >= 3 {
// Note: adjust this if your `Polygon<S>` type supports interior rings.
all_polygons.push(Polygon::new(hole_vertices_3d, metadata.clone()));
}
}
}
let mut all_polygons = Vec::new();
for geom in &self.geometry {
match geom {
Geometry::Polygon(poly2d) => {
process_polygon(poly2d, &mut all_polygons, &self.metadata);
},
Geometry::MultiPolygon(multipoly) => {
for poly2d in multipoly {
process_polygon(poly2d, &mut all_polygons, &self.metadata);
}
},
// Optional: handle other geometry types like LineString here.
_ => {},
}
}
all_polygons
}
/// Create a CSG that holds *only* 2D geometry in a `geo::GeometryCollection`.
pub fn from_geo(geometry: GeometryCollection<Real>, metadata: Option<S>) -> Self {
let mut csg = CSG::new();
csg.geometry = geometry;
csg.metadata = metadata;
csg
}
/// Take the [`geo::Polygon`]'s from the `CSG`'s geometry collection
pub fn to_multipolygon(&self) -> MultiPolygon<Real> {
// allocate vec to fit all polygons
let mut polygons = Vec::with_capacity(self.geometry.0.iter().fold(0, |len, geom| {
len + match geom {
Geometry::Polygon(_) => len + 1,
Geometry::MultiPolygon(mp) => len + mp.0.len(),
// ignore lines, points, etc.
_ => len,
}
}));
for geom in &self.geometry.0 {
match geom {
Geometry::Polygon(poly) => polygons.push(poly.clone()),
Geometry::MultiPolygon(mp) => polygons.extend(mp.0.clone()),
// ignore lines, points, etc.
_ => {},
}
}
MultiPolygon(polygons)
}
pub fn tessellate_2d(
outer: &[[Real; 2]],
holes: &[&[[Real; 2]]],
) -> Vec<[Point3<Real>; 3]> {
// Convert the outer ring into a `LineString`
let outer_coords: Vec<Coord<Real>> =
outer.iter().map(|&[x, y]| Coord { x, y }).collect();
// Convert each hole into its own `LineString`
let holes_coords: Vec<LineString<Real>> = holes
.iter()
.map(|hole| {
let coords: Vec<Coord<Real>> =
hole.iter().map(|&[x, y]| Coord { x, y }).collect();
LineString::new(coords)
})
.collect();
// Ear-cut triangulation on the polygon (outer + holes)
let polygon = GeoPolygon::new(LineString::new(outer_coords), holes_coords);
#[cfg(feature = "earcut")]
{
use geo::TriangulateEarcut;
let triangulation = polygon.earcut_triangles_raw();
let triangle_indices = triangulation.triangle_indices;
let vertices = triangulation.vertices;
// Convert the 2D result (x,y) into 3D triangles with z=0
let mut result = Vec::with_capacity(triangle_indices.len() / 3);
for tri in triangle_indices.chunks_exact(3) {
let pts = [
Point3::new(vertices[2 * tri[0]], vertices[2 * tri[0] + 1], 0.0),
Point3::new(vertices[2 * tri[1]], vertices[2 * tri[1] + 1], 0.0),
Point3::new(vertices[2 * tri[2]], vertices[2 * tri[2] + 1], 0.0),
];
result.push(pts);
}
result
}
#[cfg(feature = "delaunay")]
{
use geo::TriangulateSpade;
// We want polygons with holes => constrained triangulation.
// For safety, handle the Result the trait returns:
let Ok(tris) = polygon.constrained_triangulation(Default::default()) else {
// If a triangulation error is a possibility,
// pick the error-handling you want here:
return Vec::new();
};
let mut result = Vec::with_capacity(tris.len());
for triangle in tris {
// Each `triangle` is a geo_types::Triangle whose `.0, .1, .2`
// are the 2D coordinates. We'll embed them at z=0.
let [a, b, c] = [triangle.0, triangle.1, triangle.2];
result.push([
Point3::new(a.x, a.y, 0.0),
Point3::new(b.x, b.y, 0.0),
Point3::new(c.x, c.y, 0.0),
]);
}
result
}
}
/// Split polygons into (may_touch, cannot_touch) using bounding‑box tests
fn partition_polys(
polys: &[Polygon<S>],
other_bb: &Aabb,
) -> (Vec<Polygon<S>>, Vec<Polygon<S>>) {
let mut maybe = Vec::new();
let mut never = Vec::new();
for p in polys {
if p.bounding_box().intersects(other_bb) {
maybe.push(p.clone());
} else {
never.push(p.clone());
}
}
(maybe, never)
}
/// Return a new CSG representing union of the two CSG's.
///
/// ```no_run
/// let c = a.union(b);
/// +-------+ +-------+
/// | | | |
/// | a | | c |
/// | +--+----+ = | +----+
/// +----+--+ | +----+ |
/// | b | | c |
/// | | | |
/// +-------+ +-------+
/// ```
#[must_use = "Use new CSG representing space in both CSG's"]
pub fn union(&self, other: &CSG<S>) -> CSG<S> {
// 3D union:
// avoid splitting obvious non‑intersecting faces
let (a_clip, a_passthru) =
Self::partition_polys(&self.polygons, &other.bounding_box());
let (b_clip, b_passthru) =
Self::partition_polys(&other.polygons, &self.bounding_box());
let mut a = Node::new(&a_clip);
let mut b = Node::new(&b_clip);
a.clip_to(&b);
b.clip_to(&a);
b.invert();
b.clip_to(&a);
b.invert();
a.build(&b.all_polygons());
// combine results and untouched faces
let mut final_polys = a.all_polygons();
final_polys.extend(a_passthru);
final_polys.extend(b_passthru);
// 2D union:
// Extract multipolygon from geometry
let polys1 = self.to_multipolygon();
let polys2 = &other.to_multipolygon();
// Perform union on those multipolygons
let unioned = polys1.union(polys2); // This is valid if each is a MultiPolygon
let oriented = unioned.orient(Direction::Default);
// Wrap the unioned multipolygons + lines/points back into one GeometryCollection
let mut final_gc = GeometryCollection::default();
final_gc.0.push(Geometry::MultiPolygon(oriented));
// re-insert lines & points from both sets:
for g in &self.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {
// skip [multi]polygons
},
_ => final_gc.0.push(g.clone()),
}
}
for g in &other.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {
// skip [multi]polygons
},
_ => final_gc.0.push(g.clone()),
}
}
CSG {
polygons: final_polys,
geometry: final_gc,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Return a new CSG representing diffarence of the two CSG's.
///
/// ```no_run
/// let c = a.difference(b);
/// +-------+ +-------+
/// | | | |
/// | a | | c |
/// | +--+----+ = | +--+
/// +----+--+ | +----+
/// | b |
/// | |
/// +-------+
/// ```
#[must_use = "Use new CSG"]
pub fn difference(&self, other: &CSG<S>) -> CSG<S> {
// 3D difference:
// avoid splitting obvious non‑intersecting faces
let (a_clip, a_passthru) =
Self::partition_polys(&self.polygons, &other.bounding_box());
let (b_clip, _b_passthru) =
Self::partition_polys(&other.polygons, &self.bounding_box());
let mut a = Node::new(&a_clip);
let mut b = Node::new(&b_clip);
a.invert();
a.clip_to(&b);
b.clip_to(&a);
b.invert();
b.clip_to(&a);
b.invert();
a.build(&b.all_polygons());
a.invert();
// combine results and untouched faces
let mut final_polys = a.all_polygons();
final_polys.extend(a_passthru);
// 2D difference:
let polys1 = &self.to_multipolygon();
let polys2 = &other.to_multipolygon();
// Perform difference on those multipolygons
let differenced = polys1.difference(polys2);
let oriented = differenced.orient(Direction::Default);
// Wrap the differenced multipolygons + lines/points back into one GeometryCollection
let mut final_gc = GeometryCollection::default();
final_gc.0.push(Geometry::MultiPolygon(oriented));
// Re-insert lines & points from self only
// (If you need to exclude lines/points that lie inside other, you'd need more checks here.)
for g in &self.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {}, // skip
_ => final_gc.0.push(g.clone()),
}
}
CSG {
polygons: a.all_polygons(),
geometry: final_gc,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Return a new CSG representing intersection of the two CSG's.
///
/// ```no_run
/// let c = a.intersect(b);
/// +-------+
/// | |
/// | a |
/// | +--+----+ = +--+
/// +----+--+ | +--+
/// | b |
/// | |
/// +-------+
/// ```
pub fn intersection(&self, other: &CSG<S>) -> CSG<S> {
// 3D intersection:
// avoid splitting obvious non‑intersecting faces
let (a_clip, _a_passthru) =
Self::partition_polys(&self.polygons, &other.bounding_box());
let (b_clip, _b_passthru) =
Self::partition_polys(&other.polygons, &self.bounding_box());
let mut a = Node::new(&a_clip);
let mut b = Node::new(&b_clip);
a.invert();
b.clip_to(&a);
b.invert();
a.clip_to(&b);
b.clip_to(&a);
a.build(&b.all_polygons());
a.invert();
// 2D intersection:
let polys1 = &self.to_multipolygon();
let polys2 = &other.to_multipolygon();
// Perform intersection on those multipolygons
let intersected = polys1.intersection(polys2);
let oriented = intersected.orient(Direction::Default);
// Wrap the intersected multipolygons + lines/points into one GeometryCollection
let mut final_gc = GeometryCollection::default();
final_gc.0.push(Geometry::MultiPolygon(oriented));
// For lines and points: keep them only if they intersect in both sets
// todo: detect intersection of non-polygons
for g in &self.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {}, // skip
_ => final_gc.0.push(g.clone()),
}
}
for g in &other.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {}, // skip
_ => final_gc.0.push(g.clone()),
}
}
CSG {
polygons: a.all_polygons(),
geometry: final_gc,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Return a new CSG representing space in this CSG excluding the space in the
/// other CSG plus the space in the other CSG excluding the space in this CSG.
///
/// ```no_run
/// let c = a.xor(b);
/// +-------+ +-------+
/// | | | |
/// | a | | a |
/// | +--+----+ = | +--+----+
/// +----+--+ | +----+--+ |
/// | b | | |
/// | | | |
/// +-------+ +-------+
/// ```
pub fn xor(&self, other: &CSG<S>) -> CSG<S> {
// 3D and 2D xor:
// A \ B
let a_sub_b = self.difference(other);
// B \ A
let b_sub_a = other.difference(self);
// Union those two
a_sub_b.union(&b_sub_a)
/* here in case 2D xor misbehaves as an alternate implementation
// 2D xor:
let polys1 = &self.to_multipolygon();
let polys2 = &other.to_multipolygon();
// Perform symmetric difference (XOR)
let xored = polys1.xor(polys2);
let oriented = xored.orient(Direction::Default);
// Wrap in a new GeometryCollection
let mut final_gc = GeometryCollection::default();
final_gc.0.push(Geometry::MultiPolygon(oriented));
// Re-insert lines & points from both sets
for g in &self.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {}, // skip
_ => final_gc.0.push(g.clone()),
}
}
for g in &other.geometry.0 {
match g {
Geometry::Polygon(_) | Geometry::MultiPolygon(_) => {}, // skip
_ => final_gc.0.push(g.clone()),
}
}
CSG {
// If you also want a polygon-based Node XOR, you'd need to implement that similarly
polygons: self.polygons.clone(),
geometry: final_gc,
metadata: self.metadata.clone(),
}
*/
}
/// Invert this CSG (flip inside vs. outside)
pub fn inverse(&self) -> CSG<S> {
let mut csg = self.clone();
for p in &mut csg.polygons {
p.flip();
}
csg
}
/// Apply an arbitrary 3D transform (as a 4x4 matrix) to both polygons and polylines.
/// The polygon z-coordinates and normal vectors are fully transformed in 3D,
/// and the 2D polylines are updated by ignoring the resulting z after transform.
pub fn transform(&self, mat: &Matrix4<Real>) -> CSG<S> {
let mat_inv_transpose = mat.try_inverse().expect("Matrix not invertible?").transpose(); // todo catch error
let mut csg = self.clone();
for poly in &mut csg.polygons {
for vert in &mut poly.vertices {
// Position
let hom_pos = mat * vert.pos.to_homogeneous();
vert.pos = Point3::from_homogeneous(hom_pos).unwrap(); // todo catch error
// Normal
vert.normal = mat_inv_transpose.transform_vector(&vert.normal).normalize();
}
// keep the cached plane consistent with the new vertex positions
poly.plane = Plane::from_vertices(poly.vertices.clone());
}
// Convert the top-left 2×2 submatrix + translation of a 4×4 into a geo::AffineTransform
// The 4x4 looks like:
// [ m11 m12 m13 m14 ]
// [ m21 m22 m23 m24 ]
// [ m31 m32 m33 m34 ]
// [ m41 m42 m43 m44 ]
//
// For 2D, we use the sub-block:
// a = m11, b = m12,
// d = m21, e = m22,
// xoff = m14,
// yoff = m24,
// ignoring anything in z.
//
// So the final affine transform in 2D has matrix:
// [a b xoff]
// [d e yoff]
// [0 0 1 ]
let a = mat[(0, 0)];
let b = mat[(0, 1)];
let xoff = mat[(0, 3)];
let d = mat[(1, 0)];
let e = mat[(1, 1)];
let yoff = mat[(1, 3)];
let affine2 = AffineTransform::new(a, b, xoff, d, e, yoff);
// Transform csg.geometry (the GeometryCollection) in 2D
// Using geo’s map-coords approach or the built-in AffineOps trait.
// Below we use the `AffineOps` trait if you have `use geo::AffineOps;`
csg.geometry = csg.geometry.affine_transform(&affine2);
// invalidate the old cached bounding box
csg.bounding_box = OnceLock::new();
csg
}
/// Returns a new CSG translated by x, y, and z.
///
pub fn translate(&self, x: Real, y: Real, z: Real) -> CSG<S> {
self.translate_vector(Vector3::new(x, y, z))
}
/// Returns a new CSG translated by vector.
///
pub fn translate_vector(&self, vector: Vector3<Real>) -> CSG<S> {
let translation = Translation3::from(vector);
// Convert to a Matrix4
let mat4 = translation.to_homogeneous();
self.transform(&mat4)
}
/// Returns a new CSG translated so that its bounding-box center is at the origin (0,0,0).
pub fn center(&self) -> Self {
let aabb = self.bounding_box();
// Compute the AABB center
let center_x = (aabb.mins.x + aabb.maxs.x) * 0.5;
let center_y = (aabb.mins.y + aabb.maxs.y) * 0.5;
let center_z = (aabb.mins.z + aabb.maxs.z) * 0.5;
// Translate so that the bounding-box center goes to the origin
self.translate(-center_x, -center_y, -center_z)
}
/// Translates the CSG so that its bottommost point(s) sit exactly at z=0.
///
/// - Shifts all vertices up or down such that the minimum z coordinate of the bounding box becomes 0.
///
/// # Example
/// ```
/// let csg = CSG::cube(1.0, 1.0, 3.0, None).translate(2.0, 1.0, -2.0);
/// let floated = csg.float();
/// assert_eq!(floated.bounding_box().mins.z, 0.0);
/// ```
pub fn float(&self) -> Self {
let aabb = self.bounding_box();
let min_z = aabb.mins.z;
self.translate(0.0, 0.0, -min_z)
}
/// Rotates the CSG by x_degrees, y_degrees, z_degrees
pub fn rotate(&self, x_deg: Real, y_deg: Real, z_deg: Real) -> CSG<S> {
let rx = Rotation3::from_axis_angle(&Vector3::x_axis(), x_deg.to_radians());
let ry = Rotation3::from_axis_angle(&Vector3::y_axis(), y_deg.to_radians());
let rz = Rotation3::from_axis_angle(&Vector3::z_axis(), z_deg.to_radians());
// Compose them in the desired order
let rot = rz * ry * rx;
self.transform(&rot.to_homogeneous())
}
/// Scales the CSG by scale_x, scale_y, scale_z
pub fn scale(&self, sx: Real, sy: Real, sz: Real) -> CSG<S> {
let mat4 = Matrix4::new_nonuniform_scaling(&Vector3::new(sx, sy, sz));
self.transform(&mat4)
}
/// Reflect (mirror) this CSG about an arbitrary plane `plane`.
///
/// The plane is specified by:
/// `plane.normal` = the plane’s normal vector (need not be unit),
/// `plane.w` = the dot-product with that normal for points on the plane (offset).
///
/// Returns a new CSG whose geometry is mirrored accordingly.
pub fn mirror(&self, plane: Plane) -> Self {
// Normal might not be unit, so compute its length:
let len = plane.normal().norm();
if len.abs() < EPSILON {
// Degenerate plane? Just return clone (no transform)
return self.clone();
}
// Unit normal:
let n = plane.normal() / len;
// Adjusted offset = w / ||n||
let w = plane.offset() / len;
// Step 1) Translate so the plane crosses the origin
// The plane’s offset vector from origin is (w * n).
let offset = n * w;
let t1 = Translation3::from(-offset).to_homogeneous(); // push the plane to origin
// Step 2) Build the reflection matrix about a plane normal n at the origin
// R = I - 2 n n^T
let mut reflect_4 = Matrix4::identity();
let reflect_3 = Matrix3::identity() - 2.0 * n * n.transpose();
reflect_4.fixed_view_mut::<3, 3>(0, 0).copy_from(&reflect_3);
// Step 3) Translate back
let t2 = Translation3::from(offset).to_homogeneous(); // pull the plane back out
// Combine into a single 4×4
let mirror_mat = t2 * reflect_4 * t1;
// Apply to all polygons
self.transform(&mirror_mat).inverse()
}
/// Distribute this CSG `count` times around an arc (in XY plane) of radius,
/// from `start_angle_deg` to `end_angle_deg`.
/// Returns a new CSG with all copies (their polygons).
pub fn distribute_arc(
&self,
count: usize,
radius: Real,
start_angle_deg: Real,
end_angle_deg: Real,
) -> CSG<S> {
if count < 1 {
return self.clone();
}
let start_rad = start_angle_deg.to_radians();
let end_rad = end_angle_deg.to_radians();
let sweep = end_rad - start_rad;
// create a container to hold our unioned copies
let mut all_csg = CSG::<S>::new();
for i in 0..count {
// pick an angle fraction
let t = if count == 1 {
0.5
} else {
i as Real / ((count - 1) as Real)
};
let angle = start_rad + t * sweep;
let rot =
nalgebra::Rotation3::from_axis_angle(&nalgebra::Vector3::z_axis(), angle)
.to_homogeneous();
// translate out to radius in x
let trans = nalgebra::Translation3::new(radius, 0.0, 0.0).to_homogeneous();
let mat = rot * trans;
// Transform a copy of self and union with other copies
all_csg = all_csg.union(&self.transform(&mat));
}
// Put it in a new CSG
CSG {
polygons: all_csg.polygons,
geometry: all_csg.geometry,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Distribute this CSG `count` times along a straight line (vector),
/// each copy spaced by `spacing`.
/// E.g. if `dir=(1.0,0.0,0.0)` and `spacing=2.0`, you get copies at
/// x=0, x=2, x=4, ... etc.
pub fn distribute_linear(
&self,
count: usize,
dir: nalgebra::Vector3<Real>,
spacing: Real,
) -> CSG<S> {
if count < 1 {
return self.clone();
}
let step = dir.normalize() * spacing;
// create a container to hold our unioned copies
let mut all_csg = CSG::<S>::new();
for i in 0..count {
let offset = step * (i as Real);
let trans = nalgebra::Translation3::from(offset).to_homogeneous();
// Transform a copy of self and union with other copies
all_csg = all_csg.union(&self.transform(&trans));
}
// Put it in a new CSG
CSG {
polygons: all_csg.polygons,
geometry: all_csg.geometry,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Distribute this CSG in a grid of `rows x cols`, with spacing dx, dy in XY plane.
/// top-left or bottom-left depends on your usage of row/col iteration.
pub fn distribute_grid(&self, rows: usize, cols: usize, dx: Real, dy: Real) -> CSG<S> {
if rows < 1 || cols < 1 {
return self.clone();
}
let step_x = nalgebra::Vector3::new(dx, 0.0, 0.0);
let step_y = nalgebra::Vector3::new(0.0, dy, 0.0);
// create a container to hold our unioned copies
let mut all_csg = CSG::<S>::new();
for r in 0..rows {
for c in 0..cols {
let offset = step_x * (c as Real) + step_y * (r as Real);
let trans = nalgebra::Translation3::from(offset).to_homogeneous();
// Transform a copy of self and union with other copies
all_csg = all_csg.union(&self.transform(&trans));
}
}
// Put it in a new CSG
CSG {
polygons: all_csg.polygons,
geometry: all_csg.geometry,
bounding_box: OnceLock::new(),
metadata: self.metadata.clone(),
}
}
/// Subdivide all polygons in this CSG 'levels' times, in place.
/// This results in a triangular mesh with more detail.
///
/// ## Example
/// ```
/// let cube: CSG<()> = CSG::cube(2.0, 2.0, 2.0, None);
/// // subdivide_triangles(1) => each polygon (quad) is triangulated => 2 triangles => each tri subdivides => 4
/// // So each face with 4 vertices => 2 triangles => each becomes 4 => total 8 per face => 6 faces => 48
/// cube.subdivide_triangles(1.try_into().expect("not zero"));
/// assert_eq!(cube.polygons.len(), 6 * 8);
///
/// let cube: CSG<()> = CSG::cube(2.0, 2.0, 2.0, None);
/// cube.subdivide_triangles(2.try_into().expect("not zero"));
/// assert_eq!(cube.polygons.len(), 6 * 8 * 2);
/// ```
pub fn subdivide_triangles_mut(&mut self, levels: core::num::NonZeroU32) {
#[cfg(feature = "parallel")]
{
self.polygons = self
.polygons
.par_iter_mut()
.flat_map(|poly| {
let sub_tris = poly.subdivide_triangles(levels.into());
// Convert each small tri back to a Polygon
sub_tris
.into_par_iter()
.map(move |tri| Polygon::new(tri.to_vec(), poly.metadata.clone()))
})
.collect();
}
#[cfg(not(feature = "parallel"))]
{
self.polygons = self
.polygons
.iter_mut()
.flat_map(|poly| {
let polytri = poly.subdivide_triangles(levels.into());
polytri
.into_iter()
.map(move |tri| Polygon::new(tri.to_vec(), poly.metadata.clone()))
})
.collect();
}
}
/// Subdivide all polygons in this CSG 'levels' times, returning a new CSG.
/// This results in a triangular mesh with more detail.
pub fn subdivide_triangles(&self, levels: core::num::NonZeroU32) -> CSG<S> {
#[cfg(feature = "parallel")]
let new_polygons: Vec<Polygon<S>> = self
.polygons
.par_iter()
.flat_map(|poly| {
let sub_tris = poly.subdivide_triangles(levels);
// Convert each small tri back to a Polygon
sub_tris.into_par_iter().map(move |tri| {
Polygon::new(
vec![tri[0].clone(), tri[1].clone(), tri[2].clone()],
poly.metadata.clone(),
)
})
})
.collect();
#[cfg(not(feature = "parallel"))]
let new_polygons: Vec<Polygon<S>> = self
.polygons
.iter()
.flat_map(|poly| {
let sub_tris = poly.subdivide_triangles(levels);
sub_tris.into_iter().map(move |tri| {
Polygon::new(
vec![tri[0].clone(), tri[1].clone(), tri[2].clone()],
poly.metadata.clone(),
)
})
})
.collect();
CSG::from_polygons(&new_polygons)
}
/// Renormalize all polygons in this CSG by re-computing each polygon’s plane
/// and assigning that plane’s normal to all vertices.
pub fn renormalize(&mut self) {
for poly in &mut self.polygons {
poly.set_new_normal();
}
}
/// Casts a ray defined by `origin` + t * `direction` against all triangles
/// of this CSG and returns a list of (intersection_point, distance),
/// sorted by ascending distance.
///
/// # Parameters
/// - `origin`: The ray’s start point.
/// - `direction`: The ray’s direction vector.
///
/// # Returns
/// A `Vec` of `(Point3<Real>, Real)` where:
/// - `Point3<Real>` is the intersection coordinate in 3D,
/// - `Real` is the distance (the ray parameter t) from `origin`.
pub fn ray_intersections(
&self,
origin: &Point3<Real>,
direction: &Vector3<Real>,
) -> Vec<(Point3<Real>, Real)> {
let ray = Ray::new(*origin, *direction);
let iso = Isometry3::identity(); // No transformation on the triangles themselves.
let mut hits = Vec::new();
// 1) For each polygon in the CSG:
for poly in &self.polygons {
// 2) Triangulate it if necessary:
let triangles = poly.tessellate();
// 3) For each triangle, do a ray–triangle intersection test:
for tri in triangles {
let a = tri[0].pos;
let b = tri[1].pos;
let c = tri[2].pos;
// Construct a parry Triangle shape from the 3 vertices:
let triangle = Triangle::new(a, b, c);
// Ray-cast against the triangle:
if let Some(hit) =
triangle.cast_ray_and_get_normal(&iso, &ray, Real::MAX, true)
{
let point_on_ray = ray.point_at(hit.time_of_impact);
hits.push((Point3::from(point_on_ray.coords), hit.time_of_impact));
}
}
}
// 4) Sort hits by ascending distance (toi):
hits.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
// 5) remove duplicate hits if they fall within tolerance
hits.dedup_by(|a, b| (a.1 - b.1).abs() < EPSILON);
hits
}
/// Returns a [`parry3d::bounding_volume::Aabb`] by merging:
/// 1. The 3D bounds of all `polygons`.
/// 2. The 2D bounding rectangle of `self.geometry`, interpreted at z=0.
///
/// [`parry3d::bounding_volume::Aabb`]: crate::float_types::parry3d::bounding_volume::Aabb
pub fn bounding_box(&self) -> Aabb {
*self.bounding_box.get_or_init(|| {
// Track overall min/max in x, y, z among all 3D polygons and the 2D geometry’s bounding_rect.
let mut min_x = Real::MAX;
let mut min_y = Real::MAX;
let mut min_z = Real::MAX;
let mut max_x = -Real::MAX;
let mut max_y = -Real::MAX;
let mut max_z = -Real::MAX;
// 1) Gather from the 3D polygons
for poly in &self.polygons {
for v in &poly.vertices {
min_x = min_x.min(v.pos.x);
min_y = min_y.min(v.pos.y);
min_z = min_z.min(v.pos.z);
max_x = max_x.max(v.pos.x);
max_y = max_y.max(v.pos.y);
max_z = max_z.max(v.pos.z);
}
}
// 2) Gather from the 2D geometry using `geo::BoundingRect`
// This gives us (min_x, min_y) / (max_x, max_y) in 2D. For 3D, treat z=0.
// Explicitly capture the result of `.bounding_rect()` as an Option<Rect<Real>>
let maybe_rect: Option<Rect<Real>> = self.geometry.bounding_rect();
if let Some(rect) = maybe_rect {
let min_pt = rect.min();
let max_pt = rect.max();
// Merge the 2D bounds into our existing min/max, forcing z=0 for 2D geometry.
min_x = min_x.min(min_pt.x);
min_y = min_y.min(min_pt.y);
min_z = min_z.min(0.0);
max_x = max_x.max(max_pt.x);