forked from jscad/OpenJSCAD.org
-
Notifications
You must be signed in to change notification settings - Fork 1
/
csg.js
6561 lines (6074 loc) · 284 KB
/
csg.js
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
/*
## IMPORTANT NOTE --- IMPORTANT
The master for this file is located at:
https://github.com/joostn/openjscad/tree/gh-pages
That is the gh-pages branch of the joostn/openjscad project
If contributing from openjscad.org, please do NOT edit this local file but make pull requests against
above joostn/gh-pages branch.
## IMPORTANT NOTE --- IMPORTANT NOTE
## License
Copyright (c) 2014 bebbi ([email protected])
Copyright (c) 2013 Eduard Bespalov ([email protected])
Copyright (c) 2012 Joost Nieuwenhuijse ([email protected])
Copyright (c) 2011 Evan Wallace (http://evanw.github.com/csg.js/)
Copyright (c) 2012 Alexandre Girard (https://github.com/alx)
All code released under MIT license
## Overview
For an overview of the CSG process see the original csg.js code:
http://evanw.github.com/csg.js/
CSG operations through BSP trees suffer from one problem: heavy fragmentation
of polygons. If two CSG solids of n polygons are unified, the resulting solid may have
in the order of n*n polygons, because each polygon is split by the planes of all other
polygons. After a few operations the number of polygons explodes.
This version of CSG.js solves the problem in 3 ways:
1. Every polygon split is recorded in a tree (CSG.PolygonTreeNode). This is a separate
tree, not to be confused with the CSG tree. If a polygon is split into two parts but in
the end both fragments have not been discarded by the CSG operation, we can retrieve
the original unsplit polygon from the tree, instead of the two fragments.
This does not completely solve the issue though: if a polygon is split multiple times
the number of fragments depends on the order of subsequent splits, and we might still
end up with unncessary splits:
Suppose a polygon is first split into A and B, and then into A1, B1, A2, B2. Suppose B2 is
discarded. We will end up with 2 polygons: A and B1. Depending on the actual split boundaries
we could still have joined A and B1 into one polygon. Therefore a second approach is used as well:
2. After CSG operations all coplanar polygon fragments are joined by a retesselating
operation. See CSG.reTesselated(). Retesselation is done through a
linear sweep over the polygon surface. The sweep line passes over the y coordinates
of all vertices in the polygon. Polygons are split at each sweep line, and the fragments
are joined horizontally and vertically into larger polygons (making sure that we
will end up with convex polygons).
This still doesn't solve the problem completely: due to floating point imprecisions
we may end up with small gaps between polygons, and polygons may not be exactly coplanar
anymore, and as a result the retesselation algorithm may fail to join those polygons.
Therefore:
3. A canonicalization algorithm is implemented: it looks for vertices that have
approximately the same coordinates (with a certain tolerance, say 1e-5) and replaces
them with the same vertex. If polygons share a vertex they will actually point to the
same CSG.Vertex instance. The same is done for polygon planes. See CSG.canonicalized().
Performance improvements to the original CSG.js:
Replaced the flip() and invert() methods by flipped() and inverted() which don't
modify the source object. This allows to get rid of all clone() calls, so that
multiple polygons can refer to the same CSG.Plane instance etc.
The original union() used an extra invert(), clipTo(), invert() sequence just to remove the
coplanar front faces from b; this is now combined in a single b.clipTo(a, true) call.
Detection whether a polygon is in front or in back of a plane: for each polygon
we are caching the coordinates of the bounding sphere. If the bounding sphere is
in front or in back of the plane we don't have to check the individual vertices
anymore.
Other additions to the original CSG.js:
CSG.Vector class has been renamed into CSG.Vector3D
Classes for 3D lines, 2D vectors, 2D lines, and methods to find the intersection of
a line and a plane etc.
Transformations: CSG.transform(), CSG.translate(), CSG.rotate(), CSG.scale()
Expanding or contracting a solid: CSG.expand() and CSG.contract(). Creates nice
smooth corners.
The vertex normal has been removed since it complicates retesselation. It's not needed
for solid CAD anyway.
*/
(function(module) {
var _CSGDEBUG = false;
function fnNumberSort(a, b) {
return a - b;
}
// # class CSG
// Holds a binary space partition tree representing a 3D solid. Two solids can
// be combined using the `union()`, `subtract()`, and `intersect()` methods.
var CSG = function() {
this.polygons = [];
this.properties = new CSG.Properties();
this.isCanonicalized = true;
this.isRetesselated = true;
};
CSG.defaultResolution2D = 32;
CSG.defaultResolution3D = 12;
// Construct a CSG solid from a list of `CSG.Polygon` instances.
CSG.fromPolygons = function(polygons) {
var csg = new CSG();
csg.polygons = polygons;
csg.isCanonicalized = false;
csg.isRetesselated = false;
return csg;
};
// Construct a CSG solid from generated slices.
// Look at CSG.Polygon.prototype.solidFromSlices for details
CSG.fromSlices = function(options) {
return (new CSG.Polygon.createFromPoints([
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0]
])).solidFromSlices(options);
};
// create from an untyped object with identical property names:
CSG.fromObject = function(obj) {
var polygons = obj.polygons.map(function(p) {
return CSG.Polygon.fromObject(p);
});
var csg = CSG.fromPolygons(polygons);
csg = csg.canonicalized();
return csg;
};
// Reconstruct a CSG from the output of toCompactBinary()
CSG.fromCompactBinary = function(bin) {
if (bin['class'] != "CSG") throw new Error("Not a CSG");
var planes = [],
planeData = bin.planeData,
numplanes = planeData.length / 4,
arrayindex = 0,
x, y, z, w, normal, plane;
for (var planeindex = 0; planeindex < numplanes; planeindex++) {
x = planeData[arrayindex++];
y = planeData[arrayindex++];
z = planeData[arrayindex++];
w = planeData[arrayindex++];
normal = CSG.Vector3D.Create(x, y, z);
plane = new CSG.Plane(normal, w);
planes.push(plane);
}
var vertices = [],
vertexData = bin.vertexData,
numvertices = vertexData.length / 3,
pos, vertex;
arrayindex = 0;
for (var vertexindex = 0; vertexindex < numvertices; vertexindex++) {
x = vertexData[arrayindex++];
y = vertexData[arrayindex++];
z = vertexData[arrayindex++];
pos = CSG.Vector3D.Create(x, y, z);
vertex = new CSG.Vertex(pos);
vertices.push(vertex);
}
var shareds = bin.shared.map(function(shared) {
return CSG.Polygon.Shared.fromObject(shared);
});
var polygons = [],
numpolygons = bin.numPolygons,
numVerticesPerPolygon = bin.numVerticesPerPolygon,
polygonVertices = bin.polygonVertices,
polygonPlaneIndexes = bin.polygonPlaneIndexes,
polygonSharedIndexes = bin.polygonSharedIndexes,
numpolygonvertices, polygonvertices, shared, polygon; //already defined plane,
arrayindex = 0;
for (var polygonindex = 0; polygonindex < numpolygons; polygonindex++) {
numpolygonvertices = numVerticesPerPolygon[polygonindex];
polygonvertices = [];
for (var i = 0; i < numpolygonvertices; i++) {
polygonvertices.push(vertices[polygonVertices[arrayindex++]]);
}
plane = planes[polygonPlaneIndexes[polygonindex]];
shared = shareds[polygonSharedIndexes[polygonindex]];
polygon = new CSG.Polygon(polygonvertices, shared, plane);
polygons.push(polygon);
}
var csg = CSG.fromPolygons(polygons);
csg.isCanonicalized = true;
csg.isRetesselated = true;
return csg;
};
CSG.prototype = {
toPolygons: function() {
return this.polygons;
},
// 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.
//
// A.union(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +----+
// +----+--+ | +----+ |
// | B | | |
// | | | |
// +-------+ +-------+
//
union: function(csg) {
var csgs;
if (csg instanceof Array) {
csgs = csg.slice(0);
csgs.push(this);
} else {
csgs = [this, csg];
}
// combine csg pairs in a way that forms a balanced binary tree pattern
for (var i = 1; i < csgs.length; i += 2) {
csgs.push(csgs[i-1].unionSub(csgs[i]));
}
return csgs[i - 1].reTesselated().canonicalized();
},
unionSub: function(csg, retesselate, canonicalize) {
if (!this.mayOverlap(csg)) {
return this.unionForNonIntersecting(csg);
} else {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.clipTo(b, false);
// b.clipTo(a, true); // ERROR: this doesn't work
b.clipTo(a);
b.invert();
b.clipTo(a);
b.invert();
var newpolygons = a.allPolygons().concat(b.allPolygons());
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._merge(csg.properties);
if (retesselate) result = result.reTesselated();
if (canonicalize) result = result.canonicalized();
return result;
}
},
// Like union, but when we know that the two solids are not intersecting
// Do not use if you are not completely sure that the solids do not intersect!
unionForNonIntersecting: function(csg) {
var newpolygons = this.polygons.concat(csg.polygons);
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._merge(csg.properties);
result.isCanonicalized = this.isCanonicalized && csg.isCanonicalized;
result.isRetesselated = this.isRetesselated && csg.isRetesselated;
return result;
},
// 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.
//
// A.subtract(B)
//
// +-------+ +-------+
// | | | |
// | A | | |
// | +--+----+ = | +--+
// +----+--+ | +----+
// | B |
// | |
// +-------+
//
subtract: function(csg) {
var csgs;
if (csg instanceof Array) {
csgs = csg;
} else {
csgs = [csg];
}
var result = this;
for (var i = 0; i < csgs.length; i++) {
var islast = (i == (csgs.length - 1));
result = result.subtractSub(csgs[i], islast, islast);
}
return result;
},
subtractSub: function(csg, retesselate, canonicalize) {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.invert();
a.clipTo(b);
b.clipTo(a, true);
a.addPolygons(b.allPolygons());
a.invert();
var result = CSG.fromPolygons(a.allPolygons());
result.properties = this.properties._merge(csg.properties);
if (retesselate) result = result.reTesselated();
if (canonicalize) result = result.canonicalized();
return result;
},
// Return a new CSG solid representing space both this solid and in the
// solid `csg`. Neither this solid nor the solid `csg` are modified.
//
// A.intersect(B)
//
// +-------+
// | |
// | A |
// | +--+----+ = +--+
// +----+--+ | +--+
// | B |
// | |
// +-------+
//
intersect: function(csg) {
var csgs;
if (csg instanceof Array) {
csgs = csg;
} else {
csgs = [csg];
}
var result = this;
for (var i = 0; i < csgs.length; i++) {
var islast = (i == (csgs.length - 1));
result = result.intersectSub(csgs[i], islast, islast);
}
return result;
},
intersectSub: function(csg, retesselate, canonicalize) {
var a = new CSG.Tree(this.polygons);
var b = new CSG.Tree(csg.polygons);
a.invert();
b.clipTo(a);
b.invert();
a.clipTo(b);
b.clipTo(a);
a.addPolygons(b.allPolygons());
a.invert();
var result = CSG.fromPolygons(a.allPolygons());
result.properties = this.properties._merge(csg.properties);
if (retesselate) result = result.reTesselated();
if (canonicalize) result = result.canonicalized();
return result;
},
// Return a new CSG solid with solid and empty space switched. This solid is
// not modified.
invert: function() {
var flippedpolygons = this.polygons.map(function(p) {
return p.flipped();
});
return CSG.fromPolygons(flippedpolygons);
// TODO: flip properties?
},
// Affine transformation of CSG object. Returns a new CSG object
transform1: function(matrix4x4) {
var newpolygons = this.polygons.map(function(p) {
return p.transform(matrix4x4);
});
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._transform(matrix4x4);
result.isRetesselated = this.isRetesselated;
return result;
},
transform: function(matrix4x4) {
var ismirror = matrix4x4.isMirroring();
var transformedvertices = {};
var transformedplanes = {};
var newpolygons = this.polygons.map(function(p) {
var newplane;
var plane = p.plane;
var planetag = plane.getTag();
if (planetag in transformedplanes) {
newplane = transformedplanes[planetag];
} else {
newplane = plane.transform(matrix4x4);
transformedplanes[planetag] = newplane;
}
var newvertices = p.vertices.map(function(v) {
var newvertex;
var vertextag = v.getTag();
if (vertextag in transformedvertices) {
newvertex = transformedvertices[vertextag];
} else {
newvertex = v.transform(matrix4x4);
transformedvertices[vertextag] = newvertex;
}
return newvertex;
});
if (ismirror) newvertices.reverse();
return new CSG.Polygon(newvertices, p.shared, newplane);
});
var result = CSG.fromPolygons(newpolygons);
result.properties = this.properties._transform(matrix4x4);
result.isRetesselated = this.isRetesselated;
result.isCanonicalized = this.isCanonicalized;
return result;
},
toString: function() {
var result = "CSG solid:\n";
this.polygons.map(function(p) {
result += p.toString();
});
return result;
},
// Expand the solid
// resolution: number of points per 360 degree for the rounded corners
expand: function(radius, resolution) {
var result = this.expandedShell(radius, resolution, true);
result = result.reTesselated();
result.properties = this.properties; // keep original properties
return result;
},
// Contract the solid
// resolution: number of points per 360 degree for the rounded corners
contract: function(radius, resolution) {
var expandedshell = this.expandedShell(radius, resolution, false);
var result = this.subtract(expandedshell);
result = result.reTesselated();
result.properties = this.properties; // keep original properties
return result;
},
// cut the solid at a plane, and stretch the cross-section found along plane normal
stretchAtPlane: function(normal, point, length) {
var plane = CSG.Plane.fromNormalAndPoint(normal, point);
var onb = new CSG.OrthoNormalBasis(plane);
var crosssect = this.sectionCut(onb);
var midpiece = crosssect.extrudeInOrthonormalBasis(onb, length);
var piece1 = this.cutByPlane(plane);
var piece2 = this.cutByPlane(plane.flipped());
var result = piece1.union([midpiece, piece2.translate(plane.normal.times(length))]);
return result;
},
// Create the expanded shell of the solid:
// All faces are extruded to get a thickness of 2*radius
// Cylinders are constructed around every side
// Spheres are placed on every vertex
// unionWithThis: if true, the resulting solid will be united with 'this' solid;
// the result is a true expansion of the solid
// If false, returns only the shell
expandedShell: function(radius, resolution, unionWithThis) {
var csg = this.reTesselated();
var result;
if (unionWithThis) {
result = csg;
} else {
result = new CSG();
}
// first extrude all polygons:
csg.polygons.map(function(polygon) {
var extrudevector = polygon.plane.normal.unit().times(2 * radius);
var translatedpolygon = polygon.translate(extrudevector.times(-0.5));
var extrudedface = translatedpolygon.extrude(extrudevector);
result = result.unionSub(extrudedface, false, false);
});
// Make a list of all unique vertex pairs (i.e. all sides of the solid)
// For each vertex pair we collect the following:
// v1: first coordinate
// v2: second coordinate
// planenormals: array of normal vectors of all planes touching this side
var vertexpairs = {}; // map of 'vertex pair tag' to {v1, v2, planenormals}
csg.polygons.map(function(polygon) {
var numvertices = polygon.vertices.length;
var prevvertex = polygon.vertices[numvertices - 1];
var prevvertextag = prevvertex.getTag();
for (var i = 0; i < numvertices; i++) {
var vertex = polygon.vertices[i];
var vertextag = vertex.getTag();
var vertextagpair;
if (vertextag < prevvertextag) {
vertextagpair = vertextag + "-" + prevvertextag;
} else {
vertextagpair = prevvertextag + "-" + vertextag;
}
var obj;
if (vertextagpair in vertexpairs) {
obj = vertexpairs[vertextagpair];
} else {
obj = {
v1: prevvertex,
v2: vertex,
planenormals: []
};
vertexpairs[vertextagpair] = obj;
}
obj.planenormals.push(polygon.plane.normal);
prevvertextag = vertextag;
prevvertex = vertex;
}
});
// now construct a cylinder on every side
// The cylinder is always an approximation of a true cylinder: it will have <resolution> polygons
// around the sides. We will make sure though that the cylinder will have an edge at every
// face that touches this side. This ensures that we will get a smooth fill even
// if two edges are at, say, 10 degrees and the resolution is low.
// Note: the result is not retesselated yet but it really should be!
for (var vertextagpair in vertexpairs) {
var vertexpair = vertexpairs[vertextagpair],
startpoint = vertexpair.v1.pos,
endpoint = vertexpair.v2.pos,
// our x,y and z vectors:
zbase = endpoint.minus(startpoint).unit(),
xbase = vertexpair.planenormals[0].unit(),
ybase = xbase.cross(zbase),
// make a list of angles that the cylinder should traverse:
angles = [];
// first of all equally spaced around the cylinder:
for (var i = 0; i < resolution; i++) {
angles.push(i * Math.PI * 2 / resolution);
}
// and also at every normal of all touching planes:
for (var i = 0, iMax = vertexpair.planenormals.length; i < iMax; i++) {
var planenormal = vertexpair.planenormals[i],
si = ybase.dot(planenormal),
co = xbase.dot(planenormal),
angle = Math.atan2(si, co);
if (angle < 0) angle += Math.PI * 2;
angles.push(angle);
angle = Math.atan2(-si, -co);
if (angle < 0) angle += Math.PI * 2;
angles.push(angle);
}
// this will result in some duplicate angles but we will get rid of those later.
// Sort:
angles = angles.sort(fnNumberSort);
// Now construct the cylinder by traversing all angles:
var numangles = angles.length,
prevp1, prevp2,
startfacevertices = [],
endfacevertices = [],
polygons = [];
for (var i = -1; i < numangles; i++) {
var angle = angles[(i < 0) ? (i + numangles) : i],
si = Math.sin(angle),
co = Math.cos(angle),
p = xbase.times(co * radius).plus(ybase.times(si * radius)),
p1 = startpoint.plus(p),
p2 = endpoint.plus(p),
skip = false;
if (i >= 0) {
if (p1.distanceTo(prevp1) < 1e-5) {
skip = true;
}
}
if (!skip) {
if (i >= 0) {
startfacevertices.push(new CSG.Vertex(p1));
endfacevertices.push(new CSG.Vertex(p2));
var polygonvertices = [
new CSG.Vertex(prevp2),
new CSG.Vertex(p2),
new CSG.Vertex(p1),
new CSG.Vertex(prevp1)
];
var polygon = new CSG.Polygon(polygonvertices);
polygons.push(polygon);
}
prevp1 = p1;
prevp2 = p2;
}
}
endfacevertices.reverse();
polygons.push(new CSG.Polygon(startfacevertices));
polygons.push(new CSG.Polygon(endfacevertices));
var cylinder = CSG.fromPolygons(polygons);
result = result.unionSub(cylinder, false, false);
}
// make a list of all unique vertices
// For each vertex we also collect the list of normals of the planes touching the vertices
var vertexmap = {};
csg.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
var vertextag = vertex.getTag();
var obj;
if (vertextag in vertexmap) {
obj = vertexmap[vertextag];
} else {
obj = {
pos: vertex.pos,
normals: []
};
vertexmap[vertextag] = obj;
}
obj.normals.push(polygon.plane.normal);
});
});
// and build spheres at each vertex
// We will try to set the x and z axis to the normals of 2 planes
// This will ensure that our sphere tesselation somewhat matches 2 planes
for (var vertextag in vertexmap) {
var vertexobj = vertexmap[vertextag];
// use the first normal to be the x axis of our sphere:
var xaxis = vertexobj.normals[0].unit();
// and find a suitable z axis. We will use the normal which is most perpendicular to the x axis:
var bestzaxis = null;
var bestzaxisorthogonality = 0;
for (var i = 1; i < vertexobj.normals.length; i++) {
var normal = vertexobj.normals[i].unit();
var cross = xaxis.cross(normal);
var crosslength = cross.length();
if (crosslength > 0.05) {
if (crosslength > bestzaxisorthogonality) {
bestzaxisorthogonality = crosslength;
bestzaxis = normal;
}
}
}
if (!bestzaxis) {
bestzaxis = xaxis.randomNonParallelVector();
}
var yaxis = xaxis.cross(bestzaxis).unit();
var zaxis = yaxis.cross(xaxis);
var sphere = CSG.sphere({
center: vertexobj.pos,
radius: radius,
resolution: resolution,
axes: [xaxis, yaxis, zaxis]
});
result = result.unionSub(sphere, false, false);
}
return result;
},
canonicalized: function() {
if (this.isCanonicalized) {
return this;
} else {
var factory = new CSG.fuzzyCSGFactory();
var result = factory.getCSG(this);
result.isCanonicalized = true;
result.isRetesselated = this.isRetesselated;
result.properties = this.properties; // keep original properties
return result;
}
},
reTesselated: function() {
if (this.isRetesselated) {
return this;
} else {
var csg = this;
var polygonsPerPlane = {};
var isCanonicalized = csg.isCanonicalized;
var fuzzyfactory = new CSG.fuzzyCSGFactory();
csg.polygons.map(function(polygon) {
var plane = polygon.plane;
var shared = polygon.shared;
if (!isCanonicalized) {
// in order to identify to polygons having the same plane, we need to canonicalize the planes
// We don't have to do a full canonizalization (including vertices), to save time only do the planes and the shared data:
plane = fuzzyfactory.getPlane(plane);
shared = fuzzyfactory.getPolygonShared(shared);
}
var tag = plane.getTag() + "/" + shared.getTag();
if (!(tag in polygonsPerPlane)) {
polygonsPerPlane[tag] = [polygon];
} else {
polygonsPerPlane[tag].push(polygon);
}
});
var destpolygons = [];
for (var planetag in polygonsPerPlane) {
var sourcepolygons = polygonsPerPlane[planetag];
if (sourcepolygons.length < 2) {
destpolygons = destpolygons.concat(sourcepolygons);
} else {
var retesselayedpolygons = [];
CSG.reTesselateCoplanarPolygons(sourcepolygons, retesselayedpolygons);
destpolygons = destpolygons.concat(retesselayedpolygons);
}
}
var result = CSG.fromPolygons(destpolygons);
result.isRetesselated = true;
// result = result.canonicalized();
result.properties = this.properties; // keep original properties
return result;
}
},
// returns an array of two CSG.Vector3Ds (minimum coordinates and maximum coordinates)
getBounds: function() {
if (!this.cachedBoundingBox) {
var minpoint = new CSG.Vector3D(0, 0, 0);
var maxpoint = new CSG.Vector3D(0, 0, 0);
var polygons = this.polygons;
var numpolygons = polygons.length;
for (var i = 0; i < numpolygons; i++) {
var polygon = polygons[i];
var bounds = polygon.boundingBox();
if (i === 0) {
minpoint = bounds[0];
maxpoint = bounds[1];
} else {
minpoint = minpoint.min(bounds[0]);
maxpoint = maxpoint.max(bounds[1]);
}
}
this.cachedBoundingBox = [minpoint, maxpoint];
}
return this.cachedBoundingBox;
},
// returns true if there is a possibility that the two solids overlap
// returns false if we can be sure that they do not overlap
mayOverlap: function(csg) {
if ((this.polygons.length === 0) || (csg.polygons.length === 0)) {
return false;
} else {
var mybounds = this.getBounds();
var otherbounds = csg.getBounds();
if (mybounds[1].x < otherbounds[0].x) return false;
if (mybounds[0].x > otherbounds[1].x) return false;
if (mybounds[1].y < otherbounds[0].y) return false;
if (mybounds[0].y > otherbounds[1].y) return false;
if (mybounds[1].z < otherbounds[0].z) return false;
if (mybounds[0].z > otherbounds[1].z) return false;
return true;
}
},
// Cut the solid by a plane. Returns the solid on the back side of the plane
cutByPlane: function(plane) {
if (this.polygons.length === 0) {
return new CSG();
}
// Ideally we would like to do an intersection with a polygon of inifinite size
// but this is not supported by our implementation. As a workaround, we will create
// a cube, with one face on the plane, and a size larger enough so that the entire
// solid fits in the cube.
// find the max distance of any vertex to the center of the plane:
var planecenter = plane.normal.times(plane.w);
var maxdistance = 0;
this.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
var distance = vertex.pos.distanceToSquared(planecenter);
if (distance > maxdistance) maxdistance = distance;
});
});
maxdistance = Math.sqrt(maxdistance);
maxdistance *= 1.01; // make sure it's really larger
// Now build a polygon on the plane, at any point farther than maxdistance from the plane center:
var vertices = [];
var orthobasis = new CSG.OrthoNormalBasis(plane);
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance))));
vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance))));
var polygon = new CSG.Polygon(vertices, null, plane.flipped());
// and extrude the polygon into a cube, backwards of the plane:
var cube = polygon.extrude(plane.normal.times(-maxdistance));
// Now we can do the intersection:
var result = this.intersect(cube);
result.properties = this.properties; // keep original properties
return result;
},
// Connect a solid to another solid, such that two CSG.Connectors become connected
// myConnector: a CSG.Connector of this solid
// otherConnector: a CSG.Connector to which myConnector should be connected
// mirror: false: the 'axis' vectors of the connectors should point in the same direction
// true: the 'axis' vectors of the connectors should point in opposite direction
// normalrotation: degrees of rotation between the 'normal' vectors of the two
// connectors
connectTo: function(myConnector, otherConnector, mirror, normalrotation) {
var matrix = myConnector.getTransformationTo(otherConnector, mirror, normalrotation);
return this.transform(matrix);
},
// set the .shared property of all polygons
// Returns a new CSG solid, the original is unmodified!
setShared: function(shared) {
var polygons = this.polygons.map(function(p) {
return new CSG.Polygon(p.vertices, shared, p.plane);
});
var result = CSG.fromPolygons(polygons);
result.properties = this.properties; // keep original properties
result.isRetesselated = this.isRetesselated;
result.isCanonicalized = this.isCanonicalized;
return result;
},
setColor: function(args) {
var newshared = CSG.Polygon.Shared.fromColor.apply(this, arguments);
return this.setShared(newshared);
},
toCompactBinary: function() {
var csg = this.canonicalized(),
numpolygons = csg.polygons.length,
numpolygonvertices = 0,
numvertices = 0,
vertexmap = {},
vertices = [],
numplanes = 0,
planemap = {},
polygonindex = 0,
planes = [],
shareds = [],
sharedmap = {},
numshared = 0;
// for (var i = 0, iMax = csg.polygons.length; i < iMax; i++) {
// var p = csg.polygons[i];
// for (var j = 0, jMax = p.length; j < jMax; j++) {
// ++numpolygonvertices;
// var vertextag = p[j].getTag();
// if(!(vertextag in vertexmap)) {
// vertexmap[vertextag] = numvertices++;
// vertices.push(p[j]);
// }
// }
csg.polygons.map(function(p) {
p.vertices.map(function(v) {
++numpolygonvertices;
var vertextag = v.getTag();
if (!(vertextag in vertexmap)) {
vertexmap[vertextag] = numvertices++;
vertices.push(v);
}
});
var planetag = p.plane.getTag();
if (!(planetag in planemap)) {
planemap[planetag] = numplanes++;
planes.push(p.plane);
}
var sharedtag = p.shared.getTag();
if (!(sharedtag in sharedmap)) {
sharedmap[sharedtag] = numshared++;
shareds.push(p.shared);
}
});
var numVerticesPerPolygon = new Uint32Array(numpolygons),
polygonSharedIndexes = new Uint32Array(numpolygons),
polygonVertices = new Uint32Array(numpolygonvertices),
polygonPlaneIndexes = new Uint32Array(numpolygons),
vertexData = new Float64Array(numvertices * 3),
planeData = new Float64Array(numplanes * 4),
polygonVerticesIndex = 0;
for (var polygonindex = 0; polygonindex < numpolygons; ++polygonindex) {
var p = csg.polygons[polygonindex];
numVerticesPerPolygon[polygonindex] = p.vertices.length;
p.vertices.map(function(v) {
var vertextag = v.getTag();
var vertexindex = vertexmap[vertextag];
polygonVertices[polygonVerticesIndex++] = vertexindex;
});
var planetag = p.plane.getTag();
var planeindex = planemap[planetag];
polygonPlaneIndexes[polygonindex] = planeindex;
var sharedtag = p.shared.getTag();
var sharedindex = sharedmap[sharedtag];
polygonSharedIndexes[polygonindex] = sharedindex;
}
var verticesArrayIndex = 0;
vertices.map(function(v) {
var pos = v.pos;
vertexData[verticesArrayIndex++] = pos._x;
vertexData[verticesArrayIndex++] = pos._y;
vertexData[verticesArrayIndex++] = pos._z;
});
var planesArrayIndex = 0;
planes.map(function(p) {
var normal = p.normal;
planeData[planesArrayIndex++] = normal._x;
planeData[planesArrayIndex++] = normal._y;
planeData[planesArrayIndex++] = normal._z;
planeData[planesArrayIndex++] = p.w;
});
var result = {
"class": "CSG",
numPolygons: numpolygons,
numVerticesPerPolygon: numVerticesPerPolygon,
polygonPlaneIndexes: polygonPlaneIndexes,
polygonSharedIndexes: polygonSharedIndexes,
polygonVertices: polygonVertices,
vertexData: vertexData,
planeData: planeData,
shared: shareds
};
return result;
},
// For debugging
// Creates a new solid with a tiny cube at every vertex of the source solid
toPointCloud: function(cuberadius) {
var csg = this.reTesselated();
var result = new CSG();
// make a list of all unique vertices
// For each vertex we also collect the list of normals of the planes touching the vertices
var vertexmap = {};
csg.polygons.map(function(polygon) {
polygon.vertices.map(function(vertex) {
vertexmap[vertex.getTag()] = vertex.pos;
});
});
for (var vertextag in vertexmap) {
var pos = vertexmap[vertextag];
var cube = CSG.cube({
center: pos,
radius: cuberadius
});
result = result.unionSub(cube, false, false);
}
result = result.reTesselated();
return result;
},
// Get the transformation that transforms this CSG such that it is lying on the z=0 plane,
// as flat as possible (i.e. the least z-height).
// So that it is in an orientation suitable for CNC milling
getTransformationAndInverseTransformationToFlatLying: function() {
if (this.polygons.length === 0) {
return new CSG.Matrix4x4(); // unity
} else {
// get a list of unique planes in the CSG:
var csg = this.canonicalized();
var planemap = {};
csg.polygons.map(function(polygon) {
planemap[polygon.plane.getTag()] = polygon.plane;
});
// try each plane in the CSG and find the plane that, when we align it flat onto z=0,
// gives the least height in z-direction.
// If two planes give the same height, pick the plane that originally had a normal closest
// to [0,0,-1].
var xvector = new CSG.Vector3D(1, 0, 0);
var yvector = new CSG.Vector3D(0, 1, 0);
var zvector = new CSG.Vector3D(0, 0, 1);
var z0connectorx = new CSG.Connector([0, 0, 0], [0, 0, -1], xvector);
var z0connectory = new CSG.Connector([0, 0, 0], [0, 0, -1], yvector);
var isfirst = true;
var minheight = 0;
var maxdotz = 0;
var besttransformation, bestinversetransformation;
for (var planetag in planemap) {
var plane = planemap[planetag];
var pointonplane = plane.normal.times(plane.w);
var transformation, inversetransformation;
// We need a normal vecrtor for the transformation
// determine which is more perpendicular to the plane normal: x or y?
// we will align this as much as possible to the x or y axis vector
var xorthogonality = plane.normal.cross(xvector).length();
var yorthogonality = plane.normal.cross(yvector).length();
if (xorthogonality > yorthogonality) {
// x is better:
var planeconnector = new CSG.Connector(pointonplane, plane.normal, xvector);
transformation = planeconnector.getTransformationTo(z0connectorx, false, 0);
inversetransformation = z0connectorx.getTransformationTo(planeconnector, false, 0);
} else {
// y is better:
var planeconnector = new CSG.Connector(pointonplane, plane.normal, yvector);
transformation = planeconnector.getTransformationTo(z0connectory, false, 0);
inversetransformation = z0connectory.getTransformationTo(planeconnector, false, 0);
}