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