Salome HOME
Additional fix for the #2659 optimization
[modules/shaper.git] / src / Model / Model_BodyBuilder.cpp
index 38d349bd7386b89dd822b2ab45ff9d03d22b4c22..8428157d31ca889add69f292514427f879f1dbcd 100755 (executable)
@@ -1,8 +1,22 @@
-// Copyright (C) 2014-20xx CEA/DEN, EDF R&D
-
-// File:        Model_ResultBody.cpp
-// Created:     08 Jul 2014
-// Author:      Mikhail PONIKAROV
+// Copyright (C) 2014-2017  CEA/DEN, EDF R&D
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// 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
+//
+// See http://www.salome-platform.org/ or
+// email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
+//
 
 #include <Model_BodyBuilder.h>
 
@@ -17,6 +31,7 @@
 #include <TopoDS.hxx>
 #include <TopoDS_Face.hxx>
 #include <TDF_ChildIterator.hxx>
+#include <TDF_ChildIDIterator.hxx>
 #include <TDF_Reference.hxx>
 #include <TopTools_MapOfShape.hxx>
 #include <TopExp_Explorer.hxx>
 #include <TopExp.hxx>
 #include <BRepTools.hxx>
 #include <BRep_Tool.hxx>
+#include <BRepTools_History.hxx>
 #include <GeomAPI_Shape.h>
 #include <GeomAlgoAPI_MakeShape.h>
+#include <GeomAlgoAPI_SortListOfShapes.h>
 #include <Config_PropManager.h>
 // DEB
 //#include <TCollection_AsciiString.hxx>
 //#define DEB_IMPORT 1
 
 Model_BodyBuilder::Model_BodyBuilder(ModelAPI_Object* theOwner)
-: ModelAPI_BodyBuilder(theOwner)
+: ModelAPI_BodyBuilder(theOwner),
+  myDividedIndex(1),
+  myVIndex(1),
+  myEIndex(1),
+  myFIndex(1)
 {
 }
 
@@ -79,7 +100,12 @@ static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
     std::list<std::pair<TopoDS_Shape, TopoDS_Shape> >::iterator aPairsIter = aShapePairs.begin();
     for(; aPairsIter != aShapePairs.end(); aPairsIter++) {
       if (theFlag) { // disabled => make selection
-        aBuilder.Select(aPairsIter->second, aPairsIter->first);
+        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) {
@@ -103,7 +129,7 @@ static void evolutionToSelectionRec(TDF_Label theLab, const bool theFlag) {
 void Model_BodyBuilder::evolutionToSelection(const bool theFlag)
 {
   std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-  if (!aData) // unknown case
+  if (!aData || !aData->isValid()) // unknown case
     return;
   TDF_Label& aShapeLab = aData->shapeLab();
   evolutionToSelectionRec(aShapeLab, theFlag);
@@ -187,6 +213,18 @@ void Model_BodyBuilder::storeGenerated(const std::shared_ptr<GeomAPI_Shape>& the
   }
 }
 
+TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
+{
+  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;
+}
+
 void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theOldShape,
   const std::shared_ptr<GeomAPI_Shape>& theNewShape, const int theDecomposeSolidsTag)
 {
@@ -194,9 +232,10 @@ void Model_BodyBuilder::storeModified(const std::shared_ptr<GeomAPI_Shape>& theO
   if (aData) {
     TDF_Label& aShapeLab = aData->shapeLab();
     // clean builders
-    clean();
+    if (theDecomposeSolidsTag != -2)
+      clean();
     // store the new shape as primitive
-    TNaming_Builder aBuilder(aShapeLab);
+    TNaming_Builder* aBuilder = builder(0);
     if (!theOldShape || !theNewShape)
       return;  // bad shape
     TopoDS_Shape aShapeOld = theOldShape->impl<TopoDS_Shape>();
@@ -205,15 +244,15 @@ 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()) {
+    aBuilder->Modify(aShapeOld, aShapeNew);
+    if(!aBuilder->NamedShape()->IsEmpty()) {
       Handle(TDataStd_Name) anAttr;
-      if(aBuilder.NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
+      if(aBuilder->NamedShape()->Label().FindAttribute(TDataStd_Name::GetID(),anAttr)) {
         std::string aName (TCollection_AsciiString(anAttr->Get()).ToCString());
         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);
         }
       }
     }
@@ -237,10 +276,25 @@ void  Model_BodyBuilder::storeWithoutNaming(const std::shared_ptr<GeomAPI_Shape>
 
 void Model_BodyBuilder::clean()
 {
-  std::vector<TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
-  for(; aBuilder != myBuilders.end(); aBuilder++)
-    delete *aBuilder;
+  TDF_Label aLab = std::dynamic_pointer_cast<Model_Data>(data())->shapeLab();
+  if (aLab.IsNull())
+    return;
+  std::map<int, TNaming_Builder*>::iterator aBuilder = myBuilders.begin();
+  for(; aBuilder != myBuilders.end(); aBuilder++) {
+    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();
+    }
+  }
   myBuilders.clear();
+  // remove the old reference (if any)
+  aLab.ForgetAttribute(TDF_Reference::GetID());
+  myDividedIndex = 1;
+  myVIndex = 1;
+  myEIndex = 1;
+  myFIndex = 1;
 }
 
 Model_BodyBuilder::~Model_BodyBuilder()
@@ -248,21 +302,6 @@ Model_BodyBuilder::~Model_BodyBuilder()
   clean();
 }
 
-TNaming_Builder* Model_BodyBuilder::builder(const int theTag)
-{
-  if (myBuilders.size() <= (unsigned int)theTag) {
-    myBuilders.insert(myBuilders.end(), theTag - myBuilders.size() + 1, NULL);
-  }
-  if (!myBuilders[theTag]) {
-    std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
-    myBuilders[theTag] = new TNaming_Builder(aData->shapeLab().FindChild(theTag));
-    //TCollection_AsciiString entry;//
-    //TDF_Tool::Entry(aData->shapeLab().FindChild(theTag), entry);
-    //cout << "Label = " <<entry.ToCString() <<endl;
-  }
-  return myBuilders[theTag];
-}
-
 void Model_BodyBuilder::buildName(const int theTag, const std::string& theName)
 {
   std::shared_ptr<Model_Document> aDoc = std::dynamic_pointer_cast<Model_Document>(document());
@@ -325,22 +364,88 @@ void Model_BodyBuilder::deleted(const std::shared_ptr<GeomAPI_Shape>& theOldShap
 void Model_BodyBuilder::loadDeletedShapes (GeomAlgoAPI_MakeShape* theMS,
   std::shared_ptr<GeomAPI_Shape>  theShapeIn,
   const int  theKindOfShape,
-  const int  theTag)
+  const int  theTag,
+  const GeomShapePtr theShapes)
 {
   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
   TopTools_MapOfShape aView;
   TopExp_Explorer ShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
+  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 (!theMS->isDeleted(aRShape)
+        || aResultShape->isSubShape(aRShape, false)
+        || (theShapes.get() && theShapes->isSubShape(aRShape, false))) {
+      continue;
+    }
+
+    ListOfShape aHist;
+    if (BRepTools_History::IsSupportedType(aRoot)) // to avoid crash in #2572
+      theMS->modified(aRShape, aHist);
+    if (aHist.size() == 0 || (aHist.size() == 1 && aHist.front()->isSame(aRShape)))
       builder(theTag)->Delete(aRoot);
+  }
+}
+
+static void removeBadShapes(ListOfShape& theShapes)
+{
+  ListOfShape::iterator anIt = theShapes.begin();
+  while (anIt != theShapes.end()) {
+    TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
+    bool aSkip = aNewShape.IsNull()
+      || (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
+    if (aSkip) {
+      ListOfShape::iterator aRemoveIt = anIt++;
+      theShapes.erase(aRemoveIt);
+    } else {
+      ++anIt;
     }
   }
 }
 
+// Keep only the shapes with minimal shape type
+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();
+  while (anIt != theShapes.end()) {
+    TopoDS_Shape aNewShape = (*anIt)->impl<TopoDS_Shape>();
+    bool aSkip = aNewShape.IsNull() ||
+      (aNewShape.ShapeType() == TopAbs_EDGE && BRep_Tool::Degenerated(TopoDS::Edge(aNewShape)));
+    if (aSkip || theRoot.IsSame(aNewShape) || (theResultShape &&
+        (!theResultShape->isSubShape(*anIt, false) || theResultShape->isSame(*anIt)))) {
+      ListOfShape::iterator aRemoveIt = anIt++;
+      theShapes.erase(aRemoveIt);
+    } else {
+      GeomAPI_Shape::ShapeType aType = (*anIt)->shapeType();
+      if (aType < aKeepShapeType) {
+        // found a shape with lesser shape type => remove all previous shapes
+        aKeepShapeType = aType;
+        theShapes.erase(theShapes.begin(), anIt);
+        ++anIt;
+      } else if (aType > aKeepShapeType) {
+        // shapes with greater shape type should be removed from the list
+        ListOfShape::iterator aRemoveIt = anIt++;
+        theShapes.erase(aRemoveIt);
+      } else
+        ++anIt;
+    }
+  }
+}
+
+// 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,
@@ -348,8 +453,11 @@ void Model_BodyBuilder::loadAndOrientModifiedShapes (
   const int  theTag,
   const std::string& theName,
   GeomAPI_DataMapOfShapeShape& theSubShapes,
-  const bool theIsStoreSeparate)
+  const bool theIsStoreSeparate,
+  const bool theIsStoreAsGenerated)
 {
+  static const int THE_ANCHOR_TAG = 100000;
+
   int anIndex = 1;
   int aTag = theTag;
   bool isBuilt = !theName.empty();
@@ -358,14 +466,45 @@ void Model_BodyBuilder::loadAndOrientModifiedShapes (
   GeomShapePtr aResultShape = shape();
   TopoDS_Shape aShapeIn = theShapeIn->impl<TopoDS_Shape>();
   TopTools_MapOfShape aView;
-  TopExp_Explorer aShapeExplorer (aShapeIn, (TopAbs_ShapeEnum)theKindOfShape);
+  std::shared_ptr<Model_Data> aData = std::dynamic_pointer_cast<Model_Data>(data());
+
+  TopoDS_Shape aShapeToIterate;
+  if (theMS->newShapesCollected(theShapeIn, theKindOfShape)) {
+    // use optimized set of old shapes for this
+    GeomShapePtr aCompound = theMS->oldShapesForNew(theShapeIn, aResultShape, theKindOfShape);
+    if (aCompound.get())
+      aShapeToIterate = aCompound->impl<TopoDS_Shape>();
+  } else {
+    aShapeToIterate = aShapeIn;
+  }
+
+  TopExp_Explorer aShapeExplorer (aShapeToIterate, (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);
+      removeBadShapes(aList);
+    }
+    // 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 = (aShapeIn.ShapeType() == TopAbs_WIRE
+                             || aShapeIn.ShapeType() == TopAbs_SHELL
+                             || aShapeIn.ShapeType() == TopAbs_COMPOUND) ? 0 : -1;
     std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator
       anIt = aList.begin(), aLast = aList.end();
     for (; anIt != aLast; anIt++) {
@@ -374,22 +513,210 @@ void Model_BodyBuilder::loadAndOrientModifiedShapes (
         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)) {
-        builder(aTag)->Modify(aRoot,aNewShape);
+      isBuilt = !theName.empty();
+      if(!aRoot.IsSame(aNewShape)
+         && aResultShape->isSubShape((*anIt), false)
+         && !aResultShape->isSame(*anIt)) // to avoid put of same shape on main label and sub
+      {
+        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
+            }
+          }
+        }
+
+        int aFoundTag = 0;
+        bool isFoundSameOld = false;
+        bool isFoundDiffOld = false;
+
+        // Check if new shape was already stored.
+        for (std::map<int, TNaming_Builder*>::iterator aBuildersIt = myBuilders.begin();
+             aBuildersIt != myBuilders.end();
+             ++aBuildersIt)
+        {
+          TNaming_Builder* aBuilder = aBuildersIt->second;
+          for (TNaming_Iterator aNamingIt(aBuilder->NamedShape());
+               aNamingIt.More();
+               aNamingIt.Next())
+          {
+            if (aNamingIt.NewShape().IsSame(aNewShape))
+            {
+              aNamingIt.OldShape().IsSame(aRoot) ? isFoundSameOld = true
+                                                 : isFoundDiffOld = true;
+              aFoundTag = aBuildersIt->first;
+            }
+          }
+
+          if (isFoundSameOld || isFoundDiffOld) break;
+        }
+
+        if (isFoundSameOld) {
+          // Builder already contains same old->new shapes, don't store it twice.
+          continue;
+        }
+
+        int aBuilderTag = aSameParentShapes > 0 ? THE_ANCHOR_TAG : aTag;
+
+        int aCurShapeType = (int)((*anIt)->shapeType());
+        bool needSuffix = false; // suffix for the name based on the shape type
+        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;
+          needSuffix = true;
+        }
+        std::string aSuffix;
+        if (needSuffix) {
+          switch (aCurShapeType) {
+            case GeomAPI_Shape::VERTEX: aSuffix = "_v_" + std::to_string(myVIndex++); break;
+            case GeomAPI_Shape::EDGE:   aSuffix = "_e_" + std::to_string(myEIndex++); break;
+            case GeomAPI_Shape::FACE:   aSuffix = "_f_" + std::to_string(myFIndex++); break;
+            default: break;
+          }
+        }
+
+        std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>> aKeepShapes, aMoveShapes;
+        if (isFoundDiffOld) {
+          // Found same new shape with different old shape.
+          if (aFoundTag >= THE_ANCHOR_TAG) {
+            // Found on separated tag.
+            aBuilderTag = aFoundTag; // Store it on the same tag.
+            isBuilt = false; // Don't change name;
+          } else {
+            // Found on previous tag.
+            if (aBuilderTag < THE_ANCHOR_TAG) {
+              // New shape shouls not be separated.
+              aBuilderTag = aFoundTag; // Store it on the same tag.
+              isBuilt = false; // Don't change name;
+            } else {
+              // New shape should be separated from others. Move shapes from found tag to new tag.
+              while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
+                ++aBuilderTag;
+              }
+
+              TNaming_Builder* aFoundBuilder = myBuilders.at(aFoundTag);
+              Handle(TNaming_NamedShape) aFoundNamedShape = aFoundBuilder->NamedShape();
+              TDF_Label aFoundLabel = aFoundNamedShape->Label();
+              TNaming_Evolution anEvolution = aFoundNamedShape->Evolution();
+              for (TNaming_Iterator aNamingIt(aFoundNamedShape);
+                   aNamingIt.More();
+                   aNamingIt.Next())
+              {
+                std::pair<TopoDS_Shape, TopoDS_Shape> aShapesPair =
+                  std::make_pair(aNamingIt.OldShape(), aNamingIt.NewShape());
+                aNamingIt.NewShape().IsSame(aNewShape) ? aMoveShapes.push_back(aShapesPair)
+                                                       : aKeepShapes.push_back(aShapesPair);
+              }
+
+              aFoundNamedShape->Clear();
+              for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aKeepIt =
+                     aKeepShapes.begin();
+                   aKeepIt != aKeepShapes.end();
+                   ++aKeepIt)
+              {
+                if (anEvolution == TNaming_GENERATED) {
+                  aFoundBuilder->Generated(aKeepIt->first, aKeepIt->second);
+                } else {
+                  aFoundBuilder->Modify(aKeepIt->first, aKeepIt->second);
+                }
+              }
+            }
+          }
+        } else if (aBuilderTag == THE_ANCHOR_TAG) {
+          while (myBuilders.find(aBuilderTag) != myBuilders.end()) {
+            ++aBuilderTag;
+          }
+        }
+
+        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);
+          for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
+               aMoveShapes.begin();
+               aMoveIt != aMoveShapes.end();
+               ++aMoveIt)
+          {
+            builder(aBuilderTag)->Generated(aMoveIt->first, aMoveIt->second);
+          }
+        } else if (aNotInTree) {
+          // not in tree -> store as primitive (stored as separated)
+          builder(aBuilderTag)->Generated(aNewShape);
+        } else if (aCurShapeType != theKindOfShape) {
+           // if different shape type is produced, make it as generated
+          builder(aBuilderTag)->Generated(aRoot, aNewShape);
+        } else {
+          builder(aBuilderTag)->Modify(aRoot, aNewShape);
+          for (std::vector<std::pair<TopoDS_Shape, TopoDS_Shape>>::iterator aMoveIt =
+               aMoveShapes.begin();
+               aMoveIt != aMoveShapes.end();
+               ++aMoveIt) {
+            builder(aBuilderTag)->Modify(aMoveIt->first, aMoveIt->second);
+          }
+        }
         if(isBuilt) {
-          if(theIsStoreSeparate) {
+          aStream.str(std::string());
+          aStream.clear();
+          aStream << theName;
+          if (theIsStoreSeparate && !isFoundDiffOld)
+             aStream << "_" << anIndex++;
+
+          if (aSameParentShapes > 0) {
             aStream.str(std::string());
             aStream.clear();
-            aStream << theName << "_" << anIndex++;
-            aName = aStream.str();
+            aStream << aName << "_" << "divided" << "_" << myDividedIndex++;
           }
-          buildName(aTag, aName);
+
+          aStream << aSuffix;
+          buildName(aBuilderTag, aStream.str());
         }
-        if(theIsStoreSeparate) {
+        if(theIsStoreSeparate && !isFoundDiffOld) {
           aTag++;
         }
+      } else if (aResultShape->isSame(*anIt)) {
+        // keep the modification evolution on the root level (2241 - history propagation issue)
+        TNaming_Builder* aBuilder = builder(0);
+        TDF_Label aShapeLab = aBuilder->NamedShape()->Label();
+        Handle(TDF_Reference) aRef;
+        // Store only in case if it does not have reference.
+        if (!aShapeLab.FindAttribute(TDF_Reference::GetID(), aRef)) {
+          if (theIsStoreAsGenerated) {
+            TNaming_Builder* aBuilder = builder(0);
+            if (!aBuilder->NamedShape().IsNull() &&
+                aBuilder->NamedShape()->Evolution() != TNaming_GENERATED) {
+              myBuilders.erase(0); // clear old builder to avoid different evolutions crash
+            }
+            builder(0)->Generated(aRoot, aNewShape);
+          } else {
+            TNaming_Builder* aBuilder = builder(0);
+            if (!aBuilder->NamedShape().IsNull() &&
+              aBuilder->NamedShape()->Evolution() != TNaming_MODIFY) {
+              myBuilders.erase(0); // clear old builder to avoid different evolutions crash
+            }
+            builder(0)->Modify(aRoot, aNewShape);
+          }
+        }
       }
     }
   }
@@ -410,10 +737,13 @@ void Model_BodyBuilder::loadAndOrientGeneratedShapes (
   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++) {
@@ -543,7 +873,7 @@ 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(theTag++)->Generated(Edges.FindKey(1));
       TopExp_Explorer expl(aShape, TopAbs_VERTEX);
       for (; expl.More(); expl.Next()) {
         builder(theTag)->Generated(expl.Current());
@@ -585,42 +915,57 @@ void Model_BodyBuilder::loadNextLevels(std::shared_ptr<GeomAPI_Shape> theShape,
 int findAmbiguities(const TopoDS_Shape&           theShapeIn,
   TopTools_ListOfShape&   theList)
 {
-  int aNumEdges(0);
   theList.Clear();
-  TopTools_IndexedDataMapOfShapeListOfShape subShapeAndAncestors;
-  TopAbs_ShapeEnum aTS(TopAbs_EDGE);
-  TopAbs_ShapeEnum aTA(TopAbs_FACE);
-  TopTools_MapOfShape aMap1, aMap2; // map1 - for edge ancestors; map2 - for keys => edges
-  TopTools_ListOfShape aKeyList;
-  TopExp::MapShapesAndAncestors(theShapeIn, aTS, aTA, subShapeAndAncestors);
-  for (Standard_Integer i = 1; i <= subShapeAndAncestors.Extent(); i++) {
-    const TopoDS_Shape& aKeyEdge1 = subShapeAndAncestors.FindKey(i);
-    const TopTools_ListOfShape& ancestors1 = subShapeAndAncestors.FindFromIndex(i);
-    aMap1.Clear();
-    TopTools_ListIteratorOfListOfShape it(ancestors1);
-    for(;it.More();it.Next()) aMap1.Add(it.Value()); // fill map with key ancestors => aKey1
-    for (Standard_Integer j = 1; j <= subShapeAndAncestors.Extent(); j++) {
-      if (i == j) continue;
-      const TopoDS_Shape& aKeyEdge2 = subShapeAndAncestors.FindKey(j);
-      const TopTools_ListOfShape& ancestors2 = subShapeAndAncestors.FindFromIndex(j);
-      if(ancestors1.Extent() == ancestors2.Extent() && ancestors1.Extent() > 1) {
-        int aNum (ancestors2.Extent());
-        TopTools_ListIteratorOfListOfShape it(ancestors2);
-        for(;it.More();it.Next())
-          if(aMap1.Contains(it.Value())) aNum--;
-        if(aNum == 0) {
-          if(aMap2.Add(aKeyEdge1))
-            aKeyList.Append(aKeyEdge1);
-          if(aMap2.Add(aKeyEdge2))
-            aKeyList.Append(aKeyEdge2);
+  // edges -> ancestor faces list
+  TopTools_IndexedDataMapOfShapeListOfShape aSubShapeAndAncestors;
+  TopExp::MapShapesAndAncestors(theShapeIn, TopAbs_EDGE, TopAbs_FACE, aSubShapeAndAncestors);
+  // keeps the shapes which are already in the resulting list
+  TopTools_MapOfShape alreadyThere;
+  // map from faces identifier (combination of hash-codes) to list of edges produced such ID
+  NCollection_DataMap<int, NCollection_List<TopoDS_Shape> > aFacesIDs;
+
+  TopTools_IndexedDataMapOfShapeListOfShape::Iterator anAncestorsIter(aSubShapeAndAncestors);
+  for (; anAncestorsIter.More(); anAncestorsIter.Next()) {
+    const TopTools_ListOfShape& ancestors = anAncestorsIter.Value();
+    if (ancestors.Extent() < 2)
+      continue;
+    Standard_Integer anID = 0;
+    for(TopTools_ListIteratorOfListOfShape aFaceIt(ancestors); aFaceIt.More(); aFaceIt.Next()) {
+      anID ^= HashCode(aFaceIt.ChangeValue(), 1990657); // Pierpont prime
+    }
+    if (aFacesIDs.IsBound(anID)) { // there found same edge, check they really have same faces
+      const NCollection_List<TopoDS_Shape>& aSameFaces1 =
+        aSubShapeAndAncestors.FindFromKey(anAncestorsIter.Key());
+      NCollection_List<TopoDS_Shape>::Iterator aSameEdge(aFacesIDs.ChangeFind(anID));
+      for(; aSameEdge.More(); aSameEdge.Next()) {
+        const NCollection_List<TopoDS_Shape>& aSameFaces2 =
+          aSubShapeAndAncestors.FindFromKey(aSameEdge.Value());
+        if (aSameFaces2.Extent() != aSameFaces1.Extent()) // the number of faces is different
+          break;
+
+        NCollection_List<TopoDS_Shape>::Iterator aFaceIter1(aSameFaces1);
+        for(; aFaceIter1.More(); aFaceIter1.Next()) {
+          NCollection_List<TopoDS_Shape>::Iterator aFaceIter2(aSameFaces2);
+          for(; aFaceIter2.More(); aFaceIter2.Next()) {
+            if (aFaceIter1.Value().IsSame(aFaceIter2.Value()))
+              break;
+          }
+          if (!aFaceIter2.More()) // aFaceIter1 contains a face, which is not in aFaceIter2
+            break;
+        }
+        if (!aFaceIter1.More()) { // all the faces are same => put to the result
+          if (alreadyThere.Add(aSameEdge.Value()))
+            theList.Append(aSameEdge.Value());
+          if (alreadyThere.Add(anAncestorsIter.Key()))
+            theList.Append(anAncestorsIter.Key());
         }
       }
-    } // at the end ==> List of edges to be named in addition
+    } else { // ID is unique, just add this edge
+      aFacesIDs.Bind(anID, NCollection_List<TopoDS_Shape>());
+    }
+    aFacesIDs.ChangeFind(anID).Append(anAncestorsIter.Key()); // add to the list anyway
   }
-  aNumEdges = aKeyList.Extent();
-  if(aNumEdges)
-    theList.Assign(aKeyList);
-  return aNumEdges;
+  return theList.Extent();
 }
 
 //=======================================================================
@@ -632,12 +977,13 @@ void Model_BodyBuilder::loadFirstLevel(
   std::string aName;
   if (aShape.ShapeType() == TopAbs_COMPOUND || aShape.ShapeType() == TopAbs_COMPSOLID) {
     TopoDS_Iterator itr(aShape);
-    for (; itr.More(); itr.Next(),theTag++) {
+    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++;
       if (itr.Value().ShapeType() == TopAbs_COMPOUND ||
         itr.Value().ShapeType() == TopAbs_COMPSOLID)
       {
@@ -786,7 +1132,7 @@ void Model_BodyBuilder::loadDisconnectedVertexes(std::shared_ptr<GeomAPI_Shape>
 std::shared_ptr<GeomAPI_Shape> 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)) {