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