]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
Issue #2631: SIGSEGV when creating a point on the result of a cut edge by edge
[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 <GeomAlgoAPI_MakeShape.h>
53 #include <GeomAlgoAPI_SortListOfShapes.h>
54 #include <Config_PropManager.h>
55 // DEB
56 //#include <TCollection_AsciiString.hxx>
57 //#include <TDF_Tool.hxx>
58 //#define DEB_IMPORT 1
59
60 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
61 : ModelAPI_BodyBuilder(theOwner),
62   myDividedIndex(1),
63   myVIndex(1),
64   myEIndex(1),
65   myFIndex(1)
66 {
67 }
68
69 // Converts evolution of naming shape to selection evelution and back to avoid
70 // naming support on the disabled results. Deeply in the labels tree, recursively.
71 static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
72   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
73   Handle(TNaming_NamedShape) aName;
74   int anEvolution = -1;
75   if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
76     TNaming_Evolution aNSEvol = aName->Evolution();
77     if ((aNSEvol == TNaming_SELECTED && theFlag) ||
78         (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
79       return;
80     }
81     anEvolution = (int)(aNSEvol);
82     if (!theFlag) {
83       Handle(TDataStd_Integer) anAttrEvol;
84       if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
85         anEvolution = anAttrEvol->Get();
86       }
87     } else {
88       TDataStd_Integer::Set(theLab, anEvolution);
89     }
90
91     for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
92       // iterator goes in reversed order relatively to the Builder, to, make the list reversed
93       aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
94         (anIter.OldShape(), anIter.NewShape()));
95     }
96
97     // create new
98     TNaming_Builder aBuilder(theLab);
99     TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
100     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
101     for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
102       if (theFlag) { // disabled => make selection
103         if (anEvolution == TNaming_DELETE) // issue 2274 : don't put too many same null shapes
104           aBuilder.Select(aPairsIter->first, aPairsIter->first);
105         else if (anEvolution == TNaming_PRIMITIVE)
106           aBuilder.Select(aPairsIter->second, aPairsIter->second);
107         else
108           aBuilder.Select(aPairsIter->second, aPairsIter->first);
109       } else if (anEvol == TNaming_GENERATED) {
110         aBuilder.Generated(aPairsIter->first, aPairsIter->second);
111       } else if (anEvol == TNaming_MODIFY) {
112         aBuilder.Modify(aPairsIter->first, aPairsIter->second);
113       } else if (anEvol == TNaming_DELETE) {
114         aBuilder.Delete(aPairsIter->first);
115       } else if (anEvol == TNaming_PRIMITIVE) {
116         aBuilder.Generated(aPairsIter->second);
117       } else if (anEvol == TNaming_SELECTED) {
118         aBuilder.Select(aPairsIter->second, aPairsIter->first);
119       }
120     }
121   }
122   // recursive call for all sub-labels
123   TDF_ChildIterator anIter(theLab, Standard_False);
124   for(; anIter.More(); anIter.Next()) {
125     evolutionToSelectionRec(anIter.Value(), theFlag);
126   }
127 }
128
129 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
130 {
131   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
132   if (!aData || !aData->isValid()) // unknown case
133     return;
134   TDF_Label& aShapeLab = aData->shapeLab();
135   evolutionToSelectionRec(aShapeLab, theFlag);
136 }
137
138 void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
139                               const bool theIsStoreSameShapes)
140 {
141   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
142   if (aData) {
143     TDF_Label& aShapeLab = aData->shapeLab();
144     // clean builders
145     clean();
146     // store the new shape as primitive
147     TNaming_Builder aBuilder(aShapeLab);
148     if (!theShape)
149       return;  // bad shape
150     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
151     if (aShape.IsNull())
152       return;  // null shape inside
153
154     if(!theIsStoreSameShapes) {
155       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
156       if(!aNS.IsNull() && !aNS->IsEmpty()) {
157         // This shape is already in document, store reference instead of shape;
158         const TDF_Label aFoundLabel = aNS->Label();
159         TDF_Reference::Set(aShapeLab, aFoundLabel);
160         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
161         return;
162       }
163     }
164
165     aBuilder.Generated(aShape);
166     // register name
167     aShapeLab.ForgetAttribute(TDF_Reference::GetID());
168     if(!aBuilder.NamedShape()->IsEmpty()) {
169       Handle(TDataStd_Name) anAttr;
170       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
171         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
172         if(!aName.empty()) {
173           std::shared_ptr<Model_Document> aDoc =
174             std::dynamic_pointer_cast<Model_Document>(document());
175           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
176         }
177       }
178     }
179   }
180 }
181
182 void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& theFromShape,
183   const std::shared_ptr<GeomAPI_Shape>& theToShape)
184 {
185   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
186   if (aData) {
187     TDF_Label& aShapeLab = aData->shapeLab();
188     // clean builders
189     clean();
190     // store the new shape as primitive
191     TNaming_Builder aBuilder(aShapeLab);
192     if (!theFromShape || !theToShape)
193       return;  // bad shape
194     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
195     if (aShapeBasis.IsNull())
196       return;  // null shape inside
197     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
198     if (aShapeNew.IsNull())
199       return;  // null shape inside
200     aBuilder.Generated(aShapeBasis, aShapeNew);
201     // register name
202     if(!aBuilder.NamedShape()->IsEmpty()) {
203       Handle(TDataStd_Name) anAttr;
204       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
205         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
206         if(!aName.empty()) {
207           std::shared_ptr<Model_Document> aDoc =
208             std::dynamic_pointer_cast<Model_Document>(document());
209           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
210         }
211       }
212     }
213   }
214 }
215
216 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
217 {
218   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
219   if (aFind == myBuilders.end()) {
220     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
221     myBuilders[theTag] = new TNaming_Builder(
222       theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
223     aFind = myBuilders.find(theTag);
224   }
225   return aFind->second;
226 }
227
228 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
229   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
230 {
231   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
232   if (aData) {
233     TDF_Label& aShapeLab = aData->shapeLab();
234     // clean builders
235     if (theDecomposeSolidsTag != -2)
236       clean();
237     // store the new shape as primitive
238     TNaming_Builder* aBuilder = builder(0);
239     if (!theOldShape || !theNewShape)
240       return;  // bad shape
241     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
242     if (aShapeOld.IsNull())
243       return;  // null shape inside
244     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
245     if (aShapeNew.IsNull())
246       return;  // null shape inside
247     aBuilder->Modify(aShapeOld, aShapeNew);
248     if(!aBuilder->NamedShape()->IsEmpty()) {
249       Handle(TDataStd_Name) anAttr;
250       if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
251         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
252         if(!aName.empty()) {
253           std::shared_ptr<Model_Document> aDoc =
254             std::dynamic_pointer_cast<Model_Document>(document());
255           aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
256         }
257       }
258     }
259   }
260 }
261
262 void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
263 {
264   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
265   if (aData) {
266     clean();
267     if (!theShape.get())
268       return; // bad shape
269     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
270     if (aShape.IsNull())
271       return;  // null shape inside
272     TNaming_Builder aBuilder(aData->shapeLab());
273     aBuilder.Select(aShape, aShape);
274   }
275 }
276
277 void Model_BodyBuilder::clean()
278 {
279   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
280   if (aLab.IsNull())
281     return;
282   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
283   for(; aBuilder != myBuilders.end(); aBuilder++) {
284     delete aBuilder->second;
285     // clear also shapes on cleaned sub-labels (#2241)
286     Handle(TNaming_NamedShape) aNS;
287     if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
288       aNS->Clear();
289     }
290   }
291   myBuilders.clear();
292   // remove the old reference (if any)
293   aLab.ForgetAttribute(TDF_Reference::GetID());
294   myDividedIndex = 1;
295   myVIndex = 1;
296   myEIndex = 1;
297   myFIndex = 1;
298 }
299
300 Model_BodyBuilder::~Model_BodyBuilder()
301 {
302   clean();
303 }
304
305 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
306 {
307   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
308   //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
309   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.c_str());
310 }
311 void Model_BodyBuilder::generated(
312   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
313 {
314   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
315   builder(theTag)->Generated(aShape);
316   if(!theName.empty())
317     buildName(theTag, theName);
318 }
319
320 void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
321   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
322 {
323   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
324   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
325   builder(theTag)->Generated(anOldShape, aNewShape);
326   if(!theName.empty())
327     buildName(theTag, theName);
328   TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
329   if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
330     TopAbs_ShapeEnum anExplodeShapeType = aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
331     const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
332     int aTag = 1;
333     std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
334     for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
335       TDF_Label aChildLabel = aLabel.FindChild(aTag);
336       TNaming_Builder aBuilder(aChildLabel);
337       aBuilder.Generated(anOldShape, anExp.Current());
338       TCollection_AsciiString aChildName = TCollection_AsciiString((theName + "_").c_str()) + aTag;
339       //aDoc->addNamingName(aChildLabel, aChildName.ToCString());
340       TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
341       aTag++;
342     }
343   }
344 }
345
346
347 void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
348   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
349 {
350   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
351   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
352   builder(theTag)->Modify(anOldShape, aNewShape);
353   if(!theName.empty())
354     buildName(theTag, theName);
355 }
356
357 void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
358   const int theTag)
359 {
360   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
361   builder(theTag)->Delete(aShape);
362 }
363
364 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
365   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
366   const int  theKindOfShape,
367   const int  theTag,
368   const GeomShapePtr theShapes)
369 {
370   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
371   TopTools_MapOfShape aView;
372   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
373   GeomShapePtr aResultShape = shape();
374   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
375     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
376     if (!aView.Add(aRoot)) continue;
377     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
378     aRShape->setImpl((new TopoDS_Shape(aRoot)));
379     if (!theMS->isDeleted(aRShape)
380         || aResultShape->isSubShape(aRShape, false)
381         || (theShapes.get() && theShapes->isSubShape(aRShape, false))) {
382       continue;
383     }
384
385     ListOfShape aHist;
386     if (BRepTools_History::IsSupportedType(aRoot)) // to avoid crash in #2572
387       theMS->modified(aRShape, aHist);
388     if (aHist.size() == 0 || (aHist.size() == 1 && aHist.front()->isSame(aRShape)))
389       builder(theTag)->Delete(aRoot);
390   }
391 }
392
393 static void removeBadShapes(ListOfShape& theShapes)
394 {
395   ListOfShape::iterator anIt = theShapes.begin();
396   while (anIt != theShapes.end()) {
397     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
398     bool aSkip = aNewShape.IsNull()
399       || (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
400     if (aSkip) {
401       ListOfShape::iterator aRemoveIt = anIt++;
402       theShapes.erase(aRemoveIt);
403     } else {
404       ++anIt;
405     }
406   }
407 }
408
409 // Keep only the shapes with minimal shape type
410 static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
411   const GeomShapePtr& theResultShape = GeomShapePtr())
412 {
413   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
414   ListOfShape::iterator anIt = theShapes.begin();
415   while (anIt != theShapes.end()) {
416     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
417     bool aSkip = aNewShape.IsNull() ||
418       (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
419     if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
420         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
421       ListOfShape::iterator aRemoveIt = anIt++;
422       theShapes.erase(aRemoveIt);
423     } else {
424       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
425       if (aType < aKeepShapeType) {
426         // found a shape with lesser shape type => remove all previous shapes
427         aKeepShapeType = aType;
428         theShapes.erase(theShapes.begin(), anIt);
429         ++anIt;
430       } else if (aType > aKeepShapeType) {
431         // shapes with greater shape type should be removed from the list
432         ListOfShape::iterator aRemoveIt = anIt++;
433         theShapes.erase(aRemoveIt);
434       } else
435         ++anIt;
436     }
437   }
438 }
439
440 // returns an ancestor shape-type thaty used for naming-definition of the sub-type
441 TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
442   if (theSubType == TopAbs_VERTEX)
443     return TopAbs_EDGE;
444   if (theSubType == TopAbs_EDGE)
445     return TopAbs_FACE;
446   return TopAbs_VERTEX; // bad case
447 }
448
449 void Model_BodyBuilder::loadAndOrientModifiedShapes (
450   GeomAlgoAPI_MakeShape* theMS,
451   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
452   const int  theKindOfShape,
453   const int  theTag,
454   const std::string& theName,
455   GeomAPI_DataMapOfShapeShape& theSubShapes,
456   const bool theIsStoreSeparate,
457   const bool theIsStoreAsGenerated)
458 {
459   static const int THE_ANCHOR_TAG = 100000;
460
461   int anIndex = 1;
462   int aTag = theTag;
463   bool isBuilt = !theName.empty();
464   std::string aName = theName;
465   std::ostringstream aStream;
466   GeomShapePtr aResultShape = shape();
467   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
468   TopTools_MapOfShape aView;
469   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
470   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
471   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
472     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
473     if (!aView.Add(aRoot)) continue;
474
475     bool aNotInTree =
476       TNaming_Tool::NamedShape(aRoot, aData->shapeLab()).IsNull();
477     if (aNotInTree && !theIsStoreSeparate) {
478       // there is no sense to write history if old shape does not exist in the document
479       continue; // but if it is stored separately, it will be builded as a primitive
480     }
481     ListOfShape aList;
482     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
483     aRShape->setImpl((new TopoDS_Shape(aRoot)));
484     theMS->modified(aRShape, aList);
485     if (!theIsStoreSeparate) {
486       //keepTopLevelShapes(aList, aRoot, aResultShape);
487       removeBadShapes(aList);
488     }
489     // sort the list of images before naming
490     GeomAlgoAPI_SortListOfShapes::sort(aList);
491
492     // to trace situation where several objects are produced by one parent (#2317)
493     int aSameParentShapes = (aShapeIn.ShapeType() == TopAbs_WIRE
494                              || aShapeIn.ShapeType() == TopAbs_SHELL
495                              || aShapeIn.ShapeType() == TopAbs_COMPOUND) ? 0 : -1;
496     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
497       anIt = aList.begin(), aLast = aList.end();
498     for (; anIt != aLast; anIt++) {
499       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
500       if (theSubShapes.isBound(*anIt)) {
501         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
502         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
503       }
504       isBuilt = !theName.empty();
505       if(!aRoot.IsSame(aNewShape)
506          && aResultShape->isSubShape((*anIt), false)
507          && !aResultShape->isSame(*anIt)) // to avoid put of same shape on main label and sub
508       {
509         if (!theIsStoreSeparate) {
510           aSameParentShapes++;
511         } else if (aNotInTree) // check this new shape can not be represented as
512                               // a sub-shape of higher level sub-shapes
513         {
514           TopAbs_ShapeEnum aNewType = aNewShape.ShapeType();
515           TopAbs_ShapeEnum anAncestorType = typeOfAncestor(aNewType);
516           if (anAncestorType != TopAbs_VERTEX) {
517             bool aFound = false;
518             TopoDS_Shape aResultTShape = aResultShape->impl<TopoDS_Shape>();
519             TopExp_Explorer anAncestorExp(aResultTShape, anAncestorType);
520             for(; anAncestorExp.More() && !aFound; anAncestorExp.Next()) {
521               if (aResultTShape.IsSame(anAncestorExp.Current()))
522                 continue;
523               TopExp_Explorer aSubExp(anAncestorExp.Current(), aNewType);
524               for(; aSubExp.More(); aSubExp.Next()) {
525                 if (aNewShape.IsSame(aSubExp.Current())) {
526                   aFound = true;
527                   break;
528                 }
529               }
530             }
531             if (aFound) {
532               continue; // not need to store this shape in the BRep structure
533             }
534           }
535         }
536
537         int aFoundTag = 0;
538         bool isFoundSameOld = false;
539         bool isFoundDiffOld = false;
540
541         // Check if new shape was already stored.
542         for (std::map<int, TNaming_Builder*>::iterator aBuildersIt = myBuilders.begin();
543              aBuildersIt != myBuilders.end();
544              ++aBuildersIt)
545         {
546           TNaming_Builder* aBuilder = aBuildersIt->second;
547           for (TNaming_Iterator aNamingIt(aBuilder->NamedShape());
548                aNamingIt.More();
549                aNamingIt.Next())
550           {
551             if (aNamingIt.NewShape().IsSame(aNewShape))
552             {
553               aNamingIt.OldShape().IsSame(aRoot) ? isFoundSameOld = true
554                                                  : isFoundDiffOld = true;
555               aFoundTag = aBuildersIt->first;
556             }
557           }
558
559           if (isFoundSameOld || isFoundDiffOld) break;
560         }
561
562         if (isFoundSameOld) {
563           // Builder already contains same old->new shapes, don't store it twice.
564           continue;
565         }
566
567         int aBuilderTag = aSameParentShapes > 0 ? THE_ANCHOR_TAG : aTag;
568
569         int aCurShapeType = (int)((*anIt)->shapeType());
570         bool needSuffix = false; // suffix for the name based on the shape type
571         if (aCurShapeType != theKindOfShape) {
572           // modified shape has different type => set another tag
573           // to avoid shapes of different types on the same label
574           aBuilderTag = THE_ANCHOR_TAG;
575           needSuffix = true;
576         }
577         std::string aSuffix;
578         if (needSuffix) {
579           switch (aCurShapeType) {
580             case GeomAPI_Shape::VERTEX: aSuffix = "_v_" + std::to_string(myVIndex++); break;
581             case GeomAPI_Shape::EDGE:   aSuffix = "_e_" + std::to_string(myEIndex++); break;
582             case GeomAPI_Shape::FACE:   aSuffix = "_f_" + std::to_string(myFIndex++); break;
583             default: break;
584           }
585         }
586
587         std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>> aKeepShapes, aMoveShapes;
588         if (isFoundDiffOld) {
589           // Found same new shape with different old shape.
590           if (aFoundTag >= THE_ANCHOR_TAG) {
591             // Found on separated tag.
592             aBuilderTag = aFoundTag; // Store it on the same tag.
593             isBuilt = false; // Don't change name;
594           } else {
595             // Found on previous tag.
596             if (aBuilderTag < THE_ANCHOR_TAG) {
597               // New shape shouls not be separated.
598               aBuilderTag = aFoundTag; // Store it on the same tag.
599               isBuilt = false; // Don't change name;
600             } else {
601               // New shape should be separated from others. Move shapes from found tag to new tag.
602               while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
603                 ++aBuilderTag;
604               }
605
606               TNaming_Builder* aFoundBuilder = myBuilders.at(aFoundTag);
607               Handle(TNaming_NamedShape) aFoundNamedShape = aFoundBuilder->NamedShape();
608               TDF_Label aFoundLabel = aFoundNamedShape->Label();
609               TNaming_Evolution anEvolution = aFoundNamedShape->Evolution();
610               for (TNaming_Iterator aNamingIt(aFoundNamedShape);
611                    aNamingIt.More();
612                    aNamingIt.Next())
613               {
614                 std::pair<TopoDS_Shape, TopoDS_Shape> aShapesPair =
615                   std::make_pair(aNamingIt.OldShape(), aNamingIt.NewShape());
616                 aNamingIt.NewShape().IsSame(aNewShape) ? aMoveShapes.push_back(aShapesPair)
617                                                        : aKeepShapes.push_back(aShapesPair);
618               }
619
620               aFoundNamedShape->Clear();
621               for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aKeepIt =
622                      aKeepShapes.begin();
623                    aKeepIt != aKeepShapes.end();
624                    ++aKeepIt)
625               {
626                 if (anEvolution == TNaming_GENERATED) {
627                   aFoundBuilder->Generated(aKeepIt->first, aKeepIt->second);
628                 } else {
629                   aFoundBuilder->Modify(aKeepIt->first, aKeepIt->second);
630                 }
631               }
632             }
633           }
634         } else if (aBuilderTag == THE_ANCHOR_TAG) {
635           while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
636             ++aBuilderTag;
637           }
638         }
639
640         if(theIsStoreAsGenerated) {
641           // Here we store shapes as generated, to avoid problem when one parent shape produce
642           // several child shapes. In this case naming could not determine which shape to select.
643           builder(aBuilderTag)->Generated(aRoot, aNewShape);
644           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
645                aMoveShapes.begin();
646                aMoveIt != aMoveShapes.end();
647                ++aMoveIt)
648           {
649             builder(aBuilderTag)->Generated(aMoveIt->first, aMoveIt->second);
650           }
651         } else if (aNotInTree) {
652           // not in tree -> store as primitive (stored as separated)
653           builder(aBuilderTag)->Generated(aNewShape);
654         } else if (aCurShapeType != theKindOfShape) {
655            // if different shape type is produced, make it as generated
656           builder(aBuilderTag)->Generated(aRoot, aNewShape);
657         } else {
658           builder(aBuilderTag)->Modify(aRoot, aNewShape);
659           for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
660                aMoveShapes.begin();
661                aMoveIt != aMoveShapes.end();
662                ++aMoveIt) {
663             builder(aBuilderTag)->Modify(aMoveIt->first, aMoveIt->second);
664           }
665         }
666         if(isBuilt) {
667           aStream.str(std::string());
668           aStream.clear();
669           aStream << theName;
670           if (theIsStoreSeparate && !isFoundDiffOld)
671              aStream << "_" << anIndex++;
672
673           if (aSameParentShapes > 0) {
674             aStream.str(std::string());
675             aStream.clear();
676             aStream << aName << "_" << "divided" << "_" << myDividedIndex++;
677           }
678
679           aStream << aSuffix;
680           buildName(aBuilderTag, aStream.str());
681         }
682         if(theIsStoreSeparate && !isFoundDiffOld) {
683           aTag++;
684         }
685       } else if (aResultShape->isSame(*anIt)) {
686         // keep the modification evolution on the root level (2241 - history propagation issue)
687         TNaming_Builder* aBuilder = builder(0);
688         TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
689         Handle(TDF_Reference) aRef;
690         // Store only in case if it does not have reference.
691         if (!aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
692           if (theIsStoreAsGenerated) {
693             TNaming_Builder* aBuilder = builder(0);
694             if (!aBuilder->NamedShape().IsNull() &&
695                 aBuilder->NamedShape()->Evolution() != TNaming_GENERATED) {
696               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
697             }
698             builder(0)->Generated(aRoot, aNewShape);
699           } else {
700             TNaming_Builder* aBuilder = builder(0);
701             if (!aBuilder->NamedShape().IsNull() &&
702               aBuilder->NamedShape()->Evolution() != TNaming_MODIFY) {
703               myBuilders.erase(0); // clear old builder to avoid different evolutions crash
704             }
705             builder(0)->Modify(aRoot, aNewShape);
706           }
707         }
708       }
709     }
710   }
711 }
712
713 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
714   GeomAlgoAPI_MakeShape* theMS,
715   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
716   const int  theKindOfShape,
717   const int  theTag,
718   const std::string& theName,
719   GeomAPI_DataMapOfShapeShape& theSubShapes)
720 {
721   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
722   TopTools_MapOfShape aView;
723   bool isBuilt = !theName.empty();
724   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
725   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
726     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
727     if (!aView.Add(aRoot)) continue;
728     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
729     //  continue; // there is no sense to write history if old shape does not exist in the document
730     ListOfShape aList;
731     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
732     aRShape->setImpl((new TopoDS_Shape(aRoot)));
733     theMS->generated(aRShape, aList);
734     keepTopLevelShapes(aList, aRoot);
735     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
736       anIt = aList.begin(), aLast = aList.end();
737     for (; anIt != aLast; anIt++) {
738       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
739       if (theSubShapes.isBound(*anIt)) {
740         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
741         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
742       }
743       if (!aRoot.IsSame (aNewShape)) {
744         builder(theTag)->Generated(aRoot,aNewShape);
745         if(isBuilt)
746           buildName(theTag, theName);
747       }
748       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
749       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
750         TopAbs_ShapeEnum anExplodeShapeType =
751           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
752         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
753         int aTag = 1;
754         std::shared_ptr<Model_Document> aDoc =
755           std::dynamic_pointer_cast<Model_Document>(document());
756         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
757           TDF_Label aChildLabel = aLabel.FindChild(aTag);
758           TNaming_Builder aBuilder(aChildLabel);
759           aBuilder.Generated(aRoot, anExp.Current());
760           TCollection_AsciiString aChildName =
761             TCollection_AsciiString((theName + "_").c_str()) + aTag;
762           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
763           aTag++;
764         }
765       }
766     }
767   }
768 }
769
770 //=======================================================================
771 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
772   const TopAbs_ShapeEnum        theGeneratedFrom,
773   TopTools_DataMapOfShapeShape& theDangles)
774 {
775   theDangles.Clear();
776   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
777   TopAbs_ShapeEnum GeneratedTo;
778   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
779   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
780   else return Standard_False;
781   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
782   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
783     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
784     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
785     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
786   }
787   return theDangles.Extent();
788 }
789
790 //=======================================================================
791 void loadGeneratedDangleShapes(
792   const TopoDS_Shape&      theShapeIn,
793   const TopAbs_ShapeEnum   theGeneratedFrom,
794   TNaming_Builder *        theBuilder)
795 {
796   TopTools_DataMapOfShapeShape dangles;
797   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
798   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
799   for (; itr.More(); itr.Next())
800     theBuilder->Generated(itr.Key(), itr.Value());
801 }
802
803 //=======================================================================
804 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
805   const std::string& theName, int&  theTag)
806 {
807   if(theShape->isNull()) return;
808   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
809   std::string aName;
810   if (aShape.ShapeType() == TopAbs_SOLID) {
811     TopExp_Explorer expl(aShape, TopAbs_FACE);
812     for (; expl.More(); expl.Next()) {
813       builder(theTag)->Generated(expl.Current());
814       TCollection_AsciiString aStr(theTag);
815       aName = theName + aStr.ToCString();
816       buildName(theTag, aName);
817       theTag++;
818     }
819   }
820   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
821     // load faces and all the free edges
822     TopTools_IndexedMapOfShape Faces;
823     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
824     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
825       TopExp_Explorer expl(aShape, TopAbs_FACE);
826       for (; expl.More(); expl.Next()) {
827         builder(theTag)->Generated(expl.Current());
828         TCollection_AsciiString aStr(theTag);
829         aName = theName + aStr.ToCString();
830         buildName(theTag, aName);
831         theTag++;
832       }
833     }
834     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
835     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
836     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
837     {
838       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
839       if (aLL.Extent() < 2) {
840         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
841           continue;
842         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
843         TCollection_AsciiString aStr(theTag);
844         aName = theName + aStr.ToCString();
845         buildName(theTag, aName);
846         theTag++;
847       } else {
848         TopTools_ListIteratorOfListOfShape anIter(aLL);
849         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
850         anIter.Next();
851         if(aFace.IsEqual(anIter.Value())) {
852           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
853           TCollection_AsciiString aStr(theTag);
854           aName = theName + aStr.ToCString();
855           buildName(theTag, aName);
856           theTag++;
857         }
858       }
859     }
860   } else if (aShape.ShapeType() == TopAbs_WIRE) {
861     TopTools_IndexedMapOfShape Edges;
862     BRepTools::Map3DEdges(aShape, Edges);
863     if (Edges.Extent() == 1) {
864       builder(theTag++)->Generated(Edges.FindKey(1));
865       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
866       for (; expl.More(); expl.Next()) {
867         builder(theTag)->Generated(expl.Current());
868         TCollection_AsciiString aStr(theTag);
869         aName = theName + aStr.ToCString();
870         buildName(theTag, aName);
871         theTag++;
872       }
873     } else {
874       TopExp_Explorer expl(aShape, TopAbs_EDGE);
875       for (; expl.More(); expl.Next()) {
876         builder(theTag)->Generated(expl.Current());
877         TCollection_AsciiString aStr(theTag);
878         aName = theName + aStr.ToCString();
879         buildName(theTag, aName);
880         theTag++;
881       }
882       // and load generated vertices.
883       TopTools_DataMapOfShapeShape generated;
884       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
885       {
886         TNaming_Builder* pBuilder = builder(theTag++);
887         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
888       }
889     }
890   } else if (aShape.ShapeType() == TopAbs_EDGE) {
891     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
892     for (; expl.More(); expl.Next()) {
893       builder(theTag)->Generated(expl.Current());
894       TCollection_AsciiString aStr(theTag);
895       aName = theName + aStr.ToCString();
896       buildName(theTag, aName);
897       theTag++;
898     }
899   }
900 }
901
902 //=======================================================================
903 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
904   TopTools_ListOfShape&   theList)
905 {
906   theList.Clear();
907   // edges -> ancestor faces list
908   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
909   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
910   // keeps the shapes which are already in the resulting list
911   TopTools_MapOfShape alreadyThere;
912   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
913   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
914
915   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
916   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
917     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
918     if (ancestors.Extent() < 2)
919       continue;
920     Standard_Integer anID = 0;
921     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
922       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
923     }
924     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
925       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
926         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
927       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
928       for(; aSameEdge.More(); aSameEdge.Next()) {
929         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
930           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
931         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
932           break;
933
934         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
935         for(; aFaceIter1.More(); aFaceIter1.Next()) {
936           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
937           for(; aFaceIter2.More(); aFaceIter2.Next()) {
938             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
939               break;
940           }
941           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
942             break;
943         }
944         if (!aFaceIter1.More()) { // all the faces are same => put to the result
945           if (alreadyThere.Add(aSameEdge.Value()))
946             theList.Append(aSameEdge.Value());
947           if (alreadyThere.Add(anAncestorsIter.Key()))
948             theList.Append(anAncestorsIter.Key());
949         }
950       }
951     } else { // ID is unique, just add this edge
952       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
953     }
954     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
955   }
956   return theList.Extent();
957 }
958
959 //=======================================================================
960 void Model_BodyBuilder::loadFirstLevel(
961   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
962 {
963   if(theShape->isNull()) return;
964   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
965   std::string aName;
966   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
967     TopoDS_Iterator itr(aShape);
968     for (; itr.More(); itr.Next()) {
969       builder(theTag)->Generated(itr.Value());
970       TCollection_AsciiString aStr(theTag);
971       aName = theName + aStr.ToCString();
972       buildName(theTag, aName);
973       if(!theName.empty()) buildName(theTag, aName);
974       theTag++;
975       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
976         itr.Value().ShapeType() == TopAbs_COMPSOLID)
977       {
978         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
979         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
980         loadFirstLevel(itrShape, theName, theTag);
981       } else {
982         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
983         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
984         loadNextLevels(itrShape, theName, theTag);
985       }
986     }
987   } else {
988     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
989     itrShape->setImpl(new TopoDS_Shape(aShape));
990     loadNextLevels(itrShape, theName, theTag);
991   }
992   TopTools_ListOfShape   aList;
993   if(findAmbiguities(aShape, aList)) {
994     TopTools_ListIteratorOfListOfShape it(aList);
995     for (; it.More(); it.Next(),theTag++) {
996       builder(theTag)->Generated(it.Value());
997       TCollection_AsciiString aStr(theTag);
998       aName = theName + aStr.ToCString();
999       buildName(theTag, aName);
1000     }
1001   }
1002 }
1003
1004 //=======================================================================
1005 void Model_BodyBuilder::loadDisconnectedEdges(
1006   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
1007 {
1008   if(theShape->isNull()) return;
1009   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1010   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
1011   TopTools_ListOfShape empty;
1012   TopExp_Explorer explF(aShape, TopAbs_FACE);
1013   for (; explF.More(); explF.Next()) {
1014     const TopoDS_Shape& aFace = explF.Current();
1015     TopExp_Explorer explV(aFace, TopAbs_EDGE);
1016     for (; explV.More(); explV.Next()) {
1017       const TopoDS_Shape& anEdge = explV.Current();
1018       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
1019       Standard_Boolean faceIsNew = Standard_True;
1020       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
1021       for (; itrF.More(); itrF.Next()) {
1022         if (itrF.Value().IsSame(aFace)) {
1023           faceIsNew = Standard_False;
1024           break;
1025         }
1026       }
1027       if (faceIsNew)
1028         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
1029     }
1030   }
1031
1032   TopTools_MapOfShape anEdgesToDelete;
1033   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
1034   std::string aName;
1035   for(;anEx.More();anEx.Next()) {
1036     Standard_Boolean aC0 = Standard_False;
1037     TopoDS_Shape anEdge1 = anEx.Current();
1038     if (edgeNaborFaces.IsBound(anEdge1)) {
1039       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
1040       if (aList1.Extent()<2) continue;
1041       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
1042       for (; itr.More(); itr.Next()) {
1043         TopoDS_Shape anEdge2 = itr.Key();
1044         if(anEdgesToDelete.Contains(anEdge2)) continue;
1045         if (anEdge1.IsSame(anEdge2)) continue;
1046         const TopTools_ListOfShape& aList2 = itr.Value();
1047         // compare lists of the neighbour faces of edge1 and edge2
1048         if (aList1.Extent() == aList2.Extent()) {
1049           Standard_Integer aMatches = 0;
1050           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
1051             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
1052               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
1053           if (aMatches == aList1.Extent()) {
1054             aC0=Standard_True;
1055             builder(theTag)->Generated(anEdge2);
1056             anEdgesToDelete.Add(anEdge2);
1057             TCollection_AsciiString aStr(theTag);
1058             aName = theName + aStr.ToCString();
1059             buildName(theTag, aName);
1060             theTag++;
1061           }
1062         }
1063       }
1064       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
1065       for(;itDelete.More();itDelete.Next())
1066         edgeNaborFaces.UnBind(itDelete.Key());
1067       edgeNaborFaces.UnBind(anEdge1);
1068     }
1069     if (aC0) {
1070       builder(theTag)->Generated(anEdge1);
1071       TCollection_AsciiString aStr(theTag);
1072       aName = theName + aStr.ToCString();
1073       buildName(theTag, aName);
1074       theTag++;
1075     }
1076   }
1077 }
1078
1079 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
1080                                                  const std::string& theName, int&  theTag)
1081 {
1082   if(theShape->isNull()) return;
1083   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1084   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
1085   TopTools_ListOfShape empty;
1086   TopExp_Explorer explF(aShape, TopAbs_EDGE);
1087   for (; explF.More(); explF.Next()) {
1088     const TopoDS_Shape& anEdge = explF.Current();
1089     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
1090     for (; explV.More(); explV.Next()) {
1091       const TopoDS_Shape& aVertex = explV.Current();
1092       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
1093       Standard_Boolean faceIsNew = Standard_True;
1094       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
1095       for (; itrF.More(); itrF.Next()) {
1096         if (itrF.Value().IsSame(anEdge)) {
1097           faceIsNew = Standard_False;
1098           break;
1099         }
1100       }
1101       if (faceIsNew) {
1102         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
1103       }
1104     }
1105   }
1106   std::string aName;
1107   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
1108   for (; itr.More(); itr.Next()) {
1109     const TopTools_ListOfShape& naborEdges = itr.Value();
1110     if (naborEdges.Extent() < 2) {
1111       builder(theTag)->Generated(itr.Key());
1112       TCollection_AsciiString aStr(theTag);
1113       aName = theName + aStr.ToCString();
1114       buildName(theTag, aName);
1115       theTag++;
1116     }
1117   }
1118 }
1119
1120 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
1121 {
1122   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1123   if (aData && aData->isValid()) {
1124     TDF_Label aShapeLab = aData->shapeLab();
1125     Handle(TDF_Reference) aRef;
1126     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1127       aShapeLab = aRef->Get();
1128     }
1129     Handle(TNaming_NamedShape) aName;
1130     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1131       TopoDS_Shape aShape = aName->Get();
1132       if (!aShape.IsNull()) {
1133         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
1134         aRes->setImpl(new TopoDS_Shape(aShape));
1135         return aRes;
1136       }
1137     }
1138   }
1139   return std::shared_ptr<GeomAPI_Shape>();
1140 }
1141
1142 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
1143 {
1144   if (theShape.get()) {
1145     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
1146     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1147     if (aData) {
1148       TDF_Label& aShapeLab = aData->shapeLab();
1149       Handle(TNaming_NamedShape) aName;
1150       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1151         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
1152         if (aLatest.IsNull())
1153           return false;
1154         if (aLatest.IsEqual(aShape))
1155           return true;
1156         // check sub-shapes for comp-solids:
1157         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
1158           if (aLatest.IsEqual(anExp.Current()))
1159             return true;
1160         }
1161       }
1162     }
1163   }
1164   return false;
1165 }