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