-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathbsp.rs
More file actions
517 lines (458 loc) · 19.2 KB
/
bsp.rs
File metadata and controls
517 lines (458 loc) · 19.2 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
//! This module contains the implementation of the [BSP](https://en.wikipedia.org/wiki/Binary_space_partitioning) tree data structure
use crate::float_types::EPSILON;
use crate::plane::{BACK, COPLANAR, FRONT, Plane, SPANNING};
use crate::polygon::Polygon;
use crate::vertex::Vertex;
use std::fmt::Debug;
#[cfg(feature = "parallel")]
use rayon::{join, prelude::*};
/// A [BSP](https://en.wikipedia.org/wiki/Binary_space_partitioning) tree node, containing polygons plus optional front/back subtrees
#[derive(Debug, Clone)]
pub struct Node<S: Clone> {
/// Splitting plane for this node *or* **None** for a leaf that
/// only stores polygons.
pub plane: Option<Plane>,
/// Polygons in *front* half‑spaces.
pub front: Option<Box<Node<S>>>,
/// Polygons in *back* half‑spaces.
pub back: Option<Box<Node<S>>>,
/// Polygons that lie *exactly* on `plane`
/// (after the node has been built).
pub polygons: Vec<Polygon<S>>,
}
impl<S: Clone + Send + Sync + Debug> Node<S> {
pub fn new(polygons: &[Polygon<S>]) -> Self {
let mut node = Node {
plane: None,
front: None,
back: None,
polygons: Vec::new(),
};
if !polygons.is_empty() {
node.build(polygons);
}
node
}
/// Invert all polygons in the BSP tree
pub fn invert(&mut self) {
for p in &mut self.polygons {
p.flip();
}
if let Some(ref mut plane) = self.plane {
plane.flip();
}
// Recursively invert children in parallel, if both exist
#[cfg(feature = "parallel")]
match (&mut self.front, &mut self.back) {
(Some(front_node), Some(back_node)) => {
join(|| front_node.invert(), || back_node.invert());
},
(Some(front_node), None) => front_node.invert(),
(None, Some(back_node)) => back_node.invert(),
(None, None) => {},
}
#[cfg(not(feature = "parallel"))]
if let Some(ref mut front) = self.front {
front.invert();
}
#[cfg(not(feature = "parallel"))]
if let Some(ref mut back) = self.back {
back.invert();
}
std::mem::swap(&mut self.front, &mut self.back);
}
/// Recursively remove all polygons in `polygons` that are inside this BSP tree
#[cfg(not(feature = "parallel"))]
pub fn clip_polygons(&self, polygons: &[Polygon<S>]) -> Vec<Polygon<S>> {
// If this node has no plane (i.e. it’s empty), just return
if self.plane.is_none() {
return polygons.to_vec();
}
let plane = self.plane.as_ref().unwrap();
let mut front: Vec<Polygon<S>> = Vec::new();
let mut back: Vec<Polygon<S>> = Vec::new();
let mut coplanar_front: Vec<Polygon<S>> = Vec::new();
let mut coplanar_back: Vec<Polygon<S>> = Vec::new();
// For each polygon, split it by the node's plane.
for poly in polygons {
let (cf, cb, f, b) = plane.split_polygon(poly);
coplanar_front.extend(cf);
coplanar_back.extend(cb);
front.extend(f);
back.extend(b);
}
// Now decide where to send the coplanar polygons. If the polygon’s normal
// aligns with this node’s plane.normal, treat it as “front,” else treat as “back.”
for cp in coplanar_front {
if plane.orient_plane(&cp.plane) == FRONT {
front.push(cp);
} else {
back.push(cp);
}
}
for cp in coplanar_back {
if plane.orient_plane(&cp.plane) == FRONT {
front.push(cp);
} else {
back.push(cp);
}
}
// Recursively clip the front polygons.
if let Some(ref f) = self.front {
front = f.clip_polygons(&front);
}
// Recursively clip the back polygons.
if let Some(ref b) = self.back {
back = b.clip_polygons(&back);
} else {
back.clear();
}
// Now combine front and back
front.extend(back);
front
}
// ------------------------------------------------------------------------
// Clip Polygons (parallel version)
// ------------------------------------------------------------------------
#[cfg(feature = "parallel")]
pub fn clip_polygons(&self, polygons: &[Polygon<S>]) -> Vec<Polygon<S>> {
// If this node has no plane, just return the original set
if self.plane.is_none() {
return polygons.to_vec();
}
let plane = self.plane.as_ref().unwrap();
// Split each polygon in parallel; gather results
let (coplanar_front, coplanar_back, mut front, mut back) = polygons
.par_iter()
.map(|poly| plane.split_polygon(poly)) // <-- just pass poly
.reduce(
|| (Vec::new(), Vec::new(), Vec::new(), Vec::new()),
|mut acc, x| {
acc.0.extend(x.0);
acc.1.extend(x.1);
acc.2.extend(x.2);
acc.3.extend(x.3);
acc
},
);
// Decide where to send the coplanar polygons
for cp in coplanar_front {
if plane.orient_plane(&cp.plane) == FRONT {
front.push(cp);
} else {
back.push(cp);
}
}
for cp in coplanar_back {
if plane.orient_plane(&cp.plane) == FRONT {
front.push(cp);
} else {
back.push(cp);
}
}
// Recursively clip front & back in parallel
let (front_clipped, back_clipped) = join(
|| {
if let Some(ref f) = self.front {
f.clip_polygons(&front)
} else {
front
}
},
|| {
if let Some(ref b) = self.back {
b.clip_polygons(&back)
} else {
// If there's no back node, discard these polygons
Vec::new()
}
},
);
// Combine front and back
let mut result = front_clipped;
result.extend(back_clipped);
result
}
/// Remove all polygons in this BSP tree that are inside the other BSP tree
#[cfg(not(feature = "parallel"))]
pub fn clip_to(&mut self, bsp: &Node<S>) {
self.polygons = bsp.clip_polygons(&self.polygons);
if let Some(ref mut front) = self.front {
front.clip_to(bsp);
}
if let Some(ref mut back) = self.back {
back.clip_to(bsp);
}
}
/// Parallel remove all polygons in this BSP tree that are inside the other BSP tree
#[cfg(feature = "parallel")]
pub fn clip_to(&mut self, bsp: &Node<S>) {
// clip self.polygons in parallel
let new_polygons = bsp.clip_polygons(&self.polygons);
self.polygons = new_polygons;
// Recurse in parallel over front/back
match (&mut self.front, &mut self.back) {
(Some(front_node), Some(back_node)) => {
join(|| front_node.clip_to(bsp), || back_node.clip_to(bsp));
},
(Some(front_node), None) => front_node.clip_to(bsp),
(None, Some(back_node)) => back_node.clip_to(bsp),
(None, None) => {},
}
}
/// Return all polygons in this BSP tree
pub fn all_polygons(&self) -> Vec<Polygon<S>> {
let mut result = self.polygons.clone();
if let Some(ref front) = self.front {
result.extend(front.all_polygons());
}
if let Some(ref back) = self.back {
result.extend(back.all_polygons());
}
result
}
/// Build a BSP tree from the given polygons
#[cfg(not(feature = "parallel"))]
pub fn build(&mut self, polygons: &[Polygon<S>]) {
if polygons.is_empty() {
return;
}
// Choose the first polygon's plane as the splitting plane if not already set.
if self.plane.is_none() {
self.plane = Some(polygons[0].plane.clone());
}
let plane = self.plane.clone().unwrap();
let mut front: Vec<Polygon<S>> = Vec::new();
let mut back: Vec<Polygon<S>> = Vec::new();
// For each polygon, split it relative to the current node's plane.
for p in polygons {
let (coplanar_front, coplanar_back, f, b) = plane.split_polygon(p);
self.polygons.extend(coplanar_front);
self.polygons.extend(coplanar_back);
front.extend(f);
back.extend(b);
}
// Recursively build the front subtree.
if !front.is_empty() {
if self.front.is_none() {
self.front = Some(Box::new(Node::new(&[])));
}
self.front.as_mut().unwrap().build(&front);
}
// Recursively build the back subtree.
if !back.is_empty() {
if self.back.is_none() {
self.back = Some(Box::new(Node::new(&[])));
}
self.back.as_mut().unwrap().build(&back);
}
}
// ------------------------------------------------------------------------
// Build (parallel version)
// ------------------------------------------------------------------------
#[cfg(feature = "parallel")]
pub fn build(&mut self, polygons: &[Polygon<S>]) {
if polygons.is_empty() {
return;
}
// Choose splitting plane if not already set
if self.plane.is_none() {
self.plane = Some(polygons[0].plane.clone());
}
let plane = self.plane.clone().unwrap();
// Split polygons in parallel
let (mut coplanar_front, mut coplanar_back, front, back) = polygons
.par_iter()
.map(|p| plane.split_polygon(p)) // <-- just pass p
.reduce(
|| (Vec::new(), Vec::new(), Vec::new(), Vec::new()),
|mut acc, x| {
acc.0.extend(x.0);
acc.1.extend(x.1);
acc.2.extend(x.2);
acc.3.extend(x.3);
acc
},
);
// Append coplanar fronts/backs to self.polygons
self.polygons.append(&mut coplanar_front);
self.polygons.append(&mut coplanar_back);
// Recursively build front/back in parallel
match (!front.is_empty(), !back.is_empty()) {
(true, true) => {
if self.front.is_none() {
self.front = Some(Box::new(Node::new(&[])));
}
if self.back.is_none() {
self.back = Some(Box::new(Node::new(&[])));
}
let front_node = self.front.as_mut().unwrap();
let back_node = self.back.as_mut().unwrap();
join(|| front_node.build(&front), || back_node.build(&back));
},
(true, false) => {
if self.front.is_none() {
self.front = Some(Box::new(Node::new(&[])));
}
self.front.as_mut().unwrap().build(&front);
},
(false, true) => {
if self.back.is_none() {
self.back = Some(Box::new(Node::new(&[])));
}
self.back.as_mut().unwrap().build(&back);
},
(false, false) => {},
}
}
/// Slices this BSP node with `slicing_plane`, returning:
/// - All polygons that are coplanar with the plane (within EPSILON),
/// - A list of line‐segment intersections (each a [Vertex; 2]) from polygons that span the plane.
#[cfg(not(feature = "parallel"))]
pub fn slice(&self, slicing_plane: &Plane) -> (Vec<Polygon<S>>, Vec<[Vertex; 2]>) {
let all_polys = self.all_polygons();
let mut coplanar_polygons = Vec::new();
let mut intersection_edges = Vec::new();
for poly in &all_polys {
let vcount = poly.vertices.len();
if vcount < 2 {
continue; // degenerate polygon => skip
}
let mut polygon_type = 0;
let mut types = Vec::with_capacity(vcount);
for vertex in &poly.vertices {
let vertex_type = slicing_plane.orient_point(&vertex.pos);
polygon_type |= vertex_type;
types.push(vertex_type);
}
// Based on the combined classification of its vertices:
match polygon_type {
COPLANAR => {
// The entire polygon is in the plane, so push it to the coplanar list.
// Depending on normal alignment, it may be “coplanar_front” or “coplanar_back.”
// Usually we don’t care — we just return them as “in the plane.”
coplanar_polygons.push(poly.clone());
},
FRONT | BACK => {
// Entirely on one side => no intersection. We skip it.
},
SPANNING => {
// The polygon crosses the plane. We'll gather the intersection points
// (the new vertices introduced on edges that cross the plane).
let mut crossing_points = Vec::new();
for i in 0..vcount {
let j = (i + 1) % vcount;
let ti = types[i];
let tj = types[j];
let vi = &poly.vertices[i];
let vj = &poly.vertices[j];
// If this vertex is on the "back" side, and the next vertex is on the
// "front" side (or vice versa), that edge crosses the plane.
// (Also if exactly one is COPLANAR and the other is FRONT or BACK, etc.)
if (ti | tj) == SPANNING {
// The param intersection at which plane intersects the edge [vi -> vj].
// Avoid dividing by zero:
let denom = slicing_plane.normal().dot(&(vj.pos - vi.pos));
if denom.abs() > EPSILON {
let intersection = (slicing_plane.offset()
- slicing_plane.normal().dot(&vi.pos.coords))
/ denom;
// Interpolate:
let intersect_vert = vi.interpolate(vj, intersection);
crossing_points.push(intersect_vert);
}
}
}
// Typical convex polygons crossing a plane get exactly 2 intersection points.
// Concave polygons might produce 2 or more. We pair them up in consecutive pairs:
// e.g. if crossing_points = [p0, p1, p2, p3], we'll produce 2 edges: [p0,p1], [p2,p3].
// This is one simple heuristic. If you have an odd number, something degenerate happened.
for chunk in crossing_points.chunks_exact(2) {
intersection_edges.push([chunk[0].clone(), chunk[1].clone()]);
}
// If crossing_points.len() was not a multiple of 2, you can handle leftover
// points or flag them as errors, etc. We'll skip that detail here.
},
_ => {
// Shouldn't happen in a typical classification, but we can ignore
},
}
}
(coplanar_polygons, intersection_edges)
}
// ------------------------------------------------------------------------
// Slice (parallel version)
// ------------------------------------------------------------------------
#[cfg(feature = "parallel")]
pub fn slice(&self, slicing_plane: &Plane) -> (Vec<Polygon<S>>, Vec<[Vertex; 2]>) {
// Collect all polygons (this can be expensive, but let's do it).
let all_polys = self.all_polygons();
// Process polygons in parallel
let (coplanar_polygons, intersection_edges) = all_polys
.par_iter()
.map(|poly| {
let vcount = poly.vertices.len();
if vcount < 2 {
// Degenerate => skip
return (Vec::new(), Vec::new());
}
let mut polygon_type = 0;
let mut types = Vec::with_capacity(vcount);
for vertex in &poly.vertices {
let vertex_type = slicing_plane.orient_point(&vertex.pos);
polygon_type |= vertex_type;
types.push(vertex_type);
}
match polygon_type {
COPLANAR => {
// Entire polygon in plane
(vec![poly.clone()], Vec::new())
},
FRONT | BACK => {
// Entirely on one side => no intersection
(Vec::new(), Vec::new())
},
SPANNING => {
// The polygon crosses the plane => gather intersection edges
let mut crossing_points = Vec::new();
for i in 0..vcount {
let j = (i + 1) % vcount;
let ti = types[i];
let tj = types[j];
let vi = &poly.vertices[i];
let vj = &poly.vertices[j];
if (ti | tj) == SPANNING {
// The param intersection at which plane intersects the edge [vi -> vj].
// Avoid dividing by zero:
let denom = slicing_plane.normal().dot(&(vj.pos - vi.pos));
if denom.abs() > EPSILON {
let intersection = (slicing_plane.offset()
- slicing_plane.normal().dot(&vi.pos.coords))
/ denom;
// Interpolate:
let intersect_vert = vi.interpolate(vj, intersection);
crossing_points.push(intersect_vert);
}
}
}
// Pair up intersection points => edges
let mut edges = Vec::new();
for chunk in crossing_points.chunks_exact(2) {
edges.push([chunk[0].clone(), chunk[1].clone()]);
}
(Vec::new(), edges)
},
_ => (Vec::new(), Vec::new()),
}
})
.reduce(
|| (Vec::new(), Vec::new()),
|mut acc, x| {
acc.0.extend(x.0);
acc.1.extend(x.1);
acc
},
);
(coplanar_polygons, intersection_edges)
}
}