Salome HOME
d397d0a9b3f4176d8a862af9d6d89d1b81a4c46e
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-2024  CEA, EDF
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Model_BodyBuilder.h>
21
22 #include <Locale_Convert.h>
23
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <ModelAPI_Session.h>
27 #include <TNaming_Builder.hxx>
28 #include <TNaming_NamedShape.hxx>
29 #include <TNaming_Iterator.hxx>
30 #include <TNaming_Tool.hxx>
31 #include <TNaming_SameShapeIterator.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TDataStd_Integer.hxx>
34 #include <TDataStd_ExtStringList.hxx>
35 #include <TopoDS.hxx>
36 #include <TopoDS_Face.hxx>
37 #include <TDF_ChildIterator.hxx>
38 #include <TDF_ChildIDIterator.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_Tool.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopExp_Explorer.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_DataMapOfShapeListOfShape.hxx>
46 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
48 #include <TopTools_MapIteratorOfMapOfShape.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <TopTools_IndexedMapOfShape.hxx>
51 #include <TopTools_DataMapOfShapeShape.hxx>
52 #include <TopExp.hxx>
53 #include <BRepTools.hxx>
54 #include <BRep_Tool.hxx>
55 #include <BRepTools_History.hxx>
56 #include <GeomAPI_Shape.h>
57 #include <GeomAPI_ShapeExplorer.h>
58 #include <GeomAlgoAPI_MakeShape.h>
59 #include <GeomAlgoAPI_SortListOfShapes.h>
60 #include <Config_PropManager.h>
61 // DEB
62 //#include <TCollection_AsciiString.hxx>
63 //#define DEB_IMPORT 1
64
65 /// reference to the shape in external document: sting list attribute identifier
66 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
67
68 static const int INVALID_TAG            = -1;
69 static const int GENERATED_VERTICES_TAG = 1;
70 static const int GENERATED_EDGES_TAG    = 2;
71 static const int GENERATED_FACES_TAG    = 3;
72 static const int MODIFIED_VERTICES_TAG  = 4;
73 static const int MODIFIED_EDGES_TAG     = 5;
74 static const int MODIFIED_FACES_TAG     = 6;
75 static const int DELETED_TAG            = 7;
76 static const int PRIMITIVES_START_TAG   = 11;
77
78 static int getGenerationTag(const TopoDS_Shape& theShape) {
79   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
80   switch (aShapeType) {
81     case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
82     case TopAbs_EDGE:   return GENERATED_EDGES_TAG;
83     case TopAbs_FACE:   return GENERATED_FACES_TAG;
84     default: break; // [to avoid compilation warning]
85   }
86
87   return INVALID_TAG;
88 }
89
90 static int getModificationTag(const TopoDS_Shape& theShape) {
91   TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
92   switch (aShapeType) {
93     case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
94     case TopAbs_EDGE:   return MODIFIED_EDGES_TAG;
95     case TopAbs_FACE:   return MODIFIED_FACES_TAG;
96     default: break; // [to avoid compilation warning]
97   }
98
99   return INVALID_TAG;
100 }
101
102 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
103                             const TopoDS_Shape& theOldShape,
104                             const TopoDS_Shape& theNewShape)
105 {
106   for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
107     aNamingIt.More();
108     aNamingIt.Next())
109   {
110     if (aNamingIt.NewShape().IsSame(theNewShape)
111       && aNamingIt.OldShape().IsSame(theOldShape))
112     {
113       return true;
114     }
115   }
116
117   return false;
118 }
119
120 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
121 : ModelAPI_BodyBuilder(theOwner),
122   myFreePrimitiveTag(PRIMITIVES_START_TAG)
123 {
124 }
125
126 /// Checks that shape is presented in the tree with not-selection evolution
127 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
128 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
129   TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
130 {
131   bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
132   if (aResult) { //check evolution and a label of this shape
133     for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
134     {
135       Handle(TNaming_NamedShape) aNS;
136       if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
137         if (aNS->Evolution() != TNaming_SELECTED) {
138           theOriginalLabel = aNS->Label();
139           return true;
140         }
141       }
142     }
143   }
144   if (!theAccess2.IsNull()) {
145     static const TDF_Label anEmpty;
146     return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
147   }
148   return false;
149 }
150
151 /// Stores entry to the external label in the entries list at this label
152 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
153 {
154   // store information about the external document reference to restore old shape on open
155   if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
156     Handle(TDataStd_ExtStringList) anEntries;
157     if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
158       anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
159     }
160     TCollection_AsciiString anEntry;
161     TDF_Tool::Entry(theExternal, anEntry);
162     // check it already contains this entry
163     TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
164     for(; anIter.More(); anIter.Next())
165       if (anIter.Value() == anEntry)
166         break;
167     if (!anIter.More()) {
168       anEntries->Append(anEntry);
169     }
170   }
171 }
172
173 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
174                               const bool theIsStoreSameShapes)
175 {
176   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
177   if (aData) {
178     TDF_Label aShapeLab = aData->shapeLab();
179     // clean builders
180     clean();
181     // store the new shape as primitive
182     TNaming_Builder aBuilder(aShapeLab);
183     if (!theShape)
184       return;  // bad shape
185     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
186     if (aShape.IsNull())
187       return;  // null shape inside
188
189     if(!theIsStoreSameShapes) {
190       Handle(TNaming_NamedShape) aNS;
191       if (TNaming_Tool::HasLabel(aShapeLab, aShape))
192         aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
193       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
194       if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
195         // This shape is already in document, store reference instead of shape;
196         const TDF_Label aFoundLabel = aNS->Label();
197         TDF_Reference::Set(aShapeLab, aFoundLabel);
198         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
199         return;
200       }
201     }
202
203     aBuilder.Generated(aShape);
204     // register name
205     aShapeLab.ForgetAttribute(TDF_Reference::GetID());
206     if(!aBuilder.NamedShape()->IsEmpty()) {
207       Handle(TDataStd_Name) anAttr;
208       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
209         std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
210         if(!aName.empty()) {
211           std::shared_ptr<Model_Document> aDoc =
212             std::dynamic_pointer_cast<Model_Document>(document());
213           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
214         }
215       }
216     }
217   }
218 }
219
220 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
221   const GeomShapePtr& theToShape, const bool theIsCleanStored)
222 {
223   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
224   if (aData) {
225     // clean builders
226     if (theIsCleanStored)
227       clean();
228     TNaming_Builder* aBuilder = builder(0);
229     if (!theFromShape || !theToShape)
230       return;  // bad shape
231     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
232     if (aShapeBasis.IsNull())
233       return;  // null shape inside
234     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
235     if (aShapeNew.IsNull())
236       return;  // null shape inside
237
238     // There is no sense to write history if old shape does not exist in the document.
239     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
240       ModelAPI_Session::get()->moduleDocument())->generalLabel();
241     TDF_Label anOriginalLabel;
242     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
243       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
244         aBuilder->Generated(aShapeNew);
245       }
246     } else {
247       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
248         myBuilders.erase(0);
249         aBuilder = builder(0);
250       }
251
252       aBuilder->Generated(aShapeBasis, aShapeNew);
253       // store information about the external document reference to restore old shape on open
254       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
255     }
256
257     // register name
258     if(!aBuilder->NamedShape()->IsEmpty()) {
259       Handle(TDataStd_Name) anAttr;
260       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
261         std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
262         if(!aName.empty()) {
263           std::shared_ptr<Model_Document> aDoc =
264             std::dynamic_pointer_cast<Model_Document>(document());
265           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
266         }
267       }
268     }
269   }
270 }
271
272 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
273   const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
274 {
275   bool aStored = false;
276   std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
277   for (; anOldIter != theFromShapes.cend(); anOldIter++) {
278     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
279     if (!aStore) {
280       ListOfShape aNews; // check this old really generates theToShape
281       theMakeShape->generated(*anOldIter, aNews);
282       ListOfShape::iterator aNewIter = aNews.begin();
283       for (; aNewIter != aNews.end(); aNewIter++) {
284         if (theToShape->isSame(*aNewIter))
285           break;
286       }
287       aStore = aNewIter != aNews.end();
288     }
289     if (aStore) {
290       storeGenerated(*anOldIter, theToShape, !aStored);
291       TNaming_Builder* aBuilder = builder(0);
292       aStored = !aBuilder->NamedShape()->IsEmpty();
293     }
294   }
295   if (!aStored) { // store as PRIMITIVE, but clean in any way
296     store(theToShape);
297     return;
298   }
299 }
300
301 static TDF_Label builderLabel(DataPtr theData, const int theTag )
302 {
303   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
304   return theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
305 }
306
307 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
308 {
309   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
310   if (aFind == myBuilders.end()) {
311     myBuilders[theTag] = new TNaming_Builder(builderLabel(data(), theTag));
312     aFind = myBuilders.find(theTag);
313   }
314   return aFind->second;
315 }
316
317 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
318                                       const GeomShapePtr& theNewShape,
319                                       const bool theIsCleanStored)
320 {
321   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
322   if (aData) {
323     // clean builders
324     if (theIsCleanStored) clean();
325     TNaming_Builder* aBuilder = builder(0);
326     if (!theOldShape || !theNewShape)
327       return;  // bad shape
328     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
329     if (aShapeOld.IsNull())
330       return;  // null shape inside
331     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
332     if (aShapeNew.IsNull())
333       return;  // null shape inside
334
335     // There is no sense to write history if old shape does not exist in the document.
336     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
337       ModelAPI_Session::get()->moduleDocument())->generalLabel();
338     TDF_Label anOriginalLabel;
339     TopTools_ListOfShape anOldList;
340     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
341       // check this could be a compund by the whole feature selection
342       if (aShapeOld.ShapeType() == TopAbs_COMPOUND)  {
343         for(TopoDS_Iterator aCompIter(aShapeOld); aCompIter.More(); aCompIter.Next()) {
344           if (isShapeInTree(aData->shapeLab(), anAccess2, aCompIter.Value(), anOriginalLabel)) {
345             anOldList.Append(aCompIter.Value());
346           } else {
347             anOldList.Clear();
348             break;
349           }
350         }
351       }
352     } else {
353       anOldList.Append(aShapeOld);
354     }
355     if (anOldList.IsEmpty()) {
356       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
357         aBuilder->Generated(aShapeNew);
358       }
359     } else {
360       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
361         myBuilders.erase(0);
362         aBuilder = builder(0);
363       }
364       TopTools_ListIteratorOfListOfShape anOldIter(anOldList);
365       for(; anOldIter.More(); anOldIter.Next()) {
366         aBuilder->Modify(anOldIter.Value(), aShapeNew);
367       }
368       // store information about the external document reference to restore old shape on open
369       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
370     }
371
372     if(!aBuilder->NamedShape()->IsEmpty()) {
373       Handle(TDataStd_Name) anAttr;
374       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
375         std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
376         if(!aName.empty()) {
377           std::shared_ptr<Model_Document> aDoc =
378             std::dynamic_pointer_cast<Model_Document>(document());
379           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
380         }
381       }
382     }
383   }
384 }
385
386 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
387   const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
388 {
389   bool aStored = false;
390   std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
391   for(; anOldIter != theOldShapes.cend(); anOldIter++) {
392     // compounds may cause crash if call "modified"
393     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
394                 (*anOldIter)->isCompSolid();
395     if (!aStore) {
396       ListOfShape aNews; // check this old really modifies theNewShape
397       theMakeShape->modified(*anOldIter, aNews);
398       ListOfShape::iterator aNewIter = aNews.begin();
399       for(; aNewIter != aNews.end(); aNewIter++) {
400         if (theNewShape->isSame(*aNewIter))
401           break;
402       }
403       aStore = aNewIter != aNews.end();
404     }
405     if (aStore) {
406       storeModified(*anOldIter, theNewShape, !aStored);
407       TNaming_Builder* aBuilder = builder(0);
408       aStored = !aBuilder->NamedShape()->IsEmpty();
409     }
410   }
411   if (!aStored) {
412     // check the new shape is already in the tree, so, no need to store primitive, just reference
413     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
414     if (aData.get()) {
415       TDF_Label aShapeLab = aData->shapeLab();
416       TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
417       Handle(TNaming_NamedShape) aNS;
418       if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
419         aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
420       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
421       if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
422         // This shape is already in document, store reference instead of shape;
423         const TDF_Label aFoundLabel = aNS->Label();
424         TDF_Reference::Set(aShapeLab, aFoundLabel);
425         myBuilders.erase(0);
426         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
427         return;
428       }
429     }
430     store(theNewShape); // store as PRIMITIVE, but clean in any way
431     return;
432   }
433 }
434
435 void Model_BodyBuilder::clean()
436 {
437   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
438   if (aLab.IsNull())
439     return;
440   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
441   for(; aBuilder != myBuilders.end(); aBuilder++) {
442     Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
443     delete aBuilder->second;
444     if (!aNS.IsNull() && !aNS->Label().IsNull())
445       aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
446   }
447   myBuilders.clear();
448   myPrimitivesNamesIndexMap.clear();
449   // remove the old reference (if any)
450   aLab.ForgetAttribute(TDF_Reference::GetID());
451   myFreePrimitiveTag = PRIMITIVES_START_TAG;
452   TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
453   for(; anEntriesIter.More(); anEntriesIter.Next()) {
454     anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
455   }
456 }
457
458 void Model_BodyBuilder::cleanCash()
459 {
460   myPrimitivesNamesIndexMap.clear();
461 }
462
463 Model_BodyBuilder::~Model_BodyBuilder()
464 {
465   clean();
466 }
467
468 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
469 {
470   std::string aName = theName;
471   std::string aPrefix = "";
472   switch (theTag) {
473     case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
474     case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
475     case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
476     case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
477     case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
478     case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
479   }
480   aName.insert(0, aPrefix);
481
482   TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
483 }
484 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
485                                   const std::string& theName,
486                                   const bool theCheckIsInResult)
487 {
488   GeomShapePtr aResultShape = shape();
489   if (theCheckIsInResult) {
490     bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
491     if (aNewShapeIsNotInResultShape) {
492       return false;
493     }
494   }
495
496   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
497   builder(myFreePrimitiveTag)->Generated(aShape);
498   if (!theName.empty()) {
499     std::string aName = theName;
500     if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
501       IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
502       aName += "_" + std::to_string(++(anIndexTags.index));
503       anIndexTags.tags.push_back(myFreePrimitiveTag);
504       if (anIndexTags.index == 2) {
505         buildName(anIndexTags.tags.front(), theName + "_1");
506       }
507     }
508     else {
509       IndexTags anIndexTags;
510       anIndexTags.index = 1;
511       anIndexTags.tags.push_back(myFreePrimitiveTag);
512       myPrimitivesNamesIndexMap[theName] = anIndexTags;
513     }
514
515     buildName(myFreePrimitiveTag, aName);
516   }
517   ++myFreePrimitiveTag;
518   return true;
519 }
520
521 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
522                                   const GeomShapePtr& theNewShape,
523                                   const std::string& theName)
524 {
525   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
526   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
527   TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
528   int aTag;
529   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
530     // TODO: This is a workaround. New shape should be only vertex, edge or face.
531     TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
532     aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
533     for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
534       builder(aTag)->Generated(anOldShape, anExp.Current());
535     }
536     buildName(aTag, theName);
537   } else {
538     aTag = getGenerationTag(aNewShape);
539     if (aTag == INVALID_TAG) return;
540     builder(aTag)->Generated(anOldShape, aNewShape);
541     buildName(aTag, theName);
542   }
543 }
544
545 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
546                                  const GeomShapePtr& theNewShape,
547                                  const std::string& theName)
548 {
549   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
550   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
551   int aTag = getModificationTag(aNewShape);
552   if (aTag == INVALID_TAG) return;
553   builder(aTag)->Modify(anOldShape, aNewShape);
554   buildName(aTag, theName);
555 }
556
557 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
558                                           const GeomShapePtr& theOldShape,
559                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
560                                           const GeomShapePtr& theShapesToExclude)
561 {
562   TopTools_MapOfShape anAlreadyProcessedShapes;
563   GeomShapePtr aResultShape = shape();
564   for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
565        anExp.more();
566        anExp.next())
567   {
568     GeomShapePtr anOldSubShape = anExp.current();
569     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
570     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
571         || !theAlgo->isDeleted(anOldSubShape)
572         || aResultShape->isSubShape(anOldSubShape, false)
573         || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
574     {
575       continue;
576     }
577
578     ListOfShape aNewShapes;
579     if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
580       theAlgo->modified(anOldSubShape, aNewShapes);
581     }
582
583     if (aNewShapes.size() == 0
584         || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
585       builder(DELETED_TAG)->Delete(anOldSubShape_);
586     }
587   }
588 }
589
590 // Keep only the shapes with minimal shape type
591 static void keepTopLevelShapes(ListOfShape& theShapes,
592                                const TopoDS_Shape& theRoot,
593                                const GeomShapePtr& theResultShape = GeomShapePtr())
594 {
595   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
596   ListOfShape::iterator anIt = theShapes.begin();
597   while (anIt != theShapes.end()) {
598     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
599     bool aSkip = aNewShape.IsNull() ||
600       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
601     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
602         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
603       ListOfShape::iterator aRemoveIt = anIt++;
604       theShapes.erase(aRemoveIt);
605     } else {
606       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
607       if (aType < aKeepShapeType) {
608         // found a shape with lesser shape type => remove all previous shapes
609         aKeepShapeType = aType;
610         theShapes.erase(theShapes.begin(), anIt);
611         ++anIt;
612       } else if (aType > aKeepShapeType) {
613         // shapes with greater shape type should be removed from the list
614         ListOfShape::iterator aRemoveIt = anIt++;
615         theShapes.erase(aRemoveIt);
616       } else
617         ++anIt;
618     }
619   }
620 }
621
622 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
623                                            const GeomShapePtr& theOldShape,
624                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
625                                            const std::string& theName)
626 {
627   GeomShapePtr aResultShape = shape();
628   GeomShapePtr aShapeToExplore = theOldShape;
629   if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
630     // use optimized set of old shapes for this
631     GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
632                                                       aResultShape,
633                                                       theShapeTypeToExplore);
634     if (aCompound.get()) aShapeToExplore = aCompound;
635   }
636
637   // Store all types of subshapes in the map to use them for checking
638   // if the new shapes are sub-shapes of this result
639   TopTools_MapOfShape aResultShapeSubMap;
640   TopExp::MapShapes(aResultShape->impl<TopoDS_Shape>(), aResultShapeSubMap);
641
642   TopTools_MapOfShape anAlreadyProcessedShapes;
643   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
644   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
645        anOldShapeExp.more();
646        anOldShapeExp.next())
647   {
648     GeomShapePtr anOldSubShape = anOldShapeExp.current();
649     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
650
651     // There is no sense to write history if shape already processed
652     // or old shape does not exist in the document.
653     if (!anAlreadyProcessedShapes.Add(anOldSubShape_))
654     {
655       continue;
656     }
657
658     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument())->generalLabel();
659     TDF_Label anOriginalLabel;
660     if (!isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel))
661     {
662       continue;
663     }
664
665     // Get new shapes.
666     ListOfShape aNewShapes;
667     theAlgo->modified(anOldSubShape, aNewShapes);
668     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
669          aNewShapesIt != aNewShapes.cend();
670          ++aNewShapesIt)
671     {
672       GeomShapePtr aNewShape = *aNewShapesIt;
673       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
674
675       if (anOldSubShape->isSame(aNewShape))
676         continue;
677
678       if (aResultShape->isSame(aNewShape))
679         continue; // it is stored on the root level (2241 - history propagation issue)
680
681       // Look in the map instead of aResultShape->isSubShape(aNewShape, false)
682       // to avoid many iterations of sub-shapes hierarchy that leads to performance issues
683       if (!aResultShapeSubMap.Contains(aNewShape_))
684         continue;
685
686       const bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
687       int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
688       TNaming_Builder*aBuilder = builder(aTag);
689       if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
690         continue; // new shape was already stored.
691
692       buildName(aTag, theName);
693       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
694                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
695       // store information about the external document reference to restore old shape on open
696       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
697     }
698   }
699 }
700
701 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
702                                             const GeomShapePtr& theOldShape,
703                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
704                                             const std::string& theName,
705                                             const bool theSaveOldIfNotInTree)
706 {
707   GeomShapePtr aResultShape = shape();
708   TopTools_MapOfShape anAlreadyProcessedShapes;
709   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
710   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
711        anOldShapeExp.more();
712        anOldShapeExp.next())
713   {
714     GeomShapePtr anOldSubShape = anOldShapeExp.current();
715     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
716
717     // There is no sense to write history if shape already processed
718     // or old shape does not exist in the document.
719     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
720     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
721       ModelAPI_Session::get()->moduleDocument())->generalLabel();
722     TDF_Label anOriginalLabel;
723     bool anOldSubShapeNotInTree =
724       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
725     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
726       // The second condition is added due to #20170 because sub-shape must be added to real parent
727       // shape, not the reference. The naming name of pure reference is not registered in document.
728       if (theSaveOldIfNotInTree && !aData->shapeLab().IsAttribute(TDF_Reference::GetID())) {
729         std::string aSelectionName = theName + "Selected";
730         generated(anOldSubShape, aSelectionName, false);
731       } else
732         continue;
733     }
734
735     // Get new shapes.
736     ListOfShape aNewShapes;
737     theAlgo->generated(anOldSubShape, aNewShapes);
738
739     keepTopLevelShapes(aNewShapes, anOldSubShape_);
740
741     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
742          aNewShapesIt != aNewShapes.cend();
743          ++aNewShapesIt)
744     {
745       GeomShapePtr aNewShape = *aNewShapesIt;
746       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
747
748       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
749       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
750       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
751         continue;
752       }
753
754       if (aResultShape->isSame(aNewShape))
755         continue; // it is stored on the root level
756
757       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
758       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
759         // TODO: This is a workaround. New shape should be only edge or face.
760         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
761                                                                             : TopAbs_FACE;
762         int aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
763         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
764           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
765           // store information about the external document reference to restore old shape on open
766           storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
767         }
768         buildName(aTag, theName);
769       } else {
770         int aTag = getGenerationTag(aNewShape_);
771         if (aTag == INVALID_TAG) return;
772         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
773         buildName(aTag, theName);
774         // store information about the external document reference to restore old shape on open
775         storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
776       }
777     }
778   }
779 }
780
781 // LCOV_EXCL_START
782 //=======================================================================
783 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
784   const TopAbs_ShapeEnum        theGeneratedFrom,
785   TopTools_DataMapOfShapeShape& theDangles)
786 {
787   theDangles.Clear();
788   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
789   TopAbs_ShapeEnum GeneratedTo;
790   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
791   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
792   else return Standard_False;
793   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
794   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
795     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
796     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
797     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
798   }
799   return theDangles.Extent();
800 }
801
802 //=======================================================================
803 void loadGeneratedDangleShapes(
804   const TopoDS_Shape&      theShapeIn,
805   const TopAbs_ShapeEnum   theGeneratedFrom,
806   TNaming_Builder *        theBuilder)
807 {
808   TopTools_DataMapOfShapeShape dangles;
809   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
810   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
811   for (; itr.More(); itr.Next())
812     theBuilder->Generated(itr.Key(), itr.Value());
813 }
814 // LCOV_EXCL_STOP
815
816 //=======================================================================
817 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
818                                        const std::string& theName)
819 {
820   if(theShape->isNull()) return;
821   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
822   std::string aName;
823   if (aShape.ShapeType() == TopAbs_SOLID) {
824     TopExp_Explorer expl(aShape, TopAbs_FACE);
825     for (; expl.More(); expl.Next()) {
826       builder(myFreePrimitiveTag)->Generated(expl.Current());
827       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
828       aName = theName + "_" + aStr.ToCString();
829       buildName(myFreePrimitiveTag, aName);
830       ++myFreePrimitiveTag;
831     }
832   }
833   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
834     // load faces and all the free edges
835     TopTools_IndexedMapOfShape Faces;
836     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
837     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
838       TopExp_Explorer expl(aShape, TopAbs_FACE);
839       for (; expl.More(); expl.Next()) {
840         builder(myFreePrimitiveTag)->Generated(expl.Current());
841         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
842         aName = theName + "_" + aStr.ToCString();
843         buildName(myFreePrimitiveTag, aName);
844         ++myFreePrimitiveTag;
845       }
846     }
847     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
848     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
849     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
850     {
851       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
852       if (aLL.Extent() < 2) {
853         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
854           continue;
855         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
856         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
857         aName = theName + "_" + aStr.ToCString();
858         buildName(myFreePrimitiveTag, aName);
859         ++myFreePrimitiveTag;
860       } else {
861         TopTools_ListIteratorOfListOfShape anIter(aLL);
862         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
863         anIter.Next();
864         if(aFace.IsEqual(anIter.Value())) {
865           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
866           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
867           aName = theName + "_" + aStr.ToCString();
868           buildName(myFreePrimitiveTag, aName);
869           ++myFreePrimitiveTag;
870         }
871       }
872     }
873   } else if (aShape.ShapeType() == TopAbs_WIRE) {
874     TopTools_IndexedMapOfShape Edges;
875     BRepTools::Map3DEdges(aShape, Edges);
876     if (Edges.Extent() == 1) {
877       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
878       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
879       for (; expl.More(); expl.Next()) {
880         builder(myFreePrimitiveTag)->Generated(expl.Current());
881         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
882         aName = theName + "_" + aStr.ToCString();
883         buildName(myFreePrimitiveTag, aName);
884         ++myFreePrimitiveTag;
885       }
886     } else {
887       TopExp_Explorer expl(aShape, TopAbs_EDGE);
888       for (; expl.More(); expl.Next()) {
889         builder(myFreePrimitiveTag)->Generated(expl.Current());
890         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
891         aName = theName + "_" + aStr.ToCString();
892         buildName(myFreePrimitiveTag, aName);
893         ++myFreePrimitiveTag;
894       }
895       // and load generated vertices.
896       TopTools_DataMapOfShapeShape generated;
897       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
898       {
899         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
900         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
901       }
902     }
903   } else if (aShape.ShapeType() == TopAbs_EDGE) {
904     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
905     for (; expl.More(); expl.Next()) {
906       builder(myFreePrimitiveTag)->Generated(expl.Current());
907       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
908       aName = theName + "_" + aStr.ToCString();
909       buildName(myFreePrimitiveTag, aName);
910       ++myFreePrimitiveTag;
911     }
912   }
913 }
914
915 //=======================================================================
916 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
917   TopTools_ListOfShape&   theList)
918 {
919   theList.Clear();
920   // edges -> ancestor faces list
921   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
922   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
923   // keeps the shapes which are already in the resulting list
924   TopTools_MapOfShape alreadyThere;
925   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
926   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
927
928   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
929   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
930     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
931     if (ancestors.Extent() < 2)
932       continue;
933     Standard_Integer anID = 0;
934     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
935       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
936     }
937     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
938       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
939         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
940       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
941       for(; aSameEdge.More(); aSameEdge.Next()) {
942         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
943           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
944         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
945           break;
946
947         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
948         for(; aFaceIter1.More(); aFaceIter1.Next()) {
949           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
950           for(; aFaceIter2.More(); aFaceIter2.Next()) {
951             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
952               break;
953           }
954           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
955             break;
956         }
957         if (!aFaceIter1.More()) { // all the faces are same => put to the result
958           if (alreadyThere.Add(aSameEdge.Value()))
959             theList.Append(aSameEdge.Value());
960           if (alreadyThere.Add(anAncestorsIter.Key()))
961             theList.Append(anAncestorsIter.Key());
962         }
963       }
964     } else { // ID is unique, just add this edge
965       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
966     }
967     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
968   }
969   return theList.Extent();
970 }
971
972 //=======================================================================
973 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
974 {
975   GeomShapePtr aShapePtr = shape();
976   if (theShape->isNull() || !aShapePtr.get())
977     return;
978   TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
979   if (aShape.IsNull())
980     return;
981   std::string aName;
982   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
983     TopoDS_Iterator itr(aShape);
984     for (; itr.More(); itr.Next()) {
985       builder(myFreePrimitiveTag)->Generated(itr.Value());
986       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
987       aName = theName + "_" + aStr.ToCString();
988       buildName(myFreePrimitiveTag, aName);
989       ++myFreePrimitiveTag;
990       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
991         itr.Value().ShapeType() == TopAbs_COMPSOLID)
992       {
993         GeomShapePtr itrShape(new GeomAPI_Shape());
994         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
995         loadFirstLevel(itrShape, theName);
996       } else {
997         GeomShapePtr itrShape(new GeomAPI_Shape());
998         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
999         loadNextLevels(itrShape, theName);
1000       }
1001     }
1002   } else {
1003     GeomShapePtr itrShape(new GeomAPI_Shape());
1004     itrShape->setImpl(new TopoDS_Shape(aShape));
1005     loadNextLevels(itrShape, theName);
1006   }
1007   TopTools_ListOfShape   aList;
1008   if(findAmbiguities(aShape, aList)) {
1009     TopTools_ListIteratorOfListOfShape it(aList);
1010     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
1011       builder(myFreePrimitiveTag)->Generated(it.Value());
1012       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
1013       aName = theName + "_" + aStr.ToCString();
1014       buildName(myFreePrimitiveTag, aName);
1015     }
1016   }
1017 }
1018
1019 GeomShapePtr Model_BodyBuilder::shape()
1020 {
1021   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1022   if (aData && aData->isValid()) {
1023     TDF_Label aShapeLab = aData->shapeLab();
1024     Handle(TDF_Reference) aRef;
1025     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1026       aShapeLab = aRef->Get();
1027     }
1028     Handle(TNaming_NamedShape) aName;
1029     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1030       TopoDS_Shape aShape = aName->Get();
1031       if (!aShape.IsNull()) {
1032         GeomShapePtr aRes(new GeomAPI_Shape);
1033         aRes->setImpl(new TopoDS_Shape(aShape));
1034         return aRes;
1035       }
1036     }
1037   }
1038   return GeomShapePtr();
1039 }