]> SALOME platform Git repositories - modules/geom.git/blobdiff - src/GEOM/GEOM_Engine.cxx
Salome HOME
0021672: [CEA 565] Dump Study from script
[modules/geom.git] / src / GEOM / GEOM_Engine.cxx
index cc399462ce525bc569bac3c642b5aece0cbed8e1..cc284959899b3c6d8c5b285dbfd65abf269ba376 100644 (file)
@@ -1,23 +1,23 @@
-//  Copyright (C) 2007-2010  CEA/DEN, EDF R&D, OPEN CASCADE
+// Copyright (C) 2007-2012  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
+// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 //
-//  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.
+// 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.
 //
-//  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.
+// 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
+// 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
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 //
 
 #ifdef WNT
@@ -33,6 +33,8 @@
 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
 #include "GEOM_PythonDump.hxx"
 
+#include <Basics_OCCTVersion.hxx>
+
 #include "utilities.h"
 
 #include <Basics_Utils.hxx>
@@ -45,7 +47,6 @@
 #include <TDataStd_ChildNodeIterator.hxx>
 #include <TFunction_Driver.hxx>
 #include <TFunction_DriverTable.hxx>
-#include <TDataStd_HArray1OfByte.hxx>
 #include <TDataStd_ByteArray.hxx>
 #include <TDataStd_UAttribute.hxx>
 #include <TDF_ChildIterator.hxx>
 #include <TColStd_MapOfTransient.hxx>
 #include <TColStd_HSequenceOfInteger.hxx>
 
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+#include <TColStd_HArray1OfByte.hxx>
+#include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
+#else
+#include <TDataStd_HArray1OfByte.hxx>
 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
+#endif
+
 #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
@@ -84,6 +89,10 @@ 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;
 
 
@@ -109,14 +118,14 @@ 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,
                       const TVariablesList&    theVariables);
@@ -124,27 +133,59 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
 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,
                             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,
+                    std::map< int, TCollection_AsciiString >& 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
@@ -178,7 +219,7 @@ void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
 GEOM_Engine::GEOM_Engine()
 {
   TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
-
+  
   _OCAFApp = new GEOM_Application();
   _UndoLimit = 10;
 }
@@ -197,7 +238,12 @@ GEOM_Engine::~GEOM_Engine()
     RemoveObject(*objit);
 
   //Close all documents not closed
-  for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+  TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
+#else
+  Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
+#endif
+  for (; anItr.More(); anItr.Next())
     Close(anItr.Key());
 
   _mapIDDocument.Clear();
@@ -231,12 +277,16 @@ Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
 //=============================================================================
 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
 {
-  if(theDocument.IsNull()) return -1;
-  for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
-    if(anItr.Value() == theDocument) return anItr.Key();
+  if (theDocument.IsNull()) return -1;
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+  TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
+#else
+  Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
+#endif
+  for (; anItr.More(); anItr.Next())
+    if (anItr.Value() == theDocument) return anItr.Key();
 
   return -1;
-
 }
 
 //=============================================================================
@@ -344,7 +394,7 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
   aSSI.SetIndices(theIndices);
 
   try {
-#if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
+#if OCC_VERSION_LARGE > 0x06010000
     OCC_CATCH_SIGNALS;
 #endif
     GEOM_Solver aSolver (GEOM_Engine::GetEngine());
@@ -364,7 +414,7 @@ Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
   if (_objects.IsBound(anID)) _objects.UnBind(anID);
   _objects.Bind(anID, anObject);
 
-  // Put this subshape in the list of subshapes of theMainShape
+  // Put this sub-shape in the list of sub-shapes of theMainShape
   aMainShape->AddSubShapeReference(aFunction);
 
   GEOM::TPythonDump pd (aFunction);
@@ -400,7 +450,7 @@ bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
   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 sub-shape, remove it from the list of sub-shapes of its main shape
   if (!theObject->IsMainShape()) {
     Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
     GEOM_ISubShape aSSI (aFunction);
@@ -473,7 +523,11 @@ bool GEOM_Engine::Save(int theDocID, char* theFileName)
 bool GEOM_Engine::Load(int theDocID, char* theFileName)
 {
   Handle(TDocStd_Document) aDoc;
-  if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
+#if OCC_VERSION_LARGE > 0x06050100 // For OCCT6.5.2 and higher
+  if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
+#else
+  if (_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
+#endif
     return false;
   }
 
@@ -525,9 +579,10 @@ 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 isMultiFile, 
                                                 bool& aValidScript)
 {
   // Set "C" numeric locale to save numbers correctly
@@ -536,37 +591,51 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
   TCollection_AsciiString aScript;
   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
 
-  if (aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
+  if (aDoc.IsNull())
+  {
+    TCollection_AsciiString anEmptyScript;
+    if( isMultiFile )
+      anEmptyScript = "def RebuildData(theStudy): pass\n";
+    return anEmptyScript;
+  }
 
   aScript  = "import GEOM\n";
   aScript += "import geompy\n";
   aScript += "import math\n";
   aScript += "import SALOMEDS\n\n";
-  aScript += "def RebuildData(theStudy):";
+  if( isMultiFile )
+    aScript += "def RebuildData(theStudy):";
+
   aScript += "\n\tgeompy.init_geom(theStudy)\n";
 
   AddTextures(theDocID, aScript);
 
   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 ));
     }
   }
 
@@ -577,10 +646,9 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
   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;
@@ -603,29 +671,33 @@ TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
         continue;
       // add function description before dump
       if (!aCurScript.IsEmpty())
+      {
+        if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() )
+          // avoid repeated SubShape...() command at the end
+          if (aFuncScript.Location( aCurScript,
+                                    aFuncScript.Length() - aCurScript.Length(),
+                                    aFuncScript.Length()))
+              continue;
         aFuncScript += aCurScript;
+      }
       if (isDumpCollected ) {
         // Replace entries by the names
-        ReplaceEntriesByNames( aFuncScript, theObjectNames,
-                               isPublished, anEntryToBadName, aObjListToPublish,
-                               objectCounter, aNameToEntry );
+        ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
+                               aObjListToPublish, objectCounter, aNameToEntry );
 
         // publish collected objects
-        std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
+        std::map< int, TCollection_AsciiString > 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();
+        std::map< int, TCollection_AsciiString >::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
@@ -639,8 +711,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());
           }
         }
 
@@ -654,37 +725,53 @@ 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())
+    std::map< int, TCollection_AsciiString > 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();
+    std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
+    for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd )
+      aScript += anEntryToCmd->second;
   }
 
+  //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
+  //Add unpublish command if need
+  TCollection_AsciiString unpublishCmd("\n");
+  if(isMultiFile)
+    unpublishCmd += "\t";
+  unpublishCmd += "geompy.hideInStudy(";
+  
+  for (aStEntry2ObjDataPtrIt  = aStEntry2ObjDataPtr.begin();
+       aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
+       ++aStEntry2ObjDataPtrIt)
+    {
+      TObjectData* data = aStEntry2ObjDataPtrIt->second;      
+      if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
+       aScript +=  unpublishCmd + data->_pyName + ")";
+      }
+    }    
+  
   //aScript += "\n\tpass\n";
   aScript += "\n";
   aValidScript = true;
@@ -692,18 +779,18 @@ 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() ) {
+  if ( isMultiFile && !globalVars.IsEmpty() ) {
     globalVars.Insert( 1, "\n\tglobal " );
     aScript.Insert( posToInsertGlobalVars, globalVars );
   }
@@ -748,7 +835,11 @@ Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
 #define TEXTURE_LABEL_DATA     5
 
 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+                            const Handle(TColStd_HArray1OfByte)& theTexture,
+#else
                             const Handle(TDataStd_HArray1OfByte)& theTexture,
+#endif
                             const TCollection_AsciiString& theFileName)
 {
   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
@@ -793,11 +884,19 @@ int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
   return aTextureID;
 }
 
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
+#else
 Handle(TDataStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
-                                                       int& theWidth, int& theHeight,
-                                                       TCollection_AsciiString& theFileName)
+#endif
+                                                      int& theWidth, int& theHeight,
+                                                      TCollection_AsciiString& theFileName)
 {
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+  Handle(TColStd_HArray1OfByte) anArray;
+#else
   Handle(TDataStd_HArray1OfByte) anArray;
+#endif
   theWidth = theHeight = 0;
 
   Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
@@ -862,14 +961,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;
@@ -910,7 +1009,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());
@@ -921,7 +1020,7 @@ 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 "RestoreGivenSubShapes",
@@ -1108,7 +1207,7 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
       else if(i == aTotalNbParams)
       {
         aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
-        aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
+        aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
       }
       //Replace other parameters (bettwen two ',' characters)
       else if(i != aFirstParam && i != aTotalNbParams )
@@ -1168,6 +1267,12 @@ void ReplaceVariables(TCollection_AsciiString& theCommand,
             else
               aEndParamPos = aSection.Length() + 1;
 
+            if(MYDEBUG)
+              cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
+
+           if ( aStartParamPos == aEndParamPos)
+             continue;
+
             aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
             if(MYDEBUG)
               cout<<"aParameter: "<<aParameter<<endl;
@@ -1253,17 +1358,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,
                             Standard_Integer&                         objectCounter,
                             Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
 {
   Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
-  //Standard_Integer objectCounter = 0;
   Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
-  //Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
 
   //Replace entries by the names
   TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
@@ -1274,52 +1376,30 @@ 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;
+    
+    TObjectData& data = aEntry2ObjData[ anEntry ];
+    if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
+      if ( !data._name.IsEmpty() ) { // published object
+        data._pyName = data._name;
+        healPyName( data._pyName, anEntry, aNameToEntry);
       }
-      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;
+      else {
         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;
+          data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
+        } while(aNameToEntry.IsBound(data._pyName));
       }
     }
-    else {
-      do {
-        aName = aBaseName + TCollection_AsciiString(++objectCounter);
-      } while(aNameToEntry.IsBound(aName));
-      theObjectNames.Bind(anEntry, aName);
-    }
-    aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
-
-    anUpdatedScript += aName;
+    
+    aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
+    
+    anUpdatedScript += data._pyName;
     aStart = aSeq->Value(i+1) + 1;
   }
-
+  
   //Add final part of the script
   if (aLen && aSeq->Value(aLen) < aScriptLength)
     anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
-
+  
   theScript = anUpdatedScript;
 }
 
@@ -1328,20 +1408,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 );
@@ -1422,7 +1502,11 @@ void AddObjectColors (int                                             theDocID,
   }
 }
 
-static TCollection_AsciiString pack_data(const Handle(TDataStd_HArray1OfByte)& aData )
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
+#else
+static TCollection_AsciiString pack_data (const Handle(TDataStd_HArray1OfByte)& aData)
+#endif
 {
   TCollection_AsciiString stream;
   if (!aData.IsNull()) {
@@ -1450,7 +1534,12 @@ void AddTextures (int theDocID, TCollection_AsciiString& theScript)
       if (*it <= 0) continue;
       Standard_Integer aWidth, aHeight;
       TCollection_AsciiString aFileName;
-      Handle(TDataStd_HArray1OfByte) aTexture = engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
+#if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
+      Handle(TColStd_HArray1OfByte) aTexture =
+#else
+      Handle(TDataStd_HArray1OfByte) aTexture =
+#endif
+        engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
       if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
         TCollection_AsciiString aCommand = "\n\t";
         aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
@@ -1477,46 +1566,63 @@ 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,
+                    std::map< int, TCollection_AsciiString >& 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;
+
+  const int geomObjDepth = 3;
+
+  // 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
+    int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
+    theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), 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
+  int tag = theObjectData._entry.Token( ":", geomObjDepth ).IntegerValue();
+  theEntryToCmdMap.insert( std::make_pair( tag, 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
 }
 
 //================================================================================