Salome HOME
Fix for #19754: EDF 21721 - Problems with a study
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-2020  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       static 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 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
302 {
303   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
304   if (aFind == myBuilders.end()) {
305     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
306     TDF_Label aLab = theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
307     myBuilders[theTag] = new TNaming_Builder(aLab);
308     aFind = myBuilders.find(theTag);
309   }
310   return aFind->second;
311 }
312
313 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
314                                       const GeomShapePtr& theNewShape,
315                                       const bool theIsCleanStored)
316 {
317   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
318   if (aData) {
319     // clean builders
320     if (theIsCleanStored) clean();
321     TNaming_Builder* aBuilder = builder(0);
322     if (!theOldShape || !theNewShape)
323       return;  // bad shape
324     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
325     if (aShapeOld.IsNull())
326       return;  // null shape inside
327     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
328     if (aShapeNew.IsNull())
329       return;  // null shape inside
330
331     // There is no sense to write history if old shape does not exist in the document.
332     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
333       ModelAPI_Session::get()->moduleDocument())->generalLabel();
334     TDF_Label anOriginalLabel;
335     if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
336       if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
337         aBuilder->Generated(aShapeNew);
338       }
339     } else {
340       if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
341         myBuilders.erase(0);
342         aBuilder = builder(0);
343       }
344
345       aBuilder->Modify(aShapeOld, aShapeNew);
346       // store information about the external document reference to restore old shape on open
347       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
348     }
349
350     if(!aBuilder->NamedShape()->IsEmpty()) {
351       Handle(TDataStd_Name) anAttr;
352       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
353         std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
354         if(!aName.empty()) {
355           std::shared_ptr<Model_Document> aDoc =
356             std::dynamic_pointer_cast<Model_Document>(document());
357           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
358         }
359       }
360     }
361   }
362 }
363
364 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
365   const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
366 {
367   bool aStored = false;
368   std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
369   for(; anOldIter != theOldShapes.cend(); anOldIter++) {
370     // compounds may cause crash if call "modified"
371     bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
372                 (*anOldIter)->isCompSolid();
373     if (!aStore) {
374       ListOfShape aNews; // check this old really modifies theNewShape
375       theMakeShape->modified(*anOldIter, aNews);
376       ListOfShape::iterator aNewIter = aNews.begin();
377       for(; aNewIter != aNews.end(); aNewIter++) {
378         if (theNewShape->isSame(*aNewIter))
379           break;
380       }
381       aStore = aNewIter != aNews.end();
382     }
383     if (aStore) {
384       storeModified(*anOldIter, theNewShape, !aStored);
385       TNaming_Builder* aBuilder = builder(0);
386       aStored = !aBuilder->NamedShape()->IsEmpty();
387     }
388   }
389   if (!aStored) {
390     // check the new shape is already in the tree, so, no need to store primitive, just reference
391     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
392     if (aData.get()) {
393       TDF_Label aShapeLab = aData->shapeLab();
394       TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
395       Handle(TNaming_NamedShape) aNS;
396       if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
397         aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
398       // the last condition is for the issue 2751 : existing shape may be found in compound-NS
399       if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
400         // This shape is already in document, store reference instead of shape;
401         const TDF_Label aFoundLabel = aNS->Label();
402         TDF_Reference::Set(aShapeLab, aFoundLabel);
403         myBuilders.erase(0);
404         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
405         return;
406       }
407     }
408     store(theNewShape); // store as PRIMITIVE, but clean in any way
409     return;
410   }
411 }
412
413 void Model_BodyBuilder::clean()
414 {
415   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
416   if (aLab.IsNull())
417     return;
418   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
419   for(; aBuilder != myBuilders.end(); aBuilder++) {
420     Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
421     delete aBuilder->second;
422     if (!aNS.IsNull() && !aNS->Label().IsNull())
423       aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
424   }
425   myBuilders.clear();
426   myPrimitivesNamesIndexMap.clear();
427   // remove the old reference (if any)
428   aLab.ForgetAttribute(TDF_Reference::GetID());
429   myFreePrimitiveTag = PRIMITIVES_START_TAG;
430   TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
431   for(; anEntriesIter.More(); anEntriesIter.Next()) {
432     anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
433   }
434   // to clear old shapes in all sub-labels (they may be left without builders on Open)
435   TDF_ChildIDIterator aNSIter(aLab, TNaming_NamedShape::GetID(), true);
436   for(; aNSIter.More(); aNSIter.Next()) {
437     aNSIter.Value()->Label().ForgetAttribute(aNSIter.Value());
438   }
439 }
440
441 void Model_BodyBuilder::cleanCash()
442 {
443   myPrimitivesNamesIndexMap.clear();
444 }
445
446 Model_BodyBuilder::~Model_BodyBuilder()
447 {
448   clean();
449 }
450
451 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
452 {
453   std::string aName = theName;
454   std::string aPrefix = "";
455   switch (theTag) {
456     case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
457     case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
458     case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
459     case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
460     case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
461     case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
462   }
463   aName.insert(0, aPrefix);
464
465   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
466 }
467 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
468                                   const std::string& theName,
469                                   const bool theCheckIsInResult)
470 {
471   GeomShapePtr aResultShape = shape();
472   if (theCheckIsInResult) {
473     bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
474     if (aNewShapeIsNotInResultShape) {
475       return false;
476     }
477   }
478
479   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
480   builder(myFreePrimitiveTag)->Generated(aShape);
481   if (!theName.empty()) {
482     std::string aName = theName;
483     if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
484       IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
485       aName += "_" + std::to_string(++(anIndexTags.index));
486       anIndexTags.tags.push_back(myFreePrimitiveTag);
487       if (anIndexTags.index == 2) {
488         buildName(anIndexTags.tags.front(), theName + "_1");
489       }
490     }
491     else {
492       IndexTags anIndexTags;
493       anIndexTags.index = 1;
494       anIndexTags.tags.push_back(myFreePrimitiveTag);
495       myPrimitivesNamesIndexMap[theName] = anIndexTags;
496     }
497
498     buildName(myFreePrimitiveTag, aName);
499   }
500   ++myFreePrimitiveTag;
501   return true;
502 }
503
504 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
505                                   const GeomShapePtr& theNewShape,
506                                   const std::string& theName)
507 {
508   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
509   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
510   TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
511   int aTag;
512   if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
513     // TODO: This is a workaround. New shape should be only vertex, edge or face.
514     TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
515     aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
516     for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
517       builder(aTag)->Generated(anOldShape, anExp.Current());
518     }
519     buildName(aTag, theName);
520   } else {
521     aTag = getGenerationTag(aNewShape);
522     if (aTag == INVALID_TAG) return;
523     builder(aTag)->Generated(anOldShape, aNewShape);
524     buildName(aTag, theName);
525   }
526 }
527
528 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
529                                  const GeomShapePtr& theNewShape,
530                                  const std::string& theName)
531 {
532   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
533   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
534   int aTag = getModificationTag(aNewShape);
535   if (aTag == INVALID_TAG) return;
536   builder(aTag)->Modify(anOldShape, aNewShape);
537   buildName(aTag, theName);
538 }
539
540 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
541                                           const GeomShapePtr& theOldShape,
542                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
543                                           const GeomShapePtr& theShapesToExclude)
544 {
545   TopTools_MapOfShape anAlreadyProcessedShapes;
546   GeomShapePtr aResultShape = shape();
547   for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
548        anExp.more();
549        anExp.next())
550   {
551     GeomShapePtr anOldSubShape = anExp.current();
552     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
553     if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
554         || !theAlgo->isDeleted(anOldSubShape)
555         || aResultShape->isSubShape(anOldSubShape, false)
556         || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
557     {
558       continue;
559     }
560
561     ListOfShape aNewShapes;
562     if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
563       theAlgo->modified(anOldSubShape, aNewShapes);
564     }
565
566     if (aNewShapes.size() == 0
567         || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
568       builder(DELETED_TAG)->Delete(anOldSubShape_);
569     }
570   }
571 }
572
573 // Keep only the shapes with minimal shape type
574 static void keepTopLevelShapes(ListOfShape& theShapes,
575                                const TopoDS_Shape& theRoot,
576                                const GeomShapePtr& theResultShape = GeomShapePtr())
577 {
578   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
579   ListOfShape::iterator anIt = theShapes.begin();
580   while (anIt != theShapes.end()) {
581     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
582     bool aSkip = aNewShape.IsNull() ||
583       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
584     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
585         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
586       ListOfShape::iterator aRemoveIt = anIt++;
587       theShapes.erase(aRemoveIt);
588     } else {
589       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
590       if (aType < aKeepShapeType) {
591         // found a shape with lesser shape type => remove all previous shapes
592         aKeepShapeType = aType;
593         theShapes.erase(theShapes.begin(), anIt);
594         ++anIt;
595       } else if (aType > aKeepShapeType) {
596         // shapes with greater shape type should be removed from the list
597         ListOfShape::iterator aRemoveIt = anIt++;
598         theShapes.erase(aRemoveIt);
599       } else
600         ++anIt;
601     }
602   }
603 }
604
605 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
606                                            const GeomShapePtr& theOldShape,
607                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
608                                            const std::string& theName)
609 {
610   GeomShapePtr aResultShape = shape();
611   GeomShapePtr aShapeToExplore = theOldShape;
612   if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
613     // use optimized set of old shapes for this
614     GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
615                                                       aResultShape,
616                                                       theShapeTypeToExplore);
617     if (aCompound.get()) aShapeToExplore = aCompound;
618   }
619
620   TopTools_MapOfShape anAlreadyProcessedShapes;
621   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
622   for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
623        anOldShapeExp.more();
624        anOldShapeExp.next())
625   {
626     GeomShapePtr anOldSubShape = anOldShapeExp.current();
627     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
628
629     // There is no sense to write history if shape already processed
630     // or old shape does not exist in the document.
631     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
632     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
633       ModelAPI_Session::get()->moduleDocument())->generalLabel();
634     TDF_Label anOriginalLabel;
635     bool anOldSubShapeNotInTree =
636       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
637     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
638       continue;
639     }
640
641     // Get new shapes.
642     ListOfShape aNewShapes;
643     theAlgo->modified(anOldSubShape, aNewShapes);
644
645     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
646          aNewShapesIt != aNewShapes.cend();
647          ++aNewShapesIt)
648     {
649       GeomShapePtr aNewShape = *aNewShapesIt;
650       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
651       bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
652
653       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
654       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
655       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
656         continue;
657
658       if (aResultShape->isSame(aNewShape))
659         continue; // it is stored on the root level (2241 - history propagation issue)
660
661       int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
662       TNaming_Builder*aBuilder = builder(aTag);
663       if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
664         continue; // new shape was already stored.
665
666       buildName(aTag, theName);
667       isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
668                   : aBuilder->Modify(anOldSubShape_, aNewShape_);
669       // store information about the external document reference to restore old shape on open
670       storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
671     }
672   }
673 }
674
675 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
676                                             const GeomShapePtr& theOldShape,
677                                             const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
678                                             const std::string& theName,
679                                             const bool theSaveOldIfNotInTree)
680 {
681   GeomShapePtr aResultShape = shape();
682   TopTools_MapOfShape anAlreadyProcessedShapes;
683   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
684   for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
685        anOldShapeExp.more();
686        anOldShapeExp.next())
687   {
688     GeomShapePtr anOldSubShape = anOldShapeExp.current();
689     const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
690
691     // There is no sense to write history if shape already processed
692     // or old shape does not exist in the document.
693     bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
694     TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
695       ModelAPI_Session::get()->moduleDocument())->generalLabel();
696     TDF_Label anOriginalLabel;
697     bool anOldSubShapeNotInTree =
698       !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
699     if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
700       if (theSaveOldIfNotInTree) {
701         std::string aSelectionName = theName + "Selected";
702         generated(anOldSubShape, aSelectionName, false);
703       } else
704         continue;
705     }
706
707     // Get new shapes.
708     ListOfShape aNewShapes;
709     theAlgo->generated(anOldSubShape, aNewShapes);
710
711     keepTopLevelShapes(aNewShapes, anOldSubShape_);
712
713     for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
714          aNewShapesIt != aNewShapes.cend();
715          ++aNewShapesIt)
716     {
717       GeomShapePtr aNewShape = *aNewShapesIt;
718       const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
719
720       bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
721       bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
722       if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
723         continue;
724       }
725
726       if (aResultShape->isSame(aNewShape))
727         continue; // it is stored on the root level
728
729       TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
730       if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
731         // TODO: This is a workaround. New shape should be only edge or face.
732         TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
733                                                                             : TopAbs_FACE;
734         int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
735         for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
736           builder(aTag)->Generated(anOldSubShape_, anExp.Current());
737           // store information about the external document reference to restore old shape on open
738           storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
739         }
740         buildName(aTag, theName);
741       } else {
742         int aTag = getGenerationTag(aNewShape_);
743         if (aTag == INVALID_TAG) return;
744         builder(aTag)->Generated(anOldSubShape_, aNewShape_);
745         buildName(aTag, theName);
746         // store information about the external document reference to restore old shape on open
747         storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
748       }
749     }
750   }
751 }
752
753 // LCOV_EXCL_START
754 //=======================================================================
755 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
756   const TopAbs_ShapeEnum        theGeneratedFrom,
757   TopTools_DataMapOfShapeShape& theDangles)
758 {
759   theDangles.Clear();
760   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
761   TopAbs_ShapeEnum GeneratedTo;
762   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
763   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
764   else return Standard_False;
765   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
766   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
767     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
768     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
769     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
770   }
771   return theDangles.Extent();
772 }
773
774 //=======================================================================
775 void loadGeneratedDangleShapes(
776   const TopoDS_Shape&      theShapeIn,
777   const TopAbs_ShapeEnum   theGeneratedFrom,
778   TNaming_Builder *        theBuilder)
779 {
780   TopTools_DataMapOfShapeShape dangles;
781   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
782   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
783   for (; itr.More(); itr.Next())
784     theBuilder->Generated(itr.Key(), itr.Value());
785 }
786 // LCOV_EXCL_STOP
787
788 //=======================================================================
789 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
790                                        const std::string& theName)
791 {
792   if(theShape->isNull()) return;
793   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
794   std::string aName;
795   if (aShape.ShapeType() == TopAbs_SOLID) {
796     TopExp_Explorer expl(aShape, TopAbs_FACE);
797     for (; expl.More(); expl.Next()) {
798       builder(myFreePrimitiveTag)->Generated(expl.Current());
799       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
800       aName = theName + "_" + aStr.ToCString();
801       buildName(myFreePrimitiveTag, aName);
802       ++myFreePrimitiveTag;
803     }
804   }
805   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
806     // load faces and all the free edges
807     TopTools_IndexedMapOfShape Faces;
808     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
809     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
810       TopExp_Explorer expl(aShape, TopAbs_FACE);
811       for (; expl.More(); expl.Next()) {
812         builder(myFreePrimitiveTag)->Generated(expl.Current());
813         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
814         aName = theName + "_" + aStr.ToCString();
815         buildName(myFreePrimitiveTag, aName);
816         ++myFreePrimitiveTag;
817       }
818     }
819     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
820     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
821     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
822     {
823       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
824       if (aLL.Extent() < 2) {
825         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
826           continue;
827         builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
828         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
829         aName = theName + "_" + aStr.ToCString();
830         buildName(myFreePrimitiveTag, aName);
831         ++myFreePrimitiveTag;
832       } else {
833         TopTools_ListIteratorOfListOfShape anIter(aLL);
834         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
835         anIter.Next();
836         if(aFace.IsEqual(anIter.Value())) {
837           builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
838           TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
839           aName = theName + "_" + aStr.ToCString();
840           buildName(myFreePrimitiveTag, aName);
841           ++myFreePrimitiveTag;
842         }
843       }
844     }
845   } else if (aShape.ShapeType() == TopAbs_WIRE) {
846     TopTools_IndexedMapOfShape Edges;
847     BRepTools::Map3DEdges(aShape, Edges);
848     if (Edges.Extent() == 1) {
849       builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
850       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
851       for (; expl.More(); expl.Next()) {
852         builder(myFreePrimitiveTag)->Generated(expl.Current());
853         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
854         aName = theName + "_" + aStr.ToCString();
855         buildName(myFreePrimitiveTag, aName);
856         ++myFreePrimitiveTag;
857       }
858     } else {
859       TopExp_Explorer expl(aShape, TopAbs_EDGE);
860       for (; expl.More(); expl.Next()) {
861         builder(myFreePrimitiveTag)->Generated(expl.Current());
862         TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
863         aName = theName + "_" + aStr.ToCString();
864         buildName(myFreePrimitiveTag, aName);
865         ++myFreePrimitiveTag;
866       }
867       // and load generated vertices.
868       TopTools_DataMapOfShapeShape generated;
869       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
870       {
871         TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
872         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
873       }
874     }
875   } else if (aShape.ShapeType() == TopAbs_EDGE) {
876     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
877     for (; expl.More(); expl.Next()) {
878       builder(myFreePrimitiveTag)->Generated(expl.Current());
879       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
880       aName = theName + "_" + aStr.ToCString();
881       buildName(myFreePrimitiveTag, aName);
882       ++myFreePrimitiveTag;
883     }
884   }
885 }
886
887 //=======================================================================
888 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
889   TopTools_ListOfShape&   theList)
890 {
891   theList.Clear();
892   // edges -> ancestor faces list
893   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
894   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
895   // keeps the shapes which are already in the resulting list
896   TopTools_MapOfShape alreadyThere;
897   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
898   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
899
900   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
901   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
902     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
903     if (ancestors.Extent() < 2)
904       continue;
905     Standard_Integer anID = 0;
906     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
907       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
908     }
909     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
910       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
911         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
912       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
913       for(; aSameEdge.More(); aSameEdge.Next()) {
914         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
915           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
916         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
917           break;
918
919         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
920         for(; aFaceIter1.More(); aFaceIter1.Next()) {
921           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
922           for(; aFaceIter2.More(); aFaceIter2.Next()) {
923             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
924               break;
925           }
926           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
927             break;
928         }
929         if (!aFaceIter1.More()) { // all the faces are same => put to the result
930           if (alreadyThere.Add(aSameEdge.Value()))
931             theList.Append(aSameEdge.Value());
932           if (alreadyThere.Add(anAncestorsIter.Key()))
933             theList.Append(anAncestorsIter.Key());
934         }
935       }
936     } else { // ID is unique, just add this edge
937       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
938     }
939     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
940   }
941   return theList.Extent();
942 }
943
944 //=======================================================================
945 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
946 {
947   GeomShapePtr aShapePtr = shape();
948   if (theShape->isNull() || !aShapePtr.get())
949     return;
950   TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
951   if (aShape.IsNull())
952     return;
953   std::string aName;
954   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
955     TopoDS_Iterator itr(aShape);
956     for (; itr.More(); itr.Next()) {
957       builder(myFreePrimitiveTag)->Generated(itr.Value());
958       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
959       aName = theName + "_" + aStr.ToCString();
960       buildName(myFreePrimitiveTag, aName);
961       ++myFreePrimitiveTag;
962       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
963         itr.Value().ShapeType() == TopAbs_COMPSOLID)
964       {
965         GeomShapePtr itrShape(new GeomAPI_Shape());
966         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
967         loadFirstLevel(itrShape, theName);
968       } else {
969         GeomShapePtr itrShape(new GeomAPI_Shape());
970         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
971         loadNextLevels(itrShape, theName);
972       }
973     }
974   } else {
975     GeomShapePtr itrShape(new GeomAPI_Shape());
976     itrShape->setImpl(new TopoDS_Shape(aShape));
977     loadNextLevels(itrShape, theName);
978   }
979   TopTools_ListOfShape   aList;
980   if(findAmbiguities(aShape, aList)) {
981     TopTools_ListIteratorOfListOfShape it(aList);
982     for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
983       builder(myFreePrimitiveTag)->Generated(it.Value());
984       TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
985       aName = theName + "_" + aStr.ToCString();
986       buildName(myFreePrimitiveTag, aName);
987     }
988   }
989 }
990
991 GeomShapePtr Model_BodyBuilder::shape()
992 {
993   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
994   if (aData && aData->isValid()) {
995     TDF_Label aShapeLab = aData->shapeLab();
996     Handle(TDF_Reference) aRef;
997     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
998       aShapeLab = aRef->Get();
999     }
1000     Handle(TNaming_NamedShape) aName;
1001     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1002       TopoDS_Shape aShape = aName->Get();
1003       if (!aShape.IsNull()) {
1004         GeomShapePtr aRes(new GeomAPI_Shape);
1005         aRes->setImpl(new TopoDS_Shape(aShape));
1006         return aRes;
1007       }
1008     }
1009   }
1010   return GeomShapePtr();
1011 }