Salome HOME
Fix for the issue #1082
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        Model_ResultBody.cpp
4 // Created:     08 Jul 2014
5 // Author:      Mikhail PONIKAROV
6
7 #include <Model_BodyBuilder.h>
8
9 #include <Model_Data.h>
10 #include <Model_Document.h>
11 #include <ModelAPI_AttributeIntArray.h>
12 #include <TNaming_Builder.hxx>
13 #include <TNaming_NamedShape.hxx>
14 #include <TNaming_Iterator.hxx>
15 #include <TNaming_Tool.hxx>
16 #include <TDataStd_Name.hxx>
17 #include <TDataStd_Integer.hxx>
18 #include <TopoDS.hxx>
19 #include <TopoDS_Face.hxx>
20 #include <TDF_ChildIterator.hxx>
21 #include <TopTools_MapOfShape.hxx>
22 #include <TopExp_Explorer.hxx>
23 #include <TopTools_ListOfShape.hxx>
24 #include <TopTools_ListIteratorOfListOfShape.hxx>
25 #include <TopTools_DataMapOfShapeListOfShape.hxx>
26 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
27 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
28 #include <TopTools_MapIteratorOfMapOfShape.hxx>
29 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
30 #include <TopTools_IndexedMapOfShape.hxx>
31 #include <TopTools_DataMapOfShapeShape.hxx>
32 #include <TopExp.hxx>
33 #include <BRepTools.hxx>
34 #include <BRep_Tool.hxx>
35 #include <GeomAPI_Shape.h>
36 #include <GeomAlgoAPI_MakeShape.h>
37 #include <Config_PropManager.h>
38 // DEB
39 //#include <TCollection_AsciiString.hxx>
40 //#include <TDF_Tool.hxx>
41 //#define DEB_IMPORT 1
42
43 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
44 : ModelAPI_BodyBuilder(theOwner)
45 {
46 }
47
48 // Converts evolution of naming shape to selection evelution and back to avoid
49 // naming support on the disabled results. Deeply in the labels tree, recursively.
50 static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
51   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
52   Handle(TNaming_NamedShape) aName;
53   int anEvolution = -1;
54   if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
55     TNaming_Evolution aNSEvol = aName->Evolution();
56     if ((aNSEvol == TNaming_SELECTED && theFlag) ||
57         (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
58       return;
59     }
60     anEvolution = (int)(aNSEvol);
61     if (!theFlag) {
62       Handle(TDataStd_Integer) anAttrEvol;
63       if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
64         anEvolution = anAttrEvol->Get();
65       }
66     } else {
67       TDataStd_Integer::Set(theLab, anEvolution);
68     }
69
70     for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
71       aShapePairs.push_back(std::pair<TopoDS_Shape, TopoDS_Shape>
72         (anIter.OldShape(), anIter.NewShape()));
73     }
74   }
75   // create new
76   TNaming_Builder aBuilder(theLab);
77   TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
78   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
79   for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
80     if (theFlag) { // disabled => make selection
81       aBuilder.Select(aPairsIter->first, aPairsIter->second);
82     } else if (anEvol == TNaming_GENERATED) {
83       aBuilder.Generated(aPairsIter->first, aPairsIter->second);
84     } else if (anEvol == TNaming_MODIFY) {
85       aBuilder.Modify(aPairsIter->first, aPairsIter->second);
86     } else if (anEvol == TNaming_DELETE) {
87       aBuilder.Delete(aPairsIter->first);
88     } else if (anEvol == TNaming_PRIMITIVE) {
89       aBuilder.Generated(aPairsIter->second);
90     } else if (anEvol == TNaming_SELECTED) {
91       aBuilder.Select(aPairsIter->first, aPairsIter->second);
92     }
93   }
94   // recursive call for all sub-labels
95   TDF_ChildIterator anIter(theLab, Standard_False);
96   for(; anIter.More(); anIter.Next()) {
97     evolutionToSelectionRec(anIter.Value(), theFlag);
98   }
99 }
100
101 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
102 {
103   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
104   if (!aData) // unknown case
105     return;
106   TDF_Label& aShapeLab = aData->shapeLab();
107   evolutionToSelectionRec(aShapeLab, theFlag);
108 }
109
110 void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape)
111 {
112   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
113   if (aData) {
114     TDF_Label& aShapeLab = aData->shapeLab();
115     // clean builders
116     clean();   
117     // store the new shape as primitive
118     TNaming_Builder aBuilder(aShapeLab);
119     if (!theShape)
120       return;  // bad shape
121     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
122     if (aShape.IsNull())
123       return;  // null shape inside
124
125     aBuilder.Generated(aShape); 
126     // register name
127     if(!aBuilder.NamedShape()->IsEmpty()) {
128       Handle(TDataStd_Name) anAttr;
129       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
130         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
131         if(!aName.empty()) {
132           std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
133           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
134         }
135       }
136     }
137   }
138 }
139
140 void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& theFromShape,
141   const std::shared_ptr<GeomAPI_Shape>& theToShape)
142 {
143   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
144   if (aData) {
145     TDF_Label& aShapeLab = aData->shapeLab();
146     // clean builders
147     clean();   
148     // store the new shape as primitive
149     TNaming_Builder aBuilder(aShapeLab);
150     if (!theFromShape || !theToShape)
151       return;  // bad shape
152     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
153     if (aShapeBasis.IsNull())
154       return;  // null shape inside
155     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
156     if (aShapeNew.IsNull())
157       return;  // null shape inside
158     aBuilder.Generated(aShapeBasis, aShapeNew);
159     // register name
160     if(!aBuilder.NamedShape()->IsEmpty()) {
161       Handle(TDataStd_Name) anAttr;
162       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
163         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
164         if(!aName.empty()) {
165           std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
166           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
167         }
168       }
169     }
170   }
171 }
172
173 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
174   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
175 {
176   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
177   if (aData) {
178     TDF_Label& aShapeLab = aData->shapeLab();
179     // clean builders
180     clean();   
181     // store the new shape as primitive
182     TNaming_Builder aBuilder(aShapeLab);
183     if (!theOldShape || !theNewShape)
184       return;  // bad shape
185     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
186     if (aShapeOld.IsNull())
187       return;  // null shape inside
188     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
189     if (aShapeNew.IsNull())
190       return;  // null shape inside
191     aBuilder.Modify(aShapeOld, aShapeNew);
192     if (theDecomposeSolidsTag && aShapeNew.ShapeType() == TopAbs_COMPOUND) { // make sub elements as subs
193
194       // register name if it is possible
195       TCollection_AsciiString aName;
196       if(!aBuilder.NamedShape()->IsEmpty()) {
197         Handle(TDataStd_Name) anAttr;
198         if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
199           aName = TCollection_AsciiString(anAttr->Get()).ToCString();
200         }
201       }
202
203       TopoDS_Iterator aSubIter(aShapeNew);
204       for(int aTag = theDecomposeSolidsTag; aSubIter.More(); aSubIter.Next()) {
205         TNaming_Builder aSubBuilder(aShapeLab.FindChild(aTag++));
206         aSubBuilder.Generated(aSubIter.Value());
207         if(!aName.IsEmpty()) {
208           std::string aSolidName = 
209             (aName + "_Solid_" + TCollection_AsciiString(aTag - theDecomposeSolidsTag)).ToCString(); 
210           std::shared_ptr<Model_Document> aDoc = 
211             std::dynamic_pointer_cast<Model_Document>(document());
212           aDoc->addNamingName(aSubBuilder.NamedShape()->Label(), aSolidName);
213           TDataStd_Name::Set(aSubBuilder.NamedShape()->Label(), aSolidName.c_str());
214         }
215       }
216     }
217   }
218 }
219
220 void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
221 {
222   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
223   if (aData) {
224     clean();   
225     if (!theShape.get())
226       return; // bad shape
227     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
228     if (aShape.IsNull())
229       return;  // null shape inside
230     TNaming_Builder aBuilder(aData->shapeLab());
231     aBuilder.Select(aShape, aShape);
232   }
233 }
234
235 void Model_BodyBuilder::clean()
236 {
237   std::vector<TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
238   for(; aBuilder != myBuilders.end(); aBuilder++)
239     delete *aBuilder;
240   myBuilders.clear();
241 }
242
243 Model_BodyBuilder::~Model_BodyBuilder()
244 {
245   clean();
246 }
247
248 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
249 {
250   if (myBuilders.size() <= (unsigned int)theTag) {
251     myBuilders.insert(myBuilders.end(), theTag - myBuilders.size() + 1, NULL);
252   }
253   if (!myBuilders[theTag]) {
254     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
255     myBuilders[theTag] = new TNaming_Builder(aData->shapeLab().FindChild(theTag));
256     //TCollection_AsciiString entry;//
257     //TDF_Tool::Entry(aData->shapeLab().FindChild(theTag), entry);
258     //cout << "Label = " <<entry.ToCString() <<endl;
259   }
260   return myBuilders[theTag];
261 }
262
263 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
264 {
265   std::string aName = data()->name() + "/" + theName; 
266   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
267   aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), aName);
268   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(),aName.c_str());
269 }
270 void Model_BodyBuilder::generated(
271   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
272 {
273   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
274   builder(theTag)->Generated(aShape);
275   if(!theName.empty()) 
276     buildName(theTag, theName);
277 }
278
279 void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
280   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
281 {
282   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
283   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
284   builder(theTag)->Generated(anOldShape, aNewShape);
285   if(!theName.empty()) 
286     buildName(theTag, theName);
287 }
288
289
290 void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
291   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
292 {
293   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
294   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
295   builder(theTag)->Modify(anOldShape, aNewShape);
296   if(!theName.empty()) 
297     buildName(theTag, theName);
298 }
299
300 void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
301   const int theTag)
302 {
303   TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
304   builder(theTag)->Delete(aShape);
305 }
306
307 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
308   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
309   const int  theKindOfShape,
310   const int  theTag)
311 {
312   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
313   TopTools_MapOfShape aView;
314   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
315   for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
316     const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
317     if (!aView.Add(aRoot)) continue;
318     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
319     aRShape->setImpl((new TopoDS_Shape(aRoot)));
320     if (theMS->isDeleted (aRShape)) {
321       builder(theTag)->Delete(aRoot);
322     }
323   }
324 }
325
326 void Model_BodyBuilder::loadAndOrientModifiedShapes (
327   GeomAlgoAPI_MakeShape* theMS,
328   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
329   const int  theKindOfShape,
330   const int  theTag,
331   const std::string& theName,
332   GeomAPI_DataMapOfShapeShape& theSubShapes)
333 {
334   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
335   TopTools_MapOfShape aView;
336   bool isBuilt = theName.empty();
337   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
338   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
339     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
340     if (!aView.Add(aRoot)) continue;
341     ListOfShape aList;
342     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
343     aRShape->setImpl((new TopoDS_Shape(aRoot)));
344     theMS->modified(aRShape, aList);
345     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = aList.begin(), aLast = aList.end();
346     for (; anIt != aLast; anIt++) {
347       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();     
348       if (theSubShapes.isBound(*anIt)) {
349         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
350         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
351       }
352       if (!aRoot.IsSame (aNewShape)) {
353         builder(theTag)->Modify(aRoot,aNewShape);
354         if(!isBuilt) 
355           buildName(theTag, theName);           
356       }
357     }
358   }
359 }
360
361 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
362   GeomAlgoAPI_MakeShape* theMS,
363   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
364   const int  theKindOfShape,
365   const int  theTag,
366   const std::string& theName,
367   GeomAPI_DataMapOfShapeShape& theSubShapes)
368 {
369   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
370   TopTools_MapOfShape aView;
371   bool isBuilt = theName.empty();
372   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
373   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
374     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
375     if (!aView.Add(aRoot)) continue;
376     ListOfShape aList;
377     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
378     aRShape->setImpl((new TopoDS_Shape(aRoot)));
379     theMS->generated(aRShape, aList);
380     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = aList.begin(), aLast = aList.end();
381     for (; anIt != aLast; anIt++) {
382       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();     
383       if (theSubShapes.isBound(*anIt)) {
384         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
385         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
386       }
387       if (!aRoot.IsSame (aNewShape)) {
388         builder(theTag)->Generated(aRoot,aNewShape);
389         if(!isBuilt) 
390           buildName(theTag, theName);   
391       }
392     }
393   }
394 }
395
396 //=======================================================================
397 int getDangleShapes(const TopoDS_Shape&           theShapeIn, 
398   const TopAbs_ShapeEnum        theGeneratedFrom,
399   TopTools_DataMapOfShapeShape& theDangles) 
400 {
401   theDangles.Clear();
402   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
403   TopAbs_ShapeEnum GeneratedTo;
404   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
405   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
406   else return Standard_False;
407   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
408   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
409     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
410     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
411     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
412   }
413   return theDangles.Extent();
414 }
415
416 //=======================================================================
417 void loadGeneratedDangleShapes(
418   const TopoDS_Shape&      theShapeIn,
419   const TopAbs_ShapeEnum   theGeneratedFrom,
420   TNaming_Builder *        theBuilder)
421 {
422   TopTools_DataMapOfShapeShape dangles;
423   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
424   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
425   for (; itr.More(); itr.Next()) 
426     theBuilder->Generated(itr.Key(), itr.Value());
427 }
428
429 //=======================================================================
430 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape, 
431   const std::string& theName, int&  theTag)
432 {
433   if(theShape->isNull()) return;
434   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();    
435   std::string aName;
436   if (aShape.ShapeType() == TopAbs_SOLID) {                 
437     TopExp_Explorer expl(aShape, TopAbs_FACE);
438     for (; expl.More(); expl.Next()) {  
439       builder(theTag)->Generated(expl.Current()); 
440       TCollection_AsciiString aStr(theTag);
441       aName = theName + aStr.ToCString();
442       buildName(theTag, aName);
443       theTag++;
444     }
445   }
446   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
447     // load faces and all the free edges
448     TopTools_IndexedMapOfShape Faces;
449     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
450     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
451       TopExp_Explorer expl(aShape, TopAbs_FACE);
452       for (; expl.More(); expl.Next()) {
453         builder(theTag)->Generated(expl.Current());          
454         TCollection_AsciiString aStr(theTag);
455         aName = theName + aStr.ToCString();
456         buildName(theTag, aName);
457         theTag++;
458       }
459     }
460     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
461     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
462     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++) 
463     {
464       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
465       if (aLL.Extent() < 2) {
466         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
467           continue;
468         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
469         TCollection_AsciiString aStr(theTag);
470         aName = theName + aStr.ToCString();
471         buildName(theTag, aName);
472         theTag++;
473       } else {
474         TopTools_ListIteratorOfListOfShape anIter(aLL);
475         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
476         anIter.Next();
477         if(aFace.IsEqual(anIter.Value())) {
478           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
479           TCollection_AsciiString aStr(theTag);
480           aName = theName + aStr.ToCString();
481           buildName(theTag, aName);
482           theTag++;
483         }
484       }
485     }
486   } else if (aShape.ShapeType() == TopAbs_WIRE) {
487     TopTools_IndexedMapOfShape Edges;
488     BRepTools::Map3DEdges(aShape, Edges);
489     if (Edges.Extent() == 1) {
490       builder(++theTag)->Generated(Edges.FindKey(1));
491       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
492       for (; expl.More(); expl.Next()) {
493         builder(theTag)->Generated(expl.Current());
494         TCollection_AsciiString aStr(theTag);
495         aName = theName + aStr.ToCString();
496         buildName(theTag, aName);
497         theTag++;
498       }
499     } else {
500       TopExp_Explorer expl(aShape, TopAbs_EDGE); 
501       for (; expl.More(); expl.Next()) {        
502         builder(theTag)->Generated(expl.Current());
503         TCollection_AsciiString aStr(theTag);
504         aName = theName + aStr.ToCString();
505         buildName(theTag, aName);
506         theTag++;
507       }   
508       // and load generated vertices.
509       TopTools_DataMapOfShapeShape generated;
510       if (getDangleShapes(aShape, TopAbs_EDGE, generated)) 
511       {
512         TNaming_Builder* pBuilder = builder(theTag++);
513         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);  
514       }
515     }
516   } else if (aShape.ShapeType() == TopAbs_EDGE) {
517     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
518     for (; expl.More(); expl.Next()) {      
519       builder(theTag)->Generated(expl.Current());
520       TCollection_AsciiString aStr(theTag);
521       aName = theName + aStr.ToCString();
522       buildName(theTag, aName);
523       theTag++;
524     }
525   }
526 }
527
528 //=======================================================================
529 int findAmbiguities(const TopoDS_Shape&           theShapeIn,                                   
530   TopTools_ListOfShape&   theList) 
531 {
532   int aNumEdges(0);
533   theList.Clear();
534   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
535   TopAbs_ShapeEnum aTS(TopAbs_EDGE);
536   TopAbs_ShapeEnum aTA(TopAbs_FACE);
537   TopTools_MapOfShape aMap1, aMap2; // map1 - for edge ancestors; map2 - for keys => edges
538   TopTools_ListOfShape aKeyList;
539   TopExp::MapShapesAndAncestors(theShapeIn, aTS, aTA, subShapeAndAncestors);
540   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
541     const TopoDS_Shape& aKeyEdge1 = subShapeAndAncestors.FindKey(i);
542     const TopTools_ListOfShape& ancestors1 = subShapeAndAncestors.FindFromIndex(i);
543     aMap1.Clear();
544     TopTools_ListIteratorOfListOfShape it(ancestors1);
545     for(;it.More();it.Next()) aMap1.Add(it.Value()); // fill map with key ancestors => aKey1
546     for (Standard_Integer j = 1; j <= subShapeAndAncestors.Extent(); j++) {
547       if (i == j) continue;
548       const TopoDS_Shape& aKeyEdge2 = subShapeAndAncestors.FindKey(j);
549       const TopTools_ListOfShape& ancestors2 = subShapeAndAncestors.FindFromIndex(j);
550       if(ancestors1.Extent() == ancestors2.Extent() && ancestors1.Extent() > 1) {
551         int aNum (ancestors2.Extent());
552         TopTools_ListIteratorOfListOfShape it(ancestors2);
553         for(;it.More();it.Next()) 
554           if(aMap1.Contains(it.Value())) aNum--;
555         if(aNum == 0) {
556           if(aMap2.Add(aKeyEdge1)) 
557             aKeyList.Append(aKeyEdge1);
558           if(aMap2.Add(aKeyEdge2))
559             aKeyList.Append(aKeyEdge2);
560         }
561       }
562     } // at the end ==> List of edges to be named in addition   
563   }
564   aNumEdges = aKeyList.Extent();
565   if(aNumEdges)
566     theList.Assign(aKeyList);   
567   return aNumEdges; 
568 }
569
570 //=======================================================================
571 void Model_BodyBuilder::loadFirstLevel(
572   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
573 {
574   if(theShape->isNull()) return;
575   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>(); 
576   std::string aName;
577   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
578     TopoDS_Iterator itr(aShape);
579     for (; itr.More(); itr.Next(),theTag++) {
580       builder(theTag)->Generated(itr.Value());
581       TCollection_AsciiString aStr(theTag);
582       aName = theName + aStr.ToCString();
583       buildName(theTag, aName);
584       if(!theName.empty()) buildName(theTag, aName);
585       if (itr.Value().ShapeType() == TopAbs_COMPOUND || 
586         itr.Value().ShapeType() == TopAbs_COMPSOLID) 
587       {
588         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
589         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
590         loadFirstLevel(itrShape, theName, theTag);
591       } else {
592         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
593         itrShape->setImpl(new TopoDS_Shape(itr.Value()));               
594         loadNextLevels(itrShape, theName, theTag);
595       }
596     }
597   } else {
598     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
599     itrShape->setImpl(new TopoDS_Shape(aShape));
600     loadNextLevels(itrShape, theName, theTag); 
601   }
602   TopTools_ListOfShape   aList;
603   if(findAmbiguities(aShape, aList)) {
604     TopTools_ListIteratorOfListOfShape it(aList);
605     for (; it.More(); it.Next(),theTag++) {
606       builder(theTag)->Generated(it.Value());
607       TCollection_AsciiString aStr(theTag);
608       aName = theName + aStr.ToCString();
609       buildName(theTag, aName);
610     }
611   }
612 }
613
614 //=======================================================================
615 void Model_BodyBuilder::loadDisconnectedEdges(
616   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
617 {
618   if(theShape->isNull()) return;
619   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();  
620   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
621   TopTools_ListOfShape empty;
622   TopExp_Explorer explF(aShape, TopAbs_FACE);
623   for (; explF.More(); explF.Next()) {
624     const TopoDS_Shape& aFace = explF.Current();
625     TopExp_Explorer explV(aFace, TopAbs_EDGE);
626     for (; explV.More(); explV.Next()) {
627       const TopoDS_Shape& anEdge = explV.Current();
628       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
629       Standard_Boolean faceIsNew = Standard_True;
630       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
631       for (; itrF.More(); itrF.Next()) {
632         if (itrF.Value().IsSame(aFace)) {
633           faceIsNew = Standard_False;
634           break;
635         }
636       }
637       if (faceIsNew) 
638         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);      
639     }
640   }
641
642   /*  TopTools_IndexedDataMapOfShapeListOfShape aDM;
643   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, aDM);
644   for(int i=1; i <= aDM.Extent(); i++) {
645   if(aDM.FindFromIndex(i).Extent() > 1) continue;
646   if (BRep_Tool::Degenerated(TopoDS::Edge(aDM.FindKey(i))))
647   continue;
648   builder(theTag)->Generated(aDM.FindKey(i));
649   TCollection_AsciiString aStr(theTag);
650   std::string aName = theName + aStr.ToCString();
651   buildName(theTag, aName);
652   #ifdef DEB_IMPORT
653   aName +=  + ".brep";
654   BRepTools::Write(aDM.FindKey(i), aName.c_str());
655   #endif
656   theTag++;
657   }
658   */
659   TopTools_MapOfShape anEdgesToDelete;
660   TopExp_Explorer anEx(aShape,TopAbs_EDGE); 
661   std::string aName;
662   for(;anEx.More();anEx.Next()) {
663     Standard_Boolean aC0 = Standard_False;
664     TopoDS_Shape anEdge1 = anEx.Current();
665     if (edgeNaborFaces.IsBound(anEdge1)) {
666       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
667       if (aList1.Extent()<2) continue;
668       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
669       for (; itr.More(); itr.Next()) {
670         TopoDS_Shape anEdge2 = itr.Key();
671         if(anEdgesToDelete.Contains(anEdge2)) continue;
672         if (anEdge1.IsSame(anEdge2)) continue;
673         const TopTools_ListOfShape& aList2 = itr.Value();
674         // compare lists of the neighbour faces of edge1 and edge2
675         if (aList1.Extent() == aList2.Extent()) {
676           Standard_Integer aMatches = 0;
677           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
678             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
679               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
680           if (aMatches == aList1.Extent()) {
681             aC0=Standard_True;
682             builder(theTag)->Generated(anEdge2);
683             anEdgesToDelete.Add(anEdge2);
684             TCollection_AsciiString aStr(theTag);
685             aName = theName + aStr.ToCString();
686             buildName(theTag, aName);
687             theTag++;
688           }
689         }
690       }      
691       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
692       for(;itDelete.More();itDelete.Next()) 
693         edgeNaborFaces.UnBind(itDelete.Key());      
694       edgeNaborFaces.UnBind(anEdge1);
695     }
696     if (aC0) {
697       builder(theTag)->Generated(anEdge1);
698       TCollection_AsciiString aStr(theTag);
699       aName = theName + aStr.ToCString();
700       buildName(theTag, aName);  
701       theTag++;
702     }
703   }  
704 }
705
706 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
707 {
708   if(theShape->isNull()) return;
709   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();  
710   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
711   TopTools_ListOfShape empty;
712   TopExp_Explorer explF(aShape, TopAbs_EDGE);
713   for (; explF.More(); explF.Next()) {
714     const TopoDS_Shape& anEdge = explF.Current();
715     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
716     for (; explV.More(); explV.Next()) {
717       const TopoDS_Shape& aVertex = explV.Current();
718       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
719       Standard_Boolean faceIsNew = Standard_True;
720       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
721       for (; itrF.More(); itrF.Next()) {
722         if (itrF.Value().IsSame(anEdge)) {
723           faceIsNew = Standard_False;
724           break;
725         }
726       }
727       if (faceIsNew) {
728         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
729       }
730     }
731   }
732   std::string aName;
733   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
734   for (; itr.More(); itr.Next()) {
735     const TopTools_ListOfShape& naborEdges = itr.Value();
736     if (naborEdges.Extent() < 2) {              
737       builder(theTag)->Generated(itr.Key());
738       TCollection_AsciiString aStr(theTag);
739       aName = theName + aStr.ToCString();
740       buildName(theTag, aName);  
741       theTag++;
742     }
743   }
744 }
745
746 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
747 {
748   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
749   if (aData) {
750     TDF_Label& aShapeLab = aData->shapeLab();
751     Handle(TNaming_NamedShape) aName;
752     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
753       TopoDS_Shape aShape = aName->Get();
754       if (aShape.IsNull())
755         std::cout<<"Model_BodyBuilder::shape returns empty shape "<<std::endl;
756       else 
757         std::cout<<"Model_BodyBuilder::shape returns shape "<<&(*(aShape.TShape()))<<" with type "
758           <<aShape.ShapeType()<<std::endl;
759       if (!aShape.IsNull()) {
760         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
761         aRes->setImpl(new TopoDS_Shape(aShape));
762         return aRes;
763       }
764     }
765   }
766   return std::shared_ptr<GeomAPI_Shape>();
767 }
768
769 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
770 {
771   if (theShape.get()) {
772     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();  
773     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
774     if (aData) {
775       TDF_Label& aShapeLab = aData->shapeLab();
776       Handle(TNaming_NamedShape) aName;
777       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
778         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
779         if (aLatest.IsEqual(aShape))
780           return true;
781       }
782     }
783   }
784   return false;
785 }