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