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