forked from solvespace/solvespace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boolean.cpp
1125 lines (975 loc) · 42.3 KB
/
boolean.cpp
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
//-----------------------------------------------------------------------------
// Top-level functions to compute the Boolean union, difference or intersection
// between two shells of rational polynomial surfaces.
//
// Copyright 2008-2013 Jonathan Westhues.
//-----------------------------------------------------------------------------
#include "solvespace.h"
static int I;
#ifndef NDEBUG
static uint32_t origKept = 0, interKept = 0;
#endif
void SShell::MakeFromUnionOf(SShell *a, SShell *b) {
MakeFromBoolean(a, b, SSurface::CombineAs::UNION);
}
void SShell::MakeFromDifferenceOf(SShell *a, SShell *b) {
MakeFromBoolean(a, b, SSurface::CombineAs::DIFFERENCE);
}
void SShell::MakeFromIntersectionOf(SShell *a, SShell *b) {
MakeFromBoolean(a, b, SSurface::CombineAs::INTERSECTION);
/* // this works but is not optimal
SShell c = {};
c.MakeFromBoolean(a, b, SSurface::CombineAs::DIFFERENCE);
MakeFromBoolean(a, &c, SSurface::CombineAs::DIFFERENCE);
c.Clear(); */
}
//-----------------------------------------------------------------------------
// Take our original pwl curve. Wherever an edge intersects a surface within
// either agnstA or agnstB, split the piecewise linear element. Then refine
// the intersection so that it lies on all three relevant surfaces: the
// intersecting surface, srfA, and srfB. (So the pwl curve should lie at
// the intersection of srfA and srfB.) Return a new pwl curve with everything
// split.
//-----------------------------------------------------------------------------
SCurve SCurve::MakeCopySplitAgainst(SShell *agnstA, SShell *agnstB,
SSurface *srfA, SSurface *srfB) const
{
SCurve ret;
ret = *this;
ret.pts = {};
const SCurvePt *p = pts.First();
ssassert(p != NULL, "Cannot split an empty curve");
SCurvePt prev = *p;
ret.pts.Add(p);
p = pts.NextAfter(p);
for(; p; p = pts.NextAfter(p)) {
List<SInter> il = {};
// Find all the intersections with the two passed shells
if(agnstA)
agnstA->AllPointsIntersecting(prev.p, p->p, &il,
/*asSegment=*/true, /*trimmed=*/false, /*inclTangent=*/true);
if(agnstB)
agnstB->AllPointsIntersecting(prev.p, p->p, &il,
/*asSegment=*/true, /*trimmed=*/false, /*inclTangent=*/true);
if(!il.IsEmpty()) {
// The intersections were generated by intersecting the pwl
// edge against a surface; so they must be refined to lie
// exactly on the original curve.
il.ClearTags();
SInter *pi;
for(pi = il.First(); pi; pi = il.NextAfter(pi)) {
if(pi->srf == srfA || pi->srf == srfB) {
// The edge certainly intersects the surfaces that it
// trims (at its endpoints), but those ones don't count.
// They are culled later, but no sense calculating them
// and they will cause numerical problems (since two
// of the three surfaces they're refined to lie on will
// be identical, so the matrix will be singular).
pi->tag = 1;
continue;
}
Point2d puv;
(pi->srf)->ClosestPointTo(pi->p, &puv, /*mustConverge=*/false);
// Split the edge if the intersection lies within the surface's
// trim curves, or within the chord tol of the trim curve; want
// some slop if points are close to edge and pwl is too coarse,
// and it doesn't hurt to split unnecessarily.
Point2d dummy = { 0, 0 };
SBspUv::Class c = (pi->srf->bsp) ? pi->srf->bsp->ClassifyPoint(puv, dummy, pi->srf) : SBspUv::Class::OUTSIDE;
if(c == SBspUv::Class::OUTSIDE) {
double d = VERY_POSITIVE;
if(pi->srf->bsp) d = pi->srf->bsp->MinimumDistanceToEdge(puv, pi->srf);
if(d > SS.ChordTolMm()) {
pi->tag = 1;
continue;
}
}
// We're keeping the intersection, so actually refine it.
(pi->srf)->PointOnSurfaces(srfA, srfB, &(puv.x), &(puv.y));
pi->p = (pi->srf)->PointAt(puv);
}
il.RemoveTagged();
// And now sort them in order along the line. Note that we must
// do that after refining, in case the refining would make two
// points switch places.
const Vector lineStart = prev.p;
const Vector lineDirection = (p->p).Minus(prev.p);
std::sort(il.begin(), il.end(), [&](const SInter &a, const SInter &b) {
double ta = (a.p.Minus(lineStart)).DivProjected(lineDirection);
double tb = (b.p.Minus(lineStart)).DivProjected(lineDirection);
return (ta < tb);
});
// And now uses the intersections to generate our split pwl edge(s)
Vector prev = Vector::From(VERY_POSITIVE, 0, 0);
for(pi = il.First(); pi; pi = il.NextAfter(pi)) {
// On-edge intersection will generate same split point for
// both surfaces, so don't create zero-length edge.
if(!prev.Equals(pi->p)) {
SCurvePt scpt;
scpt.tag = 0;
scpt.p = pi->p;
scpt.vertex = true;
ret.pts.Add(&scpt);
}
prev = pi->p;
}
}
il.Clear();
ret.pts.Add(p);
prev = *p;
}
return ret;
}
void SShell::CopyCurvesSplitAgainst(bool opA, SShell *agnst, SShell *into) {
SCurve *sc;
for(sc = curve.First(); sc; sc = curve.NextAfter(sc)) {
SCurve scn = sc->MakeCopySplitAgainst(agnst, NULL,
surface.FindById(sc->surfA),
surface.FindById(sc->surfB));
scn.source = opA ? SCurve::Source::A : SCurve::Source::B;
hSCurve hsc = into->curve.AddAndAssignId(&scn);
// And note the new ID so that we can rewrite the trims appropriately
sc->newH = hsc;
}
}
void SSurface::TrimFromEdgeList(SEdgeList *el, bool asUv) {
el->l.ClearTags();
STrimBy stb = {};
for(;;) {
// Find an edge, any edge; we'll start from there.
SEdge *se;
for(se = el->l.First(); se; se = el->l.NextAfter(se)) {
if(se->tag) continue;
break;
}
if(!se) break;
se->tag = 1;
stb.start = se->a;
stb.finish = se->b;
stb.curve.v = se->auxA;
stb.backwards = se->auxB ? true : false; // ruevs: reverse here? No?
// Find adjoining edges from the same curve; those should be
// merged into a single trim.
bool merged;
do {
merged = false;
for(se = el->l.First(); se; se = el->l.NextAfter(se)) {
if(se->tag) continue;
if(se->auxA != (int)stb.curve.v) continue;
if(( se->auxB && !stb.backwards) ||
(!se->auxB && stb.backwards)) continue;
if((se->a).Equals(stb.finish)) {
stb.finish = se->b;
se->tag = 1;
merged = true;
} else if((se->b).Equals(stb.start)) {
stb.start = se->a;
se->tag = 1;
merged = true;
}
}
} while(merged);
if(asUv) {
stb.start = PointAt(stb.start.x, stb.start.y);
stb.finish = PointAt(stb.finish.x, stb.finish.y);
}
// And add the merged trim, with xyz (not uv like the polygon) pts
trim.Add(&stb);
}
}
static bool KeepRegion(SSurface::CombineAs type, bool opA, SShell::Class shell, SShell::Class orig)
{
bool inShell = (shell == SShell::Class::INSIDE),
outSide = (shell == SShell::Class::OUTSIDE),
inSame = (shell == SShell::Class::COINC_SAME),
inOrig = (orig == SShell::Class::INSIDE);
if(!inOrig) return false;
switch(type) {
case SSurface::CombineAs::UNION:
if(opA) {
return outSide;
} else {
return outSide || inSame;
}
case SSurface::CombineAs::DIFFERENCE:
if(opA) {
return outSide;
} else {
return inShell || inSame;
}
case SSurface::CombineAs::INTERSECTION:
if(opA) {
return inShell;
} else {
return inShell || inSame;
}
default: ssassert(false, "Unexpected combine type");
}
}
static bool KeepEdge(SSurface::CombineAs type, bool opA,
SShell::Class indir_shell, SShell::Class outdir_shell,
SShell::Class indir_orig, SShell::Class outdir_orig)
{
// return true;
/*
INSIDE = 100,
OUTSIDE = 200,
COINC_SAME = 300,
COINC_OPP = 400
*/
uint32_t cc = (uint32_t)indir_shell*10 + (uint32_t)outdir_shell + (uint32_t)indir_orig/10 + (uint32_t)outdir_orig/100;
bool result;
bool resultsmart;
bool keepIn = KeepRegion(type, opA, indir_shell, indir_orig),
keepOut = KeepRegion(type, opA, outdir_shell, outdir_orig);
result = (keepIn && !keepOut);
switch (type) {
case SSurface::CombineAs::UNION:
resultsmart = ((SShell::Class::INSIDE==indir_orig) && (
(SShell::Class::OUTSIDE==indir_shell) ||
((!opA) && (
(SShell::Class::COINC_SAME==indir_shell)
)
))) &&
(!((SShell::Class::INSIDE==outdir_orig) && (
(SShell::Class::OUTSIDE==outdir_shell) ||
((!opA) && (
(SShell::Class::COINC_SAME==outdir_shell)
)
))));
break;
case SSurface::CombineAs::DIFFERENCE:
resultsmart = (1112 == cc) || // Internal
(1211 == cc) ||
(2111 == cc) || // X intersections
(2311 == cc) ||
(2312 == cc) ||
(2411 == cc) ||
(4111 == cc) || // X with one side face on face opposite normals
(3112 == cc) ||
(3211 == cc) ||
((!opA) && // Edges which should be kept only from one shell
((3212 == cc) ||
(1212 == cc) || // Face on face same normal
(3312 == cc))
) ||
((opA) && // Edges which should be kept only from one shell
((2112 == cc) || // opA?
(2212 == cc))
);
/* resultsmart = (SShell::Class::OUTSIDE==indir_shell) || // 1112 1212
((!opA) && (
(SShell::Class::INSIDE==indir_shell) ||
(SShell::Class::COINC_SAME==indir_shell)
)
);*/
break;
case SSurface::CombineAs::INTERSECTION:
// "Stupid" decision derived by a lot of debugging
resultsmart = (1112 == cc) || // Internal
(1211 == cc) || // ??? visual
(1212 == cc) || // Face on face same normal
(1311 == cc) || // ??? visual
(1411 == cc) || // ??? visual
(2111 == cc) || // X intersections
(2311 == cc) || // Face on face same normal
(3111 == cc) || // from smart ;-)
(3211 == cc) || // ??? visual
(4111 == cc) || // X with one side face on face opposite normals
((!opA) && // Edges which should be kept only from one shell
( (3312 == cc) ||
(3212 == cc) /*|| // ??? visual
(2321 == cc) // Edge on edge*/
)
);
/*
// "Smart" decision derived from the above with a Karnaugh map (and the above updated in reverse later :-)
resultsmart = (SShell::Class::INSIDE==indir_shell) || // 1112 1212
((SShell::Class::INSIDE==outdir_shell)&&(SShell::Class::INSIDE==indir_orig)&&(SShell::Class::INSIDE==outdir_orig)) || // 2111 3111 4111
((!opA) && (
((SShell::Class::COINC_SAME==indir_shell)&&(SShell::Class::COINC_SAME==outdir_shell))|| // 3312
((SShell::Class::COINC_SAME==outdir_shell)&&(SShell::Class::INSIDE==outdir_orig)) // 2311 2321
)
);
*/
/*
2121 is the same as 1212 keep only one
3212 is the same as 2321 keep only one
((3112 == cc) || (3132 == cc) || (2313 == cc) ) // No
2312 3312 4212 2421 // Face on Face opposite normals, coplanar opposite do NOT include
2411 2112 4412 // Face on Face opposite normals, concave opposite do NOT include
*/
break;
default: ssassert(false, "Unexpected combine type");
}
// Test values here
// result = (2321 == cc);
// result = result && !opA;
#ifndef NDEBUG
dbp("I: %d opA: %d cc: %d %d %s", I, opA, cc, result, (result!=resultsmart)?"NOOOOOOOOOOOOOOOOOO":"");
#endif
return result;
// return resultsmart;
// If the regions to the left and right of this edge are both in or both
// out, then this edge is not useful and should be discarded.
if(keepIn && !keepOut) return true;
return false;
}
static void TagByClassifiedEdge(SBspUv::Class bspclass, SShell::Class *indir, SShell::Class *outdir)
{
switch(bspclass) {
case SBspUv::Class::INSIDE:
*indir = SShell::Class::INSIDE;
*outdir = SShell::Class::INSIDE;
break;
case SBspUv::Class::OUTSIDE:
*indir = SShell::Class::OUTSIDE;
*outdir = SShell::Class::OUTSIDE;
break;
case SBspUv::Class::EDGE_PARALLEL:
*indir = SShell::Class::INSIDE;
*outdir = SShell::Class::OUTSIDE;
break;
case SBspUv::Class::EDGE_ANTIPARALLEL:
*indir = SShell::Class::OUTSIDE;
*outdir = SShell::Class::INSIDE;
break;
default:
dbp("TagByClassifiedEdge: fail!");
*indir = SShell::Class::OUTSIDE;
*outdir = SShell::Class::OUTSIDE;
break;
}
}
void DEBUGEDGELIST(SEdgeList *sel, SSurface *surf) {
dbp("print %d edges", sel->l.n);
SEdge *se;
for(se = sel->l.First(); se; se = sel->l.NextAfter(se)) {
Vector mid = (se->a).Plus(se->b).ScaledBy(0.5);
Vector arrow = (se->b).Minus(se->a);
swap(arrow.x, arrow.y);
arrow.x *= -1;
arrow = arrow.WithMagnitude(0.05);
arrow = arrow.Plus(mid);
SS.nakedEdges.AddEdge(surf->PointAt(se->a.x, se->a.y),
surf->PointAt(se->b.x, se->b.y));
SS.nakedEdges.AddEdge(surf->PointAt(mid.x, mid.y),
surf->PointAt(arrow.x, arrow.y), se->auxA, se->auxB, se->tag,se->cc);
}
}
//-----------------------------------------------------------------------------
// We are given src, with at least one edge, and avoid, a list of points to
// avoid. We return a chain of edges (that share endpoints), such that no
// point within the avoid list ever occurs in the middle of a chain. And we
// delete the edges in that chain from our source list.
//-----------------------------------------------------------------------------
void SSurface::FindChainAvoiding(SEdgeList *src, SEdgeList *dest,
SPointList *avoid)
{
ssassert(!src->l.IsEmpty(), "Need at least one edge");
// Start with an arbitrary edge.
dest->l.Add(src->l.First());
src->l.ClearTags();
src->l.First()->tag = 1;
bool added;
do {
added = false;
// The start and finish of the current edge chain
Vector s = dest->l.First()->a,
f = dest->l.Last()->b;
// We can attach a new edge at the start or finish, as long as that
// start or finish point isn't in the list of points to avoid.
bool startOkay = !avoid->ContainsPoint(s),
finishOkay = !avoid->ContainsPoint(f);
// Now look for an unused edge that joins at the start or finish of
// our chain (if permitted by the avoid list).
SEdge *se;
for(se = src->l.First(); se; se = src->l.NextAfter(se)) {
if(se->tag) continue;
if(startOkay && s.Equals(se->b)) {
dest->l.AddToBeginning(se);
s = se->a;
se->tag = 1;
startOkay = !avoid->ContainsPoint(s);
} else if(finishOkay && f.Equals(se->a)) {
dest->l.Add(se);
f = se->b;
se->tag = 1;
finishOkay = !avoid->ContainsPoint(f);
} else {
continue;
}
added = true;
}
} while(added);
src->l.RemoveTagged();
}
void SSurface::EdgeNormalsWithinSurface(Point2d auv, Point2d buv,
Vector *pt,
Vector *enin, Vector *enout,
Vector *surfn,
uint32_t auxA,
SShell *shell, SShell *sha, SShell *shb)
{
// the midpoint of the edge
Point2d muv = (auv.Plus(buv)).ScaledBy(0.5);
*pt = PointAt(muv);
// If this edge just approximates a curve, then refine our midpoint so
// so that it actually lies on that curve too. Otherwise stuff like
// point-on-face tests will fail, since the point won't actually lie
// on the other face.
hSCurve hc = { auxA };
SCurve *sc = shell->curve.FindById(hc);
if(sc->isExact && sc->exact.deg != 1) {
double t;
sc->exact.ClosestPointTo(*pt, &t, /*mustConverge=*/false);
*pt = sc->exact.PointAt(t);
ClosestPointTo(*pt, &muv);
} else if(!sc->isExact) {
SSurface *trimmedA = sc->GetSurfaceA(sha, shb),
*trimmedB = sc->GetSurfaceB(sha, shb);
*pt = trimmedA->ClosestPointOnThisAndSurface(trimmedB, *pt);
ClosestPointTo(*pt, &muv);
}
*surfn = NormalAt(muv.x, muv.y);
// Compute the edge's inner normal in xyz space.
Vector ab = (PointAt(auv)).Minus(PointAt(buv)),
enxyz = (ab.Cross(*surfn)).WithMagnitude(SS.ChordTolMm());
// And based on that, compute the edge's inner normal in uv space. This
// vector is perpendicular to the edge in xyz, but not necessarily in uv.
Vector tu, tv;
TangentsAt(muv.x, muv.y, &tu, &tv);
Point2d enuv;
enuv.x = enxyz.Dot(tu) / tu.MagSquared();
enuv.y = enxyz.Dot(tv) / tv.MagSquared();
// Compute the inner and outer normals of this edge (within the srf),
// in xyz space. These are not necessarily antiparallel, if the
// surface is curved.
Vector pin = PointAt(muv.Minus(enuv)),
pout = PointAt(muv.Plus(enuv));
*enin = pin.Minus(*pt),
*enout = pout.Minus(*pt);
}
static uint32_t DebugEdgeClassification(Vector pt, bool opA, SShell::Class indir_shell,
SShell::Class outdir_shell, SShell::Class indir_orig,
SShell::Class outdir_orig) {
uint32_t cc = (uint32_t)indir_shell * 100 + (uint32_t)outdir_shell*10 + (uint32_t)indir_orig*1 +
(uint32_t)outdir_orig / 10 + (uint32_t)opA;
/* std::shared_ptr<SolveSpace::ViewportCanvas> canvas = SS.GW.canvas;
const Camera &camera = canvas->GetCamera();
Canvas::Stroke strokeError = Style::Stroke(Style::DRAW_ERROR);
strokeError.layer = Canvas::Layer::FRONT;
strokeError.width = 1.0f;
Canvas::hStroke hcsError = canvas->GetStroke(strokeError);
double textHeight = Style::DefaultTextHeight() / camera.scale;
canvas->DrawVectorText(ssprintf("%lu", cc), textHeight*10,
pt, camera.projRight, camera.projUp, hcsError); */
return cc;
}
//-----------------------------------------------------------------------------
// Trim this surface against the specified shell, in the way that's appropriate
// for the specified Boolean operation type (and which operand we are). We
// also need a pointer to the shell that contains our own surface, since that
// contains our original trim curves.
//-----------------------------------------------------------------------------
SSurface SSurface::MakeCopyTrimAgainst(SShell *parent,
SShell *sha, SShell *shb,
SShell *into,
SSurface::CombineAs type)
{
bool opA = (parent == sha);
SShell *agnst = opA ? shb : sha;
SSurface ret;
// The returned surface is identical, just the trim curves change
ret = *this;
ret.trim = {};
// First, build a list of the existing trim curves; update them to use
// the split curves.
STrimBy *stb;
for(stb = trim.First(); stb; stb = trim.NextAfter(stb)) {
STrimBy stn = *stb;
stn.curve = (parent->curve.FindById(stn.curve))->newH;
ret.trim.Add(&stn);
}
if(type == SSurface::CombineAs::DIFFERENCE && !opA) {
// The second operand of a Boolean difference gets turned inside out
ret.Reverse();
}
// Build up our original trim polygon; remember the coordinates could
// be changed if we just flipped the surface normal, and we are using
// the split curves (not the original curves).
SEdgeList orig = {};
ret.MakeEdgesInto(into, &orig, MakeAs::UV);
ret.trim.Clear();
// which means that we can't necessarily use the old BSP...
SBspUv *origBsp = SBspUv::From(&orig, &ret);
// And now intersect the other shell against us
SEdgeList inter = {};
SSurface *ss;
for(ss = agnst->surface.First(); ss; ss = agnst->surface.NextAfter(ss)) {
SCurve *sc;
for(sc = into->curve.First(); sc; sc = into->curve.NextAfter(sc)) {
if(sc->source != SCurve::Source::INTERSECTION) continue;
if(opA) {
if(sc->surfA != h || sc->surfB != ss->h) continue;
} else {
if(sc->surfB != h || sc->surfA != ss->h) continue;
}
int i;
for(i = 1; i < sc->pts.n; i++) {
Vector a = sc->pts[i-1].p,
b = sc->pts[i].p;
Point2d auv, buv;
ss->ClosestPointTo(a, &(auv.x), &(auv.y));
ss->ClosestPointTo(b, &(buv.x), &(buv.y));
SBspUv::Class c = (ss->bsp) ? ss->bsp->ClassifyEdge(auv, buv, ss) : SBspUv::Class::OUTSIDE;
if(c != SBspUv::Class::OUTSIDE) {
Vector ta = Vector::From(0, 0, 0);
Vector tb = Vector::From(0, 0, 0);
ret.ClosestPointTo(a, &(ta.x), &(ta.y));
ret.ClosestPointTo(b, &(tb.x), &(tb.y));
Vector tn = ret.NormalAt(ta.x, ta.y);
Vector sn = ss->NormalAt(auv.x, auv.y);
// We are subtracting the portion of our surface that
// lies in the shell, so the in-plane edge normal should
// point opposite to the surface normal.
bool bkwds = true;
if((tn.Cross(b.Minus(a))).Dot(sn) < 0) bkwds = !bkwds;
if((type == SSurface::CombineAs::DIFFERENCE && !opA) ||
(type == SSurface::CombineAs::INTERSECTION)) { // Invert all newly created edges for intersection
bkwds = !bkwds;
}
if(bkwds) {
inter.AddEdge(tb, ta, sc->h.v, 1);
} else {
inter.AddEdge(ta, tb, sc->h.v, 0);
}
}
}
}
}
// Record all the points where more than two edges join, which I will call
// the choosing points. If two edges join at a non-choosing point, then
// they must either both be kept or both be discarded (since that would
// otherwise create an open contour).
SPointList choosing = {};
SEdge *se;
for(se = orig.l.First(); se; se = orig.l.NextAfter(se)) {
choosing.IncrementTagFor(se->a);
choosing.IncrementTagFor(se->b);
}
for(se = inter.l.First(); se; se = inter.l.NextAfter(se)) {
choosing.IncrementTagFor(se->a);
choosing.IncrementTagFor(se->b);
}
SPoint *sp;
for(sp = choosing.l.First(); sp; sp = choosing.l.NextAfter(sp)) {
if(sp->tag == 2) {
sp->tag = 1;
} else {
sp->tag = 0;
}
}
choosing.l.RemoveTagged();
// The list of edges to trim our new surface, a combination of edges from
// our original and intersecting edge lists.
SEdgeList final = {};
while(!orig.l.IsEmpty()) {
SEdgeList chain = {};
FindChainAvoiding(&orig, &chain, &choosing);
// Arbitrarily choose an edge within the chain to classify; they
// should all be the same, though.
se = &(chain.l[chain.l.n/2]);
Point2d auv = (se->a).ProjectXy(),
buv = (se->b).ProjectXy();
Vector pt, enin, enout, surfn;
ret.EdgeNormalsWithinSurface(auv, buv, &pt, &enin, &enout, &surfn,
se->auxA, into, sha, shb);
SShell::Class indir_shell, outdir_shell, indir_orig, outdir_orig;
indir_orig = SShell::Class::INSIDE;
outdir_orig = SShell::Class::OUTSIDE;
agnst->ClassifyEdge(&indir_shell, &outdir_shell,
ret.PointAt(auv), ret.PointAt(buv), pt,
enin, enout, surfn);
uint32_t cc = DebugEdgeClassification(se->a, opA, indir_shell, outdir_shell, indir_orig, outdir_orig);
if(KeepEdge(type, opA, indir_shell, outdir_shell,
indir_orig, outdir_orig))
{
#ifndef NDEBUG
origKept++;
#endif
for(se = chain.l.First(); se; se = chain.l.NextAfter(se)) {
final.AddEdge(se->a, se->b, se->auxA, se->auxB, 0, cc);
}
}
chain.Clear();
}
while(!inter.l.IsEmpty()) {
SEdgeList chain = {};
FindChainAvoiding(&inter, &chain, &choosing);
// Any edge in the chain, same as above.
se = &(chain.l[chain.l.n/2]);
Point2d auv = (se->a).ProjectXy(),
buv = (se->b).ProjectXy();
Vector pt, enin, enout, surfn;
ret.EdgeNormalsWithinSurface(auv, buv, &pt, &enin, &enout, &surfn,
se->auxA, into, sha, shb);
SShell::Class indir_shell, outdir_shell, indir_orig, outdir_orig;
SBspUv::Class c_this = (origBsp) ? origBsp->ClassifyEdge(auv, buv, &ret) : SBspUv::Class::OUTSIDE;
TagByClassifiedEdge(c_this, &indir_orig, &outdir_orig);
agnst->ClassifyEdge(&indir_shell, &outdir_shell,
ret.PointAt(auv), ret.PointAt(buv), pt,
enin, enout, surfn);
uint32_t cc = DebugEdgeClassification(se->a, opA, indir_shell, outdir_shell, indir_orig, outdir_orig);
if(KeepEdge(type, opA, indir_shell, outdir_shell,
indir_orig, outdir_orig))
{
#ifndef NDEBUG
interKept++;
#endif
for(se = chain.l.First(); se; se = chain.l.NextAfter(se)) {
// se->auxB = 1; // ruevs: Will cause the TrimFromEdgeList function below to reverse edges resulting from the intersection.
final.AddEdge(se->a, se->b, se->auxA, se->auxB, 0, cc); // ruevs: swap a and b here?
}
}
chain.Clear();
}
#ifndef NDEBUG
dbp("type: %d origKept: %d interKept %d", type, origKept, interKept);
#endif
// Cull extraneous edges; duplicates or anti-parallel pairs. In particular,
// we can get duplicate edges if our surface intersects the other shell
// at an edge, so that both surfaces intersect coincident (and both
// generate an intersection edge).
final.CullExtraneousEdges(/*both=*/true); // ruevs: cull flase? Or wrong choice of edges?
#ifndef NDEBUG
dbp("Total %d, left after culling: %d", origKept + interKept, final.l.n);
#endif
// Use our reassembled edges to trim the new surface.
ret.TrimFromEdgeList(&final, /*asUv=*/true);
SPolygon poly = {};
final.l.ClearTags();
DEBUGEDGELIST(&final, &ret);
SEdge errorAt;
if(!final.AssemblePolygon(&poly, &errorAt, /*keepDir=*/true)) { // ruevs: passing false is a hack according to jwesthues https://github.com/solvespace/solvespace/issues/35#issuecomment-531173543
into->booleanFailed = true;
dbp("failed: I=%d, avoid=%d", I, choosing.l.n);
SS.nakedEdges.AddEdge(errorAt.a, errorAt.b, 0, 0, 0, 8888888);
// DEBUGEDGELIST(&final, &ret);
}
poly.Clear();
choosing.Clear();
final.Clear();
inter.Clear();
orig.Clear();
return ret;
}
void SShell::CopySurfacesTrimAgainst(SShell *sha, SShell *shb, SShell *into, SSurface::CombineAs type) {
SSurface *ss;
for(ss = surface.First(); ss; ss = surface.NextAfter(ss)) {
SSurface ssn;
ssn = ss->MakeCopyTrimAgainst(this, sha, shb, into, type);
ss->newH = into->surface.AddAndAssignId(&ssn);
I++;
}
}
void SShell::MakeIntersectionCurvesAgainst(SShell *agnst, SShell *into) {
SSurface *sa;
for(sa = surface.First(); sa; sa = surface.NextAfter(sa)) {
SSurface *sb;
for(sb = agnst->surface.First(); sb; sb = agnst->surface.NextAfter(sb)){
// Intersect every surface from our shell against every surface
// from agnst; this will add zero or more curves to the curve
// list for into.
sa->IntersectAgainst(sb, this, agnst, into);
}
}
}
void SShell::CleanupAfterBoolean() {
SSurface *ss;
for(ss = surface.First(); ss; ss = surface.NextAfter(ss)) {
ss->edges.Clear();
}
}
//-----------------------------------------------------------------------------
// All curves contain handles to the two surfaces that they trim. After a
// Boolean or assembly, we must rewrite those handles to refer to the curves
// by their new IDs.
//-----------------------------------------------------------------------------
void SShell::RewriteSurfaceHandlesForCurves(SShell *a, SShell *b) {
SCurve *sc;
for(sc = curve.First(); sc; sc = curve.NextAfter(sc)) {
sc->surfA = sc->GetSurfaceA(a, b)->newH,
sc->surfB = sc->GetSurfaceB(a, b)->newH;
}
}
//-----------------------------------------------------------------------------
// Copy all the surfaces and curves from two different shells into a single
// shell. The only difficulty is to rewrite all of their handles; we don't
// look for any surface intersections, so if two objects interfere then the
// result is just self-intersecting. This is used for assembly, since it's
// much faster than merging as union.
//-----------------------------------------------------------------------------
void SShell::MakeFromAssemblyOf(SShell *a, SShell *b) {
booleanFailed = false;
Vector t = Vector::From(0, 0, 0);
Quaternion q = Quaternion::IDENTITY;
int i = 0;
SShell *ab;
// First, copy over all the curves. Note which shell (a or b) each curve
// came from, but assign it a new ID.
curve.ReserveMore(a->curve.n + b->curve.n);
SCurve *c, cn;
for(i = 0; i < 2; i++) {
ab = (i == 0) ? a : b;
for(c = ab->curve.First(); c; c = ab->curve.NextAfter(c)) {
cn = SCurve::FromTransformationOf(c, t, q, 1.0);
cn.source = (i == 0) ? SCurve::Source::A : SCurve::Source::B;
// surfA and surfB are wrong now, and we can't fix them until
// we've assigned IDs to the surfaces. So we'll get that later.
c->newH = curve.AddAndAssignId(&cn);
}
}
// Likewise copy over all the surfaces.
surface.ReserveMore(a->surface.n + b->surface.n);
SSurface *s, sn;
for(i = 0; i < 2; i++) {
ab = (i == 0) ? a : b;
for(s = ab->surface.First(); s; s = ab->surface.NextAfter(s)) {
sn = SSurface::FromTransformationOf(s, t, q, 1.0, /*includingTrims=*/true);
// All the trim curve IDs get rewritten; we know the new handles
// to the curves since we recorded them in the previous step.
STrimBy *stb;
for(stb = sn.trim.First(); stb; stb = sn.trim.NextAfter(stb)) {
stb->curve = ab->curve.FindById(stb->curve)->newH;
}
s->newH = surface.AddAndAssignId(&sn);
}
}
// Finally, rewrite the surfaces associated with each curve to use the
// new handles.
RewriteSurfaceHandlesForCurves(a, b);
}
void SShell::MakeFromBoolean(SShell *a, SShell *b, SSurface::CombineAs type) {
booleanFailed = false;
a->MakeClassifyingBsps(NULL);
b->MakeClassifyingBsps(NULL);
// Copy over all the original curves, splitting them so that a
// piecwise linear segment never crosses a surface from the other
// shell.
a->CopyCurvesSplitAgainst(/*opA=*/true, b, this);
b->CopyCurvesSplitAgainst(/*opA=*/false, a, this);
// Generate the intersection curves for each surface in A against all
// the surfaces in B (which is all of the intersection curves).
a->MakeIntersectionCurvesAgainst(b, this);
SCurve *sc;
for(sc = curve.First(); sc; sc = curve.NextAfter(sc)) {
SSurface *srfA = sc->GetSurfaceA(a, b),
*srfB = sc->GetSurfaceB(a, b);
sc->RemoveShortSegments(srfA, srfB);
}
// And clean up the piecewise linear things we made as a calculation aid
a->CleanupAfterBoolean();
b->CleanupAfterBoolean();
// Remake the classifying BSPs with the split (and short-segment-removed)
// curves
a->MakeClassifyingBsps(this);
b->MakeClassifyingBsps(this);
if(b->surface.IsEmpty() || a->surface.IsEmpty()) {
I = 1000000;
#ifndef NDEBUG
origKept = 1000000;
interKept = 1000000;
#endif
} else {
I = 0;
#ifndef NDEBUG
origKept = 0;
interKept = 0;
#endif
}
// Then trim and copy the surfaces
a->CopySurfacesTrimAgainst(a, b, this, type);
b->CopySurfacesTrimAgainst(a, b, this, type);
// Now that we've copied the surfaces, we know their new hSurfaces, so
// rewrite the curves to refer to the surfaces by their handles in the
// result.
RewriteSurfaceHandlesForCurves(a, b);
// And clean up the piecewise linear things we made as a calculation aid
a->CleanupAfterBoolean();
b->CleanupAfterBoolean();
}
//-----------------------------------------------------------------------------
// All of the BSP routines that we use to perform and accelerate polygon ops.
//-----------------------------------------------------------------------------
void SShell::MakeClassifyingBsps(SShell *useCurvesFrom) {
SSurface *ss;
for(ss = surface.First(); ss; ss = surface.NextAfter(ss)) {
ss->MakeClassifyingBsp(this, useCurvesFrom);
}
}
void SSurface::MakeClassifyingBsp(SShell *shell, SShell *useCurvesFrom) {
SEdgeList el = {};
MakeEdgesInto(shell, &el, MakeAs::UV, useCurvesFrom);
bsp = SBspUv::From(&el, this);
el.Clear();
edges = {};
MakeEdgesInto(shell, &edges, MakeAs::XYZ, useCurvesFrom);
}
SBspUv *SBspUv::Alloc() {
return (SBspUv *)AllocTemporary(sizeof(SBspUv));
}
SBspUv *SBspUv::From(SEdgeList *el, SSurface *srf) {
SEdgeList work = {};
SEdge *se;
for(se = el->l.First(); se; se = el->l.NextAfter(se)) {
work.AddEdge(se->a, se->b, se->auxA, se->auxB);
}
std::sort(work.l.begin(), work.l.end(), [](SEdge const &a, SEdge const &b) {
double la = (a.a).Minus(a.b).Magnitude(), lb = (b.a).Minus(b.b).Magnitude();
// Sort in descending order, longest first. This improves numerical
// stability for the normals.
return la > lb;
});
SBspUv *bsp = NULL;
for(se = work.l.First(); se; se = work.l.NextAfter(se)) {
bsp = InsertOrCreateEdge(bsp, (se->a).ProjectXy(), (se->b).ProjectXy(), srf);
}
work.Clear();
return bsp;
}
//-----------------------------------------------------------------------------
// The points in this BSP are in uv space, but we want to apply our tolerances
// consistently in xyz (i.e., we want to say a point is on-edge if its xyz
// distance to that edge is less than LENGTH_EPS, irrespective of its distance
// in uv). So we linearize the surface about the point we're considering and
// then do the test. That preserves point-on-line relationships, and the only
// time we care about exact correctness is when we're very close to the line,
// which is when the linearization is accurate.
//-----------------------------------------------------------------------------
void SBspUv::ScalePoints(Point2d *pt, Point2d *a, Point2d *b, SSurface *srf) const {
Vector tu, tv;
srf->TangentsAt(pt->x, pt->y, &tu, &tv);
double mu = tu.Magnitude(), mv = tv.Magnitude();
pt->x *= mu; pt->y *= mv;
a ->x *= mu; a ->y *= mv;
b ->x *= mu; b ->y *= mv;
}
double SBspUv::ScaledSignedDistanceToLine(Point2d pt, Point2d a, Point2d b,
SSurface *srf) const
{
ScalePoints(&pt, &a, &b, srf);
Point2d n = ((b.Minus(a)).Normal()).WithMagnitude(1);
double d = a.Dot(n);