forked from FreeCAD/FreeCAD
/
TopoShapeEx.cpp
5372 lines (4856 loc) · 191 KB
/
TopoShapeEx.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) 2018 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_
# include <cmath>
# include <cstdlib>
# include <sstream>
# include <QString>
# include <BRepLib.hxx>
# include <BSplCLib.hxx>
# include <Bnd_Box.hxx>
# include <BRep_Builder.hxx>
# include <BRep_Tool.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <BRepAdaptor_CompCurve.hxx>
# if OCC_VERSION_HEX < 0x070600
# include <BRepAdaptor_HCurve.hxx>
# include <BRepAdaptor_HCompCurve.hxx>
# endif
# include <BRepAdaptor_Surface.hxx>
# include <BRepAlgoAPI_Common.hxx>
# include <BRepAlgoAPI_Cut.hxx>
# include <BRepAlgoAPI_Fuse.hxx>
# include <BRepAlgoAPI_Section.hxx>
# include <BRepBndLib.hxx>
# include <BRepBuilderAPI_FindPlane.hxx>
# include <BRepLib_FindSurface.hxx>
# include <BRepBuilderAPI_GTransform.hxx>
# include <BRepBuilderAPI_MakeEdge.hxx>
# include <BRepBuilderAPI_MakeFace.hxx>
# include <BRepBuilderAPI_MakePolygon.hxx>
# include <BRepBuilderAPI_MakeSolid.hxx>
# include <BRepBuilderAPI_MakeVertex.hxx>
# include <BRepBuilderAPI_MakeWire.hxx>
# include <BRepBuilderAPI_MakeShell.hxx>
# include <BRepBuilderAPI_NurbsConvert.hxx>
# include <BRepBuilderAPI_FaceError.hxx>
# include <BRepBuilderAPI_Copy.hxx>
# include <BRepBuilderAPI_Transform.hxx>
# include <BRepCheck_Analyzer.hxx>
# include <BRepCheck_ListIteratorOfListOfStatus.hxx>
# include <BRepCheck_Result.hxx>
# include <BRepClass_FaceClassifier.hxx>
# include <BRepFilletAPI_MakeFillet.hxx>
# include <BRepFilletAPI_MakeChamfer.hxx>
# include <BRepGProp.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <BRepMesh_Triangle.hxx>
# include <BRepMesh_Edge.hxx>
# include <BRepOffsetAPI_MakeThickSolid.hxx>
# include <BRepOffsetAPI_MakeOffsetShape.hxx>
# include <BRepOffsetAPI_MakeOffset.hxx>
# include <BRepOffsetAPI_MakePipe.hxx>
# include <BRepOffsetAPI_MakePipeShell.hxx>
# include <BRepOffsetAPI_Sewing.hxx>
# include <BRepOffsetAPI_ThruSections.hxx>
# include <BRepPrimAPI_MakePrism.hxx>
# include <BRepPrimAPI_MakeRevol.hxx>
# include <BRepFeat_MakePrism.hxx>
# include <BRepTools.hxx>
# include <BRepTools_ReShape.hxx>
# include <BRepTools_ShapeSet.hxx>
# include <BRepTools_WireExplorer.hxx>
# include <BRepFill_CompatibleWires.hxx>
# include <BRepProj_Projection.hxx>
# include <GCE2d_MakeSegment.hxx>
# include <GCPnts_AbscissaPoint.hxx>
# include <GCPnts_UniformAbscissa.hxx>
# include <Geom2d_Line.hxx>
# include <Geom2d_TrimmedCurve.hxx>
# include <GeomLProp_SLProps.hxx>
# include <GeomAPI_ProjectPointOnSurf.hxx>
# include <GeomFill_CorrectedFrenet.hxx>
# include <GeomFill_CurveAndTrihedron.hxx>
# include <GeomFill_EvolvedSection.hxx>
# include <GeomFill_Pipe.hxx>
# include <GeomFill_SectionLaw.hxx>
# include <GeomFill_Sweep.hxx>
# include <GeomLib.hxx>
# include <GProp_GProps.hxx>
# include <ShapeConstruct_Curve.hxx>
# include <Law_BSpFunc.hxx>
# include <Law_BSpline.hxx>
# include <Law_BSpFunc.hxx>
# include <Law_Constant.hxx>
# include <Law_Linear.hxx>
# include <Law_S.hxx>
# include <TopTools_HSequenceOfShape.hxx>
# include <Interface_Static.hxx>
# include <IGESControl_Controller.hxx>
# include <IGESControl_Writer.hxx>
# include <IGESControl_Reader.hxx>
# include <IGESData_GlobalSection.hxx>
# include <IGESData_IGESModel.hxx>
# include <STEPControl_Writer.hxx>
# include <STEPControl_Reader.hxx>
# include <TopTools_MapOfShape.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Compound.hxx>
# include <TopoDS_Iterator.hxx>
# include <TopoDS_Solid.hxx>
# include <TopoDS_Vertex.hxx>
# include <TopExp.hxx>
# include <TopExp_Explorer.hxx>
# include <TopTools_ListIteratorOfListOfShape.hxx>
# include <Geom2d_Ellipse.hxx>
# include <Geom_BezierCurve.hxx>
# include <Geom_BezierSurface.hxx>
# include <Geom_BSplineCurve.hxx>
# include <Geom_BSplineSurface.hxx>
# include <Geom_SurfaceOfLinearExtrusion.hxx>
# include <Geom_SurfaceOfRevolution.hxx>
# include <Geom_Circle.hxx>
# include <Geom_ConicalSurface.hxx>
# include <Geom_CylindricalSurface.hxx>
# include <Geom_Ellipse.hxx>
# include <Geom_Hyperbola.hxx>
# include <Geom_Line.hxx>
# include <Geom_Parabola.hxx>
# include <Geom_Plane.hxx>
# include <Geom_CartesianPoint.hxx>
# include <Geom_SphericalSurface.hxx>
# include <Geom_ToroidalSurface.hxx>
# include <GeomLib_IsPlanarSurface.hxx>
# include <GeomConvert.hxx>
# include <Poly_Triangulation.hxx>
# include <Standard_Failure.hxx>
# include <StlAPI_Writer.hxx>
# include <gp_GTrsf.hxx>
# include <ShapeAnalysis_Shell.hxx>
# include <ShapeBuild_ReShape.hxx>
# include <ShapeExtend_Explorer.hxx>
# include <ShapeFix_Edge.hxx>
# include <ShapeFix_Face.hxx>
# include <ShapeFix_Shell.hxx>
# include <ShapeFix_Solid.hxx>
# include <ShapeFix_Shape.hxx>
# include <ShapeFix_ShapeTolerance.hxx>
# include <ShapeUpgrade_ShellSewing.hxx>
# include <ShapeUpgrade_RemoveInternalWires.hxx>
# include <Standard_Version.hxx>
# include <ShapeFix_Wire.hxx>
# include <ShapeAnalysis.hxx>
# include <BRepFill.hxx>
# include <BRepOffsetAPI_DraftAngle.hxx>
# include <BRepPrimAPI_MakeHalfSpace.hxx>
# include <gp_Pln.hxx>
# include <BRepLProp_SLProps.hxx>
# include <BRepGProp_Face.hxx>
#endif
# include <ShapeAnalysis_FreeBoundsProperties.hxx>
# include <ShapeAnalysis_FreeBoundData.hxx>
# include <ShapeAnalysis_FreeBounds.hxx>
# include <BRepOffsetAPI_MakeFilling.hxx>
# include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
# include <GeomFill_FillingStyle.hxx>
# include <GeomFill_BSplineCurves.hxx>
# include <BRepFill_Generator.hxx>
#include <array>
#include <deque>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <Base/Exception.h>
#include <Base/Console.h>
#include <App/MappedElement.h>
#include <App/Application.h>
#include <App/Document.h>
#include "PartFeature.h"
#include "PartPyCXX.h"
#include "TopoShape.h"
#include "TopoShapeOpCode.h"
#include "CrossSection.h"
#include "TopoShapeFacePy.h"
#include "TopoShapeEdgePy.h"
#include "TopoShapeVertexPy.h"
#include "modelRefine.h"
#include "Tools.h"
#include "FaceMaker.h"
#include "BRepOffsetAPI_MakeOffsetFix.h"
#include "Geometry.h"
#include "FaceMakerBullseye.h"
#include "PartParams.h"
#define TOPOP_VERSION 15
FC_LOG_LEVEL_INIT("TopoShape",true,2);
#if OCC_VERSION_HEX >= 0x070600
using Adaptor3d_HCurve = Adaptor3d_Curve;
using BRepAdaptor_HCurve = BRepAdaptor_Curve;
using BRepAdaptor_HCompCurve = BRepAdaptor_CompCurve;
#endif
using namespace Part;
using namespace Data;
namespace bio = boost::iostreams;
#define _HANDLE_NULL_SHAPE(_msg,_throw) do {\
if(_throw) {\
FC_THROWM(NullShapeException,_msg);\
}\
FC_WARN(_msg);\
}while(0)
#define HANDLE_NULL_SHAPE _HANDLE_NULL_SHAPE("Null shape",true)
#define HANDLE_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape",true)
#define WARN_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape",false)
static void expandCompound(const TopoShape &shape, std::vector<TopoShape> &res) {
if(shape.isNull())
HANDLE_NULL_INPUT;
if(shape.getShape().ShapeType() != TopAbs_COMPOUND) {
res.push_back(shape);
return;
}
for(auto &s : shape.getSubTopoShapes())
expandCompound(s,res);
}
void ShapeMapper::expand(const TopoDS_Shape &d, std::vector<TopoDS_Shape> &shapes)
{
if (d.IsNull()) return;
for(TopExp_Explorer xp(d, TopAbs_FACE);xp.More();xp.Next())
shapes.push_back(xp.Current());
for(TopExp_Explorer xp(d, TopAbs_EDGE, TopAbs_FACE);xp.More();xp.Next())
shapes.push_back(xp.Current());
for(TopExp_Explorer xp(d, TopAbs_VERTEX, TopAbs_EDGE);xp.More();xp.Next())
shapes.push_back(xp.Current());
}
void ShapeMapper::populate(bool generated,
const TopTools_ListOfShape &src,
const TopTools_ListOfShape &dst)
{
for(TopTools_ListIteratorOfListOfShape it(src);it.More();it.Next())
populate(generated, it.Value(), dst);
}
void ShapeMapper::populate(bool generated,
const TopoShape &src,
const TopTools_ListOfShape &dst)
{
if(src.isNull())
return;
std::vector<TopoDS_Shape> dstShapes;
for(TopTools_ListIteratorOfListOfShape it(dst);it.More();it.Next())
expand(it.Value(), dstShapes);
insert(generated, src.getShape(), dstShapes);
}
void ShapeMapper::insert(bool generated, const TopoDS_Shape &s, const TopoDS_Shape &d)
{
if (s.IsNull() || d.IsNull()) return;
// Prevent an element shape from being both generated and modified
if (generated) {
if (_modifiedShapes.count(d))
return;
_generatedShapes.insert(d);
} else {
if( _generatedShapes.count(d))
return;
_modifiedShapes.insert(d);
}
auto &entry = generated?_generated[s]:_modified[s];
if(entry.shapeSet.insert(d).second)
entry.shapes.push_back(d);
};
void ShapeMapper::insert(bool generated, const TopoDS_Shape &s, const std::vector<TopoDS_Shape> &d)
{
if (s.IsNull() || d.empty()) return;
auto &entry = generated?_generated[s]:_modified[s];
for(auto &shape : d) {
// Prevent an element shape from being both generated and modified
if (generated) {
if (_modifiedShapes.count(shape))
continue;
_generatedShapes.insert(shape);
} else {
if( _generatedShapes.count(shape))
continue;
_modifiedShapes.insert(shape);
}
if(entry.shapeSet.insert(shape).second)
entry.shapes.push_back(shape);
}
};
struct ShapeRelationKey {
Data::MappedName name;
bool sameType;
ShapeRelationKey(const Data::MappedName & name, bool sameType)
:name(name), sameType(sameType)
{}
bool operator<(const ShapeRelationKey &other) const {
if(sameType != other.sameType)
return sameType;
return name < other.name;
}
};
#define INIT_SHAPE_CACHE() initCache(0,__FILE__,__LINE__)
struct ShapeSource {
TopoShape shape;
QByteArray op;
};
struct ShapeSources {
std::vector<ShapeSource> shapes;
bool expanded = false;
};
class TopoShape::Cache: public std::enable_shared_from_this<TopoShape::Cache>
{
public:
ElementMapPtr cachedElementMap;
TopLoc_Location subLocation;
TopoDS_Shape shape;
TopLoc_Location loc;
TopLoc_Location locInv;
std::size_t memsize = 0;
struct AncestorInfo {
bool inited = false;
TopTools_IndexedDataMapOfShapeListOfShape shapes;
};
class Info {
private:
Cache *owner = 0;
TopTools_IndexedMapOfShape shapes;
std::vector<TopoShape> topoShapes;
std::array<AncestorInfo, TopAbs_SHAPE+1> ancestors;
TopoShape _getTopoShape(const TopoShape &parent, int index) {
auto &s = topoShapes[index-1];
if(s.isNull()) {
s.setShape(shapes.FindKey(index), true);
s.INIT_SHAPE_CACHE();
s._Cache->subLocation = s._Shape.Location();
}
if (s._Shape.IsEqual(parent._Cache->shape))
return parent;
TopoShape res(s);
res.Tag = parent.Tag;
res.Hasher = parent.Hasher;
if(!parent.getShape().Location().IsIdentity())
res.setShape(res.getShape().Moved(parent.getShape().Location()),false);
if (s._Cache->cachedElementMap)
res.resetElementMap(s._Cache->cachedElementMap);
else if (parent._ParentCache) {
// If no cachedElementMap exists, we use _ParentCache for
// delayed generation of sub element map so that we don't need
// to always generate a full map whenever we returns a sub
// shape. To simplify the mapping and avoid circular
// dependency, we do not chain parent and grand parent.
// Instead, we always use the cache from the top parent. And to
// make it work, we must accumulate the TopLoc_Location along
// the lineage, which is required for OCCT shape mapping to
// work.
//
// Cache::subLocation is shared and only contains the location
// in the direct parent shape, while TopoShape::_SubLocation is
// used to accumulate locations in higher ancestors. We
// separate these two to avoid invalidating cache.
res._SubLocation = parent._SubLocation * parent._Cache->subLocation;
res._ParentCache = parent._ParentCache;
} else
res._ParentCache = owner->shared_from_this();
return res;
}
public:
void clear()
{
topoShapes.clear();
}
TopoShape getTopoShape(const TopoShape &parent, int index) {
TopoShape res;
if(index<=0 || index>shapes.Extent())
return res;
topoShapes.resize(shapes.Extent());
return _getTopoShape(parent,index);
}
std::vector<TopoShape> getTopoShapes(const TopoShape &parent) {
int count = shapes.Extent();
std::vector<TopoShape> res;
res.reserve(count);
topoShapes.resize(count);
for(int i=1;i<=count;++i)
res.push_back(_getTopoShape(parent,i));
return res;
}
TopoDS_Shape stripLocation(const TopoDS_Shape &parent, const TopoDS_Shape &child) {
if(parent.Location() != owner->loc) {
owner->loc = parent.Location();
owner->locInv = parent.Location().Inverted();
}
return child.Located(owner->locInv*child.Location());
}
int find(const TopoDS_Shape &parent, const TopoDS_Shape &subshape) {
if(parent.Location().IsIdentity())
return shapes.FindIndex(subshape);
return shapes.FindIndex(stripLocation(parent,subshape));
}
TopoDS_Shape find(const TopoDS_Shape &parent, int index) {
if(index<=0 || index>shapes.Extent())
return TopoDS_Shape();
if(parent.Location().IsIdentity())
return shapes.FindKey(index);
else
return shapes.FindKey(index).Moved(parent.Location());
}
int count() const {
return shapes.Extent();
}
friend Cache;
};
std::array<Info,TopAbs_SHAPE+1> infos;
std::map<ShapeRelationKey,QVector<Data::MappedElement> > relations;
Cache(const TopoDS_Shape &s)
:shape(s.Located(TopLoc_Location()))
{}
void insertRelation(const ShapeRelationKey &key, const QVector<Data::MappedElement> &value)
{
auto res = relations.insert(std::make_pair(key, value));
if (res.second)
res.first->first.name.compact();
else
res.first->second = value;
}
bool isTouched(const TopoDS_Shape &s)
{
return !this->shape.IsPartner(s) ||
this->shape.Orientation() != s.Orientation();
}
Info &getInfo(TopAbs_ShapeEnum type) {
auto &info = infos[type];
if(!info.owner) {
info.owner = this;
if(!shape.IsNull()) {
if(type == TopAbs_SHAPE) {
for(TopoDS_Iterator it(shape);it.More();it.Next())
info.shapes.Add(it.Value());
}else
TopExp::MapShapes(shape, type, info.shapes);
}
}
return info;
}
int countShape(TopAbs_ShapeEnum type) {
if(shape.IsNull())
return 0;
return getInfo(type).count();
}
int findShape(const TopoDS_Shape &parent, const TopoDS_Shape &subshape) {
if(shape.IsNull() || subshape.IsNull())
return 0;
return getInfo(subshape.ShapeType()).find(parent,subshape);
}
TopoDS_Shape findShape(const TopoDS_Shape &parent, TopAbs_ShapeEnum type, int index) {
if(!shape.IsNull())
return getInfo(type).find(parent,index);
return TopoDS_Shape();
}
TopoDS_Shape findAncestor(const TopoDS_Shape &parent, const TopoDS_Shape &subshape,
TopAbs_ShapeEnum type, std::vector<TopoDS_Shape> *ancestors=0)
{
TopoDS_Shape ret;
if(shape.IsNull() || subshape.IsNull() || type==TopAbs_SHAPE)
return ret;
auto &info = getInfo(type);
auto &ainfo = info.ancestors[subshape.ShapeType()];
if(!ainfo.inited) {
ainfo.inited = true;
TopExp::MapShapesAndAncestors(shape, subshape.ShapeType(), type, ainfo.shapes);
}
int index;
if(parent.Location().IsIdentity())
index = ainfo.shapes.FindIndex(subshape);
else
index = ainfo.shapes.FindIndex(info.stripLocation(parent,subshape));
if(!index)
return ret;
const auto &shapes = ainfo.shapes.FindFromIndex(index);
if(!shapes.Extent())
return ret;
if(ancestors) {
ancestors->reserve(ancestors->size()+shapes.Extent());
for(TopTools_ListIteratorOfListOfShape it(shapes);it.More();it.Next())
ancestors->push_back(it.Value().Moved(parent.Location()));
}
return shapes.First().Moved(parent.Location());
}
std::size_t getMemSize();
};
void TopoShape::initCache(int reset, const char *file, int line) const{
if(reset>0 || !_Cache || _Cache->isTouched(_Shape)) {
if(_Cache && reset==0) {
if(file)
_FC_TRACE(file,line,"invalidate cache");
else
FC_TRACE("invalidate cache");
}
if (_ParentCache) {
_ParentCache.reset();
_SubLocation.Identity();
}
_Cache = std::make_shared<Cache>(_Shape);
}
}
Data::ElementMapPtr TopoShape::resetElementMap(Data::ElementMapPtr elementMap)
{
if (_Cache && elementMap != this->elementMap(false)) {
for (auto &info : _Cache->infos)
info.clear();
} else
INIT_SHAPE_CACHE();
if (elementMap) {
_Cache->cachedElementMap = elementMap;
_Cache->subLocation.Identity();
_SubLocation.Identity();
_ParentCache.reset();
}
return Data::ComplexGeoData::resetElementMap(elementMap);
}
void TopoShape::flushElementMap() const
{
INIT_SHAPE_CACHE();
if (!elementMap(false) && this->_Cache) {
if (this->_Cache->cachedElementMap) {
const_cast<TopoShape*>(this)->resetElementMap(this->_Cache->cachedElementMap);
}
else if (this->_ParentCache) {
TopoShape parent(this->Tag, this->Hasher, this->_ParentCache->shape);
parent._Cache = _ParentCache;
parent.flushElementMap();
TopoShape self(this->Tag, this->Hasher,
this->_Shape.Located(this->_SubLocation * this->_Cache->subLocation));
self._Cache = _Cache;
self.mapSubElement(parent);
this->_ParentCache.reset();
this->_SubLocation.Identity();
const_cast<TopoShape*>(this)->resetElementMap(self.elementMap());
}
}
}
unsigned long TopoShape::getElementMapReserve() const
{
if (isNull())
return 0;
return countSubShapes(TopAbs_VERTEX)
+ countSubShapes(TopAbs_EDGE)
+ countSubShapes(TopAbs_FACE);
}
TopoShape::TopoShape(const TopoShape& shape)
: _Shape(*this)
{
*this = shape;
}
void TopoShape::setShape(const TopoDS_Shape & shape, bool resetElementMap)
{
if(resetElementMap)
this->resetElementMap();
else if (_Cache && _Cache->isTouched(shape))
this->flushElementMap();
_Shape._Shape = shape;
if (_Cache)
INIT_SHAPE_CACHE();
}
bool TopoShape::hasPendingElementMap() const
{
return !elementMap(false)
&& this->_Cache
&& (this->_ParentCache || this->_Cache->cachedElementMap);
}
void TopoShape::operator = (const TopoShape& sh)
{
if (this != &sh) {
this->setShape(sh._Shape, true);
this->Tag = sh.Tag;
this->Hasher = sh.Hasher;
this->_Cache = sh._Cache;
this->_ParentCache = sh._ParentCache;
this->_SubLocation = sh._SubLocation;
resetElementMap(sh.elementMap(false));
}
}
int TopoShape::findShape(const TopoDS_Shape &subshape) const {
INIT_SHAPE_CACHE();
return _Cache->findShape(_Shape,subshape);
}
static const std::string _SubShape("SubShape");
TopoDS_Shape TopoShape::findShape(const char *name) const {
if(!name)
return TopoDS_Shape();
Data::MappedElement res = getElementName(name);
if (!res.index)
return TopoDS_Shape();
auto idx = shapeTypeAndIndex(name);
if(!idx.second)
return TopoDS_Shape();
INIT_SHAPE_CACHE();
return _Cache->findShape(_Shape,idx.first,idx.second);
}
TopoDS_Shape TopoShape::findShape(TopAbs_ShapeEnum type, int idx) const {
INIT_SHAPE_CACHE();
return _Cache->findShape(_Shape,type,idx);
}
std::vector<TopoShape> TopoShape::searchSubShape(
const TopoShape &subshape, std::vector<std::string> *names,
bool checkGeometry, double tol, double atol) const
{
std::vector<TopoShape> res;
if(subshape.isNull() || this->isNull())
return res;
double tol2 = tol*tol;
int i=0;
TopAbs_ShapeEnum shapeType = subshape.shapeType();
switch(shapeType) {
case TopAbs_VERTEX:
// Vertex search will do comparison with tolerance to account for
// rounding error inccured through transformation.
for(auto &s : getSubTopoShapes(TopAbs_VERTEX)) {
++i;
if(BRep_Tool::Pnt(TopoDS::Vertex(s.getShape())).SquareDistance(
BRep_Tool::Pnt(TopoDS::Vertex(subshape.getShape()))) <= tol2)
{
if(names)
names->push_back(std::string("Vertex")+std::to_string(i));
res.push_back(s);
}
}
break;
case TopAbs_EDGE:
case TopAbs_FACE: {
std::unique_ptr<Geometry> g;
bool isLine = false;
bool isPlane = false;
std::vector<TopoDS_Shape> vertices;
TopoShape wire;
if(shapeType == TopAbs_FACE) {
wire = subshape.splitWires();
vertices = wire.getSubShapes(TopAbs_VERTEX);
} else
vertices = subshape.getSubShapes(TopAbs_VERTEX);
if(vertices.empty() || checkGeometry) {
g = Geometry::fromShape(subshape.getShape());
if(!g)
return res;
if (shapeType == TopAbs_EDGE)
isLine = (g->isDerivedFrom(GeomLine::getClassTypeId())
|| g->isDerivedFrom(GeomLineSegment::getClassTypeId()));
else
isPlane = g->isDerivedFrom(GeomPlane::getClassTypeId());
}
auto compareGeometry = [&](const TopoShape &s, bool strict) {
std::unique_ptr<Geometry> g2(Geometry::fromShape(s.getShape()));
if (!g2)
return false;
if (isLine && !strict) {
// For lines, don't compare geometry, just check the
// vertices below instead, because the exact same edge
// may have different geometrical representation.
if (!g2->isDerivedFrom(GeomLine::getClassTypeId())
&& !g2->isDerivedFrom(GeomLineSegment::getClassTypeId()))
return false;
} else if (isPlane && !strict) {
// For planes, don't compare geometry either, so that
// we don't need to worry about orientation and so on.
// Just check the edges.
if (!g2->isDerivedFrom(GeomPlane::getClassTypeId()))
return false;
} else if(!g2 || !g2->isSame(*g,tol,atol))
return false;
return true;
};
if(vertices.empty()) {
// Probably an infinite shape, so we have to search by geometry
int idx = 0;
for (auto &s : getSubTopoShapes(shapeType)) {
++idx;
if (!s.countSubShapes(TopAbs_VERTEX) && compareGeometry(s, true)) {
if(names)
names->push_back(shapeName(shapeType) + std::to_string(idx));
res.push_back(s);
}
}
break;
}
// The basic idea of shape search is about the same for both edge and face.
// * Search the first vertex, which is done with tolerance.
// * Find the ancestor shape of the found vertex
// * Compare each vertex of the ancestor shape and the input shape
// * Perform geometry comparison of the ancestor and input shape.
// * For face, perform addition geometry comparison of each edges.
std::unordered_set<TopoShape> shapeSet;
for(auto &v : searchSubShape(vertices[0],nullptr,checkGeometry,tol,atol)) {
for(auto idx : findAncestors(v.getShape(), shapeType)) {
auto s = getSubTopoShape(shapeType, idx);
if(!shapeSet.insert(s).second)
continue;
TopoShape otherWire;
std::vector<TopoDS_Shape> otherVertices;
if (shapeType == TopAbs_FACE) {
otherWire = s.splitWires();
if (wire.countSubShapes(TopAbs_EDGE) != otherWire.countSubShapes(TopAbs_EDGE))
continue;
otherVertices = otherWire.getSubShapes(TopAbs_VERTEX);
} else
otherVertices = s.getSubShapes(TopAbs_VERTEX);
if (otherVertices.size() != vertices.size())
continue;
if(checkGeometry && !compareGeometry(s, false))
continue;
unsigned i = 0;
bool matched = true;
for(auto &v : vertices) {
bool found = false;
for (unsigned j=0; j<otherVertices.size(); ++j) {
auto & v1 = otherVertices[i];
if (++i == otherVertices.size())
i = 0;
if(BRep_Tool::Pnt(TopoDS::Vertex(v)).SquareDistance(
BRep_Tool::Pnt(TopoDS::Vertex(v1))) <= tol2)
{
found = true;
break;
}
}
if (!found) {
matched = false;
break;
}
}
if(!matched)
continue;
if(shapeType == TopAbs_FACE && checkGeometry) {
// Is it really necessary to check geometries of each edge of a face?
// Right now we only do outer wire check
auto otherEdges = otherWire.getSubShapes(TopAbs_EDGE);
std::vector<std::unique_ptr<Geometry> > geos;
geos.resize(otherEdges.size());
bool matched = true;
unsigned i = 0;
auto edges = wire.getSubShapes(TopAbs_EDGE);
for(auto &e : edges) {
std::unique_ptr<Geometry> g(Geometry::fromShape(e));
if(!g) {
matched = false;
break;
}
bool isLine = false;
gp_Pnt pt1, pt2;
if (g->isDerivedFrom(GeomLine::getClassTypeId())
|| g->isDerivedFrom(GeomLineSegment::getClassTypeId()))
{
pt1 = BRep_Tool::Pnt(TopExp::FirstVertex(TopoDS::Edge(e)));
pt2 = BRep_Tool::Pnt(TopExp::LastVertex(TopoDS::Edge(e)));
isLine = true;
}
// We will tolerate on edge reordering
bool found = false;
for (unsigned j=0; j<otherEdges.size(); j++) {
auto & e1 = otherEdges[i];
auto & g1 = geos[i];
if (++i >= otherEdges.size())
i = 0;
if (!g1) {
g1 = Geometry::fromShape(e1);
if (!g1)
break;
}
if (isLine) {
if(g1->isDerivedFrom(GeomLine::getClassTypeId())
|| g1->isDerivedFrom(GeomLineSegment::getClassTypeId()))
{
auto p1 = BRep_Tool::Pnt(TopExp::FirstVertex(TopoDS::Edge(e1)));
auto p2 = BRep_Tool::Pnt(TopExp::LastVertex(TopoDS::Edge(e1)));
if((p1.SquareDistance(pt1) <= tol2
&& p2.SquareDistance(pt2) <= tol2)
|| (p1.SquareDistance(pt2) <= tol2
&& p2.SquareDistance(pt1) <= tol2))
{
found = true;
break;
}
}
continue;
}
if(g1->isSame(*g,tol,atol)) {
found = true;
break;
}
}
if (!found) {
matched = false;
break;
}
}
if (!matched)
continue;
}
if(names)
names->push_back(shapeName(shapeType) + std::to_string(idx));
res.push_back(s);
}
}
break;
}
default:
break;
}
return res;
}
int TopoShape::findAncestor(const TopoDS_Shape &subshape, TopAbs_ShapeEnum type) const {
INIT_SHAPE_CACHE();
return _Cache->findShape(_Shape,_Cache->findAncestor(_Shape,subshape,type));
}
TopoDS_Shape TopoShape::findAncestorShape(const TopoDS_Shape &subshape, TopAbs_ShapeEnum type) const {
INIT_SHAPE_CACHE();
return _Cache->findAncestor(_Shape,subshape,type);
}
std::vector<int> TopoShape::findAncestors(const TopoDS_Shape &subshape, TopAbs_ShapeEnum type) const {
const auto &shapes = findAncestorsShapes(subshape,type);
std::vector<int> ret;
ret.reserve(shapes.size());
for(const auto &shape : shapes)
ret.push_back(findShape(shape));
return ret;
}
std::vector<TopoDS_Shape> TopoShape::findAncestorsShapes(
const TopoDS_Shape &subshape, TopAbs_ShapeEnum type) const
{
INIT_SHAPE_CACHE();
std::vector<TopoDS_Shape> shapes;
_Cache->findAncestor(_Shape,subshape,type,&shapes);
return shapes;
}
bool TopoShape::canMapElement(const TopoShape &other) const {
if(isNull() || other.isNull() || this == &other)
return false;
if(!other.Tag
&& !other.elementMap(false)
&& !other.hasPendingElementMap())
return false;
INIT_SHAPE_CACHE();
other.INIT_SHAPE_CACHE();
_Cache->relations.clear();
return true;
}
void TopoShape::mapSubElement(const std::vector<TopoShape> &shapes, const char *op) {
if (shapes.empty())
return;
if (shapeType(true) == TopAbs_COMPOUND) {
int count = 0;
for (auto & s : shapes) {
if (s.isNull())
continue;
if (!getSubShape(TopAbs_SHAPE, ++count, true).IsPartner(s._Shape)) {
count = 0;
break;
}
}
if (count) {
std::vector<Data::MappedChildElements> children;
children.reserve(count*3);
TopAbs_ShapeEnum types[] = {TopAbs_VERTEX, TopAbs_EDGE, TopAbs_FACE};
for (unsigned i=0; i<sizeof(types)/sizeof(types[0]); ++i) {
int offset = 0;
for (auto & s : shapes) {
if (s.isNull())
continue;
int count = s.countSubShapes(types[i]);
if (!count)
continue;
children.emplace_back();
auto & child = children.back();
child.indexedName = Data::IndexedName::fromConst(shapeName(types[i]).c_str(), 1);
child.offset = offset;
offset += count;
child.count = count;
child.elementMap = s.elementMap();
child.tag = s.Tag;
if (op)
child.postfix = op;
}
}
setMappedChildElements(children);
return;
}
}
for(auto &shape : shapes)
mapSubElement(shape,op);
}
void TopoShape::mapSubElementsTo(std::vector<TopoShape> &shapes, const char *op) const {
for(auto &shape : shapes)
shape.mapSubElement(*this,op);
}
void TopoShape::copyElementMap(const TopoShape &s, const char *op)
{
if (s.isNull() || isNull())
return;
std::vector<Data::MappedChildElements> children;
TopAbs_ShapeEnum types[] = {TopAbs_VERTEX, TopAbs_EDGE, TopAbs_FACE};
for (unsigned i=0; i<sizeof(types)/sizeof(types[0]); ++i) {
int count = countSubShapes(types[i]);
int other = s.countSubShapes(types[i]);
if (count != other) {
FC_WARN("sub shape mismatch");
if (count > other)
count = other;
}
if (!count)