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