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