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