]> SALOME platform Git repositories - modules/shaper.git/blob - src/Model/Model_BodyBuilder.cpp
Salome HOME
Fix for the issue #2415 : generation of wide naming structure for the Compound feature
[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 // Keep only the shapes with minimal shape type
374 static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
375   const GeomShapePtr& theResultShape = GeomShapePtr())
376 {
377   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
378   ListOfShape::iterator anIt = theShapes.begin();
379   while (anIt != theShapes.end()) {
380     TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
381     if (theRoot.IsSame(aNewShape) || (theResultShape &&
382         (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
383       ListOfShape::iterator aRemoveIt = anIt++;
384       theShapes.erase(aRemoveIt);
385     } else {
386       GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
387       if (aType < aKeepShapeType) {
388         // found a shape with lesser shape type => remove all previous shapes
389         aKeepShapeType = aType;
390         theShapes.erase(theShapes.begin(), anIt);
391         ++anIt;
392       } else if (aType > aKeepShapeType) {
393         // shapes with greater shape type should be removed from the list
394         ListOfShape::iterator aRemoveIt = anIt++;
395         theShapes.erase(aRemoveIt);
396       } else
397         ++anIt;
398     }
399   }
400 }
401
402 void Model_BodyBuilder::loadAndOrientModifiedShapes (
403   GeomAlgoAPI_MakeShape* theMS,
404   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
405   const int  theKindOfShape,
406   const int  theTag,
407   const std::string& theName,
408   GeomAPI_DataMapOfShapeShape& theSubShapes,
409   const bool theIsStoreSeparate,
410   const bool theIsStoreAsGenerated)
411 {
412   int anIndex = 1;
413   int aTag = theTag;
414   bool isBuilt = !theName.empty();
415   std::string aName = theName;
416   std::ostringstream aStream;
417   GeomShapePtr aResultShape = shape();
418   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
419   TopTools_MapOfShape aView;
420   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
421   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
422     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
423     if (!aView.Add(aRoot)) continue;
424     bool aNotInTree =
425       TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull();
426     if (aNotInTree && !theIsStoreSeparate)
427       continue; // there is no sense to write history if old shape does not exist in the document
428     ListOfShape aList;
429     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
430     aRShape->setImpl((new TopoDS_Shape(aRoot)));
431     theMS->modified(aRShape, aList);
432     if (!theIsStoreSeparate)
433       keepTopLevelShapes(aList, aRoot, aResultShape);
434     // sort the list of images before naming
435     GeomAlgoAPI_SortListOfShapes::sort(aList);
436
437     // to trace situation where several objects are produced by one parent (#2317)
438     int aSameParentShapes = -1;
439     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
440       anIt = aList.begin(), aLast = aList.end();
441     for (; anIt != aLast; anIt++) {
442       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
443       if (theSubShapes.isBound(*anIt)) {
444         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
445         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
446       }
447       GeomShapePtr aGeomNewShape(new GeomAPI_Shape());
448       aGeomNewShape->setImpl(new TopoDS_Shape(aNewShape));
449       if(!aRoot.IsSame(aNewShape) && aResultShape->isSubShape(aGeomNewShape, false) &&
450          !aResultShape->isSame(*anIt)) { // to avoid put of same shape on main label and sub
451         int aBuilderTag = aTag;
452         if (!theIsStoreSeparate)
453           aSameParentShapes++;
454
455         static const int THE_ANCHOR_TAG = 100000;
456         int aCurShapeType = (int)((*anIt)->shapeType());
457         bool needSuffix = false; // suffix for the name based on the shape type
458         if (aSameParentShapes > 0) { // store in other label
459           aBuilderTag = THE_ANCHOR_TAG - aSameParentShapes * 10 - aCurShapeType;
460           needSuffix = true;
461         } else if (aCurShapeType != theKindOfShape) {
462           // modified shape has different type => set another tag
463           // to avoid shapes of different types on the same label
464           aBuilderTag = THE_ANCHOR_TAG - aCurShapeType;
465           needSuffix = true;
466         }
467         std::string aSuffix;
468         if (needSuffix) {
469           switch (aCurShapeType) {
470           case GeomAPI_Shape::VERTEX: aSuffix = "_v"; break;
471           case GeomAPI_Shape::EDGE:   aSuffix = "_e"; break;
472           case GeomAPI_Shape::FACE:   aSuffix = "_f"; break;
473           default: break;
474           }
475         }
476
477         if(theIsStoreAsGenerated) {
478           // Here we store shapes as generated, to avoid problem when one parent shape produce
479           // several child shapes. In this case naming could not determine which shape to select.
480           builder(aBuilderTag)->Generated(aRoot, aNewShape);
481         } else if (aNotInTree) {
482           // not in tree -> store as primitive (stored as separated)
483           builder(aBuilderTag)->Generated(aNewShape);
484         } else {
485           builder(aBuilderTag)->Modify(aRoot, aNewShape);
486         }
487         if(isBuilt) {
488           aStream.str(std::string());
489           aStream.clear();
490           aStream << theName;
491           if(theIsStoreSeparate)
492              aStream << "_" << anIndex++;
493
494           if (aSameParentShapes > 0) {
495             aStream.str(std::string());
496             aStream.clear();
497             aStream << aName << "_" << aSameParentShapes << "divided";
498           }
499
500           aStream << aSuffix;
501           buildName(aBuilderTag, aStream.str());
502         }
503         if(theIsStoreSeparate) {
504           aTag++;
505         }
506       } else if (aResultShape->isSame(*anIt)) {
507         // keep the modification evolution on the root level (2241 - history propagation issue)
508         if(theIsStoreAsGenerated) {
509           builder(0)->Generated(aRoot, aNewShape);
510         } else {
511           builder(0)->Modify(aRoot, aNewShape);
512         }
513       }
514     }
515   }
516 }
517
518 void Model_BodyBuilder::loadAndOrientGeneratedShapes (
519   GeomAlgoAPI_MakeShape* theMS,
520   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
521   const int  theKindOfShape,
522   const int  theTag,
523   const std::string& theName,
524   GeomAPI_DataMapOfShapeShape& theSubShapes)
525 {
526   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
527   TopTools_MapOfShape aView;
528   bool isBuilt = !theName.empty();
529   TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
530   for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
531     const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
532     if (!aView.Add(aRoot)) continue;
533     //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
534     //  continue; // there is no sense to write history if old shape does not exist in the document
535     ListOfShape aList;
536     std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
537     aRShape->setImpl((new TopoDS_Shape(aRoot)));
538     theMS->generated(aRShape, aList);
539     keepTopLevelShapes(aList, aRoot);
540     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
541       anIt = aList.begin(), aLast = aList.end();
542     for (; anIt != aLast; anIt++) {
543       TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
544       if (theSubShapes.isBound(*anIt)) {
545         std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
546         aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
547       }
548       if (!aRoot.IsSame (aNewShape)) {
549         builder(theTag)->Generated(aRoot,aNewShape);
550         if(isBuilt)
551           buildName(theTag, theName);
552       }
553       TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
554       if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
555         TopAbs_ShapeEnum anExplodeShapeType =
556           aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
557         const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
558         int aTag = 1;
559         std::shared_ptr<Model_Document> aDoc =
560           std::dynamic_pointer_cast<Model_Document>(document());
561         for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
562           TDF_Label aChildLabel = aLabel.FindChild(aTag);
563           TNaming_Builder aBuilder(aChildLabel);
564           aBuilder.Generated(aRoot, anExp.Current());
565           TCollection_AsciiString aChildName =
566             TCollection_AsciiString((theName + "_").c_str()) + aTag;
567           TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
568           aTag++;
569         }
570       }
571     }
572   }
573 }
574
575 //=======================================================================
576 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
577   const TopAbs_ShapeEnum        theGeneratedFrom,
578   TopTools_DataMapOfShapeShape& theDangles)
579 {
580   theDangles.Clear();
581   TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
582   TopAbs_ShapeEnum GeneratedTo;
583   if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
584   else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
585   else return Standard_False;
586   TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
587   for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
588     const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
589     const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
590     if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
591   }
592   return theDangles.Extent();
593 }
594
595 //=======================================================================
596 void loadGeneratedDangleShapes(
597   const TopoDS_Shape&      theShapeIn,
598   const TopAbs_ShapeEnum   theGeneratedFrom,
599   TNaming_Builder *        theBuilder)
600 {
601   TopTools_DataMapOfShapeShape dangles;
602   if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
603   TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
604   for (; itr.More(); itr.Next())
605     theBuilder->Generated(itr.Key(), itr.Value());
606 }
607
608 //=======================================================================
609 void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
610   const std::string& theName, int&  theTag)
611 {
612   if(theShape->isNull()) return;
613   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
614   std::string aName;
615   if (aShape.ShapeType() == TopAbs_SOLID) {
616     TopExp_Explorer expl(aShape, TopAbs_FACE);
617     for (; expl.More(); expl.Next()) {
618       builder(theTag)->Generated(expl.Current());
619       TCollection_AsciiString aStr(theTag);
620       aName = theName + aStr.ToCString();
621       buildName(theTag, aName);
622       theTag++;
623     }
624   }
625   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
626     // load faces and all the free edges
627     TopTools_IndexedMapOfShape Faces;
628     TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
629     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
630       TopExp_Explorer expl(aShape, TopAbs_FACE);
631       for (; expl.More(); expl.Next()) {
632         builder(theTag)->Generated(expl.Current());
633         TCollection_AsciiString aStr(theTag);
634         aName = theName + aStr.ToCString();
635         buildName(theTag, aName);
636         theTag++;
637       }
638     }
639     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
640     TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
641     for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
642     {
643       const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
644       if (aLL.Extent() < 2) {
645         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
646           continue;
647         builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
648         TCollection_AsciiString aStr(theTag);
649         aName = theName + aStr.ToCString();
650         buildName(theTag, aName);
651         theTag++;
652       } else {
653         TopTools_ListIteratorOfListOfShape anIter(aLL);
654         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
655         anIter.Next();
656         if(aFace.IsEqual(anIter.Value())) {
657           builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
658           TCollection_AsciiString aStr(theTag);
659           aName = theName + aStr.ToCString();
660           buildName(theTag, aName);
661           theTag++;
662         }
663       }
664     }
665   } else if (aShape.ShapeType() == TopAbs_WIRE) {
666     TopTools_IndexedMapOfShape Edges;
667     BRepTools::Map3DEdges(aShape, Edges);
668     if (Edges.Extent() == 1) {
669       builder(theTag++)->Generated(Edges.FindKey(1));
670       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
671       for (; expl.More(); expl.Next()) {
672         builder(theTag)->Generated(expl.Current());
673         TCollection_AsciiString aStr(theTag);
674         aName = theName + aStr.ToCString();
675         buildName(theTag, aName);
676         theTag++;
677       }
678     } else {
679       TopExp_Explorer expl(aShape, TopAbs_EDGE);
680       for (; expl.More(); expl.Next()) {
681         builder(theTag)->Generated(expl.Current());
682         TCollection_AsciiString aStr(theTag);
683         aName = theName + aStr.ToCString();
684         buildName(theTag, aName);
685         theTag++;
686       }
687       // and load generated vertices.
688       TopTools_DataMapOfShapeShape generated;
689       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
690       {
691         TNaming_Builder* pBuilder = builder(theTag++);
692         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
693       }
694     }
695   } else if (aShape.ShapeType() == TopAbs_EDGE) {
696     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
697     for (; expl.More(); expl.Next()) {
698       builder(theTag)->Generated(expl.Current());
699       TCollection_AsciiString aStr(theTag);
700       aName = theName + aStr.ToCString();
701       buildName(theTag, aName);
702       theTag++;
703     }
704   }
705 }
706
707 //=======================================================================
708 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
709   TopTools_ListOfShape&   theList)
710 {
711   theList.Clear();
712   // edges -> ancestor faces list
713   TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
714   TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
715   // keeps the shapes which are already in the resulting list
716   TopTools_MapOfShape alreadyThere;
717   // map from faces identifier (combination of hash-codes) to list of edges produced such ID
718   NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
719
720   TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
721   for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
722     const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
723     if (ancestors.Extent() < 2)
724       continue;
725     Standard_Integer anID = 0;
726     for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
727       anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
728     }
729     if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
730       const NCollection_List<TopoDS_Shape>& aSameFaces1 =
731         aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
732       NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
733       for(; aSameEdge.More(); aSameEdge.Next()) {
734         const NCollection_List<TopoDS_Shape>& aSameFaces2 =
735           aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
736         if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
737           break;
738
739         NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
740         for(; aFaceIter1.More(); aFaceIter1.Next()) {
741           NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
742           for(; aFaceIter2.More(); aFaceIter2.Next()) {
743             if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
744               break;
745           }
746           if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
747             break;
748         }
749         if (!aFaceIter1.More()) { // all the faces are same => put to the result
750           if (alreadyThere.Add(aSameEdge.Value()))
751             theList.Append(aSameEdge.Value());
752           if (alreadyThere.Add(anAncestorsIter.Key()))
753             theList.Append(anAncestorsIter.Key());
754         }
755       }
756     } else { // ID is unique, just add this edge
757       aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
758     }
759     aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
760   }
761   return theList.Extent();
762 }
763
764 //=======================================================================
765 void Model_BodyBuilder::loadFirstLevel(
766   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
767 {
768   if(theShape->isNull()) return;
769   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
770   std::string aName;
771   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
772     TopoDS_Iterator itr(aShape);
773     for (; itr.More(); itr.Next()) {
774       builder(theTag)->Generated(itr.Value());
775       TCollection_AsciiString aStr(theTag);
776       aName = theName + aStr.ToCString();
777       buildName(theTag, aName);
778       if(!theName.empty()) buildName(theTag, aName);
779       theTag++;
780       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
781         itr.Value().ShapeType() == TopAbs_COMPSOLID)
782       {
783         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
784         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
785         loadFirstLevel(itrShape, theName, theTag);
786       } else {
787         std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
788         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
789         loadNextLevels(itrShape, theName, theTag);
790       }
791     }
792   } else {
793     std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
794     itrShape->setImpl(new TopoDS_Shape(aShape));
795     loadNextLevels(itrShape, theName, theTag);
796   }
797   TopTools_ListOfShape   aList;
798   if(findAmbiguities(aShape, aList)) {
799     TopTools_ListIteratorOfListOfShape it(aList);
800     for (; it.More(); it.Next(),theTag++) {
801       builder(theTag)->Generated(it.Value());
802       TCollection_AsciiString aStr(theTag);
803       aName = theName + aStr.ToCString();
804       buildName(theTag, aName);
805     }
806   }
807 }
808
809 //=======================================================================
810 void Model_BodyBuilder::loadDisconnectedEdges(
811   std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
812 {
813   if(theShape->isNull()) return;
814   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
815   TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
816   TopTools_ListOfShape empty;
817   TopExp_Explorer explF(aShape, TopAbs_FACE);
818   for (; explF.More(); explF.Next()) {
819     const TopoDS_Shape& aFace = explF.Current();
820     TopExp_Explorer explV(aFace, TopAbs_EDGE);
821     for (; explV.More(); explV.Next()) {
822       const TopoDS_Shape& anEdge = explV.Current();
823       if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
824       Standard_Boolean faceIsNew = Standard_True;
825       TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
826       for (; itrF.More(); itrF.Next()) {
827         if (itrF.Value().IsSame(aFace)) {
828           faceIsNew = Standard_False;
829           break;
830         }
831       }
832       if (faceIsNew)
833         edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
834     }
835   }
836
837   TopTools_MapOfShape anEdgesToDelete;
838   TopExp_Explorer anEx(aShape,TopAbs_EDGE);
839   std::string aName;
840   for(;anEx.More();anEx.Next()) {
841     Standard_Boolean aC0 = Standard_False;
842     TopoDS_Shape anEdge1 = anEx.Current();
843     if (edgeNaborFaces.IsBound(anEdge1)) {
844       const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
845       if (aList1.Extent()<2) continue;
846       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
847       for (; itr.More(); itr.Next()) {
848         TopoDS_Shape anEdge2 = itr.Key();
849         if(anEdgesToDelete.Contains(anEdge2)) continue;
850         if (anEdge1.IsSame(anEdge2)) continue;
851         const TopTools_ListOfShape& aList2 = itr.Value();
852         // compare lists of the neighbour faces of edge1 and edge2
853         if (aList1.Extent() == aList2.Extent()) {
854           Standard_Integer aMatches = 0;
855           for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
856             for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
857               if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
858           if (aMatches == aList1.Extent()) {
859             aC0=Standard_True;
860             builder(theTag)->Generated(anEdge2);
861             anEdgesToDelete.Add(anEdge2);
862             TCollection_AsciiString aStr(theTag);
863             aName = theName + aStr.ToCString();
864             buildName(theTag, aName);
865             theTag++;
866           }
867         }
868       }
869       TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
870       for(;itDelete.More();itDelete.Next())
871         edgeNaborFaces.UnBind(itDelete.Key());
872       edgeNaborFaces.UnBind(anEdge1);
873     }
874     if (aC0) {
875       builder(theTag)->Generated(anEdge1);
876       TCollection_AsciiString aStr(theTag);
877       aName = theName + aStr.ToCString();
878       buildName(theTag, aName);
879       theTag++;
880     }
881   }
882 }
883
884 void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
885                                                  const std::string& theName, int&  theTag)
886 {
887   if(theShape->isNull()) return;
888   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
889   TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
890   TopTools_ListOfShape empty;
891   TopExp_Explorer explF(aShape, TopAbs_EDGE);
892   for (; explF.More(); explF.Next()) {
893     const TopoDS_Shape& anEdge = explF.Current();
894     TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
895     for (; explV.More(); explV.Next()) {
896       const TopoDS_Shape& aVertex = explV.Current();
897       if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
898       Standard_Boolean faceIsNew = Standard_True;
899       TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
900       for (; itrF.More(); itrF.Next()) {
901         if (itrF.Value().IsSame(anEdge)) {
902           faceIsNew = Standard_False;
903           break;
904         }
905       }
906       if (faceIsNew) {
907         vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
908       }
909     }
910   }
911   std::string aName;
912   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
913   for (; itr.More(); itr.Next()) {
914     const TopTools_ListOfShape& naborEdges = itr.Value();
915     if (naborEdges.Extent() < 2) {
916       builder(theTag)->Generated(itr.Key());
917       TCollection_AsciiString aStr(theTag);
918       aName = theName + aStr.ToCString();
919       buildName(theTag, aName);
920       theTag++;
921     }
922   }
923 }
924
925 std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
926 {
927   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
928   if (aData) {
929     TDF_Label aShapeLab = aData->shapeLab();
930     Handle(TDF_Reference) aRef;
931     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
932       aShapeLab = aRef->Get();
933     }
934     Handle(TNaming_NamedShape) aName;
935     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
936       TopoDS_Shape aShape = aName->Get();
937       if (!aShape.IsNull()) {
938         std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
939         aRes->setImpl(new TopoDS_Shape(aShape));
940         return aRes;
941       }
942     }
943   }
944   return std::shared_ptr<GeomAPI_Shape>();
945 }
946
947 bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
948 {
949   if (theShape.get()) {
950     TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
951     std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
952     if (aData) {
953       TDF_Label& aShapeLab = aData->shapeLab();
954       Handle(TNaming_NamedShape) aName;
955       if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
956         TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
957         if (aLatest.IsNull())
958           return false;
959         if (aLatest.IsEqual(aShape))
960           return true;
961         // check sub-shapes for comp-solids:
962         for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
963           if (aLatest.IsEqual(anExp.Current()))
964             return true;
965         }
966       }
967     }
968   }
969   return false;
970 }