-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcsgjs.h
More file actions
1471 lines (1198 loc) · 51.3 KB
/
Copy pathcsgjs.h
File metadata and controls
1471 lines (1198 loc) · 51.3 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
#ifndef CSGJSCPP_H
#define CSGJSCPP_H
// Original CSG.JS library by Evan Wallace (http://madebyevan.com), under the MIT license.
// GitHub: https://github.com/evanw/csg.js/
//
// C++ port by Tomasz Dabrowski (http://28byteslater.com), under the MIT license.
// GitHub: https://github.com/dabroz/csgjscpp-cpp/
//
// Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean
// operations like union and intersection to combine 3D solids. This library
// implements CSG operations on meshes elegantly and concisely using BSP trees,
// and is meant to serve as an easily understandable implementation of the
// algorithm. All edge cases involving overlapping coplanar polygons in both
// solids are correctly handled.
//
// modified by dazza - 200421
#include <algorithm>
#include <memory>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdint>
#if !defined(CSGJSCPP_REAL)
#define CSGJSCPP_REAL float
#endif
#if !defined(CSGJSCPP_VECTOR)
#include <vector>
#define CSGJSCPP_VECTOR std::vector
#endif
#if !defined(CSGJSCPP_DEQUE)
#include <deque>
#define CSGJSCPP_DEQUE std::deque
#endif
#if !defined(CSGJSCPP_SWAP)
#define CSGJSCPP_SWAP std::swap
#endif
#if !defined(CSGJSCPP_REVERSE)
#define CSGJSCPP_REVERSE std::reverse
#endif
#if !defined(CSGJSCPP_PAIR)
#define CSGJSCPP_PAIR std::pair
#endif
#if !defined(CSGJSCPP_MAKEPAIR)
#define CSGJSCPP_MAKEPAIR std::make_pair
#endif
#if !defined(CSGJSCPP_UNIQUEPTR)
#define CSGJSCPP_UNIQUEPTR std::unique_ptr
#endif
#if !defined(CSGJSCPP_MAP)
#include <map>
#define CSGJSCPP_MAP std::map
#endif
#if !defined(CSGJSCPP_UNORDEREDMAP)
#include <unordered_map>
#define CSGJSCPP_UNORDEREDMAP std::unordered_map
#endif
#if !defined(CSGJSCPP_FIND_IF)
#define CSGJSCPP_FIND_IF std::find_if
#endif
#if !defined (CSGJSCPP_INDEX)
#define CSGJSCPP_INDEX uint32_t
#endif
namespace csgjscpp {
// `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
// point is on the plane.
const CSGJSCPP_REAL csgjs_EPSILON = 0.0001f;
struct Vector {
CSGJSCPP_REAL x, y, z;
Vector() : x(0.0f), y(0.0f), z(0.0f) {
}
Vector(CSGJSCPP_REAL x, CSGJSCPP_REAL y, CSGJSCPP_REAL z) : x(x), y(y), z(z) {
}
};
inline bool approxequal(CSGJSCPP_REAL a, CSGJSCPP_REAL b) {
return fabs(a - b) < csgjs_EPSILON;
}
inline bool operator==(const Vector &a, const Vector &b) {
return approxequal(a.x, b.x) && approxequal(a.y, b.y) && approxequal(a.z, b.z);
}
inline bool operator!=(const Vector &a, const Vector &b) {
return !approxequal(a.x, b.x) || !approxequal(a.y, b.y) || !approxequal(a.z, b.z);
}
// Vector implementation
inline Vector operator+(const Vector &a, const Vector &b) {
return Vector(a.x + b.x, a.y + b.y, a.z + b.z);
}
inline Vector operator-(const Vector &a, const Vector &b) {
return Vector(a.x - b.x, a.y - b.y, a.z - b.z);
}
inline Vector operator*(const Vector &a, CSGJSCPP_REAL b) {
return Vector(a.x * b, a.y * b, a.z * b);
}
inline Vector operator/(const Vector &a, CSGJSCPP_REAL b) {
return a * ((CSGJSCPP_REAL)1.0 / b);
}
inline CSGJSCPP_REAL dot(const Vector &a, const Vector &b) {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
inline Vector lerp(const Vector &a, const Vector &b, CSGJSCPP_REAL v) {
return a + (b - a) * v;
}
inline Vector negate(const Vector &a) {
return a * -(CSGJSCPP_REAL)1.0;
}
inline CSGJSCPP_REAL length(const Vector &a) {
return (CSGJSCPP_REAL)sqrt(dot(a, a));
}
inline CSGJSCPP_REAL lengthsquared(const Vector &a) {
return dot(a, a);
}
inline Vector unit(const Vector &a) {
return a / length(a);
}
inline Vector cross(const Vector &a, const Vector &b) {
return Vector(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
}
inline Vector operator-(const Vector &a) {
return Vector(-a.x, -a.y, -a.z);
}
inline uint32_t lerp(uint32_t a, uint32_t b, CSGJSCPP_REAL v) {
return a + (uint32_t)((b - a) * v);
}
struct Vertex {
Vector pos;
Vector normal;
uint32_t col;
};
inline bool operator==(const Vertex &a, const Vertex &b) {
return a.pos == b.pos && a.normal == b.normal && a.col == b.col;
}
inline bool operator!=(const Vertex &a, const Vertex &b) {
return a.pos != b.pos || a.normal != b.normal || a.col != b.col;
}
struct Polygon;
// Represents a plane in 3D space.
struct Plane {
Vector normal;
CSGJSCPP_REAL w;
Plane();
Plane(const Vector &a, const Vector &b, const Vector &c);
inline bool ok() const {
return lengthsquared(this->normal) > 0.0f;
}
inline void flip() {
this->normal = negate(this->normal);
this->w *= -1.0f;
}
void splitpolygon(const Polygon &poly, CSGJSCPP_VECTOR<Polygon> &coplanarFront,
CSGJSCPP_VECTOR<Polygon> &coplanarBack, CSGJSCPP_VECTOR<Polygon> &front,
CSGJSCPP_VECTOR<Polygon> &back) const;
void splitpolygon(Polygon &&poly, CSGJSCPP_VECTOR<Polygon> &coplanarFront,
CSGJSCPP_VECTOR<Polygon> &coplanarBack, CSGJSCPP_VECTOR<Polygon> &front,
CSGJSCPP_VECTOR<Polygon> &back) const;
enum Classification { COPLANAR = 0, FRONT = 1, BACK = 2, SPANNING = 3 };
inline Classification classify(const Vector &p) const {
CSGJSCPP_REAL t = dot(normal, p) - this->w;
Classification c = (t < -csgjs_EPSILON) ? BACK : ((t > csgjs_EPSILON) ? FRONT : COPLANAR);
return c;
}
};
// Represents a convex polygon. The vertices used to initialize a polygon must
// be coplanar and form a convex loop. They do not have to be `CSG.Vertex`
// instances but they must behave similarly (duck typing can be used for
// customization).
//
// Each convex polygon has a `shared` property, which is shared between all
// polygons that are clones of each other or were split from the same polygon.
// This can be used to define per-polygon properties (such as surface color).
struct Polygon {
CSGJSCPP_VECTOR<Vertex> vertices;
Plane plane;
Polygon();
Polygon(const CSGJSCPP_VECTOR<Vertex> &list);
Polygon(CSGJSCPP_VECTOR<Vertex> &&list);
inline void flip() {
CSGJSCPP_REVERSE(vertices.begin(), vertices.end());
for (size_t i = 0; i < vertices.size(); i++)
vertices[i].normal = negate(vertices[i].normal);
plane.flip();
}
};
struct Model {
using Index = CSGJSCPP_INDEX;
CSGJSCPP_VECTOR<Vertex> vertices;
CSGJSCPP_VECTOR<Index> indices;
Index AddVertex(const Vertex &newv) {
Index i = 0;
for (const auto &v : vertices) {
if (v == newv) {
return i;
}
++i;
}
vertices.push_back(newv);
return i;
}
};
// public interface - not super efficient, if you use multiple CSG operations you should
// use BSP trees and convert them into model only once. Another optimization trick is
// replacing model with your own class.
Model csgunion(const Model &a, const Model &b);
Model csgintersection(const Model &a, const Model &b);
Model csgsubtract(const Model &a, const Model &b);
CSGJSCPP_VECTOR<Polygon> csgunion(const CSGJSCPP_VECTOR<Polygon> &a, const CSGJSCPP_VECTOR<Polygon> &b);
CSGJSCPP_VECTOR<Polygon> csgintersection(const CSGJSCPP_VECTOR<Polygon> &a, const CSGJSCPP_VECTOR<Polygon> &b);
CSGJSCPP_VECTOR<Polygon> csgsubtract(const CSGJSCPP_VECTOR<Polygon> &a, const CSGJSCPP_VECTOR<Polygon> &b);
/* API to build a set of polygons representning primatves. */
CSGJSCPP_VECTOR<Polygon> csgpolygon_cube(const Vector ¢er = {0.0f, 0.0f, 0.0f},
const Vector &dim = {1.0f, 1.0f, 1.0f}, const uint32_t col = 0xFFFFFF);
CSGJSCPP_VECTOR<Polygon> csgpolygon_sphere(const Vector ¢er = {0.0f, 0.0f, 0.0f}, CSGJSCPP_REAL radius = 1.0f,
const uint32_t col = 0xFFFFFF, int slices = 16, int stacks = 8);
CSGJSCPP_VECTOR<Polygon> csgpolygon_cylinder(const Vector &s = {0.0f, -1.0f, 0.0f},
const Vector &e = {0.0f, 1.0f, 0.0f}, CSGJSCPP_REAL radius = 1.0f,
const uint32_t col = 0xFFFFFF, int slices = 16);
CSGJSCPP_VECTOR<Polygon> csgfixtjunc(const CSGJSCPP_VECTOR<Polygon> &polygons);
Model modelfrompolygons(const CSGJSCPP_VECTOR<Polygon> &polygons);
/* API to build models representing primatives */
Model csgmodel_cube(const Vector ¢er = {0.0f, 0.0f, 0.0f}, const Vector &dim = {1.0f, 1.0f, 1.0f},
const uint32_t col = 0xFFFFFF);
Model csgmodel_sphere(const Vector ¢er = {0.0f, 0.0f, 0.0f}, CSGJSCPP_REAL radius = 1.0f,
const uint32_t col = 0xFFFFFF, int slices = 16, int stacks = 8);
Model csgmodel_cylinder(const Vector &s = {0.0f, -1.0f, 0.0f}, const Vector &e = {0.0f, 1.0f, 0.0f},
CSGJSCPP_REAL radius = 1.0f, const uint32_t col = 0xFFFFFF, int slices = 16);
} // namespace csgjscpp
#if defined(CSGJSCPP_IMPLEMENTATION)
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/***************************************************************************************************/
/* implementation below here */
#include <assert.h>
namespace csgjscpp {
// Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
// by picking a polygon to split along. That polygon (and all other coplanar
// polygons) are added directly to that node and the other polygons are added to
// the front and/or back subtrees. This is not a leafy BSP tree since there is
// no distinction between internal and leaf nodes.
struct CSGNode {
CSGJSCPP_VECTOR<Polygon> polygons;
CSGNode * front;
CSGNode * back;
Plane plane;
CSGNode();
CSGNode(const CSGJSCPP_VECTOR<Polygon> &list);
CSGNode(CSGJSCPP_VECTOR<Polygon> &&list);
~CSGNode();
CSGNode * clone() const;
void clipto(const CSGNode *other);
void invert();
void build(const CSGJSCPP_VECTOR<Polygon> &Polygon);
void build(CSGJSCPP_VECTOR<Polygon> &&Polygon);
CSGJSCPP_VECTOR<Polygon> clippolygons(const CSGJSCPP_VECTOR<Polygon> &list) const;
CSGJSCPP_VECTOR<Polygon> allpolygons() const;
/* same as allpolygons() but moves the polygons out, leaving the tree empty.
for callers that discard the node right after. */
CSGJSCPP_VECTOR<Polygon> takepolygons();
};
// Vertex implementation
// Invert all orientation-specific data (e.g. Vertex normal). Called when the
// orientation of a polygon is flipped.
inline Vertex flip(Vertex v) {
v.normal = negate(v.normal);
return v;
}
// Create a new Vertex between this Vertex and `other` by linearly
// interpolating all properties using a parameter of `t`. Subclasses should
// override this to interpolate additional properties.
inline Vertex interpolate(const Vertex &a, const Vertex &b, CSGJSCPP_REAL t) {
Vertex ret;
ret.pos = lerp(a.pos, b.pos, t);
ret.normal = lerp(a.normal, b.normal, t);
ret.col = lerp(a.col, b.col, t);
return ret;
}
// Plane implementation
Plane::Plane() : normal(), w(0.0f) {
}
Plane::Plane(const Vector &a, const Vector &b, const Vector &c) {
this->normal = unit(cross(b - a, c - a));
this->w = dot(this->normal, a);
}
// Split `polygon` by this plane if needed, then put the polygon or polygon
// fragments in the appropriate lists. Coplanar polygons go into either
// `coplanarFront` or `coplanarBack` depending on their orientation with
// respect to this plane. Polygons in front or in back of this plane go into
// either `front` or `back`.
void Plane::splitpolygon(const Polygon &poly, CSGJSCPP_VECTOR<Polygon> &coplanarFront,
CSGJSCPP_VECTOR<Polygon> &coplanarBack, CSGJSCPP_VECTOR<Polygon> &front,
CSGJSCPP_VECTOR<Polygon> &back) const {
splitpolygon(Polygon(poly), coplanarFront, coplanarBack, front, back);
}
void Plane::splitpolygon(Polygon &&poly, CSGJSCPP_VECTOR<Polygon> &coplanarFront,
CSGJSCPP_VECTOR<Polygon> &coplanarBack, CSGJSCPP_VECTOR<Polygon> &front,
CSGJSCPP_VECTOR<Polygon> &back) const {
// Classify each point as well as the entire polygon into one of the above
// four classes.
const size_t nv = poly.vertices.size();
int polygonType = 0;
for (size_t i = 0; i < nv; i++)
polygonType |= classify(poly.vertices[i].pos);
// Put the polygon in the correct list, splitting it when necessary.
switch (polygonType) {
case COPLANAR: {
if (dot(this->normal, poly.plane.normal) > 0) {
coplanarFront.push_back(std::move(poly));
} else {
coplanarBack.push_back(std::move(poly));
}
break;
}
case FRONT: {
front.push_back(std::move(poly));
break;
}
case BACK: {
back.push_back(std::move(poly));
break;
}
case SPANNING: {
CSGJSCPP_VECTOR<Vertex> f, b;
for (size_t i = 0; i < nv; i++) {
size_t j = (i + 1 == nv) ? 0 : i + 1;
const Vertex &vi = poly.vertices[i];
const Vertex &vj = poly.vertices[j];
const int ti = classify(vi.pos);
const int tj = classify(vj.pos);
if (ti != BACK)
f.push_back(vi);
if (ti != FRONT)
b.push_back(vi);
if ((ti | tj) == SPANNING) {
CSGJSCPP_REAL t = (this->w - dot(this->normal, vi.pos)) / dot(this->normal, vj.pos - vi.pos);
Vertex v = interpolate(vi, vj, t);
f.push_back(v);
b.push_back(v);
}
}
if (f.size() >= 3)
front.push_back(Polygon(std::move(f)));
if (b.size() >= 3)
back.push_back(Polygon(std::move(b)));
break;
}
}
}
// Polygon implementation
Polygon::Polygon() {
}
Polygon::Polygon(const CSGJSCPP_VECTOR<Vertex> &list)
: vertices(list), plane(vertices[0].pos, vertices[1].pos, vertices[2].pos) {
}
Polygon::Polygon(CSGJSCPP_VECTOR<Vertex> &&list)
: vertices(std::move(list)), plane(vertices[0].pos, vertices[1].pos, vertices[2].pos) {
}
// Node implementation
// Return a new CSG solid representing space in either this solid or in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
inline CSGNode *csg_union_inplace(CSGNode *a, CSGNode *b) {
a->clipto(b);
b->clipto(a);
b->invert();
b->clipto(a);
b->invert();
a->build(b->takepolygons());
return new CSGNode(a->takepolygons());
}
inline CSGNode *csg_union(const CSGNode *a1, const CSGNode *b1) {
CSGJSCPP_UNIQUEPTR<CSGNode> a(a1->clone());
CSGJSCPP_UNIQUEPTR<CSGNode> b(b1->clone());
return csg_union_inplace(a.get(), b.get());
}
// Return a new CSG solid representing space in this solid but not in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
inline CSGNode *csg_subtract_inplace(CSGNode *a, CSGNode *b) {
a->invert();
a->clipto(b);
b->clipto(a);
b->invert();
b->clipto(a);
b->invert();
a->build(b->takepolygons());
a->invert();
return new CSGNode(a->takepolygons());
}
inline CSGNode *csg_subtract(const CSGNode *a1, const CSGNode *b1) {
CSGJSCPP_UNIQUEPTR<CSGNode> a(a1->clone());
CSGJSCPP_UNIQUEPTR<CSGNode> b(b1->clone());
return csg_subtract_inplace(a.get(), b.get());
}
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
inline CSGNode *csg_intersect_inplace(CSGNode *a, CSGNode *b) {
a->invert();
b->clipto(a);
b->invert();
a->clipto(b);
b->clipto(a);
a->build(b->takepolygons());
a->invert();
return new CSGNode(a->takepolygons());
}
inline CSGNode *csg_intersect(const CSGNode *a1, const CSGNode *b1) {
CSGJSCPP_UNIQUEPTR<CSGNode> a(a1->clone());
CSGJSCPP_UNIQUEPTR<CSGNode> b(b1->clone());
return csg_intersect_inplace(a.get(), b.get());
}
// Convert solid space to empty space and empty space to solid space.
void CSGNode::invert() {
CSGJSCPP_VECTOR<CSGNode *> nodes;
nodes.push_back(this);
while (nodes.size()) {
CSGNode *me = nodes.back();
nodes.pop_back();
for (size_t i = 0; i < me->polygons.size(); i++)
me->polygons[i].flip();
me->plane.flip();
CSGJSCPP_SWAP(me->front, me->back);
if (me->front)
nodes.push_back(me->front);
if (me->back)
nodes.push_back(me->back);
}
}
// Recursively remove all polygons in `polygons` that are inside this BSP
// tree.
CSGJSCPP_VECTOR<Polygon> CSGNode::clippolygons(const CSGJSCPP_VECTOR<Polygon> &ilist) const {
CSGJSCPP_VECTOR<Polygon> result;
CSGJSCPP_VECTOR<CSGJSCPP_PAIR<const CSGNode *const, CSGJSCPP_VECTOR<Polygon>>> clips;
clips.push_back(CSGJSCPP_MAKEPAIR(this, ilist));
while (clips.size()) {
const CSGNode * me = clips.back().first;
CSGJSCPP_VECTOR<Polygon> list = std::move(clips.back().second);
clips.pop_back();
if (!me->plane.ok()) {
result.insert(result.end(), std::make_move_iterator(list.begin()),
std::make_move_iterator(list.end()));
continue;
}
CSGJSCPP_VECTOR<Polygon> list_front, list_back;
for (size_t i = 0; i < list.size(); i++)
me->plane.splitpolygon(std::move(list[i]), list_front, list_back, list_front, list_back);
if (me->front)
clips.push_back(CSGJSCPP_MAKEPAIR(me->front, std::move(list_front)));
else {
result.insert(result.end(), std::make_move_iterator(list_front.begin()),
std::make_move_iterator(list_front.end()));
}
if (me->back)
clips.push_back(CSGJSCPP_MAKEPAIR(me->back, std::move(list_back)));
}
return result;
}
// Remove all polygons in this BSP tree that are inside the other BSP tree
// `bsp`.
void CSGNode::clipto(const CSGNode *other) {
CSGJSCPP_VECTOR<CSGNode *> nodes;
nodes.push_back(this);
while (nodes.size()) {
CSGNode *me = nodes.back();
nodes.pop_back();
me->polygons = other->clippolygons(me->polygons);
if (me->front)
nodes.push_back(me->front);
if (me->back)
nodes.push_back(me->back);
}
}
// Return a list of all polygons in this BSP tree.
CSGJSCPP_VECTOR<Polygon> CSGNode::allpolygons() const {
CSGJSCPP_VECTOR<Polygon> result;
CSGJSCPP_VECTOR<const CSGNode *> nodes;
nodes.push_back(this);
while (nodes.size()) {
const CSGNode *me = nodes.back();
nodes.pop_back();
result.insert(result.end(), me->polygons.begin(), me->polygons.end());
if (me->front)
nodes.push_back(me->front);
if (me->back)
nodes.push_back(me->back);
}
return result;
}
CSGJSCPP_VECTOR<Polygon> CSGNode::takepolygons() {
CSGJSCPP_VECTOR<Polygon> result;
CSGJSCPP_VECTOR<CSGNode *> nodes;
nodes.push_back(this);
while (nodes.size()) {
CSGNode *me = nodes.back();
nodes.pop_back();
result.insert(result.end(), std::make_move_iterator(me->polygons.begin()),
std::make_move_iterator(me->polygons.end()));
me->polygons.clear();
if (me->front)
nodes.push_back(me->front);
if (me->back)
nodes.push_back(me->back);
}
return result;
}
CSGNode *CSGNode::clone() const {
CSGNode *ret = new CSGNode();
CSGJSCPP_VECTOR<CSGJSCPP_PAIR<const CSGNode *, CSGNode *>> nodes;
nodes.push_back(CSGJSCPP_MAKEPAIR(this, ret));
while (nodes.size()) {
const CSGNode *original = nodes.back().first;
CSGNode * clone = nodes.back().second;
nodes.pop_back();
clone->polygons = original->polygons;
clone->plane = original->plane;
if (original->front) {
clone->front = new CSGNode();
nodes.push_back(CSGJSCPP_MAKEPAIR(original->front, clone->front));
}
if (original->back) {
clone->back = new CSGNode();
nodes.push_back(CSGJSCPP_MAKEPAIR(original->back, clone->back));
}
}
return ret;
}
// Build a BSP tree out of `polygons`. When called on an existing tree, the
// new polygons are filtered down to the bottom of the tree and become new
// nodes there. Each set of polygons is partitioned using the first polygon
// (no heuristic is used to pick a good split).
void CSGNode::build(const CSGJSCPP_VECTOR<Polygon> &ilist) {
build(CSGJSCPP_VECTOR<Polygon>(ilist));
}
void CSGNode::build(CSGJSCPP_VECTOR<Polygon> &&ilist) {
if (!ilist.size())
return;
CSGJSCPP_VECTOR<CSGJSCPP_PAIR<CSGNode *, CSGJSCPP_VECTOR<Polygon>>> builds;
builds.push_back(CSGJSCPP_MAKEPAIR(this, std::move(ilist)));
while (builds.size()) {
CSGNode * me = builds.back().first;
CSGJSCPP_VECTOR<Polygon> list = std::move(builds.back().second);
builds.pop_back();
assert(list.size() > 0 && "logic error");
if (!me->plane.ok())
me->plane = list[0].plane;
CSGJSCPP_VECTOR<Polygon> list_front, list_back;
// me->polygons.push_back(list[0]);
for (size_t i = 0; i < list.size(); i++)
me->plane.splitpolygon(std::move(list[i]), me->polygons, me->polygons, list_front, list_back);
if (list_front.size()) {
if (!me->front)
me->front = new CSGNode;
builds.push_back(CSGJSCPP_MAKEPAIR(me->front, std::move(list_front)));
}
if (list_back.size()) {
if (!me->back)
me->back = new CSGNode;
builds.push_back(CSGJSCPP_MAKEPAIR(me->back, std::move(list_back)));
}
}
}
CSGNode::CSGNode() : front(nullptr), back(nullptr) {
}
CSGNode::CSGNode(const CSGJSCPP_VECTOR<Polygon> &list) : front(nullptr), back(nullptr) {
build(list);
}
CSGNode::CSGNode(CSGJSCPP_VECTOR<Polygon> &&list) : front(nullptr), back(nullptr) {
build(std::move(list));
}
CSGNode::~CSGNode() {
CSGJSCPP_VECTOR<CSGNode *> nodes_to_delete;
CSGJSCPP_VECTOR<CSGNode *> nodes_to_disassemble;
nodes_to_disassemble.push_back(this);
while (nodes_to_disassemble.size()) {
CSGNode *me = nodes_to_disassemble.back();
nodes_to_disassemble.pop_back();
if (me->front) {
nodes_to_disassemble.push_back(me->front);
nodes_to_delete.push_back(me->front);
me->front = NULL;
}
if (me->back) {
nodes_to_disassemble.push_back(me->back);
nodes_to_delete.push_back(me->back);
me->back = NULL;
}
}
for (auto it = nodes_to_delete.begin(); it != nodes_to_delete.end(); ++it)
delete *it;
}
// Public interface implementation
inline CSGJSCPP_VECTOR<Polygon> modeltopolygons(const Model &model) {
CSGJSCPP_VECTOR<Polygon> list;
for (size_t i = 0; i < model.indices.size(); i += 3) {
CSGJSCPP_VECTOR<Vertex> triangle;
for (int j = 0; j < 3; j++) {
Vertex v = model.vertices[model.indices[i + j]];
triangle.push_back(v);
}
list.push_back(Polygon(triangle));
}
return list;
}
namespace {
/* Spatial hash used by modelfrompolygons to find an existing equal vertex in
constant time instead of scanning every vertex already added.
A vertex is registered in every cell covering [pos - margin, pos + margin]
(at most 8). Two positions that compare equal differ by less than epsilon on
each axis, so any equal vertex is guaranteed to be registered in the cell a
lookup hashes to: one cell lookup is enough and no candidate can be missed.
Candidates are then compared with the normal Vertex operator==, so which
vertices are merged is exactly what the previous linear scan produced. */
struct VertexCell {
int32_t x, y, z;
bool operator==(const VertexCell &other) const {
return x == other.x && y == other.y && z == other.z;
}
};
struct VertexCellHash {
size_t operator()(const VertexCell &c) const {
return ((size_t)(uint32_t)c.x * 73856093u) ^ ((size_t)(uint32_t)c.y * 19349663u) ^
((size_t)(uint32_t)c.z * 83492791u);
}
};
/* Cell size is 4 * csgjs_EPSILON and vertices are registered over a window of
+/- vertexcellmargin, which is slightly wider than epsilon. The margin absorbs
the rounding of the window bounds, and a window of 2 * 1.01 * epsilon is always
narrower than one cell, so a vertex never needs more than 2 cells per axis. */
inline double vertexcellmargin() {
return 1.01 * (double)csgjs_EPSILON;
}
inline int32_t vertexcellcoord(double v) {
return (int32_t)std::floor(v / (4.0 * (double)csgjs_EPSILON));
}
} // namespace
Model modelfrompolygons(const CSGJSCPP_VECTOR<Polygon> &polygons) {
Model model;
size_t nvertices = 0;
for (size_t i = 0; i < polygons.size(); i++) {
nvertices += polygons[i].vertices.size();
}
model.vertices.reserve(nvertices);
model.indices.reserve(nvertices * 3);
/* Below this many vertices the linear scan is faster than hashing, so only
switch to the spatial hash once the quadratic cost starts to show. */
const size_t gridthreshold = 256;
CSGJSCPP_UNORDEREDMAP<VertexCell, CSGJSCPP_VECTOR<Model::Index>, VertexCellHash> grid;
bool usegrid = false;
/* register a vertex in every cell a lookup could come from */
auto registervertex = [&grid, &model](Model::Index index) {
const Vector &p = model.vertices[index].pos;
const double margin = vertexcellmargin();
const int32_t xs[2] = {vertexcellcoord((double)p.x - margin), vertexcellcoord((double)p.x + margin)};
const int32_t ys[2] = {vertexcellcoord((double)p.y - margin), vertexcellcoord((double)p.y + margin)};
const int32_t zs[2] = {vertexcellcoord((double)p.z - margin), vertexcellcoord((double)p.z + margin)};
const int nx = (xs[0] == xs[1]) ? 1 : 2;
const int ny = (ys[0] == ys[1]) ? 1 : 2;
const int nz = (zs[0] == zs[1]) ? 1 : 2;
for (int i = 0; i < nx; i++) {
for (int j = 0; j < ny; j++) {
for (int k = 0; k < nz; k++) {
const VertexCell cell = {xs[i], ys[j], zs[k]};
grid[cell].push_back(index);
}
}
}
};
auto addvertex = [&](const Vertex &newv) -> Model::Index {
if (!usegrid) {
for (Model::Index i = 0; i < (Model::Index)model.vertices.size(); i++) {
if (model.vertices[i] == newv) {
return i;
}
}
const Model::Index index = (Model::Index)model.vertices.size();
model.vertices.push_back(newv);
if (model.vertices.size() > gridthreshold) {
grid.reserve(nvertices);
for (Model::Index i = 0; i < (Model::Index)model.vertices.size(); i++) {
registervertex(i);
}
usegrid = true;
}
return index;
}
const VertexCell cell = {vertexcellcoord((double)newv.pos.x), vertexcellcoord((double)newv.pos.y),
vertexcellcoord((double)newv.pos.z)};
auto found = grid.find(cell);
if (found != grid.end()) {
const CSGJSCPP_VECTOR<Model::Index> &bucket = found->second;
bool hasmatch = false;
Model::Index match = 0;
for (size_t i = 0; i < bucket.size(); i++) {
const Model::Index candidate = bucket[i];
if (model.vertices[candidate] == newv) {
/* the linear scan returns the first match in insertion order,
keep the lowest index so the output is unchanged */
if (!hasmatch || candidate < match) {
match = candidate;
hasmatch = true;
}
}
}
if (hasmatch) {
return match;
}
}
const Model::Index index = (Model::Index)model.vertices.size();
model.vertices.push_back(newv);
registervertex(index);
return index;
};
for (size_t i = 0; i < polygons.size(); i++) {
const Polygon &poly = polygons[i];
if (poly.vertices.size()) {
Model::Index a = addvertex(poly.vertices[0]);
for (size_t j = 2; j < poly.vertices.size(); j++) {
Model::Index b = addvertex(poly.vertices[j - 1]);
Model::Index c = addvertex(poly.vertices[j]);
if (a != b && b != c && c != a) {
model.indices.push_back(a);
model.indices.push_back(b);
model.indices.push_back(c);
}
}
}
}
return model;
}
typedef CSGNode *csg_function(const CSGNode *a1, const CSGNode *b1);
typedef CSGNode *csg_inplace_function(CSGNode *a, CSGNode *b);
CSGJSCPP_VECTOR<Polygon> csgjs_operation(const CSGJSCPP_VECTOR<Polygon> &apoly, const CSGJSCPP_VECTOR<Polygon> &bpoly,
csg_inplace_function fun) {
/* A and B are ours, so the operation may consume them: no clone needed. */
CSGNode A(apoly);
CSGNode B(bpoly);
/* create a unique pointer here so we can delete AB on exit */
CSGJSCPP_UNIQUEPTR<CSGNode> AB(fun(&A, &B));
return AB->takepolygons();
}
inline CSGJSCPP_VECTOR<Polygon> csgjs_operation(const Model &a, const Model &b, csg_inplace_function fun) {
return csgjs_operation(modeltopolygons(a), modeltopolygons(b), fun);
}
/* kept for source compatibility with code passing the const/clone flavour */
inline CSGJSCPP_VECTOR<Polygon> csgjs_operation(const CSGJSCPP_VECTOR<Polygon> &apoly,
const CSGJSCPP_VECTOR<Polygon> &bpoly, csg_function fun) {
CSGNode A(apoly);
CSGNode B(bpoly);
CSGJSCPP_UNIQUEPTR<CSGNode> AB(fun(&A, &B));
return AB->takepolygons();
}
inline CSGJSCPP_VECTOR<Polygon> csgjs_operation(const Model &a, const Model &b, csg_function fun) {
return csgjs_operation(modeltopolygons(a), modeltopolygons(b), fun);
}
CSGJSCPP_VECTOR<Polygon> csgpolygon_cube(const Vector ¢er, const Vector &dim, const uint32_t col) {
struct Quad {
int indices[4];
Vector normal;
} quads[] = {{{0, 4, 6, 2}, {-1, 0, 0}}, {{1, 3, 7, 5}, {+1, 0, 0}}, {{0, 1, 5, 4}, {0, -1, 0}},
{{2, 6, 7, 3}, {0, +1, 0}}, {{0, 2, 3, 1}, {0, 0, -1}}, {{4, 5, 7, 6}, {0, 0, +1}}};
CSGJSCPP_VECTOR<Polygon> polygons;
for (const auto &q : quads) {
CSGJSCPP_VECTOR<Vertex> verts;
for (auto i : q.indices) {
Vector pos(center.x + dim.x * (2.0f * !!(i & 1) - 1), center.y + dim.y * (2.0f * !!(i & 2) - 1),
center.z + dim.z * (2.0f * !!(i & 4) - 1));
verts.push_back({pos, q.normal, col});
}
polygons.push_back(Polygon(verts));
}
return polygons;
}
Model csgmodel_cube(const Vector ¢er, const Vector &dim, uint32_t col) {
return modelfrompolygons(csgpolygon_cube(center, dim, col));
}
CSGJSCPP_VECTOR<Polygon> csgpolygon_sphere(const Vector &c, CSGJSCPP_REAL r, uint32_t col, int slices, int stacks) {
CSGJSCPP_VECTOR<Polygon> polygons;
auto mkvertex = [c, r, col](CSGJSCPP_REAL theta, CSGJSCPP_REAL phi) -> Vertex {
theta *= (CSGJSCPP_REAL)M_PI * 2;
phi *= (CSGJSCPP_REAL)M_PI;
Vector dir((CSGJSCPP_REAL)cos(theta) * (CSGJSCPP_REAL)sin(phi), (CSGJSCPP_REAL)cos(phi),
(CSGJSCPP_REAL)sin(theta) * (CSGJSCPP_REAL)sin(phi));
return Vertex{c + (dir * r), dir, col};
};
for (CSGJSCPP_REAL i = 0; i < slices; i++) {
for (CSGJSCPP_REAL j = 0; j < stacks; j++) {
CSGJSCPP_VECTOR<Vertex> vertices;
vertices.push_back(mkvertex(i / slices, j / stacks));
if (j > 0) {
vertices.push_back(mkvertex((i + 1) / slices, j / stacks));
}
if (j < stacks - 1) {
vertices.push_back(mkvertex((i + 1) / slices, (j + 1) / stacks));
}
vertices.push_back(mkvertex(i / slices, (j + 1) / stacks));
polygons.push_back(Polygon(vertices));
}
}
return polygons;
}
Model csgmodel_sphere(const Vector &c, CSGJSCPP_REAL r, uint32_t col, int slices, int stacks) {
return modelfrompolygons(csgpolygon_sphere(c, r, col, slices, stacks));
}
CSGJSCPP_VECTOR<Polygon> csgpolygon_cylinder(const Vector &s, const Vector &e, CSGJSCPP_REAL r, uint32_t col,
int slices) {
Vector ray = e - s;
Vector axisZ = unit(ray);
bool isY = fabs(axisZ.y) > 0.5f;
Vector axisX = unit(cross(Vector(isY, !isY, 0), axisZ));
Vector axisY = unit(cross(axisX, axisZ));
Vertex start{s, -axisZ, col};
Vertex end{e, unit(axisZ), col};
CSGJSCPP_VECTOR<Polygon> polygons;
auto point = [axisX, axisY, s, r, ray, axisZ, col](CSGJSCPP_REAL stack, CSGJSCPP_REAL slice,