Salome HOME
Updated copyright comment
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
old mode 100755 (executable)
new mode 100644 (file)
index 1a8ea55..d397d0a
@@ -1,4 +1,4 @@
-// Copyright (C) 2014-2017  CEA/DEN, EDF R&D
+// Copyright (C) 2014-2024  CEA, EDF
 //
 // This library is free software; you can redistribute it and/or
 // modify it under the terms of the GNU Lesser General Public
 //
 // You should have received a copy of the GNU Lesser General Public
 // License along with this library; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
-// See http://www.salome-platform.org/ or
-// email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
 #include <Model_BodyBuilder.h>
 
+#include <Locale_Convert.h>
+
 #include <Model_Data.h>
 #include <Model_Document.h>
+#include <ModelAPI_Session.h>
 #include <TNaming_Builder.hxx>
 #include <TNaming_NamedShape.hxx>
 #include <TNaming_Iterator.hxx>
 #include <TNaming_Tool.hxx>
+#include <TNaming_SameShapeIterator.hxx>
 #include <TDataStd_Name.hxx>
 #include <TDataStd_Integer.hxx>
+#include <TDataStd_ExtStringList.hxx>
 #include <TopoDS.hxx>
 #include <TopoDS_Face.hxx>
 #include <TDF_ChildIterator.hxx>
 #include <TDF_ChildIDIterator.hxx>
 #include <TDF_Reference.hxx>
+#include <TDF_Tool.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopTools_ListOfShape.hxx>
 #include <TopExp.hxx>
 #include <BRepTools.hxx>
 #include <BRep_Tool.hxx>
+#include <BRepTools_History.hxx>
 #include <GeomAPI_Shape.h>
+#include <GeomAPI_ShapeExplorer.h>
 #include <GeomAlgoAPI_MakeShape.h>
 #include <GeomAlgoAPI_SortListOfShapes.h>
 #include <Config_PropManager.h>
 // DEB
 //#include <TCollection_AsciiString.hxx>
-//#include <TDF_Tool.hxx>
 //#define DEB_IMPORT 1
 
+/// reference to the shape in external document: sting list attribute identifier
+static const Standard_GUID kEXTERNAL_SHAPE_REF("9aa5dd14-6d34-4a8d-8786-05842fd7bbbd");
+
+static const int INVALID_TAG            = -1;
+static const int GENERATED_VERTICES_TAG = 1;
+static const int GENERATED_EDGES_TAG    = 2;
+static const int GENERATED_FACES_TAG    = 3;
+static const int MODIFIED_VERTICES_TAG  = 4;
+static const int MODIFIED_EDGES_TAG     = 5;
+static const int MODIFIED_FACES_TAG     = 6;
+static const int DELETED_TAG            = 7;
+static const int PRIMITIVES_START_TAG   = 11;
+
+static int getGenerationTag(const TopoDS_Shape& theShape) {
+  TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
+  switch (aShapeType) {
+    case TopAbs_VERTEX: return GENERATED_VERTICES_TAG;
+    case TopAbs_EDGE:   return GENERATED_EDGES_TAG;
+    case TopAbs_FACE:   return GENERATED_FACES_TAG;
+    default: break; // [to avoid compilation warning]
+  }
+
+  return INVALID_TAG;
+}
+
+static int getModificationTag(const TopoDS_Shape& theShape) {
+  TopAbs_ShapeEnum aShapeType = theShape.ShapeType();
+  switch (aShapeType) {
+    case TopAbs_VERTEX: return MODIFIED_VERTICES_TAG;
+    case TopAbs_EDGE:   return MODIFIED_EDGES_TAG;
+    case TopAbs_FACE:   return MODIFIED_FACES_TAG;
+    default: break; // [to avoid compilation warning]
+  }
+
+  return INVALID_TAG;
+}
+
+static bool isAlreadyStored(const TNaming_Builder* theBuilder,
+                            const TopoDS_Shape& theOldShape,
+                            const TopoDS_Shape& theNewShape)
+{
+  for (TNaming_Iterator aNamingIt(theBuilder->NamedShape());
+    aNamingIt.More();
+    aNamingIt.Next())
+  {
+    if (aNamingIt.NewShape().IsSame(theNewShape)
+      && aNamingIt.OldShape().IsSame(theOldShape))
+    {
+      return true;
+    }
+  }
+
+  return false;
+}
+
 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
-: ModelAPI_BodyBuilder(theOwner)
+: ModelAPI_BodyBuilder(theOwner),
+  myFreePrimitiveTag(PRIMITIVES_START_TAG)
 {
 }
 
-// Converts evolution of naming shape to selection evelution and back to avoid
-// naming support on the disabled results. Deeply in the labels tree, recursively.
-static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
-  std::list<std::pair<TopoDS_Shape, TopoDS_Shape> > aShapePairs; // to store old and new shapes
-  Handle(TNaming_NamedShape) aName;
-  int anEvolution = -1;
-  if (theLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
-    TNaming_Evolution aNSEvol = aName->Evolution();
-    if ((aNSEvol == TNaming_SELECTED && theFlag) ||
-        (aNSEvol != TNaming_SELECTED && !theFlag)) { // nothing to do, it is already correct
-      return;
-    }
-    anEvolution = (int)(aNSEvol);
-    if (!theFlag) {
-      Handle(TDataStd_Integer) anAttrEvol;
-      if (theLab.FindAttribute(TDataStd_Integer::GetID(), anAttrEvol)) {
-        anEvolution = anAttrEvol->Get();
-      }
-    } else {
-      TDataStd_Integer::Set(theLab, anEvolution);
-    }
-
-    for(TNaming_Iterator anIter(aName); anIter.More(); anIter.Next()) {
-      // iterator goes in reversed order relatively to the Builder, to, make the list reversed
-      aShapePairs.push_front(std::pair<TopoDS_Shape, TopoDS_Shape>
-        (anIter.OldShape(), anIter.NewShape()));
-    }
-
-    // create new
-    TNaming_Builder aBuilder(theLab);
-    TNaming_Evolution anEvol = (TNaming_Evolution)(anEvolution);
-    std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
-    for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
-      if (theFlag) { // disabled => make selection
-        if (anEvolution == TNaming_DELETE) // issue 2274 : don't put too many same null shapes
-          aBuilder.Select(aPairsIter->first, aPairsIter->first);
-        else if (anEvolution == TNaming_PRIMITIVE)
-          aBuilder.Select(aPairsIter->second, aPairsIter->second);
-        else
-          aBuilder.Select(aPairsIter->second, aPairsIter->first);
-      } else if (anEvol == TNaming_GENERATED) {
-        aBuilder.Generated(aPairsIter->first, aPairsIter->second);
-      } else if (anEvol == TNaming_MODIFY) {
-        aBuilder.Modify(aPairsIter->first, aPairsIter->second);
-      } else if (anEvol == TNaming_DELETE) {
-        aBuilder.Delete(aPairsIter->first);
-      } else if (anEvol == TNaming_PRIMITIVE) {
-        aBuilder.Generated(aPairsIter->second);
-      } else if (anEvol == TNaming_SELECTED) {
-        aBuilder.Select(aPairsIter->second, aPairsIter->first);
+/// Checks that shape is presented in the tree with not-selection evolution
+/// In theOriginalLabel it returns label where NS of old sub-shape is stored
+static bool isShapeInTree(const TDF_Label& theAccess1, const TDF_Label& theAccess2,
+  TopoDS_Shape theShape, TDF_Label& theOriginalLabel)
+{
+  bool aResult = TNaming_Tool::HasLabel(theAccess1, theShape);
+  if (aResult) { //check evolution and a label of this shape
+    for(TNaming_SameShapeIterator aShapes(theShape, theAccess1); aShapes.More(); aShapes.Next())
+    {
+      Handle(TNaming_NamedShape) aNS;
+      if (aShapes.Label().FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
+        if (aNS->Evolution() != TNaming_SELECTED) {
+          theOriginalLabel = aNS->Label();
+          return true;
+        }
       }
     }
   }
-  // recursive call for all sub-labels
-  TDF_ChildIterator anIter(theLab, Standard_False);
-  for(; anIter.More(); anIter.Next()) {
-    evolutionToSelectionRec(anIter.Value(), theFlag);
+  if (!theAccess2.IsNull()) {
+    static const TDF_Label anEmpty;
+    return isShapeInTree(theAccess2, anEmpty, theShape, theOriginalLabel);
   }
+  return false;
 }
 
-void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
+/// Stores entry to the external label in the entries list at this label
+static void storeExternalReference(const TDF_Label& theExternal, const TDF_Label theThis)
 {
-  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  if (!aData) // unknown case
-    return;
-  TDF_Label& aShapeLab = aData->shapeLab();
-  evolutionToSelectionRec(aShapeLab, theFlag);
+  // store information about the external document reference to restore old shape on open
+  if (!theExternal.IsNull() && !theExternal.Root().IsEqual(theThis.Root())) {
+    Handle(TDataStd_ExtStringList) anEntries;
+    if (!theThis.FindAttribute(kEXTERNAL_SHAPE_REF, anEntries)) {
+      anEntries = TDataStd_ExtStringList::Set(theThis, kEXTERNAL_SHAPE_REF);
+    }
+    TCollection_AsciiString anEntry;
+    TDF_Tool::Entry(theExternal, anEntry);
+    // check it already contains this entry
+    TDataStd_ListOfExtendedString::Iterator anIter(anEntries->List());
+    for(; anIter.More(); anIter.Next())
+      if (anIter.Value() == anEntry)
+        break;
+    if (!anIter.More()) {
+      anEntries->Append(anEntry);
+    }
+  }
 }
 
-void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
+void Model_BodyBuilder::store(const GeomShapePtr& theShape,
                               const bool theIsStoreSameShapes)
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
+    TDF_Label aShapeLab = aData->shapeLab();
     // clean builders
     clean();
     // store the new shape as primitive
@@ -147,8 +187,11 @@ void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
       return;  // null shape inside
 
     if(!theIsStoreSameShapes) {
-      Handle(TNaming_NamedShape) aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
-      if(!aNS.IsNull() && !aNS->IsEmpty()) {
+      Handle(TNaming_NamedShape) aNS;
+      if (TNaming_Tool::HasLabel(aShapeLab, aShape))
+        aNS = TNaming_Tool::NamedShape(aShape, aShapeLab);
+      // the last condition is for the issue 2751 : existing shape may be found in compound-NS
+      if(!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShape)) {
         // This shape is already in document, store reference instead of shape;
         const TDF_Label aFoundLabel = aNS->Label();
         TDF_Reference::Set(aShapeLab, aFoundLabel);
@@ -163,7 +206,7 @@ void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
     if(!aBuilder.NamedShape()->IsEmpty()) {
       Handle(TDataStd_Name) anAttr;
       if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
-        std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
+        std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
         if(!aName.empty()) {
           std::shared_ptr<Model_Document> aDoc =
             std::dynamic_pointer_cast<Model_Document>(document());
@@ -174,16 +217,15 @@ void Model_BodyBuilder::store(const std::shared_ptr<GeomAPI_Shape>& theShape,
   }
 }
 
-void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& theFromShape,
-  const std::shared_ptr<GeomAPI_Shape>& theToShape)
+void Model_BodyBuilder::storeGenerated(const GeomShapePtr& theFromShape,
+  const GeomShapePtr& theToShape, const bool theIsCleanStored)
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
     // clean builders
-    clean();
-    // store the new shape as primitive
-    TNaming_Builder aBuilder(aShapeLab);
+    if (theIsCleanStored)
+      clean();
+    TNaming_Builder* aBuilder = builder(0);
     if (!theFromShape || !theToShape)
       return;  // bad shape
     TopoDS_Shape aShapeBasis = theFromShape->impl<TopoDS_Shape>();
@@ -192,33 +234,95 @@ void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& the
     TopoDS_Shape aShapeNew = theToShape->impl<TopoDS_Shape>();
     if (aShapeNew.IsNull())
       return;  // null shape inside
-    aBuilder.Generated(aShapeBasis, aShapeNew);
+
+    // There is no sense to write history if old shape does not exist in the document.
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
+      ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeBasis, anOriginalLabel)) {
+      if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
+        aBuilder->Generated(aShapeNew);
+      }
+    } else {
+      if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
+        myBuilders.erase(0);
+        aBuilder = builder(0);
+      }
+
+      aBuilder->Generated(aShapeBasis, aShapeNew);
+      // store information about the external document reference to restore old shape on open
+      storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
+    }
+
     // register name
-    if(!aBuilder.NamedShape()->IsEmpty()) {
+    if(!aBuilder->NamedShape()->IsEmpty()) {
       Handle(TDataStd_Name) anAttr;
-      if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
-        std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
+      if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
+        std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
         if(!aName.empty()) {
           std::shared_ptr<Model_Document> aDoc =
             std::dynamic_pointer_cast<Model_Document>(document());
-          aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
+          aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
         }
       }
     }
   }
 }
 
-void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
-  const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
+void Model_BodyBuilder::storeGenerated(const std::list<GeomShapePtr>& theFromShapes,
+  const GeomShapePtr& theToShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
+{
+  bool aStored = false;
+  std::list<GeomShapePtr>::const_iterator anOldIter = theFromShapes.cbegin();
+  for (; anOldIter != theFromShapes.cend(); anOldIter++) {
+    bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire();
+    if (!aStore) {
+      ListOfShape aNews; // check this old really generates theToShape
+      theMakeShape->generated(*anOldIter, aNews);
+      ListOfShape::iterator aNewIter = aNews.begin();
+      for (; aNewIter != aNews.end(); aNewIter++) {
+        if (theToShape->isSame(*aNewIter))
+          break;
+      }
+      aStore = aNewIter != aNews.end();
+    }
+    if (aStore) {
+      storeGenerated(*anOldIter, theToShape, !aStored);
+      TNaming_Builder* aBuilder = builder(0);
+      aStored = !aBuilder->NamedShape()->IsEmpty();
+    }
+  }
+  if (!aStored) { // store as PRIMITIVE, but clean in any way
+    store(theToShape);
+    return;
+  }
+}
+
+static TDF_Label builderLabel(DataPtr theData, const int theTag )
+{
+  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(theData);
+  return theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag);
+}
+
+TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
+{
+  std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
+  if (aFind == myBuilders.end()) {
+    myBuilders[theTag] = new TNaming_Builder(builderLabel(data(), theTag));
+    aFind = myBuilders.find(theTag);
+  }
+  return aFind->second;
+}
+
+void Model_BodyBuilder::storeModified(const GeomShapePtr& theOldShape,
+                                      const GeomShapePtr& theNewShape,
+                                      const bool theIsCleanStored)
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
   if (aData) {
-    TDF_Label& aShapeLab = aData->shapeLab();
     // clean builders
-    if (theDecomposeSolidsTag != -2)
-      clean();
-    // store the new shape as primitive
-    TNaming_Builder aBuilder(aShapeLab);
+    if (theIsCleanStored) clean();
+    TNaming_Builder* aBuilder = builder(0);
     if (!theOldShape || !theNewShape)
       return;  // bad shape
     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
@@ -227,33 +331,104 @@ void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theO
     TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
     if (aShapeNew.IsNull())
       return;  // null shape inside
-    aBuilder.Modify(aShapeOld, aShapeNew);
-    if(!aBuilder.NamedShape()->IsEmpty()) {
+
+    // There is no sense to write history if old shape does not exist in the document.
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
+      ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    TopTools_ListOfShape anOldList;
+    if (!isShapeInTree(aData->shapeLab(), anAccess2, aShapeOld, anOriginalLabel)) {
+      // check this could be a compund by the whole feature selection
+      if (aShapeOld.ShapeType() == TopAbs_COMPOUND)  {
+        for(TopoDS_Iterator aCompIter(aShapeOld); aCompIter.More(); aCompIter.Next()) {
+          if (isShapeInTree(aData->shapeLab(), anAccess2, aCompIter.Value(), anOriginalLabel)) {
+            anOldList.Append(aCompIter.Value());
+          } else {
+            anOldList.Clear();
+            break;
+          }
+        }
+      }
+    } else {
+      anOldList.Append(aShapeOld);
+    }
+    if (anOldList.IsEmpty()) {
+      if (aBuilder->NamedShape()->Get().IsNull()) { // store as primitive if alone anyway
+        aBuilder->Generated(aShapeNew);
+      }
+    } else {
+      if (aBuilder->NamedShape()->Evolution() == TNaming_PRIMITIVE) { // erase primitive before
+        myBuilders.erase(0);
+        aBuilder = builder(0);
+      }
+      TopTools_ListIteratorOfListOfShape anOldIter(anOldList);
+      for(; anOldIter.More(); anOldIter.Next()) {
+        aBuilder->Modify(anOldIter.Value(), aShapeNew);
+      }
+      // store information about the external document reference to restore old shape on open
+      storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
+    }
+
+    if(!aBuilder->NamedShape()->IsEmpty()) {
       Handle(TDataStd_Name) anAttr;
-      if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
-        std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
+      if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(), anAttr)) {
+        std::wstring aName = Locale::Convert::toWString(anAttr->Get().ToExtString());
         if(!aName.empty()) {
           std::shared_ptr<Model_Document> aDoc =
             std::dynamic_pointer_cast<Model_Document>(document());
-          aDoc->addNamingName(aBuilder.NamedShape()->Label(), aName);
+          aDoc->addNamingName(aBuilder->NamedShape()->Label(), aName);
         }
       }
     }
   }
 }
 
-void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>& theShape)
+void Model_BodyBuilder::storeModified(const std::list<GeomShapePtr>& theOldShapes,
+  const GeomShapePtr& theNewShape, const std::shared_ptr<GeomAlgoAPI_MakeShape> theMakeShape)
 {
-  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  if (aData) {
-    clean();
-    if (!theShape.get())
-      return; // bad shape
-    TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
-    if (aShape.IsNull())
-      return;  // null shape inside
-    TNaming_Builder aBuilder(aData->shapeLab());
-    aBuilder.Select(aShape, aShape);
+  bool aStored = false;
+  std::list<GeomShapePtr>::const_iterator anOldIter = theOldShapes.cbegin();
+  for(; anOldIter != theOldShapes.cend(); anOldIter++) {
+    // compounds may cause crash if call "modified"
+    bool aStore = (*anOldIter)->isCompound() || (*anOldIter)->isShell() || (*anOldIter)->isWire() ||
+               (*anOldIter)->isCompSolid();
+    if (!aStore) {
+      ListOfShape aNews; // check this old really modifies theNewShape
+      theMakeShape->modified(*anOldIter, aNews);
+      ListOfShape::iterator aNewIter = aNews.begin();
+      for(; aNewIter != aNews.end(); aNewIter++) {
+        if (theNewShape->isSame(*aNewIter))
+          break;
+      }
+      aStore = aNewIter != aNews.end();
+    }
+    if (aStore) {
+      storeModified(*anOldIter, theNewShape, !aStored);
+      TNaming_Builder* aBuilder = builder(0);
+      aStored = !aBuilder->NamedShape()->IsEmpty();
+    }
+  }
+  if (!aStored) {
+    // check the new shape is already in the tree, so, no need to store primitive, just reference
+    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
+    if (aData.get()) {
+      TDF_Label aShapeLab = aData->shapeLab();
+      TopoDS_Shape aShapeNew = theNewShape->impl<TopoDS_Shape>();
+      Handle(TNaming_NamedShape) aNS;
+      if (TNaming_Tool::HasLabel(aShapeLab, aShapeNew))
+        aNS = TNaming_Tool::NamedShape(aShapeNew, aShapeLab);
+      // the last condition is for the issue 2751 : existing shape may be found in compound-NS
+      if (!aNS.IsNull() && !aNS->IsEmpty() && aNS->Get().IsSame(aShapeNew)) {
+        // This shape is already in document, store reference instead of shape;
+        const TDF_Label aFoundLabel = aNS->Label();
+        TDF_Reference::Set(aShapeLab, aFoundLabel);
+        myBuilders.erase(0);
+        aShapeLab.ForgetAttribute(TNaming_NamedShape::GetID());
+        return;
+      }
+    }
+    store(theNewShape); // store as PRIMITIVE, but clean in any way
+    return;
   }
 }
 
@@ -264,122 +439,158 @@ void Model_BodyBuilder::clean()
     return;
   std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
   for(; aBuilder != myBuilders.end(); aBuilder++) {
+    Handle(TNaming_NamedShape) aNS = aBuilder->second->NamedShape();
     delete aBuilder->second;
-    // clear also shapes on cleaned sub-labels (#2241)
-    Handle(TNaming_NamedShape) aNS;
-    if (aLab.FindChild(aBuilder->first).FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
-      aNS->Clear();
-    }
+    if (!aNS.IsNull() && !aNS->Label().IsNull())
+      aNS->Label().ForgetAttribute(TNaming_NamedShape::GetID());
   }
   myBuilders.clear();
+  myPrimitivesNamesIndexMap.clear();
   // remove the old reference (if any)
   aLab.ForgetAttribute(TDF_Reference::GetID());
+  myFreePrimitiveTag = PRIMITIVES_START_TAG;
+  TDF_ChildIDIterator anEntriesIter(aLab, kEXTERNAL_SHAPE_REF, true);
+  for(; anEntriesIter.More(); anEntriesIter.Next()) {
+    anEntriesIter.Value()->Label().ForgetAttribute(kEXTERNAL_SHAPE_REF);
+  }
 }
 
-Model_BodyBuilder::~Model_BodyBuilder()
+void Model_BodyBuilder::cleanCash()
 {
-  clean();
+  myPrimitivesNamesIndexMap.clear();
 }
 
-TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
+Model_BodyBuilder::~Model_BodyBuilder()
 {
-  std::map<int, TNaming_Builder*>::iterator aFind = myBuilders.find(theTag);
-  if (aFind == myBuilders.end()) {
-    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-    myBuilders[theTag] = new TNaming_Builder(
-      theTag == 0 ? aData->shapeLab() : aData->shapeLab().FindChild(theTag));
-    aFind = myBuilders.find(theTag);
-  }
-  return aFind->second;
+  clean();
 }
 
 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
 {
-  std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
-  //aDoc->addNamingName(builder(theTag)->NamedShape()->Label(), theName);
-  TDataStd_Name::Set(builder(theTag)->NamedShape()->Label(), theName.c_str());
+  std::string aName = theName;
+  std::string aPrefix = "";
+  switch (theTag) {
+    case GENERATED_VERTICES_TAG: aPrefix = aName.empty() ? "Generated_Vertex" : "GV:"; break;
+    case GENERATED_EDGES_TAG:    aPrefix = aName.empty() ? "Generated_Edge"   : "GE:"; break;
+    case GENERATED_FACES_TAG:    aPrefix = aName.empty() ? "Generated_Face"   : "GF:"; break;
+    case MODIFIED_VERTICES_TAG:  aPrefix = aName.empty() ? "Modified_Vertex"  : "MV:"; break;
+    case MODIFIED_EDGES_TAG:     aPrefix = aName.empty() ? "Modified_Edge"    : "ME:"; break;
+    case MODIFIED_FACES_TAG:     aPrefix = aName.empty() ? "Modified_Face"    : "MF:"; break;
+  }
+  aName.insert(0, aPrefix);
+
+  TDataStd_Name::Set(builderLabel(data(), theTag), aName.c_str());
 }
-void Model_BodyBuilder::generated(
-  const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
+bool Model_BodyBuilder::generated(const GeomShapePtr& theNewShape,
+                                  const std::string& theName,
+                                  const bool theCheckIsInResult)
 {
+  GeomShapePtr aResultShape = shape();
+  if (theCheckIsInResult) {
+    bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(theNewShape, false);
+    if (aNewShapeIsNotInResultShape) {
+      return false;
+    }
+  }
+
   TopoDS_Shape aShape = theNewShape->impl<TopoDS_Shape>();
-  builder(theTag)->Generated(aShape);
-  if(!theName.empty())
-    buildName(theTag, theName);
+  builder(myFreePrimitiveTag)->Generated(aShape);
+  if (!theName.empty()) {
+    std::string aName = theName;
+    if (myPrimitivesNamesIndexMap.find(theName) != myPrimitivesNamesIndexMap.end()) {
+      IndexTags& anIndexTags = myPrimitivesNamesIndexMap.find(theName)->second;
+      aName += "_" + std::to_string(++(anIndexTags.index));
+      anIndexTags.tags.push_back(myFreePrimitiveTag);
+      if (anIndexTags.index == 2) {
+        buildName(anIndexTags.tags.front(), theName + "_1");
+      }
+    }
+    else {
+      IndexTags anIndexTags;
+      anIndexTags.index = 1;
+      anIndexTags.tags.push_back(myFreePrimitiveTag);
+      myPrimitivesNamesIndexMap[theName] = anIndexTags;
+    }
+
+    buildName(myFreePrimitiveTag, aName);
+  }
+  ++myFreePrimitiveTag;
+  return true;
 }
 
-void Model_BodyBuilder::generated(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
-  const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
+void Model_BodyBuilder::generated(const GeomShapePtr& theOldShape,
+                                  const GeomShapePtr& theNewShape,
+                                  const std::string& theName)
 {
   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
-  builder(theTag)->Generated(anOldShape, aNewShape);
-  if(!theName.empty())
-    buildName(theTag, theName);
-  TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
-  if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
-    TopAbs_ShapeEnum anExplodeShapeType = aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
-    const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
-    int aTag = 1;
-    std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
-    for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
-      TDF_Label aChildLabel = aLabel.FindChild(aTag);
-      TNaming_Builder aBuilder(aChildLabel);
-      aBuilder.Generated(anOldShape, anExp.Current());
-      TCollection_AsciiString aChildName = TCollection_AsciiString((theName + "_").c_str()) + aTag;
-      //aDoc->addNamingName(aChildLabel, aChildName.ToCString());
-      TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
-      aTag++;
+  TopAbs_ShapeEnum aNewShapeType = aNewShape.ShapeType();
+  int aTag;
+  if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
+    // TODO: This is a workaround. New shape should be only vertex, edge or face.
+    TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
+    aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
+    for (TopExp_Explorer anExp(aNewShape, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
+      builder(aTag)->Generated(anOldShape, anExp.Current());
     }
+    buildName(aTag, theName);
+  } else {
+    aTag = getGenerationTag(aNewShape);
+    if (aTag == INVALID_TAG) return;
+    builder(aTag)->Generated(anOldShape, aNewShape);
+    buildName(aTag, theName);
   }
 }
 
-
-void Model_BodyBuilder::modified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
-  const std::shared_ptr<GeomAPI_Shape>& theNewShape, const std::string& theName, const int theTag)
+void Model_BodyBuilder::modified(const GeomShapePtr& theOldShape,
+                                 const GeomShapePtr& theNewShape,
+                                 const std::string& theName)
 {
   TopoDS_Shape anOldShape = theOldShape->impl<TopoDS_Shape>();
   TopoDS_Shape aNewShape = theNewShape->impl<TopoDS_Shape>();
-  builder(theTag)->Modify(anOldShape, aNewShape);
-  if(!theName.empty())
-    buildName(theTag, theName);
+  int aTag = getModificationTag(aNewShape);
+  if (aTag == INVALID_TAG) return;
+  builder(aTag)->Modify(anOldShape, aNewShape);
+  buildName(aTag, theName);
 }
 
-void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
-  const int theTag)
+void Model_BodyBuilder::loadDeletedShapes(const GeomMakeShapePtr& theAlgo,
+                                          const GeomShapePtr& theOldShape,
+                                          const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
+                                          const GeomShapePtr& theShapesToExclude)
 {
-  TopoDS_Shape aShape = theOldShape->impl<TopoDS_Shape>();
-  builder(theTag)->Delete(aShape);
-}
-
-void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
-  std::shared_ptr<GeomAPI_Shape>  theShapeIn,
-  const int  theKindOfShape,
-  const int  theTag)
-{
-  TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
-  TopTools_MapOfShape aView;
-  TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
+  TopTools_MapOfShape anAlreadyProcessedShapes;
   GeomShapePtr aResultShape = shape();
-  for (; ShapeExplorer.More(); ShapeExplorer.Next ()) {
-    const TopoDS_Shape& aRoot = ShapeExplorer.Current ();
-    if (!aView.Add(aRoot)) continue;
-    std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
-    aRShape->setImpl((new TopoDS_Shape(aRoot)));
-    if (theMS->isDeleted (aRShape)) {
-      if (!aResultShape->isSubShape(aRShape, false)) {
-          ListOfShape aHist;
-          theMS->modified(aRShape, aHist);
-          if (aHist.size() == 0 || (aHist.size() == 1 && aHist.front()->isSame(aRShape)))
-            builder(theTag)->Delete(aRoot);
-      }
+  for (GeomAPI_ShapeExplorer anExp(theOldShape, theShapeTypeToExplore);
+       anExp.more();
+       anExp.next())
+  {
+    GeomShapePtr anOldSubShape = anExp.current();
+    const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
+    if (!anAlreadyProcessedShapes.Add(anOldSubShape_)
+        || !theAlgo->isDeleted(anOldSubShape)
+        || aResultShape->isSubShape(anOldSubShape, false)
+        || (theShapesToExclude.get() && theShapesToExclude->isSubShape(anOldSubShape, false)))
+    {
+      continue;
+    }
+
+    ListOfShape aNewShapes;
+    if (BRepTools_History::IsSupportedType(anOldSubShape_)) { // to avoid crash in #2572
+      theAlgo->modified(anOldSubShape, aNewShapes);
+    }
+
+    if (aNewShapes.size() == 0
+        || (aNewShapes.size() == 1 && aNewShapes.front()->isSame(anOldSubShape))) {
+      builder(DELETED_TAG)->Delete(anOldSubShape_);
     }
   }
 }
 
 // Keep only the shapes with minimal shape type
-static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRoot,
-  const GeomShapePtr& theResultShape = GeomShapePtr())
+static void keepTopLevelShapes(ListOfShape& theShapes,
+                               const TopoDS_Shape& theRoot,
+                               const GeomShapePtr& theResultShape = GeomShapePtr())
 {
   GeomAPI_Shape::ShapeType aKeepShapeType = GeomAPI_Shape::SHAPE;
   ListOfShape::iterator anIt = theShapes.begin();
@@ -408,219 +619,166 @@ static void keepTopLevelShapes(ListOfShape& theShapes, const TopoDS_Shape& theRo
   }
 }
 
-// returns an ancestor shape-type thaty used for naming-definition of the sub-type
-TopAbs_ShapeEnum typeOfAncestor(const TopAbs_ShapeEnum theSubType) {
-  if (theSubType == TopAbs_VERTEX)
-    return TopAbs_EDGE;
-  if (theSubType == TopAbs_EDGE)
-    return TopAbs_FACE;
-  return TopAbs_VERTEX; // bad case
-}
-
-void Model_BodyBuilder::loadAndOrientModifiedShapes (
-  GeomAlgoAPI_MakeShape* theMS,
-  std::shared_ptr<GeomAPI_Shape>  theShapeIn,
-  const int  theKindOfShape,
-  const int  theTag,
-  const std::string& theName,
-  GeomAPI_DataMapOfShapeShape& theSubShapes,
-  const bool theIsStoreSeparate,
-  const bool theIsStoreAsGenerated)
+void Model_BodyBuilder::loadModifiedShapes(const GeomMakeShapePtr& theAlgo,
+                                           const GeomShapePtr& theOldShape,
+                                           const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
+                                           const std::string& theName)
 {
-  int anIndex = 1;
-  int aTag = theTag;
-  bool isBuilt = !theName.empty();
-  std::string aName = theName;
-  std::ostringstream aStream;
   GeomShapePtr aResultShape = shape();
-  TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
-  TopTools_MapOfShape aView;
+  GeomShapePtr aShapeToExplore = theOldShape;
+  if (theAlgo->isNewShapesCollected(theOldShape, theShapeTypeToExplore)) {
+    // use optimized set of old shapes for this
+    GeomShapePtr aCompound = theAlgo->oldShapesForNew(theOldShape,
+                                                      aResultShape,
+                                                      theShapeTypeToExplore);
+    if (aCompound.get()) aShapeToExplore = aCompound;
+  }
+
+  // Store all types of subshapes in the map to use them for checking
+  // if the new shapes are sub-shapes of this result
+  TopTools_MapOfShape aResultShapeSubMap;
+  TopExp::MapShapes(aResultShape->impl<TopoDS_Shape>(), aResultShapeSubMap);
+
+  TopTools_MapOfShape anAlreadyProcessedShapes;
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
-  for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
-    const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
-    if (!aView.Add(aRoot)) continue;
-
-    bool aNotInTree =
-      TNaming_Tool::NamedShape(aRoot, aData->shapeLab()).IsNull();
-    if (aNotInTree && !theIsStoreSeparate) {
-      // there is no sense to write history if old shape does not exist in the document
-      continue; // but if it is stored separately, it will be builded as a primitive
-    }
-    ListOfShape aList;
-    std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
-    aRShape->setImpl((new TopoDS_Shape(aRoot)));
-    theMS->modified(aRShape, aList);
-    if (!theIsStoreSeparate)
-      keepTopLevelShapes(aList, aRoot, aResultShape);
-    // sort the list of images before naming
-    GeomAlgoAPI_SortListOfShapes::sort(aList);
-
-    // to trace situation where several objects are produced by one parent (#2317)
-    int aSameParentShapes = -1;
-    std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
-      anIt = aList.begin(), aLast = aList.end();
-    for (; anIt != aLast; anIt++) {
-      TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
-      if (theSubShapes.isBound(*anIt)) {
-        std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
-        aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
-      }
-      GeomShapePtr aGeomNewShape(new GeomAPI_Shape());
-      aGeomNewShape->setImpl(new TopoDS_Shape(aNewShape));
-      if(!aRoot.IsSame(aNewShape) && aResultShape->isSubShape(aGeomNewShape, false) &&
-         !aResultShape->isSame(*anIt)) { // to avoid put of same shape on main label and sub
-        int aBuilderTag = aTag;
-        if (!theIsStoreSeparate) {
-          aSameParentShapes++;
-        } else if (aNotInTree) { // check this new shape can not be represented as
-          // a sub-shape of higher level sub-shapes
-          TopAbs_ShapeEnum aNewType = aNewShape.ShapeType();
-          TopAbs_ShapeEnum anAncestorType = typeOfAncestor(aNewType);
-          if (anAncestorType != TopAbs_VERTEX) {
-            bool aFound = false;
-            TopoDS_Shape aResultTShape = aResultShape->impl<TopoDS_Shape>();
-            TopExp_Explorer anAncestorExp(aResultTShape, anAncestorType);
-            for(; anAncestorExp.More() && !aFound; anAncestorExp.Next()) {
-              if (aResultTShape.IsSame(anAncestorExp.Current()))
-                continue;
-              TopExp_Explorer aSubExp(anAncestorExp.Current(), aNewType);
-              for(; aSubExp.More(); aSubExp.Next()) {
-                if (aNewShape.IsSame(aSubExp.Current())) {
-                  aFound = true;
-                  break;
-                }
-              }
-            }
-            if (aFound) {
-              continue; // not need to store this shape in the BRep structure
-            }
-          }
-        }
+  for (GeomAPI_ShapeExplorer anOldShapeExp(aShapeToExplore, theShapeTypeToExplore);
+       anOldShapeExp.more();
+       anOldShapeExp.next())
+  {
+    GeomShapePtr anOldSubShape = anOldShapeExp.current();
+    const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
 
-        static const int THE_ANCHOR_TAG = 100000;
-        int aCurShapeType = (int)((*anIt)->shapeType());
-        bool needSuffix = false; // suffix for the name based on the shape type
-        if (aSameParentShapes > 0) { // store in other label
-          aBuilderTag = THE_ANCHOR_TAG - aSameParentShapes * 10 - aCurShapeType;
-          needSuffix = true;
-        } else if (aCurShapeType != theKindOfShape) {
-          // modified shape has different type => set another tag
-          // to avoid shapes of different types on the same label
-          aBuilderTag = THE_ANCHOR_TAG - aCurShapeType;
-          needSuffix = true;
-        }
-        std::string aSuffix;
-        if (needSuffix) {
-          switch (aCurShapeType) {
-          case GeomAPI_Shape::VERTEX: aSuffix = "_v"; break;
-          case GeomAPI_Shape::EDGE:   aSuffix = "_e"; break;
-          case GeomAPI_Shape::FACE:   aSuffix = "_f"; break;
-          default: break;
-          }
-        }
+    // There is no sense to write history if shape already processed
+    // or old shape does not exist in the document.
+    if (!anAlreadyProcessedShapes.Add(anOldSubShape_))
+    {
+      continue;
+    }
 
-        if(theIsStoreAsGenerated) {
-          // Here we store shapes as generated, to avoid problem when one parent shape produce
-          // several child shapes. In this case naming could not determine which shape to select.
-          builder(aBuilderTag)->Generated(aRoot, aNewShape);
-        } else if (aNotInTree) {
-          // not in tree -> store as primitive (stored as separated)
-          builder(aBuilderTag)->Generated(aNewShape);
-        } else if (aNewShape.ShapeType() > aRoot.ShapeType()) {
-           // if lower-level type is produced, make it as generated
-          builder(aBuilderTag)->Generated(aRoot, aNewShape);
-        } else {
-          builder(aBuilderTag)->Modify(aRoot, aNewShape);
-        }
-        if(isBuilt) {
-          aStream.str(std::string());
-          aStream.clear();
-          aStream << theName;
-          if(theIsStoreSeparate)
-             aStream << "_" << anIndex++;
-
-          if (aSameParentShapes > 0) {
-            aStream.str(std::string());
-            aStream.clear();
-            aStream << aName << "_" << aSameParentShapes << "divided";
-          }
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    if (!isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel))
+    {
+      continue;
+    }
 
-          aStream << aSuffix;
-          buildName(aBuilderTag, aStream.str());
-        }
-        if(theIsStoreSeparate) {
-          aTag++;
-        }
-      } else if (aResultShape->isSame(*anIt)) {
-        // keep the modification evolution on the root level (2241 - history propagation issue)
-        if(theIsStoreAsGenerated) {
-          builder(0)->Generated(aRoot, aNewShape);
-        } else {
-          builder(0)->Modify(aRoot, aNewShape);
-        }
-      }
+    // Get new shapes.
+    ListOfShape aNewShapes;
+    theAlgo->modified(anOldSubShape, aNewShapes);
+    for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
+         aNewShapesIt != aNewShapes.cend();
+         ++aNewShapesIt)
+    {
+      GeomShapePtr aNewShape = *aNewShapesIt;
+      const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
+
+      if (anOldSubShape->isSame(aNewShape))
+        continue;
+
+      if (aResultShape->isSame(aNewShape))
+        continue; // it is stored on the root level (2241 - history propagation issue)
+
+      // Look in the map instead of aResultShape->isSubShape(aNewShape, false)
+      // to avoid many iterations of sub-shapes hierarchy that leads to performance issues
+      if (!aResultShapeSubMap.Contains(aNewShape_))
+        continue;
+
+      const bool isGenerated = anOldSubShape_.ShapeType() != aNewShape_.ShapeType();
+      int aTag = isGenerated ? getGenerationTag(aNewShape_) : getModificationTag(aNewShape_);
+      TNaming_Builder*aBuilder = builder(aTag);
+      if (isAlreadyStored(aBuilder, anOldSubShape_, aNewShape_))
+        continue; // new shape was already stored.
+
+      buildName(aTag, theName);
+      isGenerated ? aBuilder->Generated(anOldSubShape_, aNewShape_)
+                  : aBuilder->Modify(anOldSubShape_, aNewShape_);
+      // store information about the external document reference to restore old shape on open
+      storeExternalReference(anOriginalLabel, aBuilder->NamedShape()->Label());
     }
   }
 }
 
-void Model_BodyBuilder::loadAndOrientGeneratedShapes (
-  GeomAlgoAPI_MakeShape* theMS,
-  std::shared_ptr<GeomAPI_Shape>  theShapeIn,
-  const int  theKindOfShape,
-  const int  theTag,
-  const std::string& theName,
-  GeomAPI_DataMapOfShapeShape& theSubShapes)
+void Model_BodyBuilder::loadGeneratedShapes(const GeomMakeShapePtr& theAlgo,
+                                            const GeomShapePtr& theOldShape,
+                                            const GeomAPI_Shape::ShapeType theShapeTypeToExplore,
+                                            const std::string& theName,
+                                            const bool theSaveOldIfNotInTree)
 {
-  TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
-  TopTools_MapOfShape aView;
-  bool isBuilt = !theName.empty();
-  TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
-  for (; aShapeExplorer.More(); aShapeExplorer.Next ()) {
-    const TopoDS_Shape& aRoot = aShapeExplorer.Current ();
-    if (!aView.Add(aRoot)) continue;
-    //if (TNaming_Tool::NamedShape(aRoot, builder(theTag)->NamedShape()->Label()).IsNull())
-    //  continue; // there is no sense to write history if old shape does not exist in the document
-    ListOfShape aList;
-    std::shared_ptr<GeomAPI_Shape> aRShape(new GeomAPI_Shape());
-    aRShape->setImpl((new TopoDS_Shape(aRoot)));
-    theMS->generated(aRShape, aList);
-    keepTopLevelShapes(aList, aRoot);
-    std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
-      anIt = aList.begin(), aLast = aList.end();
-    for (; anIt != aLast; anIt++) {
-      TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
-      if (theSubShapes.isBound(*anIt)) {
-        std::shared_ptr<GeomAPI_Shape> aMapShape(theSubShapes.find(*anIt));
-        aNewShape.Orientation(aMapShape->impl<TopoDS_Shape>().Orientation());
-      }
-      if (!aRoot.IsSame (aNewShape)) {
-        builder(theTag)->Generated(aRoot,aNewShape);
-        if(isBuilt)
-          buildName(theTag, theName);
+  GeomShapePtr aResultShape = shape();
+  TopTools_MapOfShape anAlreadyProcessedShapes;
+  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
+  for (GeomAPI_ShapeExplorer anOldShapeExp(theOldShape, theShapeTypeToExplore);
+       anOldShapeExp.more();
+       anOldShapeExp.next())
+  {
+    GeomShapePtr anOldSubShape = anOldShapeExp.current();
+    const TopoDS_Shape& anOldSubShape_ = anOldSubShape->impl<TopoDS_Shape>();
+
+    // There is no sense to write history if shape already processed
+    // or old shape does not exist in the document.
+    bool anOldSubShapeAlreadyProcessed = !anAlreadyProcessedShapes.Add(anOldSubShape_);
+    TDF_Label anAccess2 = std::dynamic_pointer_cast<Model_Document>(
+      ModelAPI_Session::get()->moduleDocument())->generalLabel();
+    TDF_Label anOriginalLabel;
+    bool anOldSubShapeNotInTree =
+      !isShapeInTree(aData->shapeLab(), anAccess2, anOldSubShape_, anOriginalLabel);
+    if (anOldSubShapeAlreadyProcessed || anOldSubShapeNotInTree) {
+      // The second condition is added due to #20170 because sub-shape must be added to real parent
+      // shape, not the reference. The naming name of pure reference is not registered in document.
+      if (theSaveOldIfNotInTree && !aData->shapeLab().IsAttribute(TDF_Reference::GetID())) {
+        std::string aSelectionName = theName + "Selected";
+        generated(anOldSubShape, aSelectionName, false);
+      } else
+        continue;
+    }
+
+    // Get new shapes.
+    ListOfShape aNewShapes;
+    theAlgo->generated(anOldSubShape, aNewShapes);
+
+    keepTopLevelShapes(aNewShapes, anOldSubShape_);
+
+    for (ListOfShape::const_iterator aNewShapesIt = aNewShapes.cbegin();
+         aNewShapesIt != aNewShapes.cend();
+         ++aNewShapesIt)
+    {
+      GeomShapePtr aNewShape = *aNewShapesIt;
+      const TopoDS_Shape& aNewShape_ = aNewShape->impl<TopoDS_Shape>();
+
+      bool aNewShapeIsSameAsOldShape = anOldSubShape->isSame(aNewShape);
+      bool aNewShapeIsNotInResultShape = !aResultShape->isSubShape(aNewShape, false);
+      if (aNewShapeIsSameAsOldShape || aNewShapeIsNotInResultShape) {
+        continue;
       }
-      TopAbs_ShapeEnum aGenShapeType = aNewShape.ShapeType();
-      if(aGenShapeType == TopAbs_WIRE || aGenShapeType == TopAbs_SHELL) {
-        TopAbs_ShapeEnum anExplodeShapeType =
-          aGenShapeType == TopAbs_WIRE ? TopAbs_EDGE : TopAbs_FACE;
-        const TDF_Label aLabel = builder(theTag)->NamedShape()->Label();
-        int aTag = 1;
-        std::shared_ptr<Model_Document> aDoc =
-          std::dynamic_pointer_cast<Model_Document>(document());
-        for(TopExp_Explorer anExp(aNewShape, anExplodeShapeType); anExp.More(); anExp.Next()) {
-          TDF_Label aChildLabel = aLabel.FindChild(aTag);
-          TNaming_Builder aBuilder(aChildLabel);
-          aBuilder.Generated(aRoot, anExp.Current());
-          TCollection_AsciiString aChildName =
-            TCollection_AsciiString((theName + "_").c_str()) + aTag;
-          TDataStd_Name::Set(aChildLabel, aChildName.ToCString());
-          aTag++;
+
+      if (aResultShape->isSame(aNewShape))
+        continue; // it is stored on the root level
+
+      TopAbs_ShapeEnum aNewShapeType = aNewShape_.ShapeType();
+      if (aNewShapeType == TopAbs_WIRE || aNewShapeType == TopAbs_SHELL) {
+        // TODO: This is a workaround. New shape should be only edge or face.
+        TopAbs_ShapeEnum aShapeTypeToExplore = aNewShapeType == TopAbs_WIRE ? TopAbs_EDGE
+                                                                            : TopAbs_FACE;
+        int aTag = aNewShapeType == TopAbs_WIRE ? GENERATED_EDGES_TAG : GENERATED_FACES_TAG;
+        for (TopExp_Explorer anExp(aNewShape_, aShapeTypeToExplore); anExp.More(); anExp.Next()) {
+          builder(aTag)->Generated(anOldSubShape_, anExp.Current());
+          // store information about the external document reference to restore old shape on open
+          storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
         }
+        buildName(aTag, theName);
+      } else {
+        int aTag = getGenerationTag(aNewShape_);
+        if (aTag == INVALID_TAG) return;
+        builder(aTag)->Generated(anOldSubShape_, aNewShape_);
+        buildName(aTag, theName);
+        // store information about the external document reference to restore old shape on open
+        storeExternalReference(anOriginalLabel, builderLabel(data(), aTag));
       }
     }
   }
 }
 
+// LCOV_EXCL_START
 //=======================================================================
 int getDangleShapes(const TopoDS_Shape&           theShapeIn,
   const TopAbs_ShapeEnum        theGeneratedFrom,
@@ -653,10 +811,11 @@ void loadGeneratedDangleShapes(
   for (; itr.More(); itr.Next())
     theBuilder->Generated(itr.Key(), itr.Value());
 }
+// LCOV_EXCL_STOP
 
 //=======================================================================
-void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
-  const std::string& theName, int&  theTag)
+void Model_BodyBuilder::loadNextLevels(GeomShapePtr theShape,
+                                       const std::string& theName)
 {
   if(theShape->isNull()) return;
   TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
@@ -664,11 +823,11 @@ void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
   if (aShape.ShapeType() == TopAbs_SOLID) {
     TopExp_Explorer expl(aShape, TopAbs_FACE);
     for (; expl.More(); expl.Next()) {
-      builder(theTag)->Generated(expl.Current());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(expl.Current());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
   else if (aShape.ShapeType() == TopAbs_SHELL || aShape.ShapeType() == TopAbs_FACE) {
@@ -678,11 +837,11 @@ void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
     if (Faces.Extent() > 1 || (aShape.ShapeType() == TopAbs_SHELL && Faces.Extent() == 1)) {
       TopExp_Explorer expl(aShape, TopAbs_FACE);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
     }
     TopTools_IndexedDataMapOfShapeListOfShape anEdgeAndNeighbourFaces;
@@ -693,21 +852,21 @@ void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
       if (aLL.Extent() < 2) {
         if (BRep_Tool::Degenerated(TopoDS::Edge(anEdgeAndNeighbourFaces.FindKey(i))))
           continue;
-        builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       } else {
         TopTools_ListIteratorOfListOfShape anIter(aLL);
         const TopoDS_Face& aFace = TopoDS::Face(anIter.Value());
         anIter.Next();
         if(aFace.IsEqual(anIter.Value())) {
-          builder(theTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
-          TCollection_AsciiString aStr(theTag);
-          aName = theName + aStr.ToCString();
-          buildName(theTag, aName);
-          theTag++;
+          builder(myFreePrimitiveTag)->Generated(anEdgeAndNeighbourFaces.FindKey(i));
+          TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+          aName = theName + "_" + aStr.ToCString();
+          buildName(myFreePrimitiveTag, aName);
+          ++myFreePrimitiveTag;
         }
       }
     }
@@ -715,40 +874,40 @@ void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
     TopTools_IndexedMapOfShape Edges;
     BRepTools::Map3DEdges(aShape, Edges);
     if (Edges.Extent() == 1) {
-      builder(theTag++)->Generated(Edges.FindKey(1));
+      builder(myFreePrimitiveTag++)->Generated(Edges.FindKey(1));
       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
     } else {
       TopExp_Explorer expl(aShape, TopAbs_EDGE);
       for (; expl.More(); expl.Next()) {
-        builder(theTag)->Generated(expl.Current());
-        TCollection_AsciiString aStr(theTag);
-        aName = theName + aStr.ToCString();
-        buildName(theTag, aName);
-        theTag++;
+        builder(myFreePrimitiveTag)->Generated(expl.Current());
+        TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+        aName = theName + "_" + aStr.ToCString();
+        buildName(myFreePrimitiveTag, aName);
+        ++myFreePrimitiveTag;
       }
       // and load generated vertices.
       TopTools_DataMapOfShapeShape generated;
       if (getDangleShapes(aShape, TopAbs_EDGE, generated))
       {
-        TNaming_Builder* pBuilder = builder(theTag++);
+        TNaming_Builder* pBuilder = builder(myFreePrimitiveTag++);
         loadGeneratedDangleShapes(aShape, TopAbs_EDGE, pBuilder);
       }
     }
   } else if (aShape.ShapeType() == TopAbs_EDGE) {
     TopExp_Explorer expl(aShape, TopAbs_VERTEX);
     for (; expl.More(); expl.Next()) {
-      builder(theTag)->Generated(expl.Current());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(expl.Current());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
     }
   }
 }
@@ -811,170 +970,56 @@ int findAmbiguities(const TopoDS_Shape&           theShapeIn,
 }
 
 //=======================================================================
-void Model_BodyBuilder::loadFirstLevel(
-  std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
+void Model_BodyBuilder::loadFirstLevel(GeomShapePtr theShape, const std::string& theName)
 {
-  if(theShape->isNull()) return;
-  TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
+  GeomShapePtr aShapePtr = shape();
+  if (theShape->isNull() || !aShapePtr.get())
+    return;
+  TopoDS_Shape aShape = shape()->impl<TopoDS_Shape>();
+  if (aShape.IsNull())
+    return;
   std::string aName;
   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
     TopoDS_Iterator itr(aShape);
     for (; itr.More(); itr.Next()) {
-      builder(theTag)->Generated(itr.Value());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      if(!theName.empty()) buildName(theTag, aName);
-      theTag++;
+      builder(myFreePrimitiveTag)->Generated(itr.Value());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
+      ++myFreePrimitiveTag;
       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
         itr.Value().ShapeType() == TopAbs_COMPSOLID)
       {
-        std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
+        GeomShapePtr itrShape(new GeomAPI_Shape());
         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
-        loadFirstLevel(itrShape, theName, theTag);
+        loadFirstLevel(itrShape, theName);
       } else {
-        std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
+        GeomShapePtr itrShape(new GeomAPI_Shape());
         itrShape->setImpl(new TopoDS_Shape(itr.Value()));
-        loadNextLevels(itrShape, theName, theTag);
+        loadNextLevels(itrShape, theName);
       }
     }
   } else {
-    std::shared_ptr<GeomAPI_Shape> itrShape(new GeomAPI_Shape());
+    GeomShapePtr itrShape(new GeomAPI_Shape());
     itrShape->setImpl(new TopoDS_Shape(aShape));
-    loadNextLevels(itrShape, theName, theTag);
+    loadNextLevels(itrShape, theName);
   }
   TopTools_ListOfShape   aList;
   if(findAmbiguities(aShape, aList)) {
     TopTools_ListIteratorOfListOfShape it(aList);
-    for (; it.More(); it.Next(),theTag++) {
-      builder(theTag)->Generated(it.Value());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
+    for (; it.More(); it.Next(), ++myFreePrimitiveTag) {
+      builder(myFreePrimitiveTag)->Generated(it.Value());
+      TCollection_AsciiString aStr(myFreePrimitiveTag - PRIMITIVES_START_TAG + 1);
+      aName = theName + "_" + aStr.ToCString();
+      buildName(myFreePrimitiveTag, aName);
     }
   }
 }
 
-//=======================================================================
-void Model_BodyBuilder::loadDisconnectedEdges(
-  std::shared_ptr<GeomAPI_Shape> theShape, const std::string& theName, int&  theTag)
-{
-  if(theShape->isNull()) return;
-  TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
-  TopTools_DataMapOfShapeListOfShape edgeNaborFaces;
-  TopTools_ListOfShape empty;
-  TopExp_Explorer explF(aShape, TopAbs_FACE);
-  for (; explF.More(); explF.Next()) {
-    const TopoDS_Shape& aFace = explF.Current();
-    TopExp_Explorer explV(aFace, TopAbs_EDGE);
-    for (; explV.More(); explV.Next()) {
-      const TopoDS_Shape& anEdge = explV.Current();
-      if (!edgeNaborFaces.IsBound(anEdge)) edgeNaborFaces.Bind(anEdge, empty);
-      Standard_Boolean faceIsNew = Standard_True;
-      TopTools_ListIteratorOfListOfShape itrF(edgeNaborFaces.Find(anEdge));
-      for (; itrF.More(); itrF.Next()) {
-        if (itrF.Value().IsSame(aFace)) {
-          faceIsNew = Standard_False;
-          break;
-        }
-      }
-      if (faceIsNew)
-        edgeNaborFaces.ChangeFind(anEdge).Append(aFace);
-    }
-  }
-
-  TopTools_MapOfShape anEdgesToDelete;
-  TopExp_Explorer anEx(aShape,TopAbs_EDGE);
-  std::string aName;
-  for(;anEx.More();anEx.Next()) {
-    Standard_Boolean aC0 = Standard_False;
-    TopoDS_Shape anEdge1 = anEx.Current();
-    if (edgeNaborFaces.IsBound(anEdge1)) {
-      const TopTools_ListOfShape& aList1 = edgeNaborFaces.Find(anEdge1);
-      if (aList1.Extent()<2) continue;
-      TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(edgeNaborFaces);
-      for (; itr.More(); itr.Next()) {
-        TopoDS_Shape anEdge2 = itr.Key();
-        if(anEdgesToDelete.Contains(anEdge2)) continue;
-        if (anEdge1.IsSame(anEdge2)) continue;
-        const TopTools_ListOfShape& aList2 = itr.Value();
-        // compare lists of the neighbour faces of edge1 and edge2
-        if (aList1.Extent() == aList2.Extent()) {
-          Standard_Integer aMatches = 0;
-          for(TopTools_ListIteratorOfListOfShape aLIter1(aList1);aLIter1.More();aLIter1.Next())
-            for(TopTools_ListIteratorOfListOfShape aLIter2(aList2);aLIter2.More();aLIter2.Next())
-              if (aLIter1.Value().IsSame(aLIter2.Value())) aMatches++;
-          if (aMatches == aList1.Extent()) {
-            aC0=Standard_True;
-            builder(theTag)->Generated(anEdge2);
-            anEdgesToDelete.Add(anEdge2);
-            TCollection_AsciiString aStr(theTag);
-            aName = theName + aStr.ToCString();
-            buildName(theTag, aName);
-            theTag++;
-          }
-        }
-      }
-      TopTools_MapIteratorOfMapOfShape itDelete(anEdgesToDelete);
-      for(;itDelete.More();itDelete.Next())
-        edgeNaborFaces.UnBind(itDelete.Key());
-      edgeNaborFaces.UnBind(anEdge1);
-    }
-    if (aC0) {
-      builder(theTag)->Generated(anEdge1);
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
-    }
-  }
-}
-
-void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape> theShape,
-                                                 const std::string& theName, int&  theTag)
-{
-  if(theShape->isNull()) return;
-  TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
-  TopTools_DataMapOfShapeListOfShape vertexNaborEdges;
-  TopTools_ListOfShape empty;
-  TopExp_Explorer explF(aShape, TopAbs_EDGE);
-  for (; explF.More(); explF.Next()) {
-    const TopoDS_Shape& anEdge = explF.Current();
-    TopExp_Explorer explV(anEdge, TopAbs_VERTEX);
-    for (; explV.More(); explV.Next()) {
-      const TopoDS_Shape& aVertex = explV.Current();
-      if (!vertexNaborEdges.IsBound(aVertex)) vertexNaborEdges.Bind(aVertex, empty);
-      Standard_Boolean faceIsNew = Standard_True;
-      TopTools_ListIteratorOfListOfShape itrF(vertexNaborEdges.Find(aVertex));
-      for (; itrF.More(); itrF.Next()) {
-        if (itrF.Value().IsSame(anEdge)) {
-          faceIsNew = Standard_False;
-          break;
-        }
-      }
-      if (faceIsNew) {
-        vertexNaborEdges.ChangeFind(aVertex).Append(anEdge);
-      }
-    }
-  }
-  std::string aName;
-  TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itr(vertexNaborEdges);
-  for (; itr.More(); itr.Next()) {
-    const TopTools_ListOfShape& naborEdges = itr.Value();
-    if (naborEdges.Extent() < 2) {
-      builder(theTag)->Generated(itr.Key());
-      TCollection_AsciiString aStr(theTag);
-      aName = theName + aStr.ToCString();
-      buildName(theTag, aName);
-      theTag++;
-    }
-  }
-}
-
-std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
+GeomShapePtr Model_BodyBuilder::shape()
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  if (aData) {
+  if (aData && aData->isValid()) {
     TDF_Label aShapeLab = aData->shapeLab();
     Handle(TDF_Reference) aRef;
     if (aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
@@ -984,36 +1029,11 @@ std::shared_ptr<GeomAPI_Shape> Model_BodyBuilder::shape()
     if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
       TopoDS_Shape aShape = aName->Get();
       if (!aShape.IsNull()) {
-        std::shared_ptr<GeomAPI_Shape> aRes(new GeomAPI_Shape);
+        GeomShapePtr aRes(new GeomAPI_Shape);
         aRes->setImpl(new TopoDS_Shape(aShape));
         return aRes;
       }
     }
   }
-  return std::shared_ptr<GeomAPI_Shape>();
-}
-
-bool Model_BodyBuilder::isLatestEqual(const std::shared_ptr<GeomAPI_Shape>& theShape)
-{
-  if (theShape.get()) {
-    TopoDS_Shape aShape = theShape->impl<TopoDS_Shape>();
-    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-    if (aData) {
-      TDF_Label& aShapeLab = aData->shapeLab();
-      Handle(TNaming_NamedShape) aName;
-      if (aShapeLab.FindAttribute(TNaming_NamedShape::GetID(), aName)) {
-        TopoDS_Shape aLatest = TNaming_Tool::CurrentShape(aName);
-        if (aLatest.IsNull())
-          return false;
-        if (aLatest.IsEqual(aShape))
-          return true;
-        // check sub-shapes for comp-solids:
-        for (TopExp_Explorer anExp(aShape, aLatest.ShapeType()); anExp.More(); anExp.Next()) {
-          if (aLatest.IsEqual(anExp.Current()))
-            return true;
-        }
-      }
-    }
-  }
-  return false;
+  return GeomShapePtr();
 }