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 <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;
89 static int getModificationTag(const TopoDS_Shape& theShape) {
90 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
92 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
93 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
94 case TopAbs_FACE: return MODIFIED_FACES_TAG;
100 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
101 const TopoDS_Shape& theOldShape,
102 const TopoDS_Shape& theNewShape)
104 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
108 if (aNamingIt.NewShape().IsSame(theNewShape)
109 && aNamingIt.OldShape().IsSame(theOldShape))
118 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
119 : ModelAPI_BodyBuilder(theOwner),
120 myFreePrimitiveTag(PRIMITIVES_START_TAG)
124 /// Checks that shape is presented in the tree with not-selection evolution
125 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
126 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
127 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
129 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
130 if (aResult) { //check evolution and a label of this shape
131 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
133 static Handle(TNaming_NamedShape) aNS;
134 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
135 if (aNS->Evolution() != TNaming_SELECTED) {
136 theOriginalLabel = aNS->Label();
142 if (!theAccess2.IsNull()) {
143 static const TDF_Label anEmpty;
144 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
149 /// Stores entry to the external label in the entries list at this label
150 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
152 // store information about the external document reference to restore old shape on open
153 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
154 Handle(TDataStd_ExtStringList) anEntries;
155 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
156 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
158 TCollection_AsciiString anEntry;
159 TDF_Tool::Entry(theExternal, anEntry);
160 // check it already contains this entry
161 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
162 for(; anIter.More(); anIter.Next())
163 if (anIter.Value() == anEntry)
165 if (!anIter.More()) {
166 anEntries->Append(anEntry);
171 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
172 const bool theIsStoreSameShapes)
174 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
176 TDF_Label aShapeLab = aData->shapeLab();
179 // store the new shape as primitive
180 TNaming_Builder aBuilder(aShapeLab);
183 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
185 return; // null shape inside
187 if(!theIsStoreSameShapes) {
188 Handle(TNaming_NamedShape) aNS;
189 if (TNaming_Tool::HasLabel(aShapeLab, aShape))
190 aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
191 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
192 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
193 // This shape is already in document, store reference instead of shape;
194 const TDF_Label aFoundLabel = aNS->Label();
195 TDF_Reference::Set(aShapeLab, aFoundLabel);
196 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
201 aBuilder.Generated(aShape);
203 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
204 if(!aBuilder.NamedShape()->IsEmpty()) {
205 Handle(TDataStd_Name) anAttr;
206 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
207 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
209 std::shared_ptr<Model_Document> aDoc =
210 std::dynamic_pointer_cast<Model_Document>(document());
211 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
218 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
219 const GeomShapePtr& theToShape, const bool theIsCleanStored)
221 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
223 TDF_Label aShapeLab = aData->shapeLab();
225 if (theIsCleanStored)
227 TNaming_Builder* aBuilder = builder(0);
228 if (!theFromShape || !theToShape)
230 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
231 if (aShapeBasis.IsNull())
232 return; // null shape inside
233 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
234 if (aShapeNew.IsNull())
235 return; // null shape inside
237 // There is no sense to write history if old shape does not exist in the document.
238 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
239 ModelAPI_Session::get()->moduleDocument())->generalLabel();
240 TDF_Label anOriginalLabel;
241 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
242 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
243 aBuilder->Generated(aShapeNew);
246 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
248 aBuilder = builder(0);
251 aBuilder->Generated(aShapeBasis, aShapeNew);
252 // store information about the external document reference to restore old shape on open
253 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
257 if(!aBuilder->NamedShape()->IsEmpty()) {
258 Handle(TDataStd_Name) anAttr;
259 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
260 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
262 std::shared_ptr<Model_Document> aDoc =
263 std::dynamic_pointer_cast<Model_Document>(document());
264 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
271 void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
272 const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
274 bool aStored = false;
275 std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
276 for (; anOldIter != theFromShapes.cend(); anOldIter++) {
277 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
279 ListOfShape aNews; // check this old really generates theToShape
280 theMakeShape->generated(*anOldIter, aNews);
281 ListOfShape::iterator aNewIter = aNews.begin();
282 for (; aNewIter != aNews.end(); aNewIter++) {
283 if (theToShape->isSame(*aNewIter))
286 aStore = aNewIter != aNews.end();
289 storeGenerated(*anOldIter, theToShape, !aStored);
290 TNaming_Builder* aBuilder = builder(0);
291 aStored = !aBuilder->NamedShape()->IsEmpty();
294 if (!aStored) { // store as PRIMITIVE, but clean in any way
300 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
302 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
303 if (aFind == myBuilders.end()) {
304 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
305 myBuilders[theTag] = new TNaming_Builder(
306 theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
307 aFind = myBuilders.find(theTag);
309 return aFind->second;
312 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
313 const GeomShapePtr& theNewShape,
314 const bool theIsCleanStored)
316 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
319 if (theIsCleanStored) clean();
320 TNaming_Builder* aBuilder = builder(0);
321 if (!theOldShape || !theNewShape)
323 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
324 if (aShapeOld.IsNull())
325 return; // null shape inside
326 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
327 if (aShapeNew.IsNull())
328 return; // null shape inside
330 // There is no sense to write history if old shape does not exist in the document.
331 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
332 ModelAPI_Session::get()->moduleDocument())->generalLabel();
333 TDF_Label anOriginalLabel;
334 if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
335 if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
336 aBuilder->Generated(aShapeNew);
339 if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
341 aBuilder = builder(0);
344 aBuilder->Modify(aShapeOld, aShapeNew);
345 // store information about the external document reference to restore old shape on open
346 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
349 if(!aBuilder->NamedShape()->IsEmpty()) {
350 Handle(TDataStd_Name) anAttr;
351 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
352 std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
354 std::shared_ptr<Model_Document> aDoc =
355 std::dynamic_pointer_cast<Model_Document>(document());
356 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
363 void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
364 const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
366 bool aStored = false;
367 std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
368 for(; anOldIter != theOldShapes.cend(); anOldIter++) {
369 // compounds may cause crash if call "modified"
370 bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
371 (*anOldIter)->isCompSolid();
373 ListOfShape aNews; // check this old really modifies theNewShape
374 theMakeShape->modified(*anOldIter, aNews);
375 ListOfShape::iterator aNewIter = aNews.begin();
376 for(; aNewIter != aNews.end(); aNewIter++) {
377 if (theNewShape->isSame(*aNewIter))
380 aStore = aNewIter != aNews.end();
383 storeModified(*anOldIter, theNewShape, !aStored);
384 TNaming_Builder* aBuilder = builder(0);
385 aStored = !aBuilder->NamedShape()->IsEmpty();
389 // check the new shape is already in the tree, so, no need to store primitive, just reference
390 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
392 TDF_Label aShapeLab = aData->shapeLab();
393 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
394 Handle(TNaming_NamedShape) aNS;
395 if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
396 aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
397 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
398 if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
399 // This shape is already in document, store reference instead of shape;
400 const TDF_Label aFoundLabel = aNS->Label();
401 TDF_Reference::Set(aShapeLab, aFoundLabel);
403 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
407 store(theNewShape); // store as PRIMITIVE, but clean in any way
412 void Model_BodyBuilder::clean()
414 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
417 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
418 for(; aBuilder != myBuilders.end(); aBuilder++) {
419 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
420 delete aBuilder->second;
421 if (!aNS.IsNull() && !aNS->Label().IsNull())
422 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
425 myPrimitivesNamesIndexMap.clear();
426 // remove the old reference (if any)
427 aLab.ForgetAttribute(TDF_Reference::GetID());
428 myFreePrimitiveTag = PRIMITIVES_START_TAG;
429 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
430 for(; anEntriesIter.More(); anEntriesIter.Next()) {
431 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
435 void Model_BodyBuilder::cleanCash()
437 myPrimitivesNamesIndexMap.clear();
440 Model_BodyBuilder::~Model_BodyBuilder()
445 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
447 std::string aName = theName;
448 std::string aPrefix = "";
450 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
451 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
452 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
453 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
454 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
455 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
457 aName.insert(0, aPrefix);
459 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
461 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
462 const std::string& theName,
463 const bool theCheckIsInResult)
465 GeomShapePtr aResultShape = shape();
466 if (theCheckIsInResult) {
467 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
468 if (aNewShapeIsNotInResultShape) {
473 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
474 builder(myFreePrimitiveTag)->Generated(aShape);
475 if (!theName.empty()) {
476 std::string aName = theName;
477 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
478 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
479 aName += "_" + std::to_string(++(anIndexTags.index));
480 anIndexTags.tags.push_back(myFreePrimitiveTag);
481 if (anIndexTags.index == 2) {
482 buildName(anIndexTags.tags.front(), theName + "_1");
486 IndexTags anIndexTags;
487 anIndexTags.index = 1;
488 anIndexTags.tags.push_back(myFreePrimitiveTag);
489 myPrimitivesNamesIndexMap[theName] = anIndexTags;
492 buildName(myFreePrimitiveTag, aName);
494 ++myFreePrimitiveTag;
498 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
499 const GeomShapePtr& theNewShape,
500 const std::string& theName)
502 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
503 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
504 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
506 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
507 // TODO: This is a workaround. New shape should be only vertex, edge or face.
508 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
509 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
510 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
511 builder(aTag)->Generated(anOldShape, anExp.Current());
513 buildName(aTag, theName);
515 aTag = getGenerationTag(aNewShape);
516 if (aTag == INVALID_TAG) return;
517 builder(aTag)->Generated(anOldShape, aNewShape);
518 buildName(aTag, theName);
522 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
523 const GeomShapePtr& theNewShape,
524 const std::string& theName)
526 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
527 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
528 int aTag = getModificationTag(aNewShape);
529 if (aTag == INVALID_TAG) return;
530 builder(aTag)->Modify(anOldShape, aNewShape);
531 buildName(aTag, theName);
534 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
535 const GeomShapePtr& theOldShape,
536 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
537 const GeomShapePtr& theShapesToExclude)
539 TopTools_MapOfShape anAlreadyProcessedShapes;
540 GeomShapePtr aResultShape = shape();
541 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
545 GeomShapePtr anOldSubShape = anExp.current();
546 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
547 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
548 || !theAlgo->isDeleted(anOldSubShape)
549 || aResultShape->isSubShape(anOldSubShape, false)
550 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
555 ListOfShape aNewShapes;
556 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
557 theAlgo->modified(anOldSubShape, aNewShapes);
560 if (aNewShapes.size() == 0
561 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
562 builder(DELETED_TAG)->Delete(anOldSubShape_);
567 // Keep only the shapes with minimal shape type
568 static void keepTopLevelShapes(ListOfShape& theShapes,
569 const TopoDS_Shape& theRoot,
570 const GeomShapePtr& theResultShape = GeomShapePtr())
572 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
573 ListOfShape::iterator anIt = theShapes.begin();
574 while (anIt != theShapes.end()) {
575 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
576 bool aSkip = aNewShape.IsNull() ||
577 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
578 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
579 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
580 ListOfShape::iterator aRemoveIt = anIt++;
581 theShapes.erase(aRemoveIt);
583 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
584 if (aType < aKeepShapeType) {
585 // found a shape with lesser shape type => remove all previous shapes
586 aKeepShapeType = aType;
587 theShapes.erase(theShapes.begin(), anIt);
589 } else if (aType > aKeepShapeType) {
590 // shapes with greater shape type should be removed from the list
591 ListOfShape::iterator aRemoveIt = anIt++;
592 theShapes.erase(aRemoveIt);
599 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
600 const GeomShapePtr& theOldShape,
601 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
602 const std::string& theName)
604 GeomShapePtr aResultShape = shape();
605 GeomShapePtr aShapeToExplore = theOldShape;
606 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
607 // use optimized set of old shapes for this
608 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
610 theShapeTypeToExplore);
611 if (aCompound.get()) aShapeToExplore = aCompound;
614 TopTools_MapOfShape anAlreadyProcessedShapes;
615 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
616 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
617 anOldShapeExp.more();
618 anOldShapeExp.next())
620 GeomShapePtr anOldSubShape = anOldShapeExp.current();
621 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
623 // There is no sense to write history if shape already processed
624 // or old shape does not exist in the document.
625 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
626 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
627 ModelAPI_Session::get()->moduleDocument())->generalLabel();
628 TDF_Label anOriginalLabel;
629 bool anOldSubShapeNotInTree =
630 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
631 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
636 ListOfShape aNewShapes;
637 theAlgo->modified(anOldSubShape, aNewShapes);
639 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
640 aNewShapesIt != aNewShapes.cend();
643 GeomShapePtr aNewShape = *aNewShapesIt;
644 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
645 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
647 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
648 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
649 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape)
652 if (aResultShape->isSame(aNewShape))
653 continue; // it is stored on the root level (2241 - history propagation issue)
655 int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
656 TNaming_Builder*aBuilder = builder(aTag);
657 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
658 continue; // new shape was already stored.
660 buildName(aTag, theName);
661 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
662 : aBuilder->Modify(anOldSubShape_, aNewShape_);
663 // store information about the external document reference to restore old shape on open
664 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
669 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
670 const GeomShapePtr& theOldShape,
671 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
672 const std::string& theName,
673 const bool theSaveOldIfNotInTree)
675 GeomShapePtr aResultShape = shape();
676 TopTools_MapOfShape anAlreadyProcessedShapes;
677 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
678 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
679 anOldShapeExp.more();
680 anOldShapeExp.next())
682 GeomShapePtr anOldSubShape = anOldShapeExp.current();
683 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
685 // There is no sense to write history if shape already processed
686 // or old shape does not exist in the document.
687 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
688 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
689 ModelAPI_Session::get()->moduleDocument())->generalLabel();
690 TDF_Label anOriginalLabel;
691 bool anOldSubShapeNotInTree =
692 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
693 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
694 if (theSaveOldIfNotInTree) {
695 std::string aSelectionName = theName + "Selected";
696 generated(anOldSubShape, aSelectionName, false);
702 ListOfShape aNewShapes;
703 theAlgo->generated(anOldSubShape, aNewShapes);
705 keepTopLevelShapes(aNewShapes, anOldSubShape_);
707 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
708 aNewShapesIt != aNewShapes.cend();
711 GeomShapePtr aNewShape = *aNewShapesIt;
712 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
714 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
715 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
716 if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
720 if (aResultShape->isSame(aNewShape))
721 continue; // it is stored on the root level
723 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
724 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
725 // TODO: This is a workaround. New shape should be only edge or face.
726 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
728 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
729 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
730 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
731 // store information about the external document reference to restore old shape on open
732 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
734 buildName(aTag, theName);
736 int aTag = getGenerationTag(aNewShape_);
737 if (aTag == INVALID_TAG) return;
738 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
739 buildName(aTag, theName);
740 // store information about the external document reference to restore old shape on open
741 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
748 //=======================================================================
749 int getDangleShapes(const TopoDS_Shape& theShapeIn,
750 const TopAbs_ShapeEnum theGeneratedFrom,
751 TopTools_DataMapOfShapeShape& theDangles)
754 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
755 TopAbs_ShapeEnum GeneratedTo;
756 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
757 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
758 else return Standard_False;
759 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
760 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
761 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
762 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
763 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
765 return theDangles.Extent();
768 //=======================================================================
769 void loadGeneratedDangleShapes(
770 const TopoDS_Shape& theShapeIn,
771 const TopAbs_ShapeEnum theGeneratedFrom,
772 TNaming_Builder * theBuilder)
774 TopTools_DataMapOfShapeShape dangles;
775 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
776 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
777 for (; itr.More(); itr.Next())
778 theBuilder->Generated(itr.Key(), itr.Value());
782 //=======================================================================
783 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
784 const std::string& theName)
786 if(theShape->isNull()) return;
787 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
789 if (aShape.ShapeType() == TopAbs_SOLID) {
790 TopExp_Explorer expl(aShape, TopAbs_FACE);
791 for (; expl.More(); expl.Next()) {
792 builder(myFreePrimitiveTag)->Generated(expl.Current());
793 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
794 aName = theName + "_" + aStr.ToCString();
795 buildName(myFreePrimitiveTag, aName);
796 ++myFreePrimitiveTag;
799 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
800 // load faces and all the free edges
801 TopTools_IndexedMapOfShape Faces;
802 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
803 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
804 TopExp_Explorer expl(aShape, TopAbs_FACE);
805 for (; expl.More(); expl.Next()) {
806 builder(myFreePrimitiveTag)->Generated(expl.Current());
807 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
808 aName = theName + "_" + aStr.ToCString();
809 buildName(myFreePrimitiveTag, aName);
810 ++myFreePrimitiveTag;
813 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
814 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
815 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
817 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
818 if (aLL.Extent() < 2) {
819 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
821 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
822 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
823 aName = theName + "_" + aStr.ToCString();
824 buildName(myFreePrimitiveTag, aName);
825 ++myFreePrimitiveTag;
827 TopTools_ListIteratorOfListOfShape anIter(aLL);
828 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
830 if(aFace.IsEqual(anIter.Value())) {
831 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
832 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
833 aName = theName + "_" + aStr.ToCString();
834 buildName(myFreePrimitiveTag, aName);
835 ++myFreePrimitiveTag;
839 } else if (aShape.ShapeType() == TopAbs_WIRE) {
840 TopTools_IndexedMapOfShape Edges;
841 BRepTools::Map3DEdges(aShape, Edges);
842 if (Edges.Extent() == 1) {
843 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
844 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
845 for (; expl.More(); expl.Next()) {
846 builder(myFreePrimitiveTag)->Generated(expl.Current());
847 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
848 aName = theName + "_" + aStr.ToCString();
849 buildName(myFreePrimitiveTag, aName);
850 ++myFreePrimitiveTag;
853 TopExp_Explorer expl(aShape, TopAbs_EDGE);
854 for (; expl.More(); expl.Next()) {
855 builder(myFreePrimitiveTag)->Generated(expl.Current());
856 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
857 aName = theName + "_" + aStr.ToCString();
858 buildName(myFreePrimitiveTag, aName);
859 ++myFreePrimitiveTag;
861 // and load generated vertices.
862 TopTools_DataMapOfShapeShape generated;
863 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
865 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
866 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
869 } else if (aShape.ShapeType() == TopAbs_EDGE) {
870 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
871 for (; expl.More(); expl.Next()) {
872 builder(myFreePrimitiveTag)->Generated(expl.Current());
873 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
874 aName = theName + "_" + aStr.ToCString();
875 buildName(myFreePrimitiveTag, aName);
876 ++myFreePrimitiveTag;
881 //=======================================================================
882 int findAmbiguities(const TopoDS_Shape& theShapeIn,
883 TopTools_ListOfShape& theList)
886 // edges -> ancestor faces list
887 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
888 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
889 // keeps the shapes which are already in the resulting list
890 TopTools_MapOfShape alreadyThere;
891 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
892 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
894 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
895 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
896 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
897 if (ancestors.Extent() < 2)
899 Standard_Integer anID = 0;
900 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
901 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
903 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
904 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
905 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
906 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
907 for(; aSameEdge.More(); aSameEdge.Next()) {
908 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
909 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
910 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
913 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
914 for(; aFaceIter1.More(); aFaceIter1.Next()) {
915 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
916 for(; aFaceIter2.More(); aFaceIter2.Next()) {
917 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
920 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
923 if (!aFaceIter1.More()) { // all the faces are same => put to the result
924 if (alreadyThere.Add(aSameEdge.Value()))
925 theList.Append(aSameEdge.Value());
926 if (alreadyThere.Add(anAncestorsIter.Key()))
927 theList.Append(anAncestorsIter.Key());
930 } else { // ID is unique, just add this edge
931 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
933 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
935 return theList.Extent();
938 //=======================================================================
939 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
941 GeomShapePtr aShapePtr = shape();
942 if (theShape->isNull() || !aShapePtr.get())
944 TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
948 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
949 TopoDS_Iterator itr(aShape);
950 for (; itr.More(); itr.Next()) {
951 builder(myFreePrimitiveTag)->Generated(itr.Value());
952 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
953 aName = theName + "_" + aStr.ToCString();
954 buildName(myFreePrimitiveTag, aName);
955 ++myFreePrimitiveTag;
956 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
957 itr.Value().ShapeType() == TopAbs_COMPSOLID)
959 GeomShapePtr itrShape(new GeomAPI_Shape());
960 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
961 loadFirstLevel(itrShape, theName);
963 GeomShapePtr itrShape(new GeomAPI_Shape());
964 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
965 loadNextLevels(itrShape, theName);
969 GeomShapePtr itrShape(new GeomAPI_Shape());
970 itrShape->setImpl(new TopoDS_Shape(aShape));
971 loadNextLevels(itrShape, theName);
973 TopTools_ListOfShape aList;
974 if(findAmbiguities(aShape, aList)) {
975 TopTools_ListIteratorOfListOfShape it(aList);
976 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
977 builder(myFreePrimitiveTag)->Generated(it.Value());
978 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
979 aName = theName + "_" + aStr.ToCString();
980 buildName(myFreePrimitiveTag, aName);
985 GeomShapePtr Model_BodyBuilder::shape()
987 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
988 if (aData && aData->isValid()) {
989 TDF_Label aShapeLab = aData->shapeLab();
990 Handle(TDF_Reference) aRef;
991 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
992 aShapeLab = aRef->Get();
994 Handle(TNaming_NamedShape) aName;
995 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
996 TopoDS_Shape aShape = aName->Get();
997 if (!aShape.IsNull()) {
998 GeomShapePtr aRes(new GeomAPI_Shape);
999 aRes->setImpl(new TopoDS_Shape(aShape));
1004 return GeomShapePtr();