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