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