1 // Copyright (C) 2014-2020 CEA/DEN, EDF R&D
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <Model_BodyBuilder.h>
22 #include <Model_Data.h>
23 #include <Model_Document.h>
24 #include <ModelAPI_Session.h>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Iterator.hxx>
28 #include <TNaming_Tool.hxx>
29 #include <TNaming_SameShapeIterator.hxx>
30 #include <TDataStd_Name.hxx>
31 #include <TDataStd_Integer.hxx>
32 #include <TDataStd_ExtStringList.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TDF_ChildIterator.hxx>
36 #include <TDF_ChildIDIterator.hxx>
37 #include <TDF_Reference.hxx>
38 #include <TDF_Tool.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopExp_Explorer.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
43 #include <TopTools_DataMapOfShapeListOfShape.hxx>
44 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
46 #include <TopTools_MapIteratorOfMapOfShape.hxx>
47 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
48 #include <TopTools_IndexedMapOfShape.hxx>
49 #include <TopTools_DataMapOfShapeShape.hxx>
51 #include <BRepTools.hxx>
52 #include <BRep_Tool.hxx>
53 #include <BRepTools_History.hxx>
54 #include <GeomAPI_Shape.h>
55 #include <GeomAPI_ShapeExplorer.h>
56 #include <GeomAlgoAPI_MakeShape.h>
57 #include <GeomAlgoAPI_SortListOfShapes.h>
58 #include <Config_PropManager.h>
60 //#include <TCollection_AsciiString.hxx>
61 //#define DEB_IMPORT 1
63 /// reference to the shape in external document: sting list attribute identifier
64 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
66 static const int INVALID_TAG = -1;
67 static const int GENERATED_VERTICES_TAG = 1;
68 static const int GENERATED_EDGES_TAG = 2;
69 static const int GENERATED_FACES_TAG = 3;
70 static const int MODIFIED_VERTICES_TAG = 4;
71 static const int MODIFIED_EDGES_TAG = 5;
72 static const int MODIFIED_FACES_TAG = 6;
73 static const int DELETED_TAG = 7;
74 static const int PRIMITIVES_START_TAG = 11;
76 static int getGenerationTag(const TopoDS_Shape& theShape) {
77 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
79 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
80 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
81 case TopAbs_FACE: return GENERATED_FACES_TAG;
82 default: break; // [to avoid compilation warning]
88 static int getModificationTag(const TopoDS_Shape& theShape) {
89 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
91 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
92 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
93 case TopAbs_FACE: return MODIFIED_FACES_TAG;
94 default: break; // [to avoid compilation warning]
100 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
101 const TopoDS_Shape& theOldShape,
102 const TopoDS_Shape& theNewShape)
104 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
108 if (aNamingIt.NewShape().IsSame(theNewShape)
109 && aNamingIt.OldShape().IsSame(theOldShape))
118 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
119 : ModelAPI_BodyBuilder(theOwner),
120 myFreePrimitiveTag(PRIMITIVES_START_TAG)
124 /// Checks that shape is presented in the tree with not-selection evolution
125 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
126 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
127 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
129 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
130 if (aResult) { //check evolution and a label of this shape
131 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
133 static Handle(TNaming_NamedShape) aNS;
134 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
135 if (aNS->Evolution() != TNaming_SELECTED) {
136 theOriginalLabel = aNS->Label();
142 if (!theAccess2.IsNull()) {
143 static const TDF_Label anEmpty;
144 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
149 /// Stores entry to the external label in the entries list at this label
150 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
152 // store information about the external document reference to restore old shape on open
153 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
154 Handle(TDataStd_ExtStringList) anEntries;
155 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
156 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
158 TCollection_AsciiString anEntry;
159 TDF_Tool::Entry(theExternal, anEntry);
160 // check it already contains this entry
161 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
162 for(; anIter.More(); anIter.Next())
163 if (anIter.Value() == anEntry)
165 if (!anIter.More()) {
166 anEntries->Append(anEntry);
171 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
172 const bool theIsStoreSameShapes)
174 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
176 TDF_Label aShapeLab = aData->shapeLab();
179 // store the new shape as primitive
180 TNaming_Builder aBuilder(aShapeLab);
183 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
185 return; // null shape inside
187 if(!theIsStoreSameShapes) {
188 Handle(TNaming_NamedShape) aNS;
189 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
190 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
191 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
192 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
193 // This shape is already in document, store reference instead of shape;
194 const TDF_Label aFoundLabel = aNS->Label();
195 TDF_Reference::Set(aShapeLab, aFoundLabel);
196 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
201 aBuilder.Generated(aShape);
203 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
204 if(!aBuilder.NamedShape()->IsEmpty()) {
205 Handle(TDataStd_Name) anAttr;
206 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
207 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
209 std::shared_ptr<Model_Document> aDoc =
210 std::dynamic_pointer_cast<Model_Document>(document());
211 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
218 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
219 const GeomShapePtr& theToShape, const bool theIsCleanStored)
221 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
224 if (theIsCleanStored)
226 TNaming_Builder* aBuilder = builder(0);
227 if (!theFromShape || !theToShape)
229 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
230 if (aShapeBasis.IsNull())
231 return; // null shape inside
232 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
233 if (aShapeNew.IsNull())
234 return; // null shape inside
236 // There is no sense to write history if old shape does not exist in the document.
237 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
238 ModelAPI_Session::get()->moduleDocument())->generalLabel();
239 TDF_Label anOriginalLabel;
240 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
241 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
242 aBuilder->Generated(aShapeNew);
245 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
247 aBuilder = builder(0);
250 aBuilder->Generated(aShapeBasis, aShapeNew);
251 // store information about the external document reference to restore old shape on open
252 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
256 if(!aBuilder->NamedShape()->IsEmpty()) {
257 Handle(TDataStd_Name) anAttr;
258 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
259 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
261 std::shared_ptr<Model_Document> aDoc =
262 std::dynamic_pointer_cast<Model_Document>(document());
263 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
270 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
271 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
273 bool aStored = false;
274 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
275 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
276 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
278 ListOfShape aNews; // check this old really generates theToShape
279 theMakeShape->generated(*anOldIter, aNews);
280 ListOfShape::iterator aNewIter = aNews.begin();
281 for (; aNewIter != aNews.end(); aNewIter++) {
282 if (theToShape->isSame(*aNewIter))
285 aStore = aNewIter != aNews.end();
288 storeGenerated(*anOldIter, theToShape, !aStored);
289 TNaming_Builder* aBuilder = builder(0);
290 aStored = !aBuilder->NamedShape()->IsEmpty();
293 if (!aStored) { // store as PRIMITIVE, but clean in any way
299 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
301 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
302 if (aFind == myBuilders.end()) {
303 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
304 myBuilders[theTag] = new TNaming_Builder(
305 theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
306 aFind = myBuilders.find(theTag);
308 return aFind->second;
311 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
312 const GeomShapePtr& theNewShape,
313 const bool theIsCleanStored)
315 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
318 if (theIsCleanStored) clean();
319 TNaming_Builder* aBuilder = builder(0);
320 if (!theOldShape || !theNewShape)
322 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
323 if (aShapeOld.IsNull())
324 return; // null shape inside
325 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
326 if (aShapeNew.IsNull())
327 return; // null shape inside
329 // There is no sense to write history if old shape does not exist in the document.
330 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
331 ModelAPI_Session::get()->moduleDocument())->generalLabel();
332 TDF_Label anOriginalLabel;
333 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
334 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
335 aBuilder->Generated(aShapeNew);
338 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
340 aBuilder = builder(0);
343 aBuilder->Modify(aShapeOld, aShapeNew);
344 // store information about the external document reference to restore old shape on open
345 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
348 if(!aBuilder->NamedShape()->IsEmpty()) {
349 Handle(TDataStd_Name) anAttr;
350 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
351 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
353 std::shared_ptr<Model_Document> aDoc =
354 std::dynamic_pointer_cast<Model_Document>(document());
355 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
362 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
363 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
365 bool aStored = false;
366 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
367 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
368 // compounds may cause crash if call "modified"
369 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
370 (*anOldIter)->isCompSolid();
372 ListOfShape aNews; // check this old really modifies theNewShape
373 theMakeShape->modified(*anOldIter, aNews);
374 ListOfShape::iterator aNewIter = aNews.begin();
375 for(; aNewIter != aNews.end(); aNewIter++) {
376 if (theNewShape->isSame(*aNewIter))
379 aStore = aNewIter != aNews.end();
382 storeModified(*anOldIter, theNewShape, !aStored);
383 TNaming_Builder* aBuilder = builder(0);
384 aStored = !aBuilder->NamedShape()->IsEmpty();
388 // check the new shape is already in the tree, so, no need to store primitive, just reference
389 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
391 TDF_Label aShapeLab = aData->shapeLab();
392 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
393 Handle(TNaming_NamedShape) aNS;
394 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
395 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
396 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
397 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
398 // This shape is already in document, store reference instead of shape;
399 const TDF_Label aFoundLabel = aNS->Label();
400 TDF_Reference::Set(aShapeLab, aFoundLabel);
402 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
406 store(theNewShape); // store as PRIMITIVE, but clean in any way
411 void Model_BodyBuilder::clean()
413 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
416 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
417 for(; aBuilder != myBuilders.end(); aBuilder++) {
418 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
419 delete aBuilder->second;
420 if (!aNS.IsNull() && !aNS->Label().IsNull())
421 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
424 myPrimitivesNamesIndexMap.clear();
425 // remove the old reference (if any)
426 aLab.ForgetAttribute(TDF_Reference::GetID());
427 myFreePrimitiveTag = PRIMITIVES_START_TAG;
428 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
429 for(; anEntriesIter.More(); anEntriesIter.Next()) {
430 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
434 void Model_BodyBuilder::cleanCash()
436 myPrimitivesNamesIndexMap.clear();
439 Model_BodyBuilder::~Model_BodyBuilder()
444 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
446 std::string aName = theName;
447 std::string aPrefix = "";
449 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
450 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
451 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
452 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
453 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
454 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
456 aName.insert(0, aPrefix);
458 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
460 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
461 const std::string& theName,
462 const bool theCheckIsInResult)
464 GeomShapePtr aResultShape = shape();
465 if (theCheckIsInResult) {
466 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
467 if (aNewShapeIsNotInResultShape) {
472 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
473 builder(myFreePrimitiveTag)->Generated(aShape);
474 if (!theName.empty()) {
475 std::string aName = theName;
476 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
477 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
478 aName += "_" + std::to_string(++(anIndexTags.index));
479 anIndexTags.tags.push_back(myFreePrimitiveTag);
480 if (anIndexTags.index == 2) {
481 buildName(anIndexTags.tags.front(), theName + "_1");
485 IndexTags anIndexTags;
486 anIndexTags.index = 1;
487 anIndexTags.tags.push_back(myFreePrimitiveTag);
488 myPrimitivesNamesIndexMap[theName] = anIndexTags;
491 buildName(myFreePrimitiveTag, aName);
493 ++myFreePrimitiveTag;
497 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
498 const GeomShapePtr& theNewShape,
499 const std::string& theName)
501 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
502 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
503 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
505 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
506 // TODO: This is a workaround. New shape should be only vertex, edge or face.
507 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
508 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
509 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
510 builder(aTag)->Generated(anOldShape, anExp.Current());
512 buildName(aTag, theName);
514 aTag = getGenerationTag(aNewShape);
515 if (aTag == INVALID_TAG) return;
516 builder(aTag)->Generated(anOldShape, aNewShape);
517 buildName(aTag, theName);
521 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
522 const GeomShapePtr& theNewShape,
523 const std::string& theName)
525 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
526 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
527 int aTag = getModificationTag(aNewShape);
528 if (aTag == INVALID_TAG) return;
529 builder(aTag)->Modify(anOldShape, aNewShape);
530 buildName(aTag, theName);
533 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
534 const GeomShapePtr& theOldShape,
535 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
536 const GeomShapePtr& theShapesToExclude)
538 TopTools_MapOfShape anAlreadyProcessedShapes;
539 GeomShapePtr aResultShape = shape();
540 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
544 GeomShapePtr anOldSubShape = anExp.current();
545 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
546 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
547 || !theAlgo->isDeleted(anOldSubShape)
548 || aResultShape->isSubShape(anOldSubShape, false)
549 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
554 ListOfShape aNewShapes;
555 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
556 theAlgo->modified(anOldSubShape, aNewShapes);
559 if (aNewShapes.size() == 0
560 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
561 builder(DELETED_TAG)->Delete(anOldSubShape_);
566 // Keep only the shapes with minimal shape type
567 static void keepTopLevelShapes(ListOfShape& theShapes,
568 const TopoDS_Shape& theRoot,
569 const GeomShapePtr& theResultShape = GeomShapePtr())
571 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
572 ListOfShape::iterator anIt = theShapes.begin();
573 while (anIt != theShapes.end()) {
574 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
575 bool aSkip = aNewShape.IsNull() ||
576 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
577 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
578 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
579 ListOfShape::iterator aRemoveIt = anIt++;
580 theShapes.erase(aRemoveIt);
582 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
583 if (aType < aKeepShapeType) {
584 // found a shape with lesser shape type => remove all previous shapes
585 aKeepShapeType = aType;
586 theShapes.erase(theShapes.begin(), anIt);
588 } else if (aType > aKeepShapeType) {
589 // shapes with greater shape type should be removed from the list
590 ListOfShape::iterator aRemoveIt = anIt++;
591 theShapes.erase(aRemoveIt);
598 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
599 const GeomShapePtr& theOldShape,
600 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
601 const std::string& theName)
603 GeomShapePtr aResultShape = shape();
604 GeomShapePtr aShapeToExplore = theOldShape;
605 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
606 // use optimized set of old shapes for this
607 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
609 theShapeTypeToExplore);
610 if (aCompound.get()) aShapeToExplore = aCompound;
613 TopTools_MapOfShape anAlreadyProcessedShapes;
614 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
615 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
616 anOldShapeExp.more();
617 anOldShapeExp.next())
619 GeomShapePtr anOldSubShape = anOldShapeExp.current();
620 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
622 // There is no sense to write history if shape already processed
623 // or old shape does not exist in the document.
624 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
625 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
626 ModelAPI_Session::get()->moduleDocument())->generalLabel();
627 TDF_Label anOriginalLabel;
628 bool anOldSubShapeNotInTree =
629 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
630 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
635 ListOfShape aNewShapes;
636 theAlgo->modified(anOldSubShape, aNewShapes);
638 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
639 aNewShapesIt != aNewShapes.cend();
642 GeomShapePtr aNewShape = *aNewShapesIt;
643 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
644 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
646 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
647 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
648 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
651 if (aResultShape->isSame(aNewShape))
652 continue; // it is stored on the root level (2241 - history propagation issue)
654 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
655 TNaming_Builder*aBuilder = builder(aTag);
656 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
657 continue; // new shape was already stored.
659 buildName(aTag, theName);
660 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
661 : aBuilder->Modify(anOldSubShape_, aNewShape_);
662 // store information about the external document reference to restore old shape on open
663 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
668 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
669 const GeomShapePtr& theOldShape,
670 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
671 const std::string& theName,
672 const bool theSaveOldIfNotInTree)
674 GeomShapePtr aResultShape = shape();
675 TopTools_MapOfShape anAlreadyProcessedShapes;
676 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
677 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
678 anOldShapeExp.more();
679 anOldShapeExp.next())
681 GeomShapePtr anOldSubShape = anOldShapeExp.current();
682 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
684 // There is no sense to write history if shape already processed
685 // or old shape does not exist in the document.
686 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
687 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
688 ModelAPI_Session::get()->moduleDocument())->generalLabel();
689 TDF_Label anOriginalLabel;
690 bool anOldSubShapeNotInTree =
691 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
692 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
693 if (theSaveOldIfNotInTree) {
694 std::string aSelectionName = theName + "Selected";
695 generated(anOldSubShape, aSelectionName, false);
701 ListOfShape aNewShapes;
702 theAlgo->generated(anOldSubShape, aNewShapes);
704 keepTopLevelShapes(aNewShapes, anOldSubShape_);
706 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
707 aNewShapesIt != aNewShapes.cend();
710 GeomShapePtr aNewShape = *aNewShapesIt;
711 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
713 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
714 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
715 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
719 if (aResultShape->isSame(aNewShape))
720 continue; // it is stored on the root level
722 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
723 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
724 // TODO: This is a workaround. New shape should be only edge or face.
725 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
727 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
728 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
729 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
730 // store information about the external document reference to restore old shape on open
731 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
733 buildName(aTag, theName);
735 int aTag = getGenerationTag(aNewShape_);
736 if (aTag == INVALID_TAG) return;
737 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
738 buildName(aTag, theName);
739 // store information about the external document reference to restore old shape on open
740 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
747 //=======================================================================
748 int getDangleShapes(const TopoDS_Shape& theShapeIn,
749 const TopAbs_ShapeEnum theGeneratedFrom,
750 TopTools_DataMapOfShapeShape& theDangles)
753 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
754 TopAbs_ShapeEnum GeneratedTo;
755 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
756 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
757 else return Standard_False;
758 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
759 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
760 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
761 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
762 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
764 return theDangles.Extent();
767 //=======================================================================
768 void loadGeneratedDangleShapes(
769 const TopoDS_Shape& theShapeIn,
770 const TopAbs_ShapeEnum theGeneratedFrom,
771 TNaming_Builder * theBuilder)
773 TopTools_DataMapOfShapeShape dangles;
774 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
775 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
776 for (; itr.More(); itr.Next())
777 theBuilder->Generated(itr.Key(), itr.Value());
781 //=======================================================================
782 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
783 const std::string& theName)
785 if(theShape->isNull()) return;
786 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
788 if (aShape.ShapeType() == TopAbs_SOLID) {
789 TopExp_Explorer expl(aShape, TopAbs_FACE);
790 for (; expl.More(); expl.Next()) {
791 builder(myFreePrimitiveTag)->Generated(expl.Current());
792 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
793 aName = theName + "_" + aStr.ToCString();
794 buildName(myFreePrimitiveTag, aName);
795 ++myFreePrimitiveTag;
798 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
799 // load faces and all the free edges
800 TopTools_IndexedMapOfShape Faces;
801 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
802 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
803 TopExp_Explorer expl(aShape, TopAbs_FACE);
804 for (; expl.More(); expl.Next()) {
805 builder(myFreePrimitiveTag)->Generated(expl.Current());
806 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
807 aName = theName + "_" + aStr.ToCString();
808 buildName(myFreePrimitiveTag, aName);
809 ++myFreePrimitiveTag;
812 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
813 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
814 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
816 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
817 if (aLL.Extent() < 2) {
818 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
820 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
821 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
822 aName = theName + "_" + aStr.ToCString();
823 buildName(myFreePrimitiveTag, aName);
824 ++myFreePrimitiveTag;
826 TopTools_ListIteratorOfListOfShape anIter(aLL);
827 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
829 if(aFace.IsEqual(anIter.Value())) {
830 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
831 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
832 aName = theName + "_" + aStr.ToCString();
833 buildName(myFreePrimitiveTag, aName);
834 ++myFreePrimitiveTag;
838 } else if (aShape.ShapeType() == TopAbs_WIRE) {
839 TopTools_IndexedMapOfShape Edges;
840 BRepTools::Map3DEdges(aShape, Edges);
841 if (Edges.Extent() == 1) {
842 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
843 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
844 for (; expl.More(); expl.Next()) {
845 builder(myFreePrimitiveTag)->Generated(expl.Current());
846 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
847 aName = theName + "_" + aStr.ToCString();
848 buildName(myFreePrimitiveTag, aName);
849 ++myFreePrimitiveTag;
852 TopExp_Explorer expl(aShape, TopAbs_EDGE);
853 for (; expl.More(); expl.Next()) {
854 builder(myFreePrimitiveTag)->Generated(expl.Current());
855 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
856 aName = theName + "_" + aStr.ToCString();
857 buildName(myFreePrimitiveTag, aName);
858 ++myFreePrimitiveTag;
860 // and load generated vertices.
861 TopTools_DataMapOfShapeShape generated;
862 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
864 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
865 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
868 } else if (aShape.ShapeType() == TopAbs_EDGE) {
869 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
870 for (; expl.More(); expl.Next()) {
871 builder(myFreePrimitiveTag)->Generated(expl.Current());
872 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
873 aName = theName + "_" + aStr.ToCString();
874 buildName(myFreePrimitiveTag, aName);
875 ++myFreePrimitiveTag;
880 //=======================================================================
881 int findAmbiguities(const TopoDS_Shape& theShapeIn,
882 TopTools_ListOfShape& theList)
885 // edges -> ancestor faces list
886 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
887 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
888 // keeps the shapes which are already in the resulting list
889 TopTools_MapOfShape alreadyThere;
890 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
891 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
893 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
894 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
895 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
896 if (ancestors.Extent() < 2)
898 Standard_Integer anID = 0;
899 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
900 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
902 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
903 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
904 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
905 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
906 for(; aSameEdge.More(); aSameEdge.Next()) {
907 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
908 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
909 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
912 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
913 for(; aFaceIter1.More(); aFaceIter1.Next()) {
914 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
915 for(; aFaceIter2.More(); aFaceIter2.Next()) {
916 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
919 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
922 if (!aFaceIter1.More()) { // all the faces are same => put to the result
923 if (alreadyThere.Add(aSameEdge.Value()))
924 theList.Append(aSameEdge.Value());
925 if (alreadyThere.Add(anAncestorsIter.Key()))
926 theList.Append(anAncestorsIter.Key());
929 } else { // ID is unique, just add this edge
930 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
932 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
934 return theList.Extent();
937 //=======================================================================
938 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
940 GeomShapePtr aShapePtr = shape();
941 if (theShape->isNull() || !aShapePtr.get())
943 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
947 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
948 TopoDS_Iterator itr(aShape);
949 for (; itr.More(); itr.Next()) {
950 builder(myFreePrimitiveTag)->Generated(itr.Value());
951 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
952 aName = theName + "_" + aStr.ToCString();
953 buildName(myFreePrimitiveTag, aName);
954 ++myFreePrimitiveTag;
955 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
956 itr.Value().ShapeType() == TopAbs_COMPSOLID)
958 GeomShapePtr itrShape(new GeomAPI_Shape());
959 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
960 loadFirstLevel(itrShape, theName);
962 GeomShapePtr itrShape(new GeomAPI_Shape());
963 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
964 loadNextLevels(itrShape, theName);
968 GeomShapePtr itrShape(new GeomAPI_Shape());
969 itrShape->setImpl(new TopoDS_Shape(aShape));
970 loadNextLevels(itrShape, theName);
972 TopTools_ListOfShape aList;
973 if(findAmbiguities(aShape, aList)) {
974 TopTools_ListIteratorOfListOfShape it(aList);
975 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
976 builder(myFreePrimitiveTag)->Generated(it.Value());
977 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
978 aName = theName + "_" + aStr.ToCString();
979 buildName(myFreePrimitiveTag, aName);
984 GeomShapePtr Model_BodyBuilder::shape()
986 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
987 if (aData && aData->isValid()) {
988 TDF_Label aShapeLab = aData->shapeLab();
989 Handle(TDF_Reference) aRef;
990 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
991 aShapeLab = aRef->Get();
993 Handle(TNaming_NamedShape) aName;
994 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
995 TopoDS_Shape aShape = aName->Get();
996 if (!aShape.IsNull()) {
997 GeomShapePtr aRes(new GeomAPI_Shape);
998 aRes->setImpl(new TopoDS_Shape(aShape));
1003 return GeomShapePtr();