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 TopTools_ListOfShape anOldList;
340 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
341 // check this could be a compund by the whole feature selection
342 if (aShapeOld.ShapeType() == TopAbs_COMPOUND) {
343 for(TopoDS_Iterator aCompIter(aShapeOld); aCompIter.More(); aCompIter.Next()) {
344 if (isShapeInTree(aData->shapeLab(), anAccess2, aCompIter.Value(), anOriginalLabel)) {
345 anOldList.Append(aCompIter.Value());
353 anOldList.Append(aShapeOld);
355 if (anOldList.IsEmpty()) {
356 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
357 aBuilder->Generated(aShapeNew);
360 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
362 aBuilder = builder(0);
364 TopTools_ListIteratorOfListOfShape anOldIter(anOldList);
365 for(; anOldIter.More(); anOldIter.Next()) {
366 aBuilder->Modify(anOldIter.Value(), aShapeNew);
368 // store information about the external document reference to restore old shape on open
369 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
372 if(!aBuilder->NamedShape()->IsEmpty()) {
373 Handle(TDataStd_Name) anAttr;
374 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
375 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
377 std::shared_ptr<Model_Document> aDoc =
378 std::dynamic_pointer_cast<Model_Document>(document());
379 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
386 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
387 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
389 bool aStored = false;
390 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
391 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
392 // compounds may cause crash if call "modified"
393 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
394 (*anOldIter)->isCompSolid();
396 ListOfShape aNews; // check this old really modifies theNewShape
397 theMakeShape->modified(*anOldIter, aNews);
398 ListOfShape::iterator aNewIter = aNews.begin();
399 for(; aNewIter != aNews.end(); aNewIter++) {
400 if (theNewShape->isSame(*aNewIter))
403 aStore = aNewIter != aNews.end();
406 storeModified(*anOldIter, theNewShape, !aStored);
407 TNaming_Builder* aBuilder = builder(0);
408 aStored = !aBuilder->NamedShape()->IsEmpty();
412 // check the new shape is already in the tree, so, no need to store primitive, just reference
413 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
415 TDF_Label aShapeLab = aData->shapeLab();
416 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
417 Handle(TNaming_NamedShape) aNS;
418 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
419 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
420 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
421 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
422 // This shape is already in document, store reference instead of shape;
423 const TDF_Label aFoundLabel = aNS->Label();
424 TDF_Reference::Set(aShapeLab, aFoundLabel);
426 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
430 store(theNewShape); // store as PRIMITIVE, but clean in any way
435 void Model_BodyBuilder::clean()
437 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
440 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
441 for(; aBuilder != myBuilders.end(); aBuilder++) {
442 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
443 delete aBuilder->second;
444 if (!aNS.IsNull() && !aNS->Label().IsNull())
445 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
448 myPrimitivesNamesIndexMap.clear();
449 // remove the old reference (if any)
450 aLab.ForgetAttribute(TDF_Reference::GetID());
451 myFreePrimitiveTag = PRIMITIVES_START_TAG;
452 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
453 for(; anEntriesIter.More(); anEntriesIter.Next()) {
454 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
458 void Model_BodyBuilder::cleanCash()
460 myPrimitivesNamesIndexMap.clear();
463 Model_BodyBuilder::~Model_BodyBuilder()
468 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
470 std::string aName = theName;
471 std::string aPrefix = "";
473 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
474 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
475 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
476 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
477 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
478 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
480 aName.insert(0, aPrefix);
482 TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
484 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
485 const std::string& theName,
486 const bool theCheckIsInResult)
488 GeomShapePtr aResultShape = shape();
489 if (theCheckIsInResult) {
490 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
491 if (aNewShapeIsNotInResultShape) {
496 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
497 builder(myFreePrimitiveTag)->Generated(aShape);
498 if (!theName.empty()) {
499 std::string aName = theName;
500 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
501 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
502 aName += "_" + std::to_string(++(anIndexTags.index));
503 anIndexTags.tags.push_back(myFreePrimitiveTag);
504 if (anIndexTags.index == 2) {
505 buildName(anIndexTags.tags.front(), theName + "_1");
509 IndexTags anIndexTags;
510 anIndexTags.index = 1;
511 anIndexTags.tags.push_back(myFreePrimitiveTag);
512 myPrimitivesNamesIndexMap[theName] = anIndexTags;
515 buildName(myFreePrimitiveTag, aName);
517 ++myFreePrimitiveTag;
521 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
522 const GeomShapePtr& theNewShape,
523 const std::string& theName)
525 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
526 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
527 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
529 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
530 // TODO: This is a workaround. New shape should be only vertex, edge or face.
531 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
532 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
533 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
534 builder(aTag)->Generated(anOldShape, anExp.Current());
536 buildName(aTag, theName);
538 aTag = getGenerationTag(aNewShape);
539 if (aTag == INVALID_TAG) return;
540 builder(aTag)->Generated(anOldShape, aNewShape);
541 buildName(aTag, theName);
545 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
546 const GeomShapePtr& theNewShape,
547 const std::string& theName)
549 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
550 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
551 int aTag = getModificationTag(aNewShape);
552 if (aTag == INVALID_TAG) return;
553 builder(aTag)->Modify(anOldShape, aNewShape);
554 buildName(aTag, theName);
557 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
558 const GeomShapePtr& theOldShape,
559 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
560 const GeomShapePtr& theShapesToExclude)
562 TopTools_MapOfShape anAlreadyProcessedShapes;
563 GeomShapePtr aResultShape = shape();
564 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
568 GeomShapePtr anOldSubShape = anExp.current();
569 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
570 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
571 || !theAlgo->isDeleted(anOldSubShape)
572 || aResultShape->isSubShape(anOldSubShape, false)
573 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
578 ListOfShape aNewShapes;
579 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
580 theAlgo->modified(anOldSubShape, aNewShapes);
583 if (aNewShapes.size() == 0
584 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
585 builder(DELETED_TAG)->Delete(anOldSubShape_);
590 // Keep only the shapes with minimal shape type
591 static void keepTopLevelShapes(ListOfShape& theShapes,
592 const TopoDS_Shape& theRoot,
593 const GeomShapePtr& theResultShape = GeomShapePtr())
595 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
596 ListOfShape::iterator anIt = theShapes.begin();
597 while (anIt != theShapes.end()) {
598 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
599 bool aSkip = aNewShape.IsNull() ||
600 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
601 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
602 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
603 ListOfShape::iterator aRemoveIt = anIt++;
604 theShapes.erase(aRemoveIt);
606 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
607 if (aType < aKeepShapeType) {
608 // found a shape with lesser shape type => remove all previous shapes
609 aKeepShapeType = aType;
610 theShapes.erase(theShapes.begin(), anIt);
612 } else if (aType > aKeepShapeType) {
613 // shapes with greater shape type should be removed from the list
614 ListOfShape::iterator aRemoveIt = anIt++;
615 theShapes.erase(aRemoveIt);
622 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
623 const GeomShapePtr& theOldShape,
624 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
625 const std::string& theName)
627 GeomShapePtr aResultShape = shape();
628 GeomShapePtr aShapeToExplore = theOldShape;
629 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
630 // use optimized set of old shapes for this
631 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
633 theShapeTypeToExplore);
634 if (aCompound.get()) aShapeToExplore = aCompound;
637 TopTools_MapOfShape anAlreadyProcessedShapes;
638 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
639 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
640 anOldShapeExp.more();
641 anOldShapeExp.next())
643 GeomShapePtr anOldSubShape = anOldShapeExp.current();
644 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
646 // There is no sense to write history if shape already processed
647 // or old shape does not exist in the document.
648 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
649 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
650 ModelAPI_Session::get()->moduleDocument())->generalLabel();
651 TDF_Label anOriginalLabel;
652 bool anOldSubShapeNotInTree =
653 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
654 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
659 ListOfShape aNewShapes;
660 theAlgo->modified(anOldSubShape, aNewShapes);
662 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
663 aNewShapesIt != aNewShapes.cend();
666 GeomShapePtr aNewShape = *aNewShapesIt;
667 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
668 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
670 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
671 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
672 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
675 if (aResultShape->isSame(aNewShape))
676 continue; // it is stored on the root level (2241 - history propagation issue)
678 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
679 TNaming_Builder*aBuilder = builder(aTag);
680 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
681 continue; // new shape was already stored.
683 buildName(aTag, theName);
684 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
685 : aBuilder->Modify(anOldSubShape_, aNewShape_);
686 // store information about the external document reference to restore old shape on open
687 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
692 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
693 const GeomShapePtr& theOldShape,
694 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
695 const std::string& theName,
696 const bool theSaveOldIfNotInTree)
698 GeomShapePtr aResultShape = shape();
699 TopTools_MapOfShape anAlreadyProcessedShapes;
700 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
701 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
702 anOldShapeExp.more();
703 anOldShapeExp.next())
705 GeomShapePtr anOldSubShape = anOldShapeExp.current();
706 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
708 // There is no sense to write history if shape already processed
709 // or old shape does not exist in the document.
710 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
711 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
712 ModelAPI_Session::get()->moduleDocument())->generalLabel();
713 TDF_Label anOriginalLabel;
714 bool anOldSubShapeNotInTree =
715 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
716 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
717 // The second condition is added due to #20170 because sub-shape must be added to real parent
718 // shape, not the reference. The naming name of pure reference is not registered in document.
719 if (theSaveOldIfNotInTree && !aData->shapeLab().IsAttribute(TDF_Reference::GetID())) {
720 std::string aSelectionName = theName + "Selected";
721 generated(anOldSubShape, aSelectionName, false);
727 ListOfShape aNewShapes;
728 theAlgo->generated(anOldSubShape, aNewShapes);
730 keepTopLevelShapes(aNewShapes, anOldSubShape_);
732 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
733 aNewShapesIt != aNewShapes.cend();
736 GeomShapePtr aNewShape = *aNewShapesIt;
737 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
739 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
740 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
741 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
745 if (aResultShape->isSame(aNewShape))
746 continue; // it is stored on the root level
748 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
749 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
750 // TODO: This is a workaround. New shape should be only edge or face.
751 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
753 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
754 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
755 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
756 // store information about the external document reference to restore old shape on open
757 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
759 buildName(aTag, theName);
761 int aTag = getGenerationTag(aNewShape_);
762 if (aTag == INVALID_TAG) return;
763 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
764 buildName(aTag, theName);
765 // store information about the external document reference to restore old shape on open
766 storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
773 //=======================================================================
774 int getDangleShapes(const TopoDS_Shape& theShapeIn,
775 const TopAbs_ShapeEnum theGeneratedFrom,
776 TopTools_DataMapOfShapeShape& theDangles)
779 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
780 TopAbs_ShapeEnum GeneratedTo;
781 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
782 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
783 else return Standard_False;
784 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
785 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
786 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
787 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
788 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
790 return theDangles.Extent();
793 //=======================================================================
794 void loadGeneratedDangleShapes(
795 const TopoDS_Shape& theShapeIn,
796 const TopAbs_ShapeEnum theGeneratedFrom,
797 TNaming_Builder * theBuilder)
799 TopTools_DataMapOfShapeShape dangles;
800 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
801 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
802 for (; itr.More(); itr.Next())
803 theBuilder->Generated(itr.Key(), itr.Value());
807 //=======================================================================
808 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
809 const std::string& theName)
811 if(theShape->isNull()) return;
812 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
814 if (aShape.ShapeType() == TopAbs_SOLID) {
815 TopExp_Explorer expl(aShape, TopAbs_FACE);
816 for (; expl.More(); expl.Next()) {
817 builder(myFreePrimitiveTag)->Generated(expl.Current());
818 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
819 aName = theName + "_" + aStr.ToCString();
820 buildName(myFreePrimitiveTag, aName);
821 ++myFreePrimitiveTag;
824 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
825 // load faces and all the free edges
826 TopTools_IndexedMapOfShape Faces;
827 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
828 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
829 TopExp_Explorer expl(aShape, TopAbs_FACE);
830 for (; expl.More(); expl.Next()) {
831 builder(myFreePrimitiveTag)->Generated(expl.Current());
832 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
833 aName = theName + "_" + aStr.ToCString();
834 buildName(myFreePrimitiveTag, aName);
835 ++myFreePrimitiveTag;
838 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
839 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
840 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
842 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
843 if (aLL.Extent() < 2) {
844 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
846 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
847 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
848 aName = theName + "_" + aStr.ToCString();
849 buildName(myFreePrimitiveTag, aName);
850 ++myFreePrimitiveTag;
852 TopTools_ListIteratorOfListOfShape anIter(aLL);
853 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
855 if(aFace.IsEqual(anIter.Value())) {
856 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
857 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
858 aName = theName + "_" + aStr.ToCString();
859 buildName(myFreePrimitiveTag, aName);
860 ++myFreePrimitiveTag;
864 } else if (aShape.ShapeType() == TopAbs_WIRE) {
865 TopTools_IndexedMapOfShape Edges;
866 BRepTools::Map3DEdges(aShape, Edges);
867 if (Edges.Extent() == 1) {
868 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
869 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
870 for (; expl.More(); expl.Next()) {
871 builder(myFreePrimitiveTag)->Generated(expl.Current());
872 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
873 aName = theName + "_" + aStr.ToCString();
874 buildName(myFreePrimitiveTag, aName);
875 ++myFreePrimitiveTag;
878 TopExp_Explorer expl(aShape, TopAbs_EDGE);
879 for (; expl.More(); expl.Next()) {
880 builder(myFreePrimitiveTag)->Generated(expl.Current());
881 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
882 aName = theName + "_" + aStr.ToCString();
883 buildName(myFreePrimitiveTag, aName);
884 ++myFreePrimitiveTag;
886 // and load generated vertices.
887 TopTools_DataMapOfShapeShape generated;
888 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
890 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
891 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
894 } else if (aShape.ShapeType() == TopAbs_EDGE) {
895 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
896 for (; expl.More(); expl.Next()) {
897 builder(myFreePrimitiveTag)->Generated(expl.Current());
898 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
899 aName = theName + "_" + aStr.ToCString();
900 buildName(myFreePrimitiveTag, aName);
901 ++myFreePrimitiveTag;
906 //=======================================================================
907 int findAmbiguities(const TopoDS_Shape& theShapeIn,
908 TopTools_ListOfShape& theList)
911 // edges -> ancestor faces list
912 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
913 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
914 // keeps the shapes which are already in the resulting list
915 TopTools_MapOfShape alreadyThere;
916 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
917 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
919 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
920 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
921 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
922 if (ancestors.Extent() < 2)
924 Standard_Integer anID = 0;
925 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
926 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
928 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
929 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
930 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
931 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
932 for(; aSameEdge.More(); aSameEdge.Next()) {
933 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
934 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
935 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
938 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
939 for(; aFaceIter1.More(); aFaceIter1.Next()) {
940 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
941 for(; aFaceIter2.More(); aFaceIter2.Next()) {
942 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
945 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
948 if (!aFaceIter1.More()) { // all the faces are same => put to the result
949 if (alreadyThere.Add(aSameEdge.Value()))
950 theList.Append(aSameEdge.Value());
951 if (alreadyThere.Add(anAncestorsIter.Key()))
952 theList.Append(anAncestorsIter.Key());
955 } else { // ID is unique, just add this edge
956 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
958 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
960 return theList.Extent();
963 //=======================================================================
964 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
966 GeomShapePtr aShapePtr = shape();
967 if (theShape->isNull() || !aShapePtr.get())
969 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
973 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
974 TopoDS_Iterator itr(aShape);
975 for (; itr.More(); itr.Next()) {
976 builder(myFreePrimitiveTag)->Generated(itr.Value());
977 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
978 aName = theName + "_" + aStr.ToCString();
979 buildName(myFreePrimitiveTag, aName);
980 ++myFreePrimitiveTag;
981 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
982 itr.Value().ShapeType() == TopAbs_COMPSOLID)
984 GeomShapePtr itrShape(new GeomAPI_Shape());
985 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
986 loadFirstLevel(itrShape, theName);
988 GeomShapePtr itrShape(new GeomAPI_Shape());
989 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
990 loadNextLevels(itrShape, theName);
994 GeomShapePtr itrShape(new GeomAPI_Shape());
995 itrShape->setImpl(new TopoDS_Shape(aShape));
996 loadNextLevels(itrShape, theName);
998 TopTools_ListOfShape aList;
999 if(findAmbiguities(aShape, aList)) {
1000 TopTools_ListIteratorOfListOfShape it(aList);
1001 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
1002 builder(myFreePrimitiveTag)->Generated(it.Value());
1003 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
1004 aName = theName + "_" + aStr.ToCString();
1005 buildName(myFreePrimitiveTag, aName);
1010 GeomShapePtr Model_BodyBuilder::shape()
1012 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
1013 if (aData && aData->isValid()) {
1014 TDF_Label aShapeLab = aData->shapeLab();
1015 Handle(TDF_Reference) aRef;
1016 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
1017 aShapeLab = aRef->Get();
1019 Handle(TNaming_NamedShape) aName;
1020 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
1021 TopoDS_Shape aShape = aName->Get();
1022 if (!aShape.IsNull()) {
1023 GeomShapePtr aRes(new GeomAPI_Shape);
1024 aRes->setImpl(new TopoDS_Shape(aShape));
1029 return GeomShapePtr();