Salome HOME
39fbea9b63c86f22653ac4c03ae89021e1ab1416
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include <Model_BodyBuilder.h>
22
23 #include <Model_Data.h>
24 #include <Model_Document.h>
25 #include <TNaming_Builder.hxx>
26 #include <TNaming_NamedShape.hxx>
27 #include <TNaming_Iterator.hxx>
28 #include <TNaming_Tool.hxx>
29 #include <TDataStd_Name.hxx>
30 #include <TDataStd_Integer.hxx>
31 #include <TopoDS.hxx>
32 #include <TopoDS_Face.hxx>
33 #include <TDF_ChildIterator.hxx>
34 #include <TDF_ChildIDIterator.hxx>
35 #include <TDF_Reference.hxx>
36 #include <TopTools_MapOfShape.hxx>
37 #include <TopExp_Explorer.hxx>
38 #include <TopTools_ListOfShape.hxx>
39 #include <TopTools_ListIteratorOfListOfShape.hxx>
40 #include <TopTools_DataMapOfShapeListOfShape.hxx>
41 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
42 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
43 #include <TopTools_MapIteratorOfMapOfShape.hxx>
44 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
45 #include <TopTools_IndexedMapOfShape.hxx>
46 #include <TopTools_DataMapOfShapeShape.hxx>
47 #include <TopExp.hxx>
48 #include <BRepTools.hxx>
49 #include <BRep_Tool.hxx>
50 #include <GeomAPI_Shape.h>
51 #include <GeomAlgoAPI_MakeShape.h>
52 #include <Config_PropManager.h>
53 // DEB
54 //#include <TCollection_AsciiString.hxx>
55 //#include <TDF_Tool.hxx>
56 //#define DEB_IMPORT 1
57
58 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
59 : ModelAPI_BodyBuilder(theOwner)
60 {
61 }
62
63 // Converts evolution of naming shape to selection evelution and back to avoid
64 // naming support on the disabled results. Deeply in the labels tree, recursively.
65 static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
66   std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
67   Handle(TNaming_NamedShape) aName;
68   int anEvolution = -1;
69   if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
70     TNaming_Evolution aNSEvol = aName->Evolution();
71     if ((aNSEvol == TNaming_SELECTED && theFlag) ||
72         (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
73       return;
74     }
75     anEvolution = (int)(aNSEvol);
76     if (!theFlag) {
77       Handle(TDataStd_Integer) anAttrEvol;
78       if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
79         anEvolution = anAttrEvol->Get();
80       }
81     } else {
82       TDataStd_Integer::Set(theLab, anEvolution);
83     }
84
85     for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
86       // iterator goes in reversed order relatively to the Builder, to, make the list reversed
87       aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
88         (anIter.OldShape(), anIter.NewShape()));
89     }
90
91     // create new
92     TNaming_Builder aBuilder(theLab);
93     TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
94     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
95     for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
96       if (theFlag) { // disabled => make selection
97         aBuilder.Select(aPairsIter->second, aPairsIter->first);
98       } else if (anEvol == TNaming_GENERATED) {
99         aBuilder.Generated(aPairsIter->first, aPairsIter->second);
100       } else if (anEvol == TNaming_MODIFY) {
101         aBuilder.Modify(aPairsIter->first, aPairsIter->second);
102       } else if (anEvol == TNaming_DELETE) {
103         aBuilder.Delete(aPairsIter->first);
104       } else if (anEvol == TNaming_PRIMITIVE) {
105         aBuilder.Generated(aPairsIter->second);
106       } else if (anEvol == TNaming_SELECTED) {
107         aBuilder.Select(aPairsIter->second, aPairsIter->first);
108       }
109     }
110   }
111   // recursive call for all sub-labels
112   TDF_ChildIterator anIter(theLab, Standard_False);
113   for(; anIter.More(); anIter.Next()) {
114     evolutionToSelectionRec(anIter.Value(), theFlag);
115   }
116 }
117
118 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
119 {
120   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
121   if (!aData) // unknown case
122     return;
123   TDF_Label& aShapeLab = aData->shapeLab();
124   evolutionToSelectionRec(aShapeLab, theFlag);
125 }
126
127 void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
128                               const bool theIsStoreSameShapes)
129 {
130   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
131   if (aData) {
132     TDF_Label& aShapeLab = aData->shapeLab();
133     // clean builders
134     clean();
135     // store the new shape as primitive
136     TNaming_Builder aBuilder(aShapeLab);
137     if (!theShape)
138       return;  // bad shape
139     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
140     if (aShape.IsNull())
141       return;  // null shape inside
142
143     if(!theIsStoreSameShapes) {
144       Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
145       if(!aNS.IsNull() && !aNS->IsEmpty()) {
146         // This shape is already in document, store reference instead of shape;
147         const TDF_Label aFoundLabel = aNS->Label();
148         TDF_Reference::Set(aShapeLab, aFoundLabel);
149         aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
150         return;
151       }
152     }
153
154     aBuilder.Generated(aShape);
155     // register name
156     aShapeLab.ForgetAttribute(TDF_Reference::GetID());
157     if(!aBuilder.NamedShape()->IsEmpty()) {
158       Handle(TDataStd_Name) anAttr;
159       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
160         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
161         if(!aName.empty()) {
162           std::shared_ptr<Model_Document> aDoc =
163             std::dynamic_pointer_cast<Model_Document>(document());
164           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
165         }
166       }
167     }
168   }
169 }
170
171 void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& theFromShape,
172   const std::shared_ptr<GeomAPI_Shape>& theToShape)
173 {
174   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
175   if (aData) {
176     TDF_Label& aShapeLab = aData->shapeLab();
177     // clean builders
178     clean();
179     // store the new shape as primitive
180     TNaming_Builder aBuilder(aShapeLab);
181     if (!theFromShape || !theToShape)
182       return;  // bad shape
183     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
184     if (aShapeBasis.IsNull())
185       return;  // null shape inside
186     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
187     if (aShapeNew.IsNull())
188       return;  // null shape inside
189     aBuilder.Generated(aShapeBasis, aShapeNew);
190     // register name
191     if(!aBuilder.NamedShape()->IsEmpty()) {
192       Handle(TDataStd_Name) anAttr;
193       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
194         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
195         if(!aName.empty()) {
196           std::shared_ptr<Model_Document> aDoc =
197             std::dynamic_pointer_cast<Model_Document>(document());
198           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
199         }
200       }
201     }
202   }
203 }
204
205 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
206   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
207 {
208   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
209   if (aData) {
210     TDF_Label& aShapeLab = aData->shapeLab();
211     // clean builders
212     clean();
213     // store the new shape as primitive
214     TNaming_Builder aBuilder(aShapeLab);
215     if (!theOldShape || !theNewShape)
216       return;  // bad shape
217     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
218     if (aShapeOld.IsNull())
219       return;  // null shape inside
220     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
221     if (aShapeNew.IsNull())
222       return;  // null shape inside
223     aBuilder.Modify(aShapeOld, aShapeNew);
224     if(!aBuilder.NamedShape()->IsEmpty()) {
225       Handle(TDataStd_Name) anAttr;
226       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
227         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
228         if(!aName.empty()) {
229           std::shared_ptr<Model_Document> aDoc =
230             std::dynamic_pointer_cast<Model_Document>(document());
231           aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
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   TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
256   if (aLab.IsNull())
257     return;
258   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
259   for(; aBuilder != myBuilders.end(); aBuilder++) {
260     delete aBuilder->second;
261     // clear also shapes on cleaned sub-labels (#2241)
262     Handle(TNaming_NamedShape) aNS;
263     if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
264       aNS->Clear();
265     }
266   }
267   myBuilders.clear();
268 }
269
270 Model_BodyBuilder::~Model_BodyBuilder()
271 {
272   clean();
273 }
274
275 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
276 {
277   std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
278   if (aFind == myBuilders.end()) {
279     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
280     myBuilders[theTag] = new TNaming_Builder(aData->shapeLab().FindChild(theTag));
281     aFind = myBuilders.find(theTag);
282   }
283   return aFind->second;
284 }
285
286 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
287 {
288   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
289   //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
290   TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.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((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   const bool theIsStoreAsGenerated)
373 {
374   int anIndex = 1;
375   int aTag = theTag;
376   bool isBuilt = !theName.empty();
377   std::string aName = theName;
378   std::ostringstream aStream;
379   GeomShapePtr aResultShape = shape();
380   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
381   TopTools_MapOfShape aView;
382   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
383   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
384     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
385     if (!aView.Add(aRoot)) continue;
386     if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
387       continue; // there is no sence to write history is old shape does not persented in document
388     ListOfShape aList;
389     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
390     aRShape->setImpl((new TopoDS_Shape(aRoot)));
391     theMS->modified(aRShape, aList);
392     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
393       anIt = aList.begin(), aLast = aList.end();
394     for (; anIt != aLast; anIt++) {
395       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
396       if (theSubShapes.isBound(*anIt)) {
397         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
398         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
399       }
400       GeomShapePtr aGeomNewShape(new GeomAPI_Shape());
401       aGeomNewShape->setImpl(new TopoDS_Shape(aNewShape));
402       if(!aRoot.IsSame(aNewShape) && aResultShape->isSubShape(aGeomNewShape)) {
403         if(theIsStoreAsGenerated) {
404           // Here we store shapes as generated, to avoid problem when one parent shape produce
405           // several child shapes. In this case naming could not determine which shape to select.
406           builder(aTag)->Generated(aRoot,aNewShape);
407         } else {
408           builder(aTag)->Modify(aRoot,aNewShape);
409         }
410         if(isBuilt) {
411           if(theIsStoreSeparate) {
412             aStream.str(std::string());
413             aStream.clear();
414             aStream << theName << "_" << anIndex++;
415             aName = aStream.str();
416           }
417           buildName(aTag, aName);
418         }
419         if(theIsStoreSeparate) {
420           aTag++;
421         }
422       }
423     }
424   }
425 }
426
427 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
428   GeomAlgoAPI_MakeShape* theMS,
429   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
430   const int  theKindOfShape,
431   const int  theTag,
432   const std::string& theName,
433   GeomAPI_DataMapOfShapeShape& theSubShapes)
434 {
435   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
436   TopTools_MapOfShape aView;
437   bool isBuilt = !theName.empty();
438   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
439   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
440     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
441     if (!aView.Add(aRoot)) continue;
442     if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
443       continue; // there is no sence to write history is old shape does not persented in document
444     ListOfShape aList;
445     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
446     aRShape->setImpl((new TopoDS_Shape(aRoot)));
447     theMS->generated(aRShape, aList);
448     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
449       anIt = aList.begin(), aLast = aList.end();
450     for (; anIt != aLast; anIt++) {
451       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
452       if (theSubShapes.isBound(*anIt)) {
453         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
454         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
455       }
456       if (!aRoot.IsSame (aNewShape)) {
457         builder(theTag)->Generated(aRoot,aNewShape);
458         if(isBuilt)
459           buildName(theTag, theName);
460       }
461       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
462       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
463         TopAbs_ShapeEnum anExplodeShapeType =
464           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
465         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
466         int aTag = 1;
467         std::shared_ptr<Model_Document> aDoc =
468           std::dynamic_pointer_cast<Model_Document>(document());
469         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
470           TDF_Label aChildLabel = aLabel.FindChild(aTag);
471           TNaming_Builder aBuilder(aChildLabel);
472           aBuilder.Generated(aRoot, anExp.Current());
473           TCollection_AsciiString aChildName =
474             TCollection_AsciiString((theName + "_").c_str()) + aTag;
475           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
476           aTag++;
477         }
478       }
479     }
480   }
481 }
482
483 //=======================================================================
484 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
485   const TopAbs_ShapeEnum        theGeneratedFrom,
486   TopTools_DataMapOfShapeShape& theDangles)
487 {
488   theDangles.Clear();
489   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
490   TopAbs_ShapeEnum GeneratedTo;
491   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
492   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
493   else return Standard_False;
494   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
495   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
496     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
497     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
498     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
499   }
500   return theDangles.Extent();
501 }
502
503 //=======================================================================
504 void loadGeneratedDangleShapes(
505   const TopoDS_Shape&      theShapeIn,
506   const TopAbs_ShapeEnum   theGeneratedFrom,
507   TNaming_Builder *        theBuilder)
508 {
509   TopTools_DataMapOfShapeShape dangles;
510   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
511   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
512   for (; itr.More(); itr.Next())
513     theBuilder->Generated(itr.Key(), itr.Value());
514 }
515
516 //=======================================================================
517 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
518   const std::string& theName, int&  theTag)
519 {
520   if(theShape->isNull()) return;
521   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
522   std::string aName;
523   if (aShape.ShapeType() == TopAbs_SOLID) {
524     TopExp_Explorer expl(aShape, TopAbs_FACE);
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   }
533   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
534     // load faces and all the free edges
535     TopTools_IndexedMapOfShape Faces;
536     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
537     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
538       TopExp_Explorer expl(aShape, TopAbs_FACE);
539       for (; expl.More(); expl.Next()) {
540         builder(theTag)->Generated(expl.Current());
541         TCollection_AsciiString aStr(theTag);
542         aName = theName + aStr.ToCString();
543         buildName(theTag, aName);
544         theTag++;
545       }
546     }
547     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
548     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
549     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
550     {
551       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
552       if (aLL.Extent() < 2) {
553         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
554           continue;
555         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
556         TCollection_AsciiString aStr(theTag);
557         aName = theName + aStr.ToCString();
558         buildName(theTag, aName);
559         theTag++;
560       } else {
561         TopTools_ListIteratorOfListOfShape anIter(aLL);
562         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
563         anIter.Next();
564         if(aFace.IsEqual(anIter.Value())) {
565           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
566           TCollection_AsciiString aStr(theTag);
567           aName = theName + aStr.ToCString();
568           buildName(theTag, aName);
569           theTag++;
570         }
571       }
572     }
573   } else if (aShape.ShapeType() == TopAbs_WIRE) {
574     TopTools_IndexedMapOfShape Edges;
575     BRepTools::Map3DEdges(aShape, Edges);
576     if (Edges.Extent() == 1) {
577       builder(++theTag)->Generated(Edges.FindKey(1));
578       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
579       for (; expl.More(); expl.Next()) {
580         builder(theTag)->Generated(expl.Current());
581         TCollection_AsciiString aStr(theTag);
582         aName = theName + aStr.ToCString();
583         buildName(theTag, aName);
584         theTag++;
585       }
586     } else {
587       TopExp_Explorer expl(aShape, TopAbs_EDGE);
588       for (; expl.More(); expl.Next()) {
589         builder(theTag)->Generated(expl.Current());
590         TCollection_AsciiString aStr(theTag);
591         aName = theName + aStr.ToCString();
592         buildName(theTag, aName);
593         theTag++;
594       }
595       // and load generated vertices.
596       TopTools_DataMapOfShapeShape generated;
597       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
598       {
599         TNaming_Builder* pBuilder = builder(theTag++);
600         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
601       }
602     }
603   } else if (aShape.ShapeType() == TopAbs_EDGE) {
604     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
605     for (; expl.More(); expl.Next()) {
606       builder(theTag)->Generated(expl.Current());
607       TCollection_AsciiString aStr(theTag);
608       aName = theName + aStr.ToCString();
609       buildName(theTag, aName);
610       theTag++;
611     }
612   }
613 }
614
615 //=======================================================================
616 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
617   TopTools_ListOfShape&   theList)
618 {
619   int aNumEdges(0);
620   theList.Clear();
621   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
622   TopAbs_ShapeEnum aTS(TopAbs_EDGE);
623   TopAbs_ShapeEnum aTA(TopAbs_FACE);
624   TopTools_MapOfShape aMap1, aMap2; // map1 - for edge ancestors; map2 - for keys => edges
625   TopTools_ListOfShape aKeyList;
626   TopExp::MapShapesAndAncestors(theShapeIn, aTS, aTA, subShapeAndAncestors);
627   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
628     const TopoDS_Shape& aKeyEdge1 = subShapeAndAncestors.FindKey(i);
629     const TopTools_ListOfShape& ancestors1 = subShapeAndAncestors.FindFromIndex(i);
630     aMap1.Clear();
631     TopTools_ListIteratorOfListOfShape it(ancestors1);
632     for(;it.More();it.Next()) aMap1.Add(it.Value()); // fill map with key ancestors => aKey1
633     for (Standard_Integer j = 1; j <= subShapeAndAncestors.Extent(); j++) {
634       if (i == j) continue;
635       const TopoDS_Shape& aKeyEdge2 = subShapeAndAncestors.FindKey(j);
636       const TopTools_ListOfShape& ancestors2 = subShapeAndAncestors.FindFromIndex(j);
637       if(ancestors1.Extent() == ancestors2.Extent() && ancestors1.Extent() > 1) {
638         int aNum (ancestors2.Extent());
639         TopTools_ListIteratorOfListOfShape it(ancestors2);
640         for(;it.More();it.Next())
641           if(aMap1.Contains(it.Value())) aNum--;
642         if(aNum == 0) {
643           if(aMap2.Add(aKeyEdge1))
644             aKeyList.Append(aKeyEdge1);
645           if(aMap2.Add(aKeyEdge2))
646             aKeyList.Append(aKeyEdge2);
647         }
648       }
649     } // at the end ==> List of edges to be named in addition
650   }
651   aNumEdges = aKeyList.Extent();
652   if(aNumEdges)
653     theList.Assign(aKeyList);
654   return aNumEdges;
655 }
656
657 //=======================================================================
658 void Model_BodyBuilder::loadFirstLevel(
659   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
660 {
661   if(theShape->isNull()) return;
662   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
663   std::string aName;
664   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
665     TopoDS_Iterator itr(aShape);
666     for (; itr.More(); itr.Next(),theTag++) {
667       builder(theTag)->Generated(itr.Value());
668       TCollection_AsciiString aStr(theTag);
669       aName = theName + aStr.ToCString();
670       buildName(theTag, aName);
671       if(!theName.empty()) buildName(theTag, aName);
672       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
673         itr.Value().ShapeType() == TopAbs_COMPSOLID)
674       {
675         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
676         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
677         loadFirstLevel(itrShape, theName, theTag);
678       } else {
679         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
680         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
681         loadNextLevels(itrShape, theName, theTag);
682       }
683     }
684   } else {
685     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
686     itrShape->setImpl(new TopoDS_Shape(aShape));
687     loadNextLevels(itrShape, theName, theTag);
688   }
689   TopTools_ListOfShape   aList;
690   if(findAmbiguities(aShape, aList)) {
691     TopTools_ListIteratorOfListOfShape it(aList);
692     for (; it.More(); it.Next(),theTag++) {
693       builder(theTag)->Generated(it.Value());
694       TCollection_AsciiString aStr(theTag);
695       aName = theName + aStr.ToCString();
696       buildName(theTag, aName);
697     }
698   }
699 }
700
701 //=======================================================================
702 void Model_BodyBuilder::loadDisconnectedEdges(
703   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
704 {
705   if(theShape->isNull()) return;
706   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
707   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
708   TopTools_ListOfShape empty;
709   TopExp_Explorer explF(aShape, TopAbs_FACE);
710   for (; explF.More(); explF.Next()) {
711     const TopoDS_Shape& aFace = explF.Current();
712     TopExp_Explorer explV(aFace, TopAbs_EDGE);
713     for (; explV.More(); explV.Next()) {
714       const TopoDS_Shape& anEdge = explV.Current();
715       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
716       Standard_Boolean faceIsNew = Standard_True;
717       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
718       for (; itrF.More(); itrF.Next()) {
719         if (itrF.Value().IsSame(aFace)) {
720           faceIsNew = Standard_False;
721           break;
722         }
723       }
724       if (faceIsNew)
725         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
726     }
727   }
728
729   TopTools_MapOfShape anEdgesToDelete;
730   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
731   std::string aName;
732   for(;anEx.More();anEx.Next()) {
733     Standard_Boolean aC0 = Standard_False;
734     TopoDS_Shape anEdge1 = anEx.Current();
735     if (edgeNaborFaces.IsBound(anEdge1)) {
736       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
737       if (aList1.Extent()<2) continue;
738       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
739       for (; itr.More(); itr.Next()) {
740         TopoDS_Shape anEdge2 = itr.Key();
741         if(anEdgesToDelete.Contains(anEdge2)) continue;
742         if (anEdge1.IsSame(anEdge2)) continue;
743         const TopTools_ListOfShape& aList2 = itr.Value();
744         // compare lists of the neighbour faces of edge1 and edge2
745         if (aList1.Extent() == aList2.Extent()) {
746           Standard_Integer aMatches = 0;
747           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
748             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
749               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
750           if (aMatches == aList1.Extent()) {
751             aC0=Standard_True;
752             builder(theTag)->Generated(anEdge2);
753             anEdgesToDelete.Add(anEdge2);
754             TCollection_AsciiString aStr(theTag);
755             aName = theName + aStr.ToCString();
756             buildName(theTag, aName);
757             theTag++;
758           }
759         }
760       }
761       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
762       for(;itDelete.More();itDelete.Next())
763         edgeNaborFaces.UnBind(itDelete.Key());
764       edgeNaborFaces.UnBind(anEdge1);
765     }
766     if (aC0) {
767       builder(theTag)->Generated(anEdge1);
768       TCollection_AsciiString aStr(theTag);
769       aName = theName + aStr.ToCString();
770       buildName(theTag, aName);
771       theTag++;
772     }
773   }
774 }
775
776 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
777                                                  const std::string& theName, int&  theTag)
778 {
779   if(theShape->isNull()) return;
780   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
781   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
782   TopTools_ListOfShape empty;
783   TopExp_Explorer explF(aShape, TopAbs_EDGE);
784   for (; explF.More(); explF.Next()) {
785     const TopoDS_Shape& anEdge = explF.Current();
786     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
787     for (; explV.More(); explV.Next()) {
788       const TopoDS_Shape& aVertex = explV.Current();
789       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
790       Standard_Boolean faceIsNew = Standard_True;
791       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
792       for (; itrF.More(); itrF.Next()) {
793         if (itrF.Value().IsSame(anEdge)) {
794           faceIsNew = Standard_False;
795           break;
796         }
797       }
798       if (faceIsNew) {
799         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
800       }
801     }
802   }
803   std::string aName;
804   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
805   for (; itr.More(); itr.Next()) {
806     const TopTools_ListOfShape& naborEdges = itr.Value();
807     if (naborEdges.Extent() < 2) {
808       builder(theTag)->Generated(itr.Key());
809       TCollection_AsciiString aStr(theTag);
810       aName = theName + aStr.ToCString();
811       buildName(theTag, aName);
812       theTag++;
813     }
814   }
815 }
816
817 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
818 {
819   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
820   if (aData) {
821     TDF_Label aShapeLab = aData->shapeLab();
822     Handle(TDF_Reference) aRef;
823     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
824       aShapeLab = aRef->Get();
825     }
826     Handle(TNaming_NamedShape) aName;
827     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
828       TopoDS_Shape aShape = aName->Get();
829       if (!aShape.IsNull()) {
830         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
831         aRes->setImpl(new TopoDS_Shape(aShape));
832         return aRes;
833       }
834     }
835   }
836   return std::shared_ptr<GeomAPI_Shape>();
837 }
838
839 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
840 {
841   if (theShape.get()) {
842     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
843     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
844     if (aData) {
845       TDF_Label& aShapeLab = aData->shapeLab();
846       Handle(TNaming_NamedShape) aName;
847       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
848         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
849         if (aLatest.IsNull())
850           return false;
851         if (aLatest.IsEqual(aShape))
852           return true;
853         // check sub-shapes for comp-solids:
854         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
855           if (aLatest.IsEqual(anExp.Current()))
856             return true;
857         }
858       }
859     }
860   }
861   return false;
862 }