Salome HOME
0021189: [CEA 451] areCoordsInside implementation in GE
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
index e6da3ad15bddf34d4343ea906390ab0e6e7891a6..9fffbf9779b214de5cb039e451b6a2a6103514bc 100644 (file)
@@ -1,4 +1,4 @@
-//  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+//  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
 //
 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
@@ -18,6 +18,7 @@
 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 //
 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
 
 #ifdef WNT
 #pragma warning( disable:4786 )
@@ -34,6 +35,8 @@
 
 #include "utilities.h"
 
+#include <Basics_Utils.hxx>
+
 #include <TDF_Tool.hxx>
 #include <TDF_Data.hxx>
 #include <TDF_Reference.hxx>
@@ -61,9 +64,6 @@
 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
 
 #include <set>
-#include <map>
-#include <string>
-#include <vector>
 
 #include <Standard_Failure.hxx>
 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
@@ -81,9 +81,12 @@ static int MYDEBUG = 0;
 static int MYDEBUG = 0;
 #endif
 
+typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
+typedef std::map< TCollection_AsciiString, TObjectData >             TSting2ObjDataMap;
+typedef std::map< TCollection_AsciiString, TObjectData* >            TSting2ObjDataPtrMap;
+
 static GEOM_Engine* TheEngine = NULL;
 
-using namespace std;
 
 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
 {
@@ -107,40 +110,74 @@ static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
   return aDocID.IntegerValue();
 }
 
-bool ProcessFunction(Handle(GEOM_Function)&   theFunction,
-                     TCollection_AsciiString& theScript,
-                     TCollection_AsciiString& theAfterScript,
-                     const TVariablesList&    theVariables,
-                     const bool               theIsPublished,
-                     TDF_LabelMap&            theProcessed,
-                     std::set<std::string>&   theIgnoreObjs,
-                     bool&                    theIsDumpCollected);
+bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
+                     TCollection_AsciiString&           theScript,
+                     TCollection_AsciiString&           theAfterScript,
+                     const TVariablesList&              theVariables,
+                     const bool                         theIsPublished,
+                     TDF_LabelMap&                      theProcessed,
+                     std::set<TCollection_AsciiString>& theIgnoreObjs,
+                     bool&                              theIsDumpCollected);
 
-void ReplaceVariables(TCollection_AsciiString& theCommand, 
+void ReplaceVariables(TCollection_AsciiString& theCommand,
                       const TVariablesList&    theVariables);
 
 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
 
 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
-                            Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
+                            TSting2ObjDataMap&                        aEntry2ObjData,
                             const bool                                theIsPublished,
-                            Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
-                            TColStd_SequenceOfAsciiString&            theObjListToPublish);
+                            TColStd_SequenceOfAsciiString&            theObjListToPublish,
+                            Standard_Integer&                         objectCounter,
+                            Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
 
-void AddObjectColors (int                                             theDocID,
-                      TCollection_AsciiString&                        theScript,
-                      const Resource_DataMapOfAsciiStringAsciiString& theObjectNames);
+void AddObjectColors (int                      theDocID,
+                      TCollection_AsciiString& theScript,
+                      const TSting2ObjDataMap& theEntry2ObjData);
 
 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
 
-void PublishObject (const TCollection_AsciiString&                  theEntry,
-                    const TCollection_AsciiString&                  theName,
-                    const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
-                    const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
-                    const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
-                    const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
-                    std::map< int, std::string >&                   theEntryToCommandMap,
-                    std::set<std::string>&                          theMapOfPublished);
+void PublishObject (TObjectData&                              theObjectData,
+                    TSting2ObjDataMap&                        theEntry2ObjData,
+                    const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
+                    Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
+                    TSting2StringMap&                         theEntryToCmdMap,
+                    std::set<TCollection_AsciiString>&        theMapOfPublished);
+
+namespace
+{
+  //================================================================================
+  /*!
+   * \brief Fix up the name of python variable
+   */
+  //================================================================================
+
+  void healPyName( TCollection_AsciiString&                  pyName,
+                   const TCollection_AsciiString&            anEntry,
+                   Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
+  {
+    const TCollection_AsciiString allowedChars
+      ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
+
+    if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
+      pyName.Insert( 1, 'a' );
+    }
+    int p, p2=1; // replace not allowed chars
+    while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
+      pyName.SetValue(p, '_');
+      p2=p;
+    }
+    if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
+    {  // diff objects have same name - make a new name by appending a digit
+      TCollection_AsciiString aName2;
+      Standard_Integer i = 0;
+      do {
+        aName2 = pyName + "_" + ++i;
+      } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
+      pyName = aName2;
+    }
+  }
+}
 
 //=======================================================================
 //function : GetTextureGUID
@@ -185,10 +222,12 @@ GEOM_Engine::GEOM_Engine()
 GEOM_Engine::~GEOM_Engine()
 {
   GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
+  std::list< Handle(GEOM_Object) > objs;
   for(; It.More(); It.Next())
-    {
-      RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
-    }
+    objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
+  std::list< Handle(GEOM_Object) >::iterator objit;
+  for(objit = objs.begin(); objit != objs.end(); ++objit)
+    RemoveObject(*objit);
 
   //Close all documents not closed
   for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
@@ -306,7 +345,7 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
                                              Handle(TColStd_HArray1OfInteger) theIndices,
                                              bool isStandaloneOperation)
 {
-  if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
+  if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
 
   Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
   Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
@@ -315,21 +354,6 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
   //            if this label has been freed (object deleted)
   bool useExisting = false;
   TDF_Label aChild;
-  /*
-  if (!_lastCleared.IsNull()) {
-    if (_lastCleared.Root() == aDoc->Main().Root()) {
-      useExisting = true;
-      aChild = _lastCleared;
-      // 0020229: if next label exists and is empty, try to reuse it
-      Standard_Integer aNextTag = aChild.Tag() + 1;
-      TDF_Label aNextL = aDoc->Main().FindChild(aNextTag, Standard_False);
-      if (!aNextL.IsNull() && !aNextL.HasAttribute())
-        _lastCleared = aNextL;
-      else
-        _lastCleared.Nullify();
-    }
-  }
-  */
   int aDocID = theMainShape->GetDocID();
   if (_freeLabels.find(aDocID) != _freeLabels.end()) {
     std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
@@ -345,10 +369,10 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
   }
 
   Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
-  Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
+  Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
   Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
 
-  GEOM_ISubShape aSSI(aFunction);
+  GEOM_ISubShape aSSI (aFunction);
   aSSI.SetMainShape(aMainShape);
   aSSI.SetIndices(theIndices);
 
@@ -368,11 +392,14 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
     return NULL;
   }
 
-  //Put an object in the map of created objects
+  // Put an object in the map of created objects
   TCollection_AsciiString anID = BuildIDFromObject(anObject);
-  if(_objects.IsBound(anID)) _objects.UnBind(anID);
+  if (_objects.IsBound(anID)) _objects.UnBind(anID);
   _objects.Bind(anID, anObject);
 
+  // Put this subshape in the list of subshapes of theMainShape
+  aMainShape->AddSubShapeReference(aFunction);
+
   GEOM::TPythonDump pd (aFunction);
 
   if (isStandaloneOperation) {
@@ -401,14 +428,24 @@ bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
   int aDocID = theObject->GetDocID();
   if(!_mapIDDocument.IsBound(aDocID))
     return false;  // document is closed...
-  
+
   //Remove an object from the map of available objects
   TCollection_AsciiString anID = BuildIDFromObject(theObject);
   if (_objects.IsBound(anID)) _objects.UnBind(anID);
 
+  // If subshape, remove it from the list of subshapes of its main shape
+  if (!theObject->IsMainShape()) {
+    Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
+    GEOM_ISubShape aSSI (aFunction);
+    Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
+    //If main shape is not null, then remove
+    if(!aMainShape.IsNull())
+      aMainShape->RemoveSubShapeReference(aFunction);
+  }
+
   int nb = theObject->GetNbFunctions();
   Handle(TDataStd_TreeNode) aNode;
-  for (int i = 1; i<=nb; i++) {
+  for (int i = 1; i <= nb; i++) {
     Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
     if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
       aNode->Remove();
@@ -521,11 +558,14 @@ void GEOM_Engine::Close(int theDocID)
  */
 //=============================================================================
 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
-                                                Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
+                                                std::vector<TObjectData>& theObjectData,
                                                 TVariablesList theVariables,
                                                 bool isPublished,
                                                 bool& aValidScript)
 {
+  // Set "C" numeric locale to save numbers correctly
+  Kernel_Utils::Localizer loc;
+
   TCollection_AsciiString aScript;
   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
 
@@ -542,38 +582,47 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
 
   Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
 
-  Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
-  Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
-  // build maps entry <-> studyEntry
-  for (anEntryToNameIt.Initialize( theObjectNames );
-       anEntryToNameIt.More();
-       anEntryToNameIt.Next())
+  // a map containing copies of TObjectData from theObjectData
+  TSting2ObjDataMap    aEntry2ObjData;
+  // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
+  // occures when several StudyEntries correspond to one Entry
+  TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
+
+  //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
+  for (unsigned i = 0; i < theObjectData.size(); ++i )
   {
-    const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
+    TObjectData& data = theObjectData[i];
     // look for an object by entry
     TDF_Label L;
-    TDF_Tool::Label( aDoc->GetData(), aEntry, L );
+    TDF_Tool::Label( aDoc->GetData(), data._entry, L );
     if ( L.IsNull() ) continue;
     Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
     // fill maps
     if ( !obj.IsNull() ) {
-      TCollection_AsciiString aStudyEntry (obj->GetAuxData());
-      aEntry2StEntry.Bind( aEntry,  aStudyEntry);
-      aStEntry2Entry.Bind( aStudyEntry, aEntry );
+      TSting2ObjDataMap::iterator ent2Data =
+        aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
+
+      if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
+        aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
+      else
+        aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
     }
   }
 
   // collect objects entries to be published
   TColStd_SequenceOfAsciiString aObjListToPublish;
-  
+
   // iterates on functions till critical (that requiers publication of objects)
   Handle(TDataStd_TreeNode) aNode, aRoot;
   Handle(GEOM_Function) aFunction;
   TDF_LabelMap aCheckedFuncMap;
-  std::set<std::string> anIgnoreObjMap;
+  std::set< TCollection_AsciiString > anIgnoreObjMap;
 
   TCollection_AsciiString aFuncScript;
-  Resource_DataMapOfAsciiStringAsciiString anEntryToBadName;
+
+  // Mantis issue 0020768
+  Standard_Integer objectCounter = 0;
+  Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
 
   if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
     TDataStd_ChildNodeIterator Itr(aRoot);
@@ -595,29 +644,28 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
         aFuncScript += aCurScript;
       if (isDumpCollected ) {
         // Replace entries by the names
-        ReplaceEntriesByNames( aFuncScript, theObjectNames,
-                               isPublished, anEntryToBadName, aObjListToPublish );
-        
+        ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
+                               aObjListToPublish, objectCounter, aNameToEntry );
+
         // publish collected objects
-        std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
+        TSting2StringMap anEntryToCmdMap; // sort publishing commands by study entry
         int i = 1, n = aObjListToPublish.Length();
         for ( ; i <= n; i++ )
         {
           const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
-          if (!theObjectNames.IsBound( aEntry ))
-            continue;
-          PublishObject( aEntry, theObjectNames.Find(aEntry),
-                        theObjectNames, aEntry2StEntry, aStEntry2Entry,
-                        anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
+          PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
+                         aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
         }
         // add publishing commands to the script
-        std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
-        for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
-          aFuncScript += (char*)anEntryToCommand->second.c_str();
-        
-        // PTv, 0020001 add result objects from RestoreSubShapes into ignore list,
+        TSting2StringMap::iterator anEntryToCmd = anEntryToCmdMap.begin();
+        for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
+          aFuncScript += anEntryToCmd->second;
+
+        // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
         //  because they will be published during command execution
-        int indx = anAfterScript.Search( "RestoreSubShapes" );
+        int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
+        if ( indx == -1 )
+          indx = anAfterScript.Search( "RestoreSubShapes" );
         if ( indx != -1 ) {
           TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
           Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
@@ -625,8 +673,7 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
           for ( ; i <= n; i+=2) {
             TCollection_AsciiString anEntry =
               aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
-            if (!anIgnoreObjMap.count(anEntry.ToCString()))
-              anIgnoreObjMap.insert(anEntry.ToCString());
+            anIgnoreObjMap.insert(anEntry.ToCString());
           }
         }
 
@@ -640,34 +687,34 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
 
   // Replace entries by the names
   aObjListToPublish.Clear();
-  ReplaceEntriesByNames( aFuncScript, theObjectNames,
-                         isPublished, anEntryToBadName, aObjListToPublish );
-  
+  ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
+                         objectCounter, aNameToEntry );
+
   aScript += aFuncScript;
 
   // ouv : NPAL12872
-  AddObjectColors( theDocID, aScript, theObjectNames );
+  AddObjectColors( theDocID, aScript, aEntry2ObjData );
 
   // Make script to publish in study
+  TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
   if ( isPublished )
   {
-    std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
-    for (anEntryToNameIt.Initialize( theObjectNames );
-         anEntryToNameIt.More();
-         anEntryToNameIt.Next())
+    TSting2StringMap anEntryToCmdMap; // sort publishing commands by object entry
+
+    for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
+         aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
+         ++aStEntry2ObjDataPtrIt)
     {
-      const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
-      if (anIgnoreObjMap.count(aEntry.ToCString()))
+      TObjectData* data = aStEntry2ObjDataPtrIt->second;
+      if ( anIgnoreObjMap.count( data->_entry ))
         continue; // should not be dumped
-      const TCollection_AsciiString& aName = anEntryToNameIt.Value();
-      PublishObject( aEntry, aName, theObjectNames,
-                    aEntry2StEntry, aStEntry2Entry,
-                    anEntryToBadName, anEntryToCommandMap, anIgnoreObjMap );
+      PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
+                     aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
     }
     // add publishing commands to the script
-    std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
-    for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand )
-      aScript += (char*)anEntryToCommand->second.c_str();
+    TSting2StringMap::iterator anEntryToCmd = anEntryToCmdMap.begin();
+    for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
+      aScript += anEntryToCmd->second;
   }
 
   //aScript += "\n\tpass\n";
@@ -677,16 +724,16 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
   // fill _studyEntry2NameMap and build globalVars
   TCollection_AsciiString globalVars;
   _studyEntry2NameMap.Clear();
-  Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
-  for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
-       aStEntryToEntryIt.More();
-       aStEntryToEntryIt.Next() )
+  for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
+       aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
+       ++aStEntry2ObjDataPtrIt)
   {
-    const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
-    _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
+    const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
+    const TObjectData*                   data = aStEntry2ObjDataPtrIt->second;
+    _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
     if ( !globalVars.IsEmpty() )
       globalVars += ", ";
-    globalVars += name;
+    globalVars += data->_pyName;
   }
   if ( !globalVars.IsEmpty() ) {
     globalVars.Insert( 1, "\n\tglobal " );
@@ -732,7 +779,7 @@ Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
 #define TEXTURE_LABEL_HEIGHT   4
 #define TEXTURE_LABEL_DATA     5
 
-int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight, 
+int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
                             const Handle(TDataStd_HArray1OfByte)& theTexture,
                             const TCollection_AsciiString& theFileName)
 {
@@ -770,7 +817,7 @@ int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
   TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
 
   Handle(TDataStd_ByteArray) anAttr =
-    TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA), 
+    TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
                             theTexture.IsNull() ? 0 : theTexture->Lower(),
                             theTexture.IsNull() ? 0 : theTexture->Upper());
   anAttr->ChangeArray(theTexture);
@@ -794,7 +841,7 @@ Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theText
     if (aTextureLabel.IsAttribute( GetTextureGUID())) {
       TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
       Handle(TDataStd_Integer) anIdAttr;
-      if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) && 
+      if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
          anIdAttr->Get() == theTextureID) {
         TDF_Label aFileLabel   = aTextureLabel.FindChild(TEXTURE_LABEL_FILE,    Standard_False);
         TDF_Label aWidthLabel  = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH,   Standard_False);
@@ -847,14 +894,14 @@ std::list<int> GEOM_Engine::getAllTextures(int theDocID)
  *  ProcessFunction: Dump fucntion description into script
  */
 //=============================================================================
-bool ProcessFunction(Handle(GEOM_Function)&     theFunction,
-                     TCollection_AsciiString&   theScript,
-                     TCollection_AsciiString&   theAfterScript,
-                     const TVariablesList&      theVariables,
-                     const bool                 theIsPublished,
-                     TDF_LabelMap&              theProcessed,
-                     std::set<std::string>&     theIgnoreObjs,
-                     bool&                      theIsDumpCollected)
+bool ProcessFunction(Handle(GEOM_Function)&             theFunction,
+                     TCollection_AsciiString&           theScript,
+                     TCollection_AsciiString&           theAfterScript,
+                     const TVariablesList&              theVariables,
+                     const bool                         theIsPublished,
+                     TDF_LabelMap&                      theProcessed,
+                     std::set<TCollection_AsciiString>& theIgnoreObjs,
+                     bool&                              theIsDumpCollected)
 {
   theIsDumpCollected = false;
   if (theFunction.IsNull()) return false;
@@ -895,7 +942,7 @@ bool ProcessFunction(Handle(GEOM_Function)&     theFunction,
   if (doNotProcess) {
     TCollection_AsciiString anObjEntry;
     TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
-    theIgnoreObjs.insert(anObjEntry.ToCString());
+    theIgnoreObjs.insert(anObjEntry);
     return false;
   }
   theProcessed.Add(theFunction->GetEntry());
@@ -906,12 +953,14 @@ bool ProcessFunction(Handle(GEOM_Function)&     theFunction,
   //Check if its internal function which doesn't requires dumping
   if(aDescr == "None") return false;
 
-  // 0020001 PTv, check for critical functions, which requier dump of objects
+  // 0020001 PTv, check for critical functions, which require dump of objects
   if (theIsPublished)
   {
-    // currently, there is only one function "RestoreSubShapes",
+    // currently, there is only one function "RestoreGivenSubShapes",
     // later this check could be replaced by iterations on list of such functions
-    if (aDescr.Search( "RestoreSubShapes" ) != -1)
+    if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
+      theIsDumpCollected = true;
+    else if (aDescr.Search( "RestoreSubShapes" ) != -1)
       theIsDumpCollected = true;
   }
 
@@ -922,7 +971,9 @@ bool ProcessFunction(Handle(GEOM_Function)&     theFunction,
     bool isBefore = true;
     TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
     while (!aSubStr.IsEmpty()) {
-      if (isBefore && aSubStr.Search( "RestoreSubShapes" ) == -1)
+      if (isBefore &&
+          aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
+          aSubStr.Search( "RestoreSubShapes" ) == -1)
         theScript += TCollection_AsciiString("\n\t") + aSubStr;
       else
         theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
@@ -975,11 +1026,11 @@ Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theStrin
 
 //=============================================================================
 /*!
- *  ReplaceVariables: Replace parameters of the function by variales from 
+ *  ReplaceVariables: Replace parameters of the function by variales from
  *                    Notebook if need
  */
 //=============================================================================
-void ReplaceVariables(TCollection_AsciiString& theCommand, 
+void ReplaceVariables(TCollection_AsciiString& theCommand,
                       const TVariablesList&    theVariables)
 {
   if (MYDEBUG)
@@ -1038,7 +1089,7 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
       if(MYDEBUG)
         cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
     }
-    
+
     //Find variables used for object construction
     ObjectStates* aStates = 0;
     TVariablesList::const_iterator it = theVariables.find(anEntry);
@@ -1083,7 +1134,7 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
         if(aTotalNbParams - aNbEntries > 0 )
           aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
         else
-          aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length()); 
+          aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
       }
       //Replace last parameter (bettwen ',' character and ')' character)
       else if(i == aTotalNbParams)
@@ -1105,14 +1156,14 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
       if ( aStartPos == aEndPos )
         continue; // PAL20889: for "[]"
 
-      if(MYDEBUG) 
+      if(MYDEBUG)
         cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
 
       aVar = aCommand.SubString(aStartPos, aEndPos-1);
       aVar.RightAdjust();
       aVar.LeftAdjust();
-    
-      if(MYDEBUG) 
+
+      if(MYDEBUG)
         cout<<"Variable: '"<< aVar <<"'"<<endl;
 
       // specific case for sketcher
@@ -1132,7 +1183,7 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
             aEndSectionPos = aVar.Length();
 
           aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
-          if(MYDEBUG) 
+          if(MYDEBUG)
             cout<<"aSection: "<<aSection<<endl;
 
           Standard_Integer aNbParams = 1;
@@ -1150,7 +1201,7 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
               aEndParamPos = aSection.Length() + 1;
 
             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
-            if(MYDEBUG) 
+            if(MYDEBUG)
               cout<<"aParameter: "<<aParameter<<endl;
 
             if(iVar >= aVariables.size())
@@ -1167,27 +1218,27 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
               aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
             }
 
-            if(MYDEBUG) 
+            if(MYDEBUG)
               cout<<"aSection before : "<<aSection<<endl;
             aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
             aSection.Insert(aStartParamPos, aReplacedParameter);
-            if(MYDEBUG) 
+            if(MYDEBUG)
               cout<<"aSection after  : "<<aSection<<endl<<endl;
             iVar++;
           }
-          if(MYDEBUG) 
+          if(MYDEBUG)
             cout<<"aVar before : "<<aVar<<endl;
           aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
           aVar.Insert(aStartSectionPos, aSection);
-          if(MYDEBUG) 
+          if(MYDEBUG)
             cout<<"aVar after  : "<<aVar<<endl<<endl;
         }
 
-        if(MYDEBUG) 
+        if(MYDEBUG)
           cout<<"aCommand before : "<<aCommand<<endl;
         aCommand.Remove(aStartPos, aEndPos - aStartPos);
         aCommand.Insert(aStartPos, aVar);
-        if(MYDEBUG) 
+        if(MYDEBUG)
           cout<<"aCommand after  : "<<aCommand<<endl;
 
         break;
@@ -1234,14 +1285,14 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
  */
 //=============================================================================
 void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
-                            Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
+                            TSting2ObjDataMap&                        aEntry2ObjData,
                             const bool                                theIsPublished,
-                            Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
-                            TColStd_SequenceOfAsciiString&            theObjListToPublish)
+                            TColStd_SequenceOfAsciiString&            theObjListToPublish,
+                            Standard_Integer&                         objectCounter,
+                            Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
 {
   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
-  Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = theScript.Length();
-  Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
+  Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
 
   //Replace entries by the names
   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
@@ -1252,45 +1303,22 @@ void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
     anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
     anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
     theObjListToPublish.Append( anEntry );
-    if (theObjectNames.IsBound(anEntry)) {
-      aName = theObjectNames.Find(anEntry);
-      // check validity of aName
-      bool isValidName = true;
-      if ( aName.IsIntegerValue() ) { // aName must not start with a digit
-        aName.Insert( 1, 'a' );
-        isValidName = false;
-      }
-      int p, p2=1; // replace not allowed chars
-      while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
-        aName.SetValue(p, '_');
-        p2=p;
-        isValidName = false;
-      }
-      if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
-      {  // diff objects have same name - make a new name by appending a digit
-        TCollection_AsciiString aName2;
-        Standard_Integer i = 0;
-        do {
-          aName2 = aName + "_" + ++i;
-        } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
-        aName = aName2;
-        isValidName = false;
-      }
-      if ( !isValidName ) {
-        if ( theIsPublished )
-          theEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
-        theObjectNames( anEntry ) = aName;
+    
+    TObjectData& data = aEntry2ObjData[ anEntry ];
+    if ( !data._name.IsEmpty() ) { // published object
+      if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
+        data._pyName = data._name;
+        healPyName( data._pyName, anEntry, aNameToEntry);
       }
     }
     else {
       do {
-        aName = aBaseName + TCollection_AsciiString(++objectCounter);
-      } while(aNameToEntry.IsBound(aName));
-      theObjectNames.Bind(anEntry, aName);
+        data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
+      } while(aNameToEntry.IsBound(data._pyName));
     }
-    aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
+    aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
 
-    anUpdatedScript += aName;
+    anUpdatedScript += data._pyName;
     aStart = aSeq->Value(i+1) + 1;
   }
 
@@ -1306,20 +1334,20 @@ void ReplaceEntriesByNames (TCollection_AsciiString&                  theScript,
  *  AddObjectColors: Add color to objects
  */
 //=============================================================================
-void AddObjectColors (int                                             theDocID,
-                      TCollection_AsciiString&                        theScript,
-                      const Resource_DataMapOfAsciiStringAsciiString& theObjectNames)
+void AddObjectColors (int                      theDocID,
+                      TCollection_AsciiString& theScript,
+                      const TSting2ObjDataMap& theEntry2ObjData)
 {
   GEOM_Engine* engine = GEOM_Engine::GetEngine();
   Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
 
-  Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
-  for (anEntryToNameIt.Initialize( theObjectNames );
-       anEntryToNameIt.More();
-       anEntryToNameIt.Next())
+  TSting2ObjDataMap::const_iterator anEntryToNameIt;
+  for (anEntryToNameIt = theEntry2ObjData.begin();
+       anEntryToNameIt!= theEntry2ObjData.end();
+       ++anEntryToNameIt)
   {
-    const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
-    const TCollection_AsciiString& aName = anEntryToNameIt.Value();
+    const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
+    const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
 
     TDF_Label L;
     TDF_Tool::Label( aDoc->GetData(), aEntry, L );
@@ -1338,14 +1366,14 @@ void AddObjectColors (int                                             theDocID,
       theScript += aCommand.ToCString();
     }
 
-    SALOMEDS::Color aColor = obj->GetColor();
+    GEOM_Object::Color aColor = obj->GetColor();
     if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
     {
       TCollection_AsciiString aCommand( "\n\t" );
       aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
       theScript += aCommand.ToCString();
     }
-    
+
     Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
     if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
       TCollection_AsciiString aCommand( "\n\t" );
@@ -1423,7 +1451,7 @@ void AddTextures (int theDocID, TCollection_AsciiString& theScript)
 
   if (allTextures.size() > 0) {
     theScript += "\n\ttexture_map = {}\n";
-    
+
     for (it = allTextures.begin(); it != allTextures.end(); ++it) {
       if (*it <= 0) continue;
       Standard_Integer aWidth, aHeight;
@@ -1455,46 +1483,61 @@ void AddTextures (int theDocID, TCollection_AsciiString& theScript)
  *  PublishObject: publish object in study script
  */
 //=============================================================================
-void PublishObject (const TCollection_AsciiString&                  theEntry,
-                    const TCollection_AsciiString&                  theName,
-                    const Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
-                    const Resource_DataMapOfAsciiStringAsciiString& theEntry2StEntry,
-                    const Resource_DataMapOfAsciiStringAsciiString& theStEntry2Entry,
-                    const Resource_DataMapOfAsciiStringAsciiString& theEntryToBadName,
-                    std::map< int, std::string >&                   theEntryToCommandMap,
-                    std::set<std::string>&                          theMapOfPublished)
+void PublishObject (TObjectData&                              theObjectData,
+                    TSting2ObjDataMap&                        theEntry2ObjData,
+                    const TSting2ObjDataPtrMap&               theStEntry2ObjDataPtr,
+                    Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
+                    TSting2StringMap&                         theEntryToCmdMap,
+                    std::set< TCollection_AsciiString>&       theIgnoreMap)
 {
-  if ( !theEntry2StEntry.IsBound( theEntry ))
+  if ( theObjectData._studyEntry.IsEmpty() )
     return; // was not published
-  if ( theMapOfPublished.count(theEntry.ToCString()) )
-    return; // aready published
-  theMapOfPublished.insert( theEntry.ToCString() );
+  if ( theIgnoreMap.count( theObjectData._entry ) )
+    return; // not to publish
 
-  TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
+  TCollection_AsciiString aCommand("\n\tgeompy.");
 
   // find a father entry
-  const TCollection_AsciiString& aStudyEntry = theEntry2StEntry( theEntry );
+  TObjectData* aFatherData = 0;
   TCollection_AsciiString aFatherStudyEntry =
-    aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
-  if ( theStEntry2Entry.IsBound( aFatherStudyEntry ))
-    aFatherEntry = theStEntry2Entry( aFatherStudyEntry );
+    theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
+  TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
+    theStEntry2ObjDataPtr.find( aFatherStudyEntry );
+  if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
+    aFatherData = stEntry2DataPtr->second;
+
+  // treat multiply published object
+  if ( theObjectData._pyName.IsEmpty() )
+  {
+    TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
+    if ( data0._pyName.IsEmpty() ) return; // something wrong
+
+    theObjectData._pyName = theObjectData._name;
+    healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
+
+    TCollection_AsciiString aCreationCommand("\n\t");
+    aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
+
+    // store aCreationCommand before publishing commands
+    TCollection_AsciiString mapKey(" ");
+    mapKey += theObjectData._studyEntry;
+    theEntryToCmdMap.insert( std::make_pair( mapKey, aCreationCommand ));
+  }
 
   // make a command
-  if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
-        aCommand += "addToStudyInFather( ";
-        aCommand += theObjectNames( aFatherEntry ) + ", ";
+  if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
+    aCommand += "addToStudyInFather( ";
+    aCommand += aFatherData->_pyName + ", ";
   }
-  else
+  else {
     aCommand += "addToStudy( ";
-  if ( theEntryToBadName.IsBound( theEntry ))
-    aCommand += theName + ", \"" + theEntryToBadName( theEntry ) + "\" )";
-  else
-    aCommand += theName + ", \"" + theName + "\" )";
+  }
+  aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
+
+  // bind a command to the study entry
+  theEntryToCmdMap.insert( std::make_pair( theObjectData._studyEntry, aCommand ));
 
-  // bind a command to the last digit of the entry
-  int tag =
-    theEntry.SubString( theEntry.SearchFromEnd(":")+1, theEntry.Length() ).IntegerValue();
-  theEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
+  theObjectData._studyEntry.Clear(); // not to publish any more
 }
 
 //================================================================================
@@ -1531,7 +1574,7 @@ TState ObjectStates::GetCurrectState() const
 
 //================================================================================
 /*!
- * \brief Add new object state 
+ * \brief Add new object state
  * \param theState - Object state (vector of notebook variable)
  */
 //================================================================================