/
Area.cpp
2037 lines (1845 loc) · 69.3 KB
/
Area.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
/****************************************************************************
* Copyright (c) 2017 Zheng, Lei (realthunder) <realthunder.dev@gmail.com>*
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
****************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <boost/range/adaptor/reversed.hpp>
#include <BRepLib.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <BRepBuilderAPI_FindPlane.hxx>
#include <BRepLib_FindSurface.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepTools.hxx>
#include <BRepTools_WireExplorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <GeomAbs_JoinType.hxx>
#include <Geom_Circle.hxx>
#include <Geom_Ellipse.hxx>
#include <Geom_Line.hxx>
#include <Geom_Plane.hxx>
#include <Standard_Failure.hxx>
#include <gp_Circ.hxx>
#include <gp_GTrsf.hxx>
#include <Standard_Version.hxx>
#include <GCPnts_QuasiUniformDeflection.hxx>
#include <GCPnts_UniformAbscissa.hxx>
#include <BRepBndLib.hxx>
#include <BRepLib_MakeFace.hxx>
#include <Bnd_Box.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepExtrema_DistShapeShape.hxx>
#include <Base/Exception.h>
#include <Base/Tools.h>
#include <App/Application.h>
#include <App/Document.h>
#include <Mod/Part/App/PartFeature.h>
#include <Mod/Part/App/FaceMakerBullseye.h>
#include <Mod/Part/App/CrossSection.h>
#include "Area.h"
#include "../libarea/Area.h"
using namespace Path;
CAreaParams::CAreaParams()
:PARAM_INIT(PARAM_FNAME,AREA_PARAMS_CAREA)
{}
AreaParams::AreaParams()
:PARAM_INIT(PARAM_FNAME,AREA_PARAMS_AREA)
{}
CAreaConfig::CAreaConfig(const CAreaParams &p, bool noFitArcs)
{
#define AREA_CONF_SAVE_AND_APPLY(_param) \
PARAM_FNAME(_param) = BOOST_PP_CAT(CArea::get_,PARAM_FARG(_param))();\
BOOST_PP_CAT(CArea::set_,PARAM_FARG(_param))(p.PARAM_FNAME(_param));
PARAM_FOREACH(AREA_CONF_SAVE_AND_APPLY,AREA_PARAMS_CAREA)
// Arc fitting is lossy. We shall reduce the number of unnecessary fit
if(noFitArcs)
CArea::set_fit_arcs(false);
}
CAreaConfig::~CAreaConfig() {
#define AREA_CONF_RESTORE(_param) \
BOOST_PP_CAT(CArea::set_,PARAM_FARG(_param))(PARAM_FNAME(_param));
PARAM_FOREACH(AREA_CONF_RESTORE,AREA_PARAMS_CAREA)
}
//////////////////////////////////////////////////////////////////////////////
TYPESYSTEM_SOURCE(Path::Area, Base::BaseClass);
bool Area::s_aborting;
Area::Area(const AreaParams *params)
:myParams(s_params)
,myHaveFace(false)
,myHaveSolid(false)
,myShapeDone(false)
{
if(params)
setParams(*params);
}
Area::Area(const Area &other, bool deep_copy)
:Base::BaseClass(other)
,myShapes(other.myShapes)
,myTrsf(other.myTrsf)
,myParams(other.myParams)
,myWorkPlane(other.myWorkPlane)
,myHaveFace(other.myHaveFace)
,myHaveSolid(other.myHaveSolid)
,myShapeDone(false)
{
if(!deep_copy || !other.isBuilt())
return;
if(other.myArea)
myArea.reset(new CArea(*other.myArea));
myShapePlane = other.myShapePlane;
myShape = other.myShape;
myShapeDone = other.myShapeDone;
mySections.reserve(other.mySections.size());
for(shared_ptr<Area> area:mySections)
mySections.push_back(make_shared<Area>(*area,true));
}
Area::~Area() {
clean();
}
void Area::setPlane(const TopoDS_Shape &shape) {
clean();
if(shape.IsNull()) {
myWorkPlane.Nullify();
return;
}
gp_Trsf trsf;
TopoDS_Shape plane = findPlane(shape,trsf);
if (plane.IsNull())
throw Base::ValueError("shape is not planar");
myWorkPlane = plane;
myTrsf = trsf;
}
bool Area::isCoplanar(const TopoDS_Shape &s1, const TopoDS_Shape &s2) {
if(s1.IsNull() || s2.IsNull()) return false;
if(s1.IsEqual(s2)) return true;
TopoDS_Builder builder;
TopoDS_Compound comp;
builder.MakeCompound(comp);
builder.Add(comp,s1);
builder.Add(comp,s2);
BRepLib_FindSurface planeFinder(comp,-1,Standard_True);
return planeFinder.Found();
}
int Area::addShape(CArea &area, const TopoDS_Shape &shape, const gp_Trsf *trsf,
double deflection, const TopoDS_Shape *plane, bool force_coplanar,
CArea *areaOpen, bool to_edges, bool reorient)
{
bool haveShape = false;
int skipped = 0;
for (TopExp_Explorer it(shape, TopAbs_FACE); it.More(); it.Next()) {
haveShape = true;
const TopoDS_Face &face = TopoDS::Face(it.Current());
if(plane && !isCoplanar(face,*plane)) {
++skipped;
if(force_coplanar) continue;
}
for (TopExp_Explorer it(face, TopAbs_WIRE); it.More(); it.Next())
addWire(area,TopoDS::Wire(it.Current()),trsf,deflection);
}
if(haveShape) return skipped;
CArea _area;
CArea _areaOpen;
for (TopExp_Explorer it(shape, TopAbs_WIRE); it.More(); it.Next()) {
haveShape = true;
const TopoDS_Wire &wire = TopoDS::Wire(it.Current());
if(plane && !isCoplanar(wire,*plane)) {
++skipped;
if(force_coplanar) continue;
}
if(BRep_Tool::IsClosed(wire))
addWire(_area,wire,trsf,deflection);
else if(to_edges) {
for (TopExp_Explorer it(wire, TopAbs_EDGE); it.More(); it.Next())
addWire(_areaOpen,BRepBuilderAPI_MakeWire(
TopoDS::Edge(it.Current())).Wire(),trsf,deflection,true);
}else
addWire(_areaOpen,wire,trsf,deflection);
}
if(!haveShape) {
for (TopExp_Explorer it(shape, TopAbs_EDGE); it.More(); it.Next()) {
if(plane && !isCoplanar(it.Current(),*plane)) {
++skipped;
if(force_coplanar) continue;
}
TopoDS_Wire wire = BRepBuilderAPI_MakeWire(
TopoDS::Edge(it.Current())).Wire();
addWire(BRep_Tool::IsClosed(wire)?_area:_areaOpen,wire,trsf,deflection);
}
}
if(reorient)
_area.Reorder();
area.m_curves.splice(area.m_curves.end(),_area.m_curves);
if(areaOpen)
areaOpen->m_curves.splice(areaOpen->m_curves.end(),_areaOpen.m_curves);
else
area.m_curves.splice(area.m_curves.end(),_areaOpen.m_curves);
return skipped;
}
void Area::addWire(CArea &area, const TopoDS_Wire& wire,
const gp_Trsf *trsf, double deflection, bool to_edges)
{
CCurve ccurve;
BRepTools_WireExplorer xp(trsf?TopoDS::Wire(
wire.Moved(TopLoc_Location(*trsf))):wire);
gp_Pnt p = BRep_Tool::Pnt(xp.CurrentVertex());
ccurve.append(CVertex(Point(p.X(),p.Y())));
for (;xp.More();xp.Next()) {
const TopoDS_Edge &edge = TopoDS::Edge(xp.Current());
BRepAdaptor_Curve curve(edge);
bool reversed = (xp.Current().Orientation()==TopAbs_REVERSED);
p = curve.Value(reversed?curve.FirstParameter():curve.LastParameter());
switch (curve.GetType()) {
case GeomAbs_Line: {
ccurve.append(CVertex(Point(p.X(),p.Y())));
if(to_edges) {
area.append(ccurve);
ccurve.m_vertices.pop_front();
}
break;
} case GeomAbs_Circle:{
if(!to_edges) {
double first = curve.FirstParameter();
double last = curve.LastParameter();
gp_Circ circle = curve.Circle();
gp_Dir dir = circle.Axis().Direction();
gp_Pnt center = circle.Location();
int type = dir.Z()<0?-1:1;
if(reversed) type = -type;
if(fabs(first-last)>M_PI) {
// Split arc(circle) larger than half circle. Because gcode
// can't handle full circle?
gp_Pnt mid = curve.Value((last-first)*0.5+first);
ccurve.append(CVertex(type,Point(mid.X(),mid.Y()),
Point(center.X(),center.Y())));
}
ccurve.append(CVertex(type,Point(p.X(),p.Y()),
Point(center.X(),center.Y())));
break;
}
//fall through
} default: {
// Discretize all other type of curves
GCPnts_QuasiUniformDeflection discretizer(curve, deflection,
curve.FirstParameter(), curve.LastParameter());
if (discretizer.IsDone () && discretizer.NbPoints () > 1) {
int nbPoints = discretizer.NbPoints ();
//strangly OCC discretizer points are one-based, not zero-based, why?
if(reversed) {
for (int i=nbPoints-1; i>=1; --i) {
gp_Pnt pt = discretizer.Value (i);
ccurve.append(CVertex(Point(pt.X(),pt.Y())));
if(to_edges) {
area.append(ccurve);
ccurve.m_vertices.pop_front();
}
}
}else{
for (int i=2; i<=nbPoints; i++) {
gp_Pnt pt = discretizer.Value (i);
ccurve.append(CVertex(Point(pt.X(),pt.Y())));
if(to_edges) {
area.append(ccurve);
ccurve.m_vertices.pop_front();
}
}
}
}else
Standard_Failure::Raise("Curve discretization failed");
}}
}
if(!to_edges) {
if(BRep_Tool::IsClosed(wire) && !ccurve.IsClosed()) {
AREA_WARN("ccurve not closed");
ccurve.append(ccurve.m_vertices.front());
}
area.append(ccurve);
}
}
void Area::clean(bool deleteShapes) {
myShapeDone = false;
mySections.clear();
myShape.Nullify();
myArea.reset();
myAreaOpen.reset();
myShapePlane.Nullify();
if(deleteShapes){
myShapes.clear();
myHaveFace = false;
myHaveSolid = false;
}
}
static inline ClipperLib::ClipType toClipperOp(short op) {
switch(op){
case Area::OperationUnion:
return ClipperLib::ctUnion;
break;
case Area::OperationDifference:
return ClipperLib::ctDifference;
break;
case Area::OperationIntersection:
return ClipperLib::ctIntersection;
break;
case Area::OperationXor:
return ClipperLib::ctXor;
break;
default:
throw Base::ValueError("invalid Operation");
}
}
void Area::add(const TopoDS_Shape &shape,short op) {
if(shape.IsNull())
throw Base::ValueError("null shape");
if(op!=OperationCompound)
toClipperOp(op);
bool haveSolid = false;
for(TopExp_Explorer it(shape, TopAbs_SOLID);it.More();) {
haveSolid = true;
break;
}
//TODO: shall we support Shells?
if((!haveSolid && myHaveSolid) ||
(haveSolid && !myHaveSolid && !myShapes.empty()))
throw Base::ValueError("mixing solid and planar shapes is not allowed");
myHaveSolid = haveSolid;
clean();
if(op!=OperationCompound && myShapes.empty())
op = OperationUnion;
myShapes.push_back(Shape(op,shape));
}
void Area::setParams(const AreaParams ¶ms) {
#define AREA_SRC2(_param) params.PARAM_FNAME(_param)
// Validate all enum type of parameters
PARAM_ENUM_CHECK(AREA_SRC2,PARAM_ENUM_EXCEPT,AREA_PARAMS_CONF);
if(params!=myParams) {
clean();
myParams = params;
}
}
void Area::addToBuild(CArea &area, const TopoDS_Shape &shape) {
if(myParams.Fill==FillAuto && !myHaveFace) {
TopExp_Explorer it(shape, TopAbs_FACE);
myHaveFace = it.More();
}
TopoDS_Shape plane = getPlane();
CArea areaOpen;
mySkippedShapes += addShape(area,shape,&myTrsf,myParams.Deflection,
myParams.Coplanar==CoplanarNone?NULL:&plane,
myHaveSolid||myParams.Coplanar==CoplanarForce,&areaOpen,
myParams.OpenMode==OpenModeEdges,myParams.Reorient);
if(areaOpen.m_curves.size()) {
if(&area == myArea.get() || myParams.OpenMode == OpenModeNone)
myAreaOpen->m_curves.splice(myAreaOpen->m_curves.end(),areaOpen.m_curves);
else
AREA_WARN("open wires discarded in clipping shapes");
}
}
namespace Part {
extern PartExport std::list<TopoDS_Edge> sort_Edges(double tol3d, std::list<TopoDS_Edge>& edges);
}
void Area::explode(const TopoDS_Shape &shape) {
const TopoDS_Shape &plane = getPlane();
bool haveShape = false;
for(TopExp_Explorer it(shape, TopAbs_FACE); it.More(); it.Next()) {
haveShape = true;
if(myParams.Coplanar!=CoplanarNone && !isCoplanar(it.Current(),plane)){
++mySkippedShapes;
if(myParams.Coplanar == CoplanarForce)
continue;
}
for(TopExp_Explorer itw(it.Current(), TopAbs_WIRE); itw.More(); itw.Next()) {
for(BRepTools_WireExplorer xp(TopoDS::Wire(itw.Current()));xp.More();xp.Next())
addWire(*myArea,BRepBuilderAPI_MakeWire(
TopoDS::Edge(xp.Current())).Wire(),&myTrsf,myParams.Deflection,true);
}
}
if(haveShape) return;
for(TopExp_Explorer it(shape, TopAbs_EDGE); it.More(); it.Next()) {
if(myParams.Coplanar!=CoplanarNone && !isCoplanar(it.Current(),plane)){
++mySkippedShapes;
if(myParams.Coplanar == CoplanarForce)
continue;
}
addWire(*myArea,BRepBuilderAPI_MakeWire(
TopoDS::Edge(it.Current())).Wire(),&myTrsf,myParams.Deflection,true);
}
}
#if 0
static void show(const TopoDS_Shape &shape, const char *name) {
App::Document *pcDoc = App::GetApplication().getActiveDocument();
if (!pcDoc)
pcDoc = App::GetApplication().newDocument();
Part::Feature *pcFeature = (Part::Feature *)pcDoc->addObject("Part::Feature", name);
// copy the data
//TopoShape* shape = new MeshObject(*pShape->getTopoShapeObjectPtr());
pcFeature->Shape.setValue(shape);
//pcDoc->recompute();
}
#endif
template<class Func>
static int foreachSubshape(const TopoDS_Shape &shape, Func func, int type=TopAbs_FACE) {
bool haveShape = false;
switch(type) {
case TopAbs_FACE:
for(TopExp_Explorer it(shape,TopAbs_FACE); it.More(); it.Next()) {
haveShape = true;
func(it.Current(),TopAbs_FACE);
}
if(haveShape) return TopAbs_FACE;
//fall through
case TopAbs_WIRE:
for(TopExp_Explorer it(shape,TopAbs_WIRE); it.More(); it.Next()) {
haveShape = true;
func(it.Current(),TopAbs_WIRE);
}
if(haveShape) return TopAbs_WIRE;
//fall through
default:
for(TopExp_Explorer it(shape,TopAbs_EDGE); it.More(); it.Next()) {
haveShape = true;
func(it.Current(),TopAbs_EDGE);
}
}
return haveShape?TopAbs_EDGE:-1;
}
struct FindPlane {
TopoDS_Shape &myPlaneShape;
gp_Trsf &myTrsf;
double &myZ;
FindPlane(TopoDS_Shape &s, gp_Trsf &t, double &z)
:myPlaneShape(s),myTrsf(t),myZ(z)
{}
void operator()(const TopoDS_Shape &shape, int) {
gp_Trsf trsf;
BRepLib_FindSurface finder(shape,-1,Standard_True);
if (!finder.Found())
return;
gp_Ax3 pos = GeomAdaptor_Surface(finder.Surface()).Plane().Position();
// It seemed that FindSurface disregard shape's transformation,
// so we have to transformed the found plane manually, or is it??
// pos.Transform(shape.Location().Transformation());
// We only use right hand coordinate, hence gp_Ax2 instead of gp_Ax3
// This means that no matter what the work plane face oriented, we
// will treat it as face upward in a right hand coordinate system.
if(!pos.Direct())
pos = gp_Ax3(pos.Ax2());
gp_Dir dir(pos.Direction());
trsf.SetTransformation(pos);
if(fabs(dir.X())<Precision::Confusion() &&
fabs(dir.Y())<Precision::Confusion())
{
TopExp_Explorer it(shape,TopAbs_VERTEX);
const auto &pt = BRep_Tool::Pnt(TopoDS::Vertex(it.Current()));
if(!myPlaneShape.IsNull() && myZ > pt.Z())
return;
myZ = pt.Z();
}else if(!myPlaneShape.IsNull())
return;
myPlaneShape = shape;
myTrsf = trsf;
}
};
TopoDS_Shape Area::findPlane(const TopoDS_Shape &shape, gp_Trsf &trsf)
{
TopoDS_Shape plane;
double top_z;
foreachSubshape(shape,FindPlane(plane,trsf,top_z));
return plane;
}
std::vector<shared_ptr<Area> > Area::makeSections(
PARAM_ARGS(PARAM_FARG,AREA_PARAMS_SECTION_EXTRA),
const std::vector<double> &_heights,
const TopoDS_Shape §ion_plane)
{
TopoDS_Shape plane;
gp_Trsf trsf;
if(!section_plane.IsNull())
plane = findPlane(section_plane,trsf);
else
plane = getPlane(&trsf);
if(plane.IsNull())
throw Base::ValueError("failed to obtain section plane");
TIME_INIT2(t,t1);
TopLoc_Location loc(trsf);
Bnd_Box bounds;
for(const Shape &s : myShapes) {
const TopoDS_Shape &shape = s.shape.Moved(loc);
BRepBndLib::Add(shape, bounds, Standard_False);
}
bounds.SetGap(0.0);
Standard_Real xMin, yMin, zMin, xMax, yMax, zMax;
bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax);
AREA_TRACE("section bounds X("<<xMin<<','<<xMax<<"), Y("<<
yMin<<','<<yMax<<"), Z("<<zMin<<','<<zMax<<')');
std::vector<double> heights;
double tolerance = 0.0;
if(_heights.empty()) {
double z;
double d = fabs(myParams.Stepdown);
if(myParams.SectionCount>1 && d<Precision::Confusion())
throw Base::ValueError("invalid stepdown");
if(mode == SectionModeBoundBox) {
if(myParams.Stepdown > 0.0)
z = zMax-myParams.SectionOffset;
else
z = zMin+myParams.SectionOffset;
}else if(mode == SectionModeWorkplane){
// Because we've transformed the shapes using the work plane so
// that the work plane is aligned with xy0 plane, the starting Z
// value shall be 0 minus the given section offset. Note the
// section offset is relative to the starting Z
if(myParams.Stepdown > 0.0)
z = -myParams.SectionOffset;
else
z = myParams.SectionOffset;
} else {
gp_Pnt pt(0,0,myParams.SectionOffset);
z = pt.Transformed(loc).Z();
}
if(z > zMax)
z = zMax;
else if(z < zMin)
z = zMin;
double dz;
if(myParams.Stepdown>0.0) {
dz = z - zMin;
tolerance = myParams.SectionTolerance;
}else{
dz = zMax - z;
tolerance = -myParams.SectionTolerance;
}
int count = myParams.SectionCount;
if(count<0 || count*d > dz)
count = floor(dz/d)+1;
heights.reserve(count);
for(int i=0;i<count;++i,z-=myParams.Stepdown) {
double height = z-tolerance;
if(z-zMin<myParams.SectionTolerance){
height = zMin+myParams.SectionTolerance;
AREA_WARN("hit bottom " <<z<<','<<zMin<<','<<height);
heights.push_back(height);
if(myParams.Stepdown>0.0) break;
}else if(zMax-z<myParams.SectionTolerance) {
height = zMax-myParams.SectionTolerance;
AREA_WARN("hit top " <<z<<','<<zMax<<','<<height);
heights.push_back(height);
if(myParams.Stepdown<0.0) break;
}else
heights.push_back(height);
}
}else{
heights.reserve(_heights.size());
bool hitMax = false, hitMin = false;
for(double z : _heights) {
switch(mode) {
case SectionModeAbsolute: {
gp_Pnt pt(0,0,z);
z = pt.Transformed(loc).Z();
break;
}case SectionModeBoundBox:
z = zMax - z;
break;
case SectionModeWorkplane:
z = -z;
break;
default:
throw Base::ValueError("invalid section mode");
}
if(z-zMin<myParams.SectionTolerance) {
if(hitMin) continue;
hitMin = true;
double zNew = zMin+myParams.SectionTolerance;
AREA_WARN("hit bottom " <<z<<','<<zMin<<','<<zNew);
z = zNew;
}else if (zMax-z<myParams.SectionTolerance) {
if(hitMax) continue;
double zNew = zMax-myParams.SectionTolerance;
AREA_WARN("hit top " <<z<<','<<zMax<<','<<zNew);
z = zNew;
}
heights.push_back(z);
}
}
if(heights.empty())
throw Base::ValueError("no sections");
std::vector<shared_ptr<Area> > sections;
sections.reserve(heights.size());
tolerance *= 2.0;
bool can_retry = fabs(tolerance)>Precision::Confusion();
for(double z : heights) {
bool retried = !can_retry;
while(true) {
gp_Pln pln(gp_Pnt(0,0,z),gp_Dir(0,0,1));
Standard_Real a,b,c,d;
pln.Coefficients(a,b,c,d);
BRepLib_MakeFace mkFace(pln,xMin,xMax,yMin,yMax);
const TopoDS_Shape &face = mkFace.Face();
shared_ptr<Area> area(new Area(&myParams));
area->setPlane(face);
for(auto it=myShapes.begin();it!=myShapes.end();++it) {
const auto &s = *it;
BRep_Builder builder;
TopoDS_Compound comp;
builder.MakeCompound(comp);
for(TopExp_Explorer xp(s.shape.Moved(loc), TopAbs_SOLID); xp.More(); xp.Next()) {
Part::CrossSection section(a,b,c,xp.Current());
std::list<TopoDS_Wire> wires = section.slice(-d);
if(wires.empty()) {
AREA_LOG("Section returns no wires");
continue;
}
Part::FaceMakerBullseye mkFace;
mkFace.setPlane(pln);
for(const TopoDS_Wire &wire : wires)
mkFace.addWire(wire);
try {
mkFace.Build();
if (mkFace.Shape().IsNull())
AREA_WARN("FaceMakerBullseye return null shape on section");
else {
builder.Add(comp,mkFace.Shape());
continue;
}
}catch (Base::Exception &e){
AREA_WARN("FaceMakerBullseye failed on section: " << e.what());
}
for(const TopoDS_Wire &wire : wires)
builder.Add(comp,wire);
}
// Make sure the compound has at least one edge
TopExp_Explorer xp(comp,TopAbs_EDGE);
if(xp.More()) {
area->add(comp,s.op);
}else if(area->myShapes.empty()){
auto itNext = it;
if(++itNext != myShapes.end() &&
(itNext->op==OperationIntersection ||
itNext->op==OperationDifference))
{
break;
}
}
}
if(area->myShapes.size()){
sections.push_back(area);
break;
}
if(retried) {
AREA_WARN("Discard empty section");
break;
}else{
AREA_TRACE("retry section " <<z<<"->"<<z+tolerance);
z += tolerance;
retried = true;
}
}
TIME_PRINT(t1,"makeSection " << z);
}
TIME_PRINT(t,"makeSection count: " << sections.size()<<", total");
return std::move(sections);
}
TopoDS_Shape Area::getPlane(gp_Trsf *trsf) {
if(!myWorkPlane.IsNull()) {
if(trsf) *trsf = myTrsf;
return myWorkPlane;
}
if(myShapePlane.IsNull()) {
if(myShapes.empty())
throw Base::ValueError("no shape added");
double top_z;
for(auto &s : myShapes)
foreachSubshape(s.shape,FindPlane(myShapePlane,myTrsf,top_z));
if(myShapePlane.IsNull())
throw Base::ValueError("shapes are not planar");
}
if(trsf) *trsf = myTrsf;
return myShapePlane;
}
bool Area::isBuilt() const {
return (myArea || mySections.size());
}
void Area::build() {
if(isBuilt()) return;
if(myShapes.empty())
throw Base::ValueError("no shape added");
#define AREA_SRC(_param) myParams.PARAM_FNAME(_param)
PARAM_ENUM_CONVERT(AREA_SRC,PARAM_FNAME,PARAM_ENUM_EXCEPT,AREA_PARAMS_CLIPPER_FILL);
if(myHaveSolid && myParams.SectionCount) {
mySections = makeSections(myParams.SectionMode);
return;
}
TIME_INIT(t);
getPlane();
try {
myArea.reset(new CArea());
myAreaOpen.reset(new CArea());
CAreaConfig conf(myParams);
CArea areaClip;
mySkippedShapes = 0;
short op = OperationUnion;
bool pending = false;
bool exploding = myParams.Explode;
for(const Shape &s : myShapes) {
if(exploding) {
exploding = false;
explode(s.shape);
continue;
}else if(op!=s.op) {
if(myParams.OpenMode!=OpenModeNone)
myArea->m_curves.splice(myArea->m_curves.end(),myAreaOpen->m_curves);
pending = false;
if(areaClip.m_curves.size()) {
if(op == OperationCompound)
myArea->m_curves.splice(myArea->m_curves.end(),areaClip.m_curves);
else{
myArea->Clip(toClipperOp(op),&areaClip,SubjectFill,ClipFill);
areaClip.m_curves.clear();
}
}
op=s.op;
}
addToBuild(op==OperationUnion?*myArea:areaClip,s.shape);
pending = true;
}
if(mySkippedShapes && !myHaveSolid)
AREA_WARN((myParams.Coplanar==CoplanarForce?"Skipped ":"Found ")<<
mySkippedShapes<<" non coplanar shapes");
if(pending){
if(myParams.OpenMode!=OpenModeNone)
myArea->m_curves.splice(myArea->m_curves.end(),myAreaOpen->m_curves);
if(op == OperationCompound)
myArea->m_curves.splice(myArea->m_curves.end(),areaClip.m_curves);
else{
myArea->Clip(toClipperOp(op),&areaClip,SubjectFill,ClipFill);
}
}
myArea->m_curves.splice(myArea->m_curves.end(),myAreaOpen->m_curves);
//Reassemble wires after explode
if(myParams.Explode) {
std::list<TopoDS_Edge> edges;
gp_Trsf trsf(myTrsf.Inverted());
for(const auto &c : myArea->m_curves) {
TopoDS_Wire wire = toShape(c,&trsf);
if(wire.IsNull()) continue;
TopExp_Explorer it(wire, TopAbs_EDGE);
edges.push_back(TopoDS::Edge(it.Current()));
}
Area area(&myParams);
area.myParams.Explode = false;
area.myParams.Coplanar = CoplanarNone;
area.myWorkPlane = getPlane(&area.myTrsf);
while(edges.size()) {
BRepBuilderAPI_MakeWire mkWire;
for(const auto &e : Part::sort_Edges(myParams.Tolerance,edges))
mkWire.Add(TopoDS::Edge(e));
area.add(mkWire.Wire(),OperationCompound);
}
area.build();
myArea = std::move(area.myArea);
}
TIME_TRACE(t,"prepare");
}catch(...) {
clean();
throw;
}
}
list<TopoDS_Shape> Area::sortWires(int index, int count, const gp_Pnt *pstart,
gp_Pnt *_pend, PARAM_ARGS(PARAM_FARG,AREA_PARAMS_SORT))
{
std::list<TopoDS_Shape> wires;
build();
gp_Pnt pend,pt;
if(pstart) pt = *pstart;
pt.Transform(TopLoc_Location(myTrsf));
if(mySections.size()) {
if(index>=(int)mySections.size())
throw Base::ValueError("index out of bound");
TopLoc_Location loc(myTrsf.Inverted());
if(index<0) {
index = 0;
count = mySections.size();
}
if(count<=0 || count>(int)mySections.size())
count = mySections.size();
for(int i=index;i<count;++i) {
const std::list<TopoDS_Shape> ws =
mySections[i]->sortWires(0,0,&pt,&pend,
PARAM_FIELDS(PARAM_FARG,AREA_PARAMS_SORT));
for(auto &wire : ws)
wires.push_back(wire.Moved(loc));
pt = pend;
}
if(_pend)
*_pend = pend.Transformed(loc);
return std::move(wires);
}
if(!myArea || myArea->m_curves.empty()) return wires;
CArea area(*myArea);
Point p(pt.X(),pt.Y());
area.ChangeStartToNearest(&p, PARAM_FIELDS(PARAM_FARG,AREA_PARAMS_MIN_DIST));
gp_Trsf trsf(myTrsf.Inverted());
for(const CCurve &c : area.m_curves) {
const TopoDS_Wire &wire = toShape(c,&trsf);
if(wire.IsNull()) continue;
wires.push_back(toShape(c,&trsf));
}
if(_pend) {
gp_Pnt pend = pt;
if(area.m_curves.size() &&
area.m_curves.back().m_vertices.size())
{
const Point &pt = area.m_curves.back().m_vertices.back().m_p;
pend.SetCoord(pt.x,pt.y,0.0);
}
*_pend = pend.Transformed(TopLoc_Location(trsf));
}
return std::move(wires);
}
TopoDS_Shape Area::toShape(CArea &area, short fill) {
gp_Trsf trsf(myTrsf.Inverted());
bool bFill;
switch(fill){
case Area::FillAuto:
bFill = myHaveFace;
break;
case Area::FillFace:
bFill = true;
break;
default:
bFill = false;
}
if(myParams.FitArcs) {
if(&area == myArea.get()) {
CArea copy(area);
copy.FitArcs();
return toShape(copy,bFill,&trsf);
}
area.FitArcs();
}
return toShape(area,bFill,&trsf);
}
#define AREA_SECTION(_op,_index,...) do {\
if(mySections.size()) {\
if(_index>=(int)mySections.size())\
return TopoDS_Shape();\
TopLoc_Location loc(myTrsf.Inverted());\
if(_index<0) {\
BRep_Builder builder;\
TopoDS_Compound compound;\
builder.MakeCompound(compound);\
for(shared_ptr<Area> area : mySections){\
const TopoDS_Shape &s = area->_op(-1, ## __VA_ARGS__);\
if(s.IsNull()) continue;\
builder.Add(compound,s.Moved(loc));\
}\
for(TopExp_Explorer it(compound,TopAbs_EDGE);it.More();)\
return compound;\
return TopoDS_Shape();\
}\
const TopoDS_Shape &shape = mySections[_index]->_op(-1, ## __VA_ARGS__);\
if(!shape.IsNull())\
return shape.Moved(loc);\
return shape;\
}\
}while(0)
TopoDS_Shape Area::getShape(int index) {
build();
AREA_SECTION(getShape,index);
if(myShapeDone) return myShape;
if(!myArea) return TopoDS_Shape();
CAreaConfig conf(myParams);
#define AREA_MY(_param) myParams.PARAM_FNAME(_param)
// if no offset or thicken, try pocket
if(fabs(myParams.Offset) < Precision::Confusion() && !myParams.Thicken) {
if(myParams.PocketMode == PocketModeNone) {
myShape = toShape(*myArea,myParams.Fill);
myShapeDone = true;
return myShape;
}
myShape = makePocket(-1,PARAM_FIELDS(AREA_MY,AREA_PARAMS_POCKET));
myShapeDone = true;
return myShape;
}
// if no pocket, do offset or thicken
if(myParams.PocketMode == PocketModeNone){
myShape = makeOffset(-1,PARAM_FIELDS(AREA_MY,AREA_PARAMS_OFFSET));
myShapeDone = true;
return myShape;
}