1 // Copyright (C) 2014-2020 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 <Locale_Convert.h>
24 #include <Model_Data.h>
25 #include <Model_Document.h>
26 #include <ModelAPI_Session.h>
27 #include <TNaming_Builder.hxx>
28 #include <TNaming_NamedShape.hxx>
29 #include <TNaming_Iterator.hxx>
30 #include <TNaming_Tool.hxx>
31 #include <TNaming_SameShapeIterator.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <TDataStd_Integer.hxx>
34 #include <TDataStd_ExtStringList.hxx>
36 #include <TopoDS_Face.hxx>
37 #include <TDF_ChildIterator.hxx>
38 #include <TDF_ChildIDIterator.hxx>
39 #include <TDF_Reference.hxx>
40 #include <TDF_Tool.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopExp_Explorer.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <TopTools_DataMapOfShapeListOfShape.hxx>
46 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
48 #include <TopTools_MapIteratorOfMapOfShape.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <TopTools_IndexedMapOfShape.hxx>
51 #include <TopTools_DataMapOfShapeShape.hxx>
53 #include <BRepTools.hxx>
54 #include <BRep_Tool.hxx>
55 #include <BRepTools_History.hxx>
56 #include <GeomAPI_Shape.h>
57 #include <GeomAPI_ShapeExplorer.h>
58 #include <GeomAlgoAPI_MakeShape.h>
59 #include <GeomAlgoAPI_SortListOfShapes.h>
60 #include <Config_PropManager.h>
62 //#include <TCollection_AsciiString.hxx>
63 //#define DEB_IMPORT 1
65 /// reference to the shape in external document: sting list attribute identifier
66 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
68 static const int INVALID_TAG = -1;
69 static const int GENERATED_VERTICES_TAG = 1;
70 static const int GENERATED_EDGES_TAG = 2;
71 static const int GENERATED_FACES_TAG = 3;
72 static const int MODIFIED_VERTICES_TAG = 4;
73 static const int MODIFIED_EDGES_TAG = 5;
74 static const int MODIFIED_FACES_TAG = 6;
75 static const int DELETED_TAG = 7;
76 static const int PRIMITIVES_START_TAG = 11;
78 static int getGenerationTag(const TopoDS_Shape& theShape) {
79 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
81 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
82 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
83 case TopAbs_FACE: return GENERATED_FACES_TAG;
84 default: break; // [to avoid compilation warning]
90 static int getModificationTag(const TopoDS_Shape& theShape) {
91 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
93 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
94 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
95 case TopAbs_FACE: return MODIFIED_FACES_TAG;
96 default: break; // [to avoid compilation warning]
102 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
103 const TopoDS_Shape& theOldShape,
104 const TopoDS_Shape& theNewShape)
106 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
110 if (aNamingIt.NewShape().IsSame(theNewShape)
111 && aNamingIt.OldShape().IsSame(theOldShape))
120 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
121 : ModelAPI_BodyBuilder(theOwner),
122 myFreePrimitiveTag(PRIMITIVES_START_TAG)
126 /// Checks that shape is presented in the tree with not-selection evolution
127 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
128 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
129 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
131 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
132 if (aResult) { //check evolution and a label of this shape
133 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
135 static Handle(TNaming_NamedShape) aNS;
136 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
137 if (aNS->Evolution() != TNaming_SELECTED) {
138 theOriginalLabel = aNS->Label();
144 if (!theAccess2.IsNull()) {
145 static const TDF_Label anEmpty;
146 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
151 /// Stores entry to the external label in the entries list at this label
152 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
154 // store information about the external document reference to restore old shape on open
155 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
156 Handle(TDataStd_ExtStringList) anEntries;
157 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
158 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
160 TCollection_AsciiString anEntry;
161 TDF_Tool::Entry(theExternal, anEntry);
162 // check it already contains this entry
163 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
164 for(; anIter.More(); anIter.Next())
165 if (anIter.Value() == anEntry)
167 if (!anIter.More()) {
168 anEntries->Append(anEntry);
173 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
174 const bool theIsStoreSameShapes)
176 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
178 TDF_Label aShapeLab = aData->shapeLab();
181 // store the new shape as primitive
182 TNaming_Builder aBuilder(aShapeLab);
185 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
187 return; // null shape inside
189 if(!theIsStoreSameShapes) {
190 Handle(TNaming_NamedShape) aNS;
191 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
192 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
193 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
194 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
195 // This shape is already in document, store reference instead of shape;
196 const TDF_Label aFoundLabel = aNS->Label();
197 TDF_Reference::Set(aShapeLab, aFoundLabel);
198 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
203 aBuilder.Generated(aShape);
205 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
206 if(!aBuilder.NamedShape()->IsEmpty()) {
207 Handle(TDataStd_Name) anAttr;
208 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
209 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
211 std::shared_ptr<Model_Document> aDoc =
212 std::dynamic_pointer_cast<Model_Document>(document());
213 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
220 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
221 const GeomShapePtr& theToShape, const bool theIsCleanStored)
223 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
226 if (theIsCleanStored)
228 TNaming_Builder* aBuilder = builder(0);
229 if (!theFromShape || !theToShape)
231 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
232 if (aShapeBasis.IsNull())
233 return; // null shape inside
234 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
235 if (aShapeNew.IsNull())
236 return; // null shape inside
238 // There is no sense to write history if old shape does not exist in the document.
239 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
240 ModelAPI_Session::get()->moduleDocument())->generalLabel();
241 TDF_Label anOriginalLabel;
242 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
243 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
244 aBuilder->Generated(aShapeNew);
247 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
249 aBuilder = builder(0);
252 aBuilder->Generated(aShapeBasis, aShapeNew);
253 // store information about the external document reference to restore old shape on open
254 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
258 if(!aBuilder->NamedShape()->IsEmpty()) {
259 Handle(TDataStd_Name) anAttr;
260 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
261 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
263 std::shared_ptr<Model_Document> aDoc =
264 std::dynamic_pointer_cast<Model_Document>(document());
265 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
272 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
273 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
275 bool aStored = false;
276 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
277 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
278 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
280 ListOfShape aNews; // check this old really generates theToShape
281 theMakeShape->generated(*anOldIter, aNews);
282 ListOfShape::iterator aNewIter = aNews.begin();
283 for (; aNewIter != aNews.end(); aNewIter++) {
284 if (theToShape->isSame(*aNewIter))
287 aStore = aNewIter != aNews.end();
290 storeGenerated(*anOldIter, theToShape, !aStored);
291 TNaming_Builder* aBuilder = builder(0);
292 aStored = !aBuilder->NamedShape()->IsEmpty();
295 if (!aStored) { // store as PRIMITIVE, but clean in any way
301 static TDF_Label builderLabel(DataPtr theData, const int theTag )
303 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
304 return theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
307 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
309 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
310 if (aFind == myBuilders.end()) {
311 myBuilders[theTag] = new TNaming_Builder(builderLabel(data(), theTag));
312 aFind = myBuilders.find(theTag);
314 return aFind->second;
317 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
318 const GeomShapePtr& theNewShape,
319 const bool theIsCleanStored)
321 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
324 if (theIsCleanStored) clean();
325 TNaming_Builder* aBuilder = builder(0);
326 if (!theOldShape || !theNewShape)
328 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
329 if (aShapeOld.IsNull())
330 return; // null shape inside
331 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
332 if (aShapeNew.IsNull())
333 return; // null shape inside
335 // There is no sense to write history if old shape does not exist in the document.
336 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
337 ModelAPI_Session::get()->moduleDocument())->generalLabel();
338 TDF_Label anOriginalLabel;
339 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
340 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
341 aBuilder->Generated(aShapeNew);
344 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
346 aBuilder = builder(0);
349 aBuilder->Modify(aShapeOld, aShapeNew);
350 // store information about the external document reference to restore old shape on open
351 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
354 if(!aBuilder->NamedShape()->IsEmpty()) {
355 Handle(TDataStd_Name) anAttr;
356 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
357 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
359 std::shared_ptr<Model_Document> aDoc =
360 std::dynamic_pointer_cast<Model_Document>(document());
361 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
368 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
369 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
371 bool aStored = false;
372 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
373 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
374 // compounds may cause crash if call "modified"
375 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
376 (*anOldIter)->isCompSolid();
378 ListOfShape aNews; // check this old really modifies theNewShape
379 theMakeShape->modified(*anOldIter, aNews);
380 ListOfShape::iterator aNewIter = aNews.begin();
381 for(; aNewIter != aNews.end(); aNewIter++) {
382 if (theNewShape->isSame(*aNewIter))
385 aStore = aNewIter != aNews.end();
388 storeModified(*anOldIter, theNewShape, !aStored);
389 TNaming_Builder* aBuilder = builder(0);
390 aStored = !aBuilder->NamedShape()->IsEmpty();
394 // check the new shape is already in the tree, so, no need to store primitive, just reference
395 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
397 TDF_Label aShapeLab = aData->shapeLab();
398 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
399 Handle(TNaming_NamedShape) aNS;
400 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
401 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
402 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
403 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
404 // This shape is already in document, store reference instead of shape;
405 const TDF_Label aFoundLabel = aNS->Label();
406 TDF_Reference::Set(aShapeLab, aFoundLabel);
408 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
412 store(theNewShape); // store as PRIMITIVE, but clean in any way
417 void Model_BodyBuilder::clean()
419 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
422 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
423 for(; aBuilder != myBuilders.end(); aBuilder++) {
424 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
425 delete aBuilder->second;
426 if (!aNS.IsNull() && !aNS->Label().IsNull())
427 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
430 myPrimitivesNamesIndexMap.clear();
431 // remove the old reference (if any)
432 aLab.ForgetAttribute(TDF_Reference::GetID());
433 myFreePrimitiveTag = PRIMITIVES_START_TAG;
434 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
435 for(; anEntriesIter.More(); anEntriesIter.Next()) {
436 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
440 void Model_BodyBuilder::cleanCash()
442 myPrimitivesNamesIndexMap.clear();
445 Model_BodyBuilder::~Model_BodyBuilder()
450 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
452 std::string aName = theName;
453 std::string aPrefix = "";
455 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
456 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
457 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
458 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
459 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
460 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
462 aName.insert(0, aPrefix);
464 TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
466 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
467 const std::string& theName,
468 const bool theCheckIsInResult)
470 GeomShapePtr aResultShape = shape();
471 if (theCheckIsInResult) {
472 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
473 if (aNewShapeIsNotInResultShape) {
478 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
479 builder(myFreePrimitiveTag)->Generated(aShape);
480 if (!theName.empty()) {
481 std::string aName = theName;
482 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
483 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
484 aName += "_" + std::to_string(++(anIndexTags.index));
485 anIndexTags.tags.push_back(myFreePrimitiveTag);
486 if (anIndexTags.index == 2) {
487 buildName(anIndexTags.tags.front(), theName + "_1");
491 IndexTags anIndexTags;
492 anIndexTags.index = 1;
493 anIndexTags.tags.push_back(myFreePrimitiveTag);
494 myPrimitivesNamesIndexMap[theName] = anIndexTags;
497 buildName(myFreePrimitiveTag, aName);
499 ++myFreePrimitiveTag;
503 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
504 const GeomShapePtr& theNewShape,
505 const std::string& theName)
507 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
508 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
509 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
511 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
512 // TODO: This is a workaround. New shape should be only vertex, edge or face.
513 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
514 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
515 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
516 builder(aTag)->Generated(anOldShape, anExp.Current());
518 buildName(aTag, theName);
520 aTag = getGenerationTag(aNewShape);
521 if (aTag == INVALID_TAG) return;
522 builder(aTag)->Generated(anOldShape, aNewShape);
523 buildName(aTag, theName);
527 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
528 const GeomShapePtr& theNewShape,
529 const std::string& theName)
531 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
532 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
533 int aTag = getModificationTag(aNewShape);
534 if (aTag == INVALID_TAG) return;
535 builder(aTag)->Modify(anOldShape, aNewShape);
536 buildName(aTag, theName);
539 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
540 const GeomShapePtr& theOldShape,
541 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
542 const GeomShapePtr& theShapesToExclude)
544 TopTools_MapOfShape anAlreadyProcessedShapes;
545 GeomShapePtr aResultShape = shape();
546 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
550 GeomShapePtr anOldSubShape = anExp.current();
551 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
552 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
553 || !theAlgo->isDeleted(anOldSubShape)
554 || aResultShape->isSubShape(anOldSubShape, false)
555 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
560 ListOfShape aNewShapes;
561 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
562 theAlgo->modified(anOldSubShape, aNewShapes);
565 if (aNewShapes.size() == 0
566 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
567 builder(DELETED_TAG)->Delete(anOldSubShape_);
572 // Keep only the shapes with minimal shape type
573 static void keepTopLevelShapes(ListOfShape& theShapes,
574 const TopoDS_Shape& theRoot,
575 const GeomShapePtr& theResultShape = GeomShapePtr())
577 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
578 ListOfShape::iterator anIt = theShapes.begin();
579 while (anIt != theShapes.end()) {
580 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
581 bool aSkip = aNewShape.IsNull() ||
582 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
583 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
584 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
585 ListOfShape::iterator aRemoveIt = anIt++;
586 theShapes.erase(aRemoveIt);
588 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
589 if (aType < aKeepShapeType) {
590 // found a shape with lesser shape type => remove all previous shapes
591 aKeepShapeType = aType;
592 theShapes.erase(theShapes.begin(), anIt);
594 } else if (aType > aKeepShapeType) {
595 // shapes with greater shape type should be removed from the list
596 ListOfShape::iterator aRemoveIt = anIt++;
597 theShapes.erase(aRemoveIt);
604 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
605 const GeomShapePtr& theOldShape,
606 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
607 const std::string& theName)
609 GeomShapePtr aResultShape = shape();
610 GeomShapePtr aShapeToExplore = theOldShape;
611 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
612 // use optimized set of old shapes for this
613 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
615 theShapeTypeToExplore);
616 if (aCompound.get()) aShapeToExplore = aCompound;
619 TopTools_MapOfShape anAlreadyProcessedShapes;
620 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
621 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
622 anOldShapeExp.more();
623 anOldShapeExp.next())
625 GeomShapePtr anOldSubShape = anOldShapeExp.current();
626 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
628 // There is no sense to write history if shape already processed
629 // or old shape does not exist in the document.
630 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
631 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
632 ModelAPI_Session::get()->moduleDocument())->generalLabel();
633 TDF_Label anOriginalLabel;
634 bool anOldSubShapeNotInTree =
635 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
636 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
641 ListOfShape aNewShapes;
642 theAlgo->modified(anOldSubShape, aNewShapes);
644 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
645 aNewShapesIt != aNewShapes.cend();
648 GeomShapePtr aNewShape = *aNewShapesIt;
649 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
650 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
652 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
653 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
654 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
657 if (aResultShape->isSame(aNewShape))
658 continue; // it is stored on the root level (2241 - history propagation issue)
660 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
661 TNaming_Builder*aBuilder = builder(aTag);
662 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
663 continue; // new shape was already stored.
665 buildName(aTag, theName);
666 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
667 : aBuilder->Modify(anOldSubShape_, aNewShape_);
668 // store information about the external document reference to restore old shape on open
669 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
674 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
675 const GeomShapePtr& theOldShape,
676 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
677 const std::string& theName,
678 const bool theSaveOldIfNotInTree)
680 GeomShapePtr aResultShape = shape();
681 TopTools_MapOfShape anAlreadyProcessedShapes;
682 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
683 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
684 anOldShapeExp.more();
685 anOldShapeExp.next())
687 GeomShapePtr anOldSubShape = anOldShapeExp.current();
688 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
690 // There is no sense to write history if shape already processed
691 // or old shape does not exist in the document.
692 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
693 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
694 ModelAPI_Session::get()->moduleDocument())->generalLabel();
695 TDF_Label anOriginalLabel;
696 bool anOldSubShapeNotInTree =
697 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
698 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
699 if (theSaveOldIfNotInTree) {
700 std::string aSelectionName = theName + "Selected";
701 generated(anOldSubShape, aSelectionName, false);
707 ListOfShape aNewShapes;
708 theAlgo->generated(anOldSubShape, aNewShapes);
710 keepTopLevelShapes(aNewShapes, anOldSubShape_);
712 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
713 aNewShapesIt != aNewShapes.cend();
716 GeomShapePtr aNewShape = *aNewShapesIt;
717 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
719 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
720 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
721 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
725 if (aResultShape->isSame(aNewShape))
726 continue; // it is stored on the root level
728 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
729 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
730 // TODO: This is a workaround. New shape should be only edge or face.
731 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
733 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
734 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
735 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
736 // store information about the external document reference to restore old shape on open
737 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
739 buildName(aTag, theName);
741 int aTag = getGenerationTag(aNewShape_);
742 if (aTag == INVALID_TAG) return;
743 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
744 buildName(aTag, theName);
745 // store information about the external document reference to restore old shape on open
746 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
753 //=======================================================================
754 int getDangleShapes(const TopoDS_Shape& theShapeIn,
755 const TopAbs_ShapeEnum theGeneratedFrom,
756 TopTools_DataMapOfShapeShape& theDangles)
759 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
760 TopAbs_ShapeEnum GeneratedTo;
761 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
762 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
763 else return Standard_False;
764 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
765 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
766 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
767 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
768 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
770 return theDangles.Extent();
773 //=======================================================================
774 void loadGeneratedDangleShapes(
775 const TopoDS_Shape& theShapeIn,
776 const TopAbs_ShapeEnum theGeneratedFrom,
777 TNaming_Builder * theBuilder)
779 TopTools_DataMapOfShapeShape dangles;
780 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
781 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
782 for (; itr.More(); itr.Next())
783 theBuilder->Generated(itr.Key(), itr.Value());
787 //=======================================================================
788 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
789 const std::string& theName)
791 if(theShape->isNull()) return;
792 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
794 if (aShape.ShapeType() == TopAbs_SOLID) {
795 TopExp_Explorer expl(aShape, TopAbs_FACE);
796 for (; expl.More(); expl.Next()) {
797 builder(myFreePrimitiveTag)->Generated(expl.Current());
798 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
799 aName = theName + "_" + aStr.ToCString();
800 buildName(myFreePrimitiveTag, aName);
801 ++myFreePrimitiveTag;
804 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
805 // load faces and all the free edges
806 TopTools_IndexedMapOfShape Faces;
807 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
808 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
809 TopExp_Explorer expl(aShape, TopAbs_FACE);
810 for (; expl.More(); expl.Next()) {
811 builder(myFreePrimitiveTag)->Generated(expl.Current());
812 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
813 aName = theName + "_" + aStr.ToCString();
814 buildName(myFreePrimitiveTag, aName);
815 ++myFreePrimitiveTag;
818 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
819 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
820 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
822 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
823 if (aLL.Extent() < 2) {
824 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
826 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
827 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
828 aName = theName + "_" + aStr.ToCString();
829 buildName(myFreePrimitiveTag, aName);
830 ++myFreePrimitiveTag;
832 TopTools_ListIteratorOfListOfShape anIter(aLL);
833 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
835 if(aFace.IsEqual(anIter.Value())) {
836 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
837 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
838 aName = theName + "_" + aStr.ToCString();
839 buildName(myFreePrimitiveTag, aName);
840 ++myFreePrimitiveTag;
844 } else if (aShape.ShapeType() == TopAbs_WIRE) {
845 TopTools_IndexedMapOfShape Edges;
846 BRepTools::Map3DEdges(aShape, Edges);
847 if (Edges.Extent() == 1) {
848 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
849 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
850 for (; expl.More(); expl.Next()) {
851 builder(myFreePrimitiveTag)->Generated(expl.Current());
852 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
853 aName = theName + "_" + aStr.ToCString();
854 buildName(myFreePrimitiveTag, aName);
855 ++myFreePrimitiveTag;
858 TopExp_Explorer expl(aShape, TopAbs_EDGE);
859 for (; expl.More(); expl.Next()) {
860 builder(myFreePrimitiveTag)->Generated(expl.Current());
861 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
862 aName = theName + "_" + aStr.ToCString();
863 buildName(myFreePrimitiveTag, aName);
864 ++myFreePrimitiveTag;
866 // and load generated vertices.
867 TopTools_DataMapOfShapeShape generated;
868 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
870 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
871 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
874 } else if (aShape.ShapeType() == TopAbs_EDGE) {
875 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
876 for (; expl.More(); expl.Next()) {
877 builder(myFreePrimitiveTag)->Generated(expl.Current());
878 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
879 aName = theName + "_" + aStr.ToCString();
880 buildName(myFreePrimitiveTag, aName);
881 ++myFreePrimitiveTag;
886 //=======================================================================
887 int findAmbiguities(const TopoDS_Shape& theShapeIn,
888 TopTools_ListOfShape& theList)
891 // edges -> ancestor faces list
892 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
893 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
894 // keeps the shapes which are already in the resulting list
895 TopTools_MapOfShape alreadyThere;
896 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
897 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
899 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
900 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
901 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
902 if (ancestors.Extent() < 2)
904 Standard_Integer anID = 0;
905 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
906 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
908 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
909 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
910 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
911 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
912 for(; aSameEdge.More(); aSameEdge.Next()) {
913 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
914 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
915 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
918 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
919 for(; aFaceIter1.More(); aFaceIter1.Next()) {
920 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
921 for(; aFaceIter2.More(); aFaceIter2.Next()) {
922 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
925 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
928 if (!aFaceIter1.More()) { // all the faces are same => put to the result
929 if (alreadyThere.Add(aSameEdge.Value()))
930 theList.Append(aSameEdge.Value());
931 if (alreadyThere.Add(anAncestorsIter.Key()))
932 theList.Append(anAncestorsIter.Key());
935 } else { // ID is unique, just add this edge
936 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
938 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
940 return theList.Extent();
943 //=======================================================================
944 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
946 GeomShapePtr aShapePtr = shape();
947 if (theShape->isNull() || !aShapePtr.get())
949 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
953 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
954 TopoDS_Iterator itr(aShape);
955 for (; itr.More(); itr.Next()) {
956 builder(myFreePrimitiveTag)->Generated(itr.Value());
957 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
958 aName = theName + "_" + aStr.ToCString();
959 buildName(myFreePrimitiveTag, aName);
960 ++myFreePrimitiveTag;
961 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
962 itr.Value().ShapeType() == TopAbs_COMPSOLID)
964 GeomShapePtr itrShape(new GeomAPI_Shape());
965 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
966 loadFirstLevel(itrShape, theName);
968 GeomShapePtr itrShape(new GeomAPI_Shape());
969 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
970 loadNextLevels(itrShape, theName);
974 GeomShapePtr itrShape(new GeomAPI_Shape());
975 itrShape->setImpl(new TopoDS_Shape(aShape));
976 loadNextLevels(itrShape, theName);
978 TopTools_ListOfShape aList;
979 if(findAmbiguities(aShape, aList)) {
980 TopTools_ListIteratorOfListOfShape it(aList);
981 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
982 builder(myFreePrimitiveTag)->Generated(it.Value());
983 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
984 aName = theName + "_" + aStr.ToCString();
985 buildName(myFreePrimitiveTag, aName);
990 GeomShapePtr Model_BodyBuilder::shape()
992 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
993 if (aData && aData->isValid()) {
994 TDF_Label aShapeLab = aData->shapeLab();
995 Handle(TDF_Reference) aRef;
996 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
997 aShapeLab = aRef->Get();
999 Handle(TNaming_NamedShape) aName;
1000 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1001 TopoDS_Shape aShape = aName->Get();
1002 if (!aShape.IsNull()) {
1003 GeomShapePtr aRes(new GeomAPI_Shape);
1004 aRes->setImpl(new TopoDS_Shape(aShape));
1009 return GeomShapePtr();