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