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