1 // Copyright (C) 2014-2017 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
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
21 #include <Model_BodyBuilder.h>
23 #include <Model_Data.h>
24 #include <Model_Document.h>
25 #include <ModelAPI_Session.h>
26 #include <TNaming_Builder.hxx>
27 #include <TNaming_NamedShape.hxx>
28 #include <TNaming_Iterator.hxx>
29 #include <TNaming_Tool.hxx>
30 #include <TNaming_SameShapeIterator.hxx>
31 #include <TDataStd_Name.hxx>
32 #include <TDataStd_Integer.hxx>
33 #include <TDataStd_ExtStringList.hxx>
35 #include <TopoDS_Face.hxx>
36 #include <TDF_ChildIterator.hxx>
37 #include <TDF_ChildIDIterator.hxx>
38 #include <TDF_Reference.hxx>
39 #include <TDF_Tool.hxx>
40 #include <TopTools_MapOfShape.hxx>
41 #include <TopExp_Explorer.hxx>
42 #include <TopTools_ListOfShape.hxx>
43 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <TopTools_DataMapOfShapeListOfShape.hxx>
45 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
46 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
47 #include <TopTools_MapIteratorOfMapOfShape.hxx>
48 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
49 #include <TopTools_IndexedMapOfShape.hxx>
50 #include <TopTools_DataMapOfShapeShape.hxx>
52 #include <BRepTools.hxx>
53 #include <BRep_Tool.hxx>
54 #include <BRepTools_History.hxx>
55 #include <GeomAPI_Shape.h>
56 #include <GeomAPI_ShapeExplorer.h>
57 #include <GeomAlgoAPI_MakeShape.h>
58 #include <GeomAlgoAPI_SortListOfShapes.h>
59 #include <Config_PropManager.h>
61 //#include <TCollection_AsciiString.hxx>
62 //#define DEB_IMPORT 1
64 /// reference to the shape in external document: sting list attribute identifier
65 static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
67 static const int INVALID_TAG = -1;
68 static const int GENERATED_VERTICES_TAG = 1;
69 static const int GENERATED_EDGES_TAG = 2;
70 static const int GENERATED_FACES_TAG = 3;
71 static const int MODIFIED_VERTICES_TAG = 4;
72 static const int MODIFIED_EDGES_TAG = 5;
73 static const int MODIFIED_FACES_TAG = 6;
74 static const int DELETED_TAG = 7;
75 static const int PRIMITIVES_START_TAG = 11;
77 static int getGenerationTag(const TopoDS_Shape& theShape) {
78 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
80 case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
81 case TopAbs_EDGE: return GENERATED_EDGES_TAG;
82 case TopAbs_FACE: return GENERATED_FACES_TAG;
88 static int getModificationTag(const TopoDS_Shape& theShape) {
89 TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
91 case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
92 case TopAbs_EDGE: return MODIFIED_EDGES_TAG;
93 case TopAbs_FACE: return MODIFIED_FACES_TAG;
99 static bool isAlreadyStored(const TNaming_Builder* theBuilder,
100 const TopoDS_Shape& theOldShape,
101 const TopoDS_Shape& theNewShape)
103 for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
107 if (aNamingIt.NewShape().IsSame(theNewShape)
108 && aNamingIt.OldShape().IsSame(theOldShape))
117 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
118 : ModelAPI_BodyBuilder(theOwner),
119 myFreePrimitiveTag(PRIMITIVES_START_TAG)
123 void Model_BodyBuilder::store(const GeomShapePtr& theShape,
124 const bool theIsStoreSameShapes)
126 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
128 TDF_Label aShapeLab = aData->shapeLab();
131 // store the new shape as primitive
132 TNaming_Builder aBuilder(aShapeLab);
135 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
137 return; // null shape inside
139 if(!theIsStoreSameShapes) {
140 Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
141 // the last condition is for the issue 2751 : existing shape may be found in compound-NS
142 if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
143 // This shape is already in document, store reference instead of shape;
144 const TDF_Label aFoundLabel = aNS->Label();
145 TDF_Reference::Set(aShapeLab, aFoundLabel);
146 aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
151 aBuilder.Generated(aShape);
153 aShapeLab.ForgetAttribute(TDF_Reference::GetID());
154 if(!aBuilder.NamedShape()->IsEmpty()) {
155 Handle(TDataStd_Name) anAttr;
156 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
157 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
159 std::shared_ptr<Model_Document> aDoc =
160 std::dynamic_pointer_cast<Model_Document>(document());
161 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
168 void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
169 const GeomShapePtr& theToShape)
171 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
173 TDF_Label aShapeLab = aData->shapeLab();
176 // store the new shape as primitive
177 TNaming_Builder aBuilder(aShapeLab);
178 if (!theFromShape || !theToShape)
180 TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
181 if (aShapeBasis.IsNull())
182 return; // null shape inside
183 TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
184 if (aShapeNew.IsNull())
185 return; // null shape inside
186 aBuilder.Generated(aShapeBasis, aShapeNew);
188 if(!aBuilder.NamedShape()->IsEmpty()) {
189 Handle(TDataStd_Name) anAttr;
190 if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
191 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
193 std::shared_ptr<Model_Document> aDoc =
194 std::dynamic_pointer_cast<Model_Document>(document());
195 aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
202 TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
204 std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
205 if (aFind == myBuilders.end()) {
206 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
207 myBuilders[theTag] = new TNaming_Builder(
208 theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
209 aFind = myBuilders.find(theTag);
211 return aFind->second;
214 void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
215 const GeomShapePtr& theNewShape,
216 const bool theIsCleanStored)
218 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
221 if (theIsCleanStored) clean();
222 // store the new shape as primitive
223 TNaming_Builder* aBuilder = builder(0);
224 if (!theOldShape || !theNewShape)
226 TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
227 if (aShapeOld.IsNull())
228 return; // null shape inside
229 TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
230 if (aShapeNew.IsNull())
231 return; // null shape inside
232 aBuilder->Modify(aShapeOld, aShapeNew);
233 if(!aBuilder->NamedShape()->IsEmpty()) {
234 Handle(TDataStd_Name) anAttr;
235 if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
236 std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
238 std::shared_ptr<Model_Document> aDoc =
239 std::dynamic_pointer_cast<Model_Document>(document());
240 aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
247 void Model_BodyBuilder::clean()
249 TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
252 std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
253 for(; aBuilder != myBuilders.end(); aBuilder++) {
254 Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
255 delete aBuilder->second;
256 if (!aNS.IsNull() && !aNS->Label().IsNull())
257 aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
260 myPrimitivesNamesIndexMap.clear();
261 // remove the old reference (if any)
262 aLab.ForgetAttribute(TDF_Reference::GetID());
263 myFreePrimitiveTag = PRIMITIVES_START_TAG;
264 TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
265 for(; anEntriesIter.More(); anEntriesIter.Next()) {
266 anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
270 void Model_BodyBuilder::cleanCash()
272 myPrimitivesNamesIndexMap.clear();
275 Model_BodyBuilder::~Model_BodyBuilder()
280 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
282 std::string aName = theName;
283 std::string aPrefix = "";
285 case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
286 case GENERATED_EDGES_TAG: aPrefix = aName.empty() ? "Generated_Edge" : "GE:"; break;
287 case GENERATED_FACES_TAG: aPrefix = aName.empty() ? "Generated_Face" : "GF:"; break;
288 case MODIFIED_VERTICES_TAG: aPrefix = aName.empty() ? "Modified_Vertex" : "MV:"; break;
289 case MODIFIED_EDGES_TAG: aPrefix = aName.empty() ? "Modified_Edge" : "ME:"; break;
290 case MODIFIED_FACES_TAG: aPrefix = aName.empty() ? "Modified_Face" : "MF:"; break;
292 aName.insert(0, aPrefix);
294 TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), aName.c_str());
296 bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
297 const std::string& theName,
298 const bool theCheckIsInResult)
300 GeomShapePtr aResultShape = shape();
301 if (theCheckIsInResult) {
302 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
303 if (aNewShapeIsNotInResultShape) {
308 TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
309 builder(myFreePrimitiveTag)->Generated(aShape);
310 if (!theName.empty()) {
311 std::string aName = theName;
312 if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
313 IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
314 aName += "_" + std::to_string(++(anIndexTags.index));
315 anIndexTags.tags.push_back(myFreePrimitiveTag);
316 if (anIndexTags.index == 2) {
317 buildName(anIndexTags.tags.front(), theName + "_1");
321 IndexTags anIndexTags;
322 anIndexTags.index = 1;
323 anIndexTags.tags.push_back(myFreePrimitiveTag);
324 myPrimitivesNamesIndexMap[theName] = anIndexTags;
327 buildName(myFreePrimitiveTag, aName);
329 ++myFreePrimitiveTag;
333 void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
334 const GeomShapePtr& theNewShape,
335 const std::string& theName)
337 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
338 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
339 TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
341 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
342 // TODO: This is a workaround. New shape should be only vertex, edge or face.
343 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
344 aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
345 for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
346 builder(aTag)->Generated(anOldShape, anExp.Current());
348 buildName(aTag, theName);
350 aTag = getGenerationTag(aNewShape);
351 if (aTag == INVALID_TAG) return;
352 builder(aTag)->Generated(anOldShape, aNewShape);
353 buildName(aTag, theName);
357 void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
358 const GeomShapePtr& theNewShape,
359 const std::string& theName)
361 TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
362 TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
363 int aTag = getModificationTag(aNewShape);
364 if (aTag == INVALID_TAG) return;
365 builder(aTag)->Modify(anOldShape, aNewShape);
366 buildName(aTag, theName);
369 void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
370 const GeomShapePtr& theOldShape,
371 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
372 const GeomShapePtr& theShapesToExclude)
374 TopTools_MapOfShape anAlreadyProcessedShapes;
375 GeomShapePtr aResultShape = shape();
376 for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
380 GeomShapePtr anOldSubShape = anExp.current();
381 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
382 if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
383 || !theAlgo->isDeleted(anOldSubShape)
384 || aResultShape->isSubShape(anOldSubShape, false)
385 || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
390 ListOfShape aNewShapes;
391 if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
392 theAlgo->modified(anOldSubShape, aNewShapes);
395 if (aNewShapes.size() == 0
396 || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
397 builder(DELETED_TAG)->Delete(anOldSubShape_);
402 // Keep only the shapes with minimal shape type
403 static void keepTopLevelShapes(ListOfShape& theShapes,
404 const TopoDS_Shape& theRoot,
405 const GeomShapePtr& theResultShape = GeomShapePtr())
407 GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
408 ListOfShape::iterator anIt = theShapes.begin();
409 while (anIt != theShapes.end()) {
410 TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
411 bool aSkip = aNewShape.IsNull() ||
412 (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
413 if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
414 (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
415 ListOfShape::iterator aRemoveIt = anIt++;
416 theShapes.erase(aRemoveIt);
418 GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
419 if (aType < aKeepShapeType) {
420 // found a shape with lesser shape type => remove all previous shapes
421 aKeepShapeType = aType;
422 theShapes.erase(theShapes.begin(), anIt);
424 } else if (aType > aKeepShapeType) {
425 // shapes with greater shape type should be removed from the list
426 ListOfShape::iterator aRemoveIt = anIt++;
427 theShapes.erase(aRemoveIt);
434 /// Checks that shape is presented in the tree with not-selection evolution
435 /// In theOriginalLabel it returns label where NS of old sub-shape is stored
436 static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
437 TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
439 bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
440 if (aResult) { //check evolution and a label of this shape
441 for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
443 static Handle(TNaming_NamedShape) aNS;
444 if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
445 if (aNS->Evolution() != TNaming_SELECTED) {
446 theOriginalLabel = aNS->Label();
452 if (!theAccess2.IsNull()) {
453 static const TDF_Label anEmpty;
454 return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
459 /// Stores entry to the external label in the entries list at this label
460 static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
462 // store information about the external document reference to restore old shape on open
463 if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
464 Handle(TDataStd_ExtStringList) anEntries;
465 if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
466 anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
468 TCollection_AsciiString anEntry;
469 TDF_Tool::Entry(theExternal, anEntry);
470 // check it already contains this entry
471 TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
472 for(; anIter.More(); anIter.Next())
473 if (anIter.Value() == anEntry)
475 if (!anIter.More()) {
476 anEntries->Append(anEntry);
481 void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
482 const GeomShapePtr& theOldShape,
483 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
484 const std::string& theName)
486 GeomShapePtr aResultShape = shape();
487 GeomShapePtr aShapeToExplore = theOldShape;
488 if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
489 // use optimized set of old shapes for this
490 GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
492 theShapeTypeToExplore);
493 if (aCompound.get()) aShapeToExplore = aCompound;
496 TopTools_MapOfShape anAlreadyProcessedShapes;
497 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
498 for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
499 anOldShapeExp.more();
500 anOldShapeExp.next())
502 GeomShapePtr anOldSubShape = anOldShapeExp.current();
503 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
505 // There is no sense to write history if shape already processed
506 // or old shape does not exist in the document.
507 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
508 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
509 ModelAPI_Session::get()->moduleDocument())->generalLabel();
510 TDF_Label anOriginalLabel;
511 bool anOldSubShapeNotInTree =
512 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
513 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
518 ListOfShape aNewShapes;
519 theAlgo->modified(anOldSubShape, aNewShapes);
521 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
522 aNewShapesIt != aNewShapes.cend();
525 GeomShapePtr aNewShape = *aNewShapesIt;
526 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
527 bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
529 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
530 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
531 if (aNewShapeIsSameAsOldShape
532 || aNewShapeIsNotInResultShape)
537 TNaming_Builder* aBuilder;
538 if (aResultShape->isSame(aNewShape)) {
539 // keep the modification evolution on the root level (2241 - history propagation issue)
540 aBuilder = builder(0);
541 TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
542 Handle(TDF_Reference) aRef;
543 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
544 // Store only in case if it does not have reference.
548 // Check if new shape was already stored.
549 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
551 if (!aBuilder->NamedShape().IsNull() &&
552 ((isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_GENERATED)
553 || (!isGenerated && aBuilder->NamedShape()->Evolution() != TNaming_MODIFY)))
555 myBuilders.erase(0); // clear old builder to avoid different evolutions crash
556 aBuilder = builder(0);
559 int aTag = isGenerated ? getGenerationTag(aNewShape_)
560 : getModificationTag(aNewShape_);
561 aBuilder = builder(aTag);
563 // Check if new shape was already stored.
564 if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_)) continue;
566 buildName(aTag, theName);
569 isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
570 : aBuilder->Modify(anOldSubShape_, aNewShape_);
571 // store information about the external document reference to restore old shape on open
572 storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
577 void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
578 const GeomShapePtr& theOldShape,
579 const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
580 const std::string& theName)
582 GeomShapePtr aResultShape = shape();
583 TopTools_MapOfShape anAlreadyProcessedShapes;
584 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
585 for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
586 anOldShapeExp.more();
587 anOldShapeExp.next())
589 GeomShapePtr anOldSubShape = anOldShapeExp.current();
590 const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
592 // There is no sense to write history if shape already processed
593 // or old shape does not exist in the document.
594 bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
595 TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
596 ModelAPI_Session::get()->moduleDocument())->generalLabel();
597 TDF_Label anOriginalLabel;
598 bool anOldSubShapeNotInTree =
599 !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
600 if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
605 ListOfShape aNewShapes;
606 theAlgo->generated(anOldSubShape, aNewShapes);
608 keepTopLevelShapes(aNewShapes, anOldSubShape_);
610 for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
611 aNewShapesIt != aNewShapes.cend();
614 GeomShapePtr aNewShape = *aNewShapesIt;
615 const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
617 bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
618 bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
619 if (aNewShapeIsSameAsOldShape
620 || aNewShapeIsNotInResultShape)
625 TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
626 if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
627 // TODO: This is a workaround. New shape should be only edge or face.
628 TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
630 int aTag = TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
631 for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
632 builder(aTag)->Generated(anOldSubShape_, anExp.Current());
633 // store information about the external document reference to restore old shape on open
634 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
636 buildName(aTag, theName);
639 int aTag = getGenerationTag(aNewShape_);
640 if (aTag == INVALID_TAG) return;
641 builder(aTag)->Generated(anOldSubShape_, aNewShape_);
642 buildName(aTag, theName);
643 // store information about the external document reference to restore old shape on open
644 storeExternalReference(anOriginalLabel, builder(aTag)->NamedShape()->Label());
651 //=======================================================================
652 int getDangleShapes(const TopoDS_Shape& theShapeIn,
653 const TopAbs_ShapeEnum theGeneratedFrom,
654 TopTools_DataMapOfShapeShape& theDangles)
657 TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
658 TopAbs_ShapeEnum GeneratedTo;
659 if (theGeneratedFrom == TopAbs_FACE) GeneratedTo = TopAbs_EDGE;
660 else if (theGeneratedFrom == TopAbs_EDGE) GeneratedTo = TopAbs_VERTEX;
661 else return Standard_False;
662 TopExp::MapShapesAndAncestors(theShapeIn, GeneratedTo, theGeneratedFrom, subShapeAndAncestors);
663 for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
664 const TopoDS_Shape& mayBeDangle = subShapeAndAncestors.FindKey(i);
665 const TopTools_ListOfShape& ancestors = subShapeAndAncestors.FindFromIndex(i);
666 if (ancestors.Extent() == 1) theDangles.Bind(ancestors.First(), mayBeDangle);
668 return theDangles.Extent();
671 //=======================================================================
672 void loadGeneratedDangleShapes(
673 const TopoDS_Shape& theShapeIn,
674 const TopAbs_ShapeEnum theGeneratedFrom,
675 TNaming_Builder * theBuilder)
677 TopTools_DataMapOfShapeShape dangles;
678 if (!getDangleShapes(theShapeIn, theGeneratedFrom, dangles)) return;
679 TopTools_DataMapIteratorOfDataMapOfShapeShape itr(dangles);
680 for (; itr.More(); itr.Next())
681 theBuilder->Generated(itr.Key(), itr.Value());
685 //=======================================================================
686 void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
687 const std::string& theName)
689 if(theShape->isNull()) return;
690 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
692 if (aShape.ShapeType() == TopAbs_SOLID) {
693 TopExp_Explorer expl(aShape, TopAbs_FACE);
694 for (; expl.More(); expl.Next()) {
695 builder(myFreePrimitiveTag)->Generated(expl.Current());
696 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
697 aName = theName + "_" + aStr.ToCString();
698 buildName(myFreePrimitiveTag, aName);
699 ++myFreePrimitiveTag;
702 else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
703 // load faces and all the free edges
704 TopTools_IndexedMapOfShape Faces;
705 TopExp::MapShapes(aShape, TopAbs_FACE, Faces);
706 if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
707 TopExp_Explorer expl(aShape, TopAbs_FACE);
708 for (; expl.More(); expl.Next()) {
709 builder(myFreePrimitiveTag)->Generated(expl.Current());
710 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
711 aName = theName + "_" + aStr.ToCString();
712 buildName(myFreePrimitiveTag, aName);
713 ++myFreePrimitiveTag;
716 TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
717 TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, anEdgeAndNeighbourFaces);
718 for (Standard_Integer i = 1; i <= anEdgeAndNeighbourFaces.Extent(); i++)
720 const TopTools_ListOfShape& aLL = anEdgeAndNeighbourFaces.FindFromIndex(i);
721 if (aLL.Extent() < 2) {
722 if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
724 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
725 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
726 aName = theName + "_" + aStr.ToCString();
727 buildName(myFreePrimitiveTag, aName);
728 ++myFreePrimitiveTag;
730 TopTools_ListIteratorOfListOfShape anIter(aLL);
731 const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
733 if(aFace.IsEqual(anIter.Value())) {
734 builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
735 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
736 aName = theName + "_" + aStr.ToCString();
737 buildName(myFreePrimitiveTag, aName);
738 ++myFreePrimitiveTag;
742 } else if (aShape.ShapeType() == TopAbs_WIRE) {
743 TopTools_IndexedMapOfShape Edges;
744 BRepTools::Map3DEdges(aShape, Edges);
745 if (Edges.Extent() == 1) {
746 builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
747 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
748 for (; expl.More(); expl.Next()) {
749 builder(myFreePrimitiveTag)->Generated(expl.Current());
750 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
751 aName = theName + "_" + aStr.ToCString();
752 buildName(myFreePrimitiveTag, aName);
753 ++myFreePrimitiveTag;
756 TopExp_Explorer expl(aShape, TopAbs_EDGE);
757 for (; expl.More(); expl.Next()) {
758 builder(myFreePrimitiveTag)->Generated(expl.Current());
759 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
760 aName = theName + "_" + aStr.ToCString();
761 buildName(myFreePrimitiveTag, aName);
762 ++myFreePrimitiveTag;
764 // and load generated vertices.
765 TopTools_DataMapOfShapeShape generated;
766 if (getDangleShapes(aShape, TopAbs_EDGE, generated))
768 TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
769 loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
772 } else if (aShape.ShapeType() == TopAbs_EDGE) {
773 TopExp_Explorer expl(aShape, TopAbs_VERTEX);
774 for (; expl.More(); expl.Next()) {
775 builder(myFreePrimitiveTag)->Generated(expl.Current());
776 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
777 aName = theName + "_" + aStr.ToCString();
778 buildName(myFreePrimitiveTag, aName);
779 ++myFreePrimitiveTag;
784 //=======================================================================
785 int findAmbiguities(const TopoDS_Shape& theShapeIn,
786 TopTools_ListOfShape& theList)
789 // edges -> ancestor faces list
790 TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
791 TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
792 // keeps the shapes which are already in the resulting list
793 TopTools_MapOfShape alreadyThere;
794 // map from faces identifier (combination of hash-codes) to list of edges produced such ID
795 NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
797 TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
798 for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
799 const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
800 if (ancestors.Extent() < 2)
802 Standard_Integer anID = 0;
803 for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
804 anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
806 if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
807 const NCollection_List<TopoDS_Shape>& aSameFaces1 =
808 aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
809 NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
810 for(; aSameEdge.More(); aSameEdge.Next()) {
811 const NCollection_List<TopoDS_Shape>& aSameFaces2 =
812 aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
813 if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
816 NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
817 for(; aFaceIter1.More(); aFaceIter1.Next()) {
818 NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
819 for(; aFaceIter2.More(); aFaceIter2.Next()) {
820 if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
823 if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
826 if (!aFaceIter1.More()) { // all the faces are same => put to the result
827 if (alreadyThere.Add(aSameEdge.Value()))
828 theList.Append(aSameEdge.Value());
829 if (alreadyThere.Add(anAncestorsIter.Key()))
830 theList.Append(anAncestorsIter.Key());
833 } else { // ID is unique, just add this edge
834 aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
836 aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
838 return theList.Extent();
841 //=======================================================================
842 void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
844 if(theShape->isNull()) return;
845 TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
847 if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
848 TopoDS_Iterator itr(aShape);
849 for (; itr.More(); itr.Next()) {
850 builder(myFreePrimitiveTag)->Generated(itr.Value());
851 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
852 aName = theName + "_" + aStr.ToCString();
853 buildName(myFreePrimitiveTag, aName);
854 ++myFreePrimitiveTag;
855 if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
856 itr.Value().ShapeType() == TopAbs_COMPSOLID)
858 GeomShapePtr itrShape(new GeomAPI_Shape());
859 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
860 loadFirstLevel(itrShape, theName);
862 GeomShapePtr itrShape(new GeomAPI_Shape());
863 itrShape->setImpl(new TopoDS_Shape(itr.Value()));
864 loadNextLevels(itrShape, theName);
868 GeomShapePtr itrShape(new GeomAPI_Shape());
869 itrShape->setImpl(new TopoDS_Shape(aShape));
870 loadNextLevels(itrShape, theName);
872 TopTools_ListOfShape aList;
873 if(findAmbiguities(aShape, aList)) {
874 TopTools_ListIteratorOfListOfShape it(aList);
875 for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
876 builder(myFreePrimitiveTag)->Generated(it.Value());
877 TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
878 aName = theName + "_" + aStr.ToCString();
879 buildName(myFreePrimitiveTag, aName);
884 GeomShapePtr Model_BodyBuilder::shape()
886 std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
887 if (aData && aData->isValid()) {
888 TDF_Label aShapeLab = aData->shapeLab();
889 Handle(TDF_Reference) aRef;
890 if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
891 aShapeLab = aRef->Get();
893 Handle(TNaming_NamedShape) aName;
894 if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
895 TopoDS_Shape aShape = aName->Get();
896 if (!aShape.IsNull()) {
897 GeomShapePtr aRes(new GeomAPI_Shape);
898 aRes->setImpl(new TopoDS_Shape(aShape));
903 return GeomShapePtr();