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