Salome HOME
ded9641986c7f62e5e461e35d44b30dbb46e075d
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-2023  CEA/DEN, EDF R&D
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   TopTools_MapOfShape anAlreadyProcessedShapes;
638   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
639   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
640        anOldShapeExp.more();
641        anOldShapeExp.next())
642   {
643     GeomShapePtr anOldSubShape = anOldShapeExp.current();
644     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
645
646     // There is no sense to write history if shape already processed
647     // or old shape does not exist in the document.
648     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
649     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
650       ModelAPI_Session::get()->moduleDocument())->generalLabel();
651     TDF_Label anOriginalLabel;
652     bool anOldSubShapeNotInTree =
653       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
654     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
655       continue;
656     }
657
658     // Get new shapes.
659     ListOfShape aNewShapes;
660     theAlgo->modified(anOldSubShape, aNewShapes);
661
662     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
663          aNewShapesIt != aNewShapes.cend();
664          ++aNewShapesIt)
665     {
666       GeomShapePtr aNewShape = *aNewShapesIt;
667       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
668       bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
669
670       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
671       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
672       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
673         continue;
674
675       if (aResultShape->isSame(aNewShape))
676         continue; // it is stored on the root level (2241 - history propagation issue)
677
678       int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
679       TNaming_Builder*aBuilder = builder(aTag);
680       if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
681         continue; // new shape was already stored.
682
683       buildName(aTag, theName);
684       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
685                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
686       // store information about the external document reference to restore old shape on open
687       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
688     }
689   }
690 }
691
692 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
693                                             const GeomShapePtr& theOldShape,
694                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
695                                             const std::string& theName,
696                                             const bool theSaveOldIfNotInTree)
697 {
698   GeomShapePtr aResultShape = shape();
699   TopTools_MapOfShape anAlreadyProcessedShapes;
700   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
701   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
702        anOldShapeExp.more();
703        anOldShapeExp.next())
704   {
705     GeomShapePtr anOldSubShape = anOldShapeExp.current();
706     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
707
708     // There is no sense to write history if shape already processed
709     // or old shape does not exist in the document.
710     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
711     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
712       ModelAPI_Session::get()->moduleDocument())->generalLabel();
713     TDF_Label anOriginalLabel;
714     bool anOldSubShapeNotInTree =
715       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
716     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
717       // The second condition is added due to #20170 because sub-shape must be added to real parent
718       // shape, not the reference. The naming name of pure reference is not registered in document.
719       if (theSaveOldIfNotInTree && !aData->shapeLab().IsAttribute(TDF_Reference::GetID())) {
720         std::string aSelectionName = theName + "Selected";
721         generated(anOldSubShape, aSelectionName, false);
722       } else
723         continue;
724     }
725
726     // Get new shapes.
727     ListOfShape aNewShapes;
728     theAlgo->generated(anOldSubShape, aNewShapes);
729
730     keepTopLevelShapes(aNewShapes, anOldSubShape_);
731
732     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
733          aNewShapesIt != aNewShapes.cend();
734          ++aNewShapesIt)
735     {
736       GeomShapePtr aNewShape = *aNewShapesIt;
737       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
738
739       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
740       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
741       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
742         continue;
743       }
744
745       if (aResultShape->isSame(aNewShape))
746         continue; // it is stored on the root level
747
748       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
749       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
750         // TODO: This is a workaround. New shape should be only edge or face.
751         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
752                                                                             : TopAbs_FACE;
753         int aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
754         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
755           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
756           // store information about the external document reference to restore old shape on open
757           storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
758         }
759         buildName(aTag, theName);
760       } else {
761         int aTag = getGenerationTag(aNewShape_);
762         if (aTag == INVALID_TAG) return;
763         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
764         buildName(aTag, theName);
765         // store information about the external document reference to restore old shape on open
766         storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
767       }
768     }
769   }
770 }
771
772 // LCOV_EXCL_START
773 //=======================================================================
774 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
775   const TopAbs_ShapeEnum        theGeneratedFrom,
776   TopTools_DataMapOfShapeShape& theDangles)
777 {
778   theDangles.Clear();
779   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
780   TopAbs_ShapeEnum GeneratedTo;
781   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
782   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
783   else return Standard_False;
784   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
785   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
786     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
787     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
788     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
789   }
790   return theDangles.Extent();
791 }
792
793 //=======================================================================
794 void loadGeneratedDangleShapes(
795   const TopoDS_Shape&      theShapeIn,
796   const TopAbs_ShapeEnum   theGeneratedFrom,
797   TNaming_Builder *        theBuilder)
798 {
799   TopTools_DataMapOfShapeShape dangles;
800   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
801   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
802   for (; itr.More(); itr.Next())
803     theBuilder->Generated(itr.Key(), itr.Value());
804 }
805 // LCOV_EXCL_STOP
806
807 //=======================================================================
808 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
809                                        const std::string& theName)
810 {
811   if(theShape->isNull()) return;
812   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
813   std::string aName;
814   if (aShape.ShapeType() == TopAbs_SOLID) {
815     TopExp_Explorer expl(aShape, TopAbs_FACE);
816     for (; expl.More(); expl.Next()) {
817       builder(myFreePrimitiveTag)->Generated(expl.Current());
818       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
819       aName = theName + "_" + aStr.ToCString();
820       buildName(myFreePrimitiveTag, aName);
821       ++myFreePrimitiveTag;
822     }
823   }
824   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
825     // load faces and all the free edges
826     TopTools_IndexedMapOfShape Faces;
827     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
828     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
829       TopExp_Explorer expl(aShape, TopAbs_FACE);
830       for (; expl.More(); expl.Next()) {
831         builder(myFreePrimitiveTag)->Generated(expl.Current());
832         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
833         aName = theName + "_" + aStr.ToCString();
834         buildName(myFreePrimitiveTag, aName);
835         ++myFreePrimitiveTag;
836       }
837     }
838     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
839     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
840     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
841     {
842       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
843       if (aLL.Extent() < 2) {
844         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
845           continue;
846         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
847         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
848         aName = theName + "_" + aStr.ToCString();
849         buildName(myFreePrimitiveTag, aName);
850         ++myFreePrimitiveTag;
851       } else {
852         TopTools_ListIteratorOfListOfShape anIter(aLL);
853         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
854         anIter.Next();
855         if(aFace.IsEqual(anIter.Value())) {
856           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
857           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
858           aName = theName + "_" + aStr.ToCString();
859           buildName(myFreePrimitiveTag, aName);
860           ++myFreePrimitiveTag;
861         }
862       }
863     }
864   } else if (aShape.ShapeType() == TopAbs_WIRE) {
865     TopTools_IndexedMapOfShape Edges;
866     BRepTools::Map3DEdges(aShape, Edges);
867     if (Edges.Extent() == 1) {
868       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
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;
876       }
877     } else {
878       TopExp_Explorer expl(aShape, TopAbs_EDGE);
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       // and load generated vertices.
887       TopTools_DataMapOfShapeShape generated;
888       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
889       {
890         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
891         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
892       }
893     }
894   } else if (aShape.ShapeType() == TopAbs_EDGE) {
895     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
896     for (; expl.More(); expl.Next()) {
897       builder(myFreePrimitiveTag)->Generated(expl.Current());
898       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
899       aName = theName + "_" + aStr.ToCString();
900       buildName(myFreePrimitiveTag, aName);
901       ++myFreePrimitiveTag;
902     }
903   }
904 }
905
906 //=======================================================================
907 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
908   TopTools_ListOfShape&   theList)
909 {
910   theList.Clear();
911   // edges -> ancestor faces list
912   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
913   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
914   // keeps the shapes which are already in the resulting list
915   TopTools_MapOfShape alreadyThere;
916   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
917   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
918
919   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
920   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
921     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
922     if (ancestors.Extent() < 2)
923       continue;
924     Standard_Integer anID = 0;
925     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
926       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
927     }
928     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
929       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
930         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
931       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
932       for(; aSameEdge.More(); aSameEdge.Next()) {
933         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
934           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
935         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
936           break;
937
938         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
939         for(; aFaceIter1.More(); aFaceIter1.Next()) {
940           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
941           for(; aFaceIter2.More(); aFaceIter2.Next()) {
942             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
943               break;
944           }
945           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
946             break;
947         }
948         if (!aFaceIter1.More()) { // all the faces are same => put to the result
949           if (alreadyThere.Add(aSameEdge.Value()))
950             theList.Append(aSameEdge.Value());
951           if (alreadyThere.Add(anAncestorsIter.Key()))
952             theList.Append(anAncestorsIter.Key());
953         }
954       }
955     } else { // ID is unique, just add this edge
956       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
957     }
958     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
959   }
960   return theList.Extent();
961 }
962
963 //=======================================================================
964 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
965 {
966   GeomShapePtr aShapePtr = shape();
967   if (theShape->isNull() || !aShapePtr.get())
968     return;
969   TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
970   if (aShape.IsNull())
971     return;
972   std::string aName;
973   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
974     TopoDS_Iterator itr(aShape);
975     for (; itr.More(); itr.Next()) {
976       builder(myFreePrimitiveTag)->Generated(itr.Value());
977       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
978       aName = theName + "_" + aStr.ToCString();
979       buildName(myFreePrimitiveTag, aName);
980       ++myFreePrimitiveTag;
981       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
982         itr.Value().ShapeType() == TopAbs_COMPSOLID)
983       {
984         GeomShapePtr itrShape(new GeomAPI_Shape());
985         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
986         loadFirstLevel(itrShape, theName);
987       } else {
988         GeomShapePtr itrShape(new GeomAPI_Shape());
989         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
990         loadNextLevels(itrShape, theName);
991       }
992     }
993   } else {
994     GeomShapePtr itrShape(new GeomAPI_Shape());
995     itrShape->setImpl(new TopoDS_Shape(aShape));
996     loadNextLevels(itrShape, theName);
997   }
998   TopTools_ListOfShape   aList;
999   if(findAmbiguities(aShape, aList)) {
1000     TopTools_ListIteratorOfListOfShape it(aList);
1001     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
1002       builder(myFreePrimitiveTag)->Generated(it.Value());
1003       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
1004       aName = theName + "_" + aStr.ToCString();
1005       buildName(myFreePrimitiveTag, aName);
1006     }
1007   }
1008 }
1009
1010 GeomShapePtr Model_BodyBuilder::shape()
1011 {
1012   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1013   if (aData && aData->isValid()) {
1014     TDF_Label aShapeLab = aData->shapeLab();
1015     Handle(TDF_Reference) aRef;
1016     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1017       aShapeLab = aRef->Get();
1018     }
1019     Handle(TNaming_NamedShape) aName;
1020     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1021       TopoDS_Shape aShape = aName->Get();
1022       if (!aShape.IsNull()) {
1023         GeomShapePtr aRes(new GeomAPI_Shape);
1024         aRes->setImpl(new TopoDS_Shape(aShape));
1025         return aRes;
1026       }
1027     }
1028   }
1029   return GeomShapePtr();
1030 }