1 // Copyright (C) 2014-2019 CEA/DEN, EDF R&D
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.
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.
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
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #include <Model_BodyBuilder.h>
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>
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>
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>
60 //#include <TCollection_AsciiString.hxx>
61 //#define DEB_IMPORT 1
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");
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;
76 static int getGenerationTag(const TopoDS_Shape& theShape) {
77 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
79 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
80 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
81 case TopAbs_FACE: return GENERATED_FACES_TAG;
87 static int getModificationTag(const TopoDS_Shape& theShape) {
88 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
90 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
91 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
92 case TopAbs_FACE: return MODIFIED_FACES_TAG;
98 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
99 const TopoDS_Shape& theOldShape,
100 const TopoDS_Shape& theNewShape)
102 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
106 if (aNamingIt.NewShape().IsSame(theNewShape)
107 && aNamingIt.OldShape().IsSame(theOldShape))
116 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
117 : ModelAPI_BodyBuilder(theOwner),
118 myFreePrimitiveTag(PRIMITIVES_START_TAG)
122 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
123 const bool theIsStoreSameShapes)
125 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
127 TDF_Label aShapeLab = aData->shapeLab();
130 // store the new shape as primitive
131 TNaming_Builder aBuilder(aShapeLab);
134 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
136 return; // null shape inside
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());
150 aBuilder.Generated(aShape);
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());
158 std::shared_ptr<Model_Document> aDoc =
159 std::dynamic_pointer_cast<Model_Document>(document());
160 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
167 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
168 const GeomShapePtr& theToShape)
170 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
172 TDF_Label aShapeLab = aData->shapeLab();
175 // store the new shape as primitive
176 TNaming_Builder aBuilder(aShapeLab);
177 if (!theFromShape || !theToShape)
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);
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());
192 std::shared_ptr<Model_Document> aDoc =
193 std::dynamic_pointer_cast<Model_Document>(document());
194 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
201 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
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);
210 return aFind->second;
213 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
214 const GeomShapePtr& theNewShape,
215 const bool theIsCleanStored)
217 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
220 if (theIsCleanStored) clean();
221 // store the new shape as primitive
222 TNaming_Builder* aBuilder = builder(0);
223 if (!theOldShape || !theNewShape)
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());
237 std::shared_ptr<Model_Document> aDoc =
238 std::dynamic_pointer_cast<Model_Document>(document());
239 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
246 void Model_BodyBuilder::clean()
248 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
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());
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);
269 void Model_BodyBuilder::cleanCash()
271 myPrimitivesNamesIndexMap.clear();
274 Model_BodyBuilder::~Model_BodyBuilder()
279 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
281 std::string aName = theName;
282 std::string aPrefix = "";
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;
291 aName.insert(0, aPrefix);
293 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
295 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
296 const std::string& theName,
297 const bool theCheckIsInResult)
299 GeomShapePtr aResultShape = shape();
300 if (theCheckIsInResult) {
301 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
302 if (aNewShapeIsNotInResultShape) {
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");
320 IndexTags anIndexTags;
321 anIndexTags.index = 1;
322 anIndexTags.tags.push_back(myFreePrimitiveTag);
323 myPrimitivesNamesIndexMap[theName] = anIndexTags;
326 buildName(myFreePrimitiveTag, aName);
328 ++myFreePrimitiveTag;
332 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
333 const GeomShapePtr& theNewShape,
334 const std::string& theName)
336 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
337 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
338 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
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());
347 buildName(aTag, theName);
349 aTag = getGenerationTag(aNewShape);
350 if (aTag == INVALID_TAG) return;
351 builder(aTag)->Generated(anOldShape, aNewShape);
352 buildName(aTag, theName);
356 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
357 const GeomShapePtr& theNewShape,
358 const std::string& theName)
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);
368 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
369 const GeomShapePtr& theOldShape,
370 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
371 const GeomShapePtr& theShapesToExclude)
373 TopTools_MapOfShape anAlreadyProcessedShapes;
374 GeomShapePtr aResultShape = shape();
375 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
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)))
389 ListOfShape aNewShapes;
390 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
391 theAlgo->modified(anOldSubShape, aNewShapes);
394 if (aNewShapes.size() == 0
395 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
396 builder(DELETED_TAG)->Delete(anOldSubShape_);
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())
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);
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);
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);
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)
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())
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();
451 if (!theAccess2.IsNull()) {
452 static const TDF_Label anEmpty;
453 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
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)
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);
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)
474 if (!anIter.More()) {
475 anEntries->Append(anEntry);
480 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
481 const GeomShapePtr& theOldShape,
482 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
483 const std::string& theName)
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,
491 theShapeTypeToExplore);
492 if (aCompound.get()) aShapeToExplore = aCompound;
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())
501 GeomShapePtr anOldSubShape = anOldShapeExp.current();
502 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
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) {
517 ListOfShape aNewShapes;
518 theAlgo->modified(anOldSubShape, aNewShapes);
520 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
521 aNewShapesIt != aNewShapes.cend();
524 GeomShapePtr aNewShape = *aNewShapesIt;
525 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
526 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
528 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
529 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
530 if (aNewShapeIsSameAsOldShape
531 || aNewShapeIsNotInResultShape)
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.
547 // Check if new shape was already stored.
548 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
550 if (!aBuilder->NamedShape().IsNull() &&
551 ((isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_GENERATED)
552 || (!isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_MODIFY)))
554 myBuilders.erase(0); // clear old builder to avoid different evolutions crash
555 aBuilder = builder(0);
558 int aTag = isGenerated ? getGenerationTag(aNewShape_)
559 : getModificationTag(aNewShape_);
560 aBuilder = builder(aTag);
562 // Check if new shape was already stored.
563 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
565 buildName(aTag, theName);
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());
576 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
577 const GeomShapePtr& theOldShape,
578 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
579 const std::string& theName)
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())
588 GeomShapePtr anOldSubShape = anOldShapeExp.current();
589 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
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) {
604 ListOfShape aNewShapes;
605 theAlgo->generated(anOldSubShape, aNewShapes);
607 keepTopLevelShapes(aNewShapes, anOldSubShape_);
609 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
610 aNewShapesIt != aNewShapes.cend();
613 GeomShapePtr aNewShape = *aNewShapesIt;
614 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
616 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
617 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
618 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
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
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());
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.
644 // Check if new shape was already stored.
645 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
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);
652 aBuilder->Generated(anOldSubShape_, aNewShape_);
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());
666 //=======================================================================
667 int getDangleShapes(const TopoDS_Shape& theShapeIn,
668 const TopAbs_ShapeEnum theGeneratedFrom,
669 TopTools_DataMapOfShapeShape& theDangles)
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);
683 return theDangles.Extent();
686 //=======================================================================
687 void loadGeneratedDangleShapes(
688 const TopoDS_Shape& theShapeIn,
689 const TopAbs_ShapeEnum theGeneratedFrom,
690 TNaming_Builder * theBuilder)
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());
700 //=======================================================================
701 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
702 const std::string& theName)
704 if(theShape->isNull()) return;
705 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
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;
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;
731 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
732 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
733 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
735 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
736 if (aLL.Extent() < 2) {
737 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
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;
745 TopTools_ListIteratorOfListOfShape anIter(aLL);
746 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
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;
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;
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;
779 // and load generated vertices.
780 TopTools_DataMapOfShapeShape generated;
781 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
783 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
784 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
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;
799 //=======================================================================
800 int findAmbiguities(const TopoDS_Shape& theShapeIn,
801 TopTools_ListOfShape& theList)
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;
812 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
813 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
814 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
815 if (ancestors.Extent() < 2)
817 Standard_Integer anID = 0;
818 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
819 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
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
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()))
838 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
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());
848 } else { // ID is unique, just add this edge
849 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
851 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
853 return theList.Extent();
856 //=======================================================================
857 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
859 if(theShape->isNull()) return;
860 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
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)
873 GeomShapePtr itrShape(new GeomAPI_Shape());
874 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
875 loadFirstLevel(itrShape, theName);
877 GeomShapePtr itrShape(new GeomAPI_Shape());
878 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
879 loadNextLevels(itrShape, theName);
883 GeomShapePtr itrShape(new GeomAPI_Shape());
884 itrShape->setImpl(new TopoDS_Shape(aShape));
885 loadNextLevels(itrShape, theName);
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);
899 GeomShapePtr Model_BodyBuilder::shape()
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();
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));
918 return GeomShapePtr();