1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 #pragma warning( disable:4786 )
27 #include "GEOM_Engine.hxx"
29 #include "GEOM_Field.hxx"
30 #include "GEOM_Function.hxx"
31 #include "GEOM_ISubShape.hxx"
32 #include "GEOM_PythonDump.hxx"
33 #include "GEOM_Solver.hxx"
34 #include "GEOM_SubShapeDriver.hxx"
35 #include "Sketcher_Profile.hxx"
37 #include <Basics_OCCTVersion.hxx>
39 #include "utilities.h"
41 #include <Basics_Utils.hxx>
43 #include <TDF_Tool.hxx>
44 #include <TDF_Data.hxx>
45 #include <TDF_Reference.hxx>
46 #include <TDF_LabelSequence.hxx>
47 #include <TDataStd_Integer.hxx>
48 #include <TDataStd_ChildNodeIterator.hxx>
49 #include <TFunction_Driver.hxx>
50 #include <TFunction_DriverTable.hxx>
51 #include <TDataStd_ByteArray.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDF_ChildIterator.hxx>
54 #include <TDataStd_Comment.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
59 #include <TCollection_AsciiString.hxx>
60 #include <TCollection_ExtendedString.hxx>
61 #include <TColStd_SequenceOfAsciiString.hxx>
62 #include <TColStd_MapOfTransient.hxx>
63 #include <TColStd_HSequenceOfInteger.hxx>
65 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
67 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
69 #if OCC_VERSION_LARGE > 0x07000000
70 #include <BinDrivers.hxx>
71 #include <StdDrivers_DocumentRetrievalDriver.hxx>
72 #include <PCDM_StorageDriver.hxx>
77 #include <Standard_Failure.hxx>
78 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
83 #define O_SQR_BRACKET '['
84 #define C_SQR_BRACKET ']'
85 #define PY_NULL "None"
88 static int MYDEBUG = 0;
90 static int MYDEBUG = 0;
93 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
94 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
95 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
96 typedef std::map< int, std::list < int > > TIntToListIntMap;
98 static GEOM_Engine* TheEngine = NULL;
101 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
103 TCollection_AsciiString anEntry;
104 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
108 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
109 TCollection_AsciiString& theScript,
110 TCollection_AsciiString& theAfterScript,
111 const TVariablesList& theVariables,
112 const bool theIsPublished,
113 TDF_LabelMap& theProcessed,
114 std::set<TCollection_AsciiString>& theIgnoreObjs,
115 bool& theIsDumpCollected);
117 static int GetTag(const TCollection_AsciiString &theEntry);
119 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
120 TIntToListIntMap &theRefMap);
122 void ReplaceVariables(TCollection_AsciiString& theCommand,
123 const TVariablesList& theVariables);
125 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
127 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
128 TSting2ObjDataMap& aEntry2ObjData,
129 const bool theIsPublished,
130 TColStd_SequenceOfAsciiString& theObjListToPublish,
131 Standard_Integer& objectCounter,
132 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
134 void AddObjectColors (TCollection_AsciiString& theScript,
135 const TSting2ObjDataMap& theEntry2ObjData);
137 void AddTextures (TCollection_AsciiString& theScript);
139 void PublishObject (TObjectData& theObjectData,
140 TSting2ObjDataMap& theEntry2ObjData,
141 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
142 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
143 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
144 std::set<TCollection_AsciiString>& theMapOfPublished);
146 static TCollection_AsciiString GetPublishCommands
148 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
149 const TIntToListIntMap &theMapRefs,
150 std::set< int > &thePublished);
152 //================================================================================
154 * \brief Fix up the name of python variable
156 //================================================================================
158 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
159 const TCollection_AsciiString& anEntry,
160 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
162 const TCollection_AsciiString allowedChars
163 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
165 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
166 pyName.Insert( 1, 'a' );
168 int p, p2=1; // replace not allowed chars
169 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
170 pyName.SetValue(p, '_');
173 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
174 { // diff objects have same name - make a new name by appending a digit
175 TCollection_AsciiString aName2;
176 Standard_Integer i = 0;
178 aName2 = pyName + "_" + ++i;
179 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
184 //=======================================================================
185 //function : GetTextureGUID
187 //=======================================================================
188 const Standard_GUID& GEOM_Engine::GetTextureGUID()
190 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
194 //=============================================================================
198 //=============================================================================
199 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
201 //=============================================================================
205 //=============================================================================
206 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
208 //=============================================================================
212 //=============================================================================
213 GEOM_Engine::GEOM_Engine()
215 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
217 _OCAFApp = new GEOM_Application();
218 #if OCC_VERSION_LARGE > 0x07000000
219 _OCAFApp->DefineFormat("SALOME_GEOM", "GEOM Document Version 1.0", "sgd",
220 new StdDrivers_DocumentRetrievalDriver, 0);
221 BinDrivers::DefineFormat(_OCAFApp);
229 GEOM_Engine::~GEOM_Engine()
231 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
232 std::list< Handle(GEOM_Object) > objs;
233 for(; It.More(); It.Next())
234 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
235 std::list< Handle(GEOM_Object) >::iterator objit;
236 for(objit = objs.begin(); objit != objs.end(); ++objit)
237 RemoveObject(*objit);
244 //=============================================================================
248 //=============================================================================
249 Handle(TDocStd_Document) GEOM_Engine::GetDocument(bool force)
251 Handle(TDocStd_Document) aDoc;
256 #if OCC_VERSION_MAJOR > 6
257 _OCAFApp->NewDocument("BinOcaf", aDoc);
259 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
261 aDoc->SetUndoLimit(_UndoLimit);
267 //=============================================================================
271 //=============================================================================
273 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(const char* theEntry, bool force)
275 Handle(GEOM_BaseObject) anObject;
277 if (_objects.IsBound(theEntry)) {
278 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(theEntry));
281 Handle(TDocStd_Document) aDoc = GetDocument(force);
282 if ( !aDoc.IsNull()) {
284 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
285 if ( !aLabel.IsNull() ) {
286 int objType = GEOM_BaseObject::GetType( aLabel );
288 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
289 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
290 default: anObject = new GEOM_Object (aLabel);
292 _objects.Bind(theEntry, anObject);
300 //=============================================================================
304 //=============================================================================
306 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theType)
308 Handle(TDocStd_Document) aDoc = GetDocument();
309 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
311 // NPAL18604: use existing label to decrease memory usage,
312 // if this label has been freed (object deleted)
313 bool useExisting = false;
315 if (!_freeLabels.empty()) {
317 aChild = _freeLabels.front();
318 _freeLabels.pop_front();
322 aChild = TDF_TagSource::NewChild(aDoc->Main());
325 Handle(GEOM_BaseObject) anObject;
327 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
328 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
329 default: anObject = new GEOM_Object (aChild, theType);
332 //Put an object in the map of created objects
333 TCollection_AsciiString anID = BuildIDFromObject(anObject);
334 if(_objects.IsBound(anID)) _objects.UnBind(anID);
335 _objects.Bind(anID, anObject);
340 //================================================================================
342 * \brief Adds a new object of the type theType in the OCAF document
344 //================================================================================
346 Handle(GEOM_Object) GEOM_Engine::AddObject(int theType)
348 return Handle(GEOM_Object)::DownCast( AddBaseObject(theType) );
351 //=============================================================================
355 //=============================================================================
357 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
358 Handle(TColStd_HArray1OfInteger) theIndices,
359 bool isStandaloneOperation)
361 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
363 Handle(TDocStd_Document) aDoc = GetDocument();
364 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
366 // NPAL18604: use existing label to decrease memory usage,
367 // if this label has been freed (object deleted)
368 bool useExisting = false;
370 if (!_freeLabels.empty()) {
372 aChild = _freeLabels.front();
373 _freeLabels.pop_front();
377 aChild = TDF_TagSource::NewChild(aDoc->Main());
380 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
381 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
382 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
384 GEOM_ISubShape aSSI (aFunction);
385 aSSI.SetMainShape(aMainShape);
386 aSSI.SetIndices(theIndices);
390 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
391 if (!aSolver.ComputeFunction(aFunction)) {
392 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
396 catch (Standard_Failure) {
397 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
398 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
402 // Put an object in the map of created objects
403 TCollection_AsciiString anID = BuildIDFromObject(anObject);
404 if (_objects.IsBound(anID)) _objects.UnBind(anID);
405 _objects.Bind(anID, anObject);
407 // Put this sub-shape in the list of sub-shapes of theMainShape
408 aMainShape->AddSubShapeReference(aFunction);
410 GEOM::TPythonDump pd (aFunction);
412 if (isStandaloneOperation) {
413 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
414 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
415 for (; i <= up - 1; i++) {
416 pd << theIndices->Value(i) << ", ";
418 pd << theIndices->Value(up) << "])";
426 //=============================================================================
430 //=============================================================================
431 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
433 if (theObject.IsNull()) return false;
436 return false; // document is closed...
438 //Remove an object from the map of available objects
439 TCollection_AsciiString anID = BuildIDFromObject(theObject);
440 if (_objects.IsBound(anID)) {
441 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
442 if ( anObject != theObject )
443 anObject->_label = anObject->_label.Root();
444 _objects.UnBind(anID);
447 // If sub-shape, remove it from the list of sub-shapes of its main shape
448 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
449 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
450 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
451 GEOM_ISubShape aSSI (aFunction);
452 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
453 //If main shape is not null, then remove
454 if(!aMainShape.IsNull())
455 aMainShape->RemoveSubShapeReference(aFunction);
458 int nb = theObject->GetNbFunctions();
459 Handle(TDataStd_TreeNode) aNode;
460 for (int i = 1; i <= nb; i++) {
461 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
462 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
466 TDF_Label aLabel = theObject->GetEntry();
467 aLabel.ForgetAllAttributes(Standard_True);
469 // Remember the label to reuse it then
470 if ( _freeLabels.empty() || _freeLabels.back() != aLabel )
471 _freeLabels.push_back(aLabel);
473 // we can't explicitely delete theObject. At least prevent its functioning
474 // as an alive object when aLabel is reused for a new object
475 theObject->_label = aLabel.Root();
476 theObject->_ior.Clear();
477 theObject->_parameters.Clear();;
484 //=============================================================================
488 //=============================================================================
489 void GEOM_Engine::Undo()
491 GetDocument()->Undo();
494 //=============================================================================
498 //=============================================================================
499 void GEOM_Engine::Redo()
501 GetDocument()->Redo();
504 //=============================================================================
508 //=============================================================================
509 bool GEOM_Engine::Save(const char* theFileName)
511 if(!_document) return false;
513 _OCAFApp->SaveAs(_document, theFileName);
518 //=============================================================================
522 //=============================================================================
523 bool GEOM_Engine::Load(const char* theFileName)
525 Handle(TDocStd_Document) aDoc;
526 if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
530 #if OCC_VERSION_MAJOR > 6
531 // Replace old document format by the new one.
532 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
533 aDoc->ChangeStorageFormat("BinOcaf");
537 aDoc->SetUndoLimit(_UndoLimit);
544 //=============================================================================
548 //=============================================================================
549 void GEOM_Engine::Close()
552 //Remove all GEOM Objects associated to the document
553 TColStd_SequenceOfAsciiString aSeq;
554 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
555 for (; It.More(); It.Next()) {
556 aSeq.Append(It.Key());
558 for (Standard_Integer i=1; i<=aSeq.Length(); i++) {
559 _objects.UnBind(aSeq.Value(i));
562 // Forget free labels for document
565 _OCAFApp->Close(_document);
570 //=============================================================================
574 //=============================================================================
575 TCollection_AsciiString GEOM_Engine::DumpPython(std::vector<TObjectData>& theObjectData,
576 TVariablesList theVariables,
581 // Set "C" numeric locale to save numbers correctly
582 Kernel_Utils::Localizer loc;
584 TCollection_AsciiString aScript;
585 Handle(TDocStd_Document) aDoc = GetDocument();
589 TCollection_AsciiString anEmptyScript;
591 anEmptyScript = "def RebuildData(): pass\n";
592 return anEmptyScript;
596 aScript = "import salome\n";
598 aScript += "import GEOM\n";
599 aScript += "from salome.geom import geomBuilder\n";
600 aScript += "import math\n";
601 aScript += "import SALOMEDS\n\n";
603 aScript += "def RebuildData():";
605 aScript += "\n\tgeompy = geomBuilder.New()\n";
607 AddTextures(aScript);
609 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
611 // a map containing copies of TObjectData from theObjectData
612 TSting2ObjDataMap aEntry2ObjData;
613 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
614 // occures when several StudyEntries correspond to one Entry
615 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
617 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
618 for (unsigned i = 0; i < theObjectData.size(); ++i )
620 TObjectData& data = theObjectData[i];
621 // look for an object by entry
623 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
624 if ( L.IsNull() ) continue;
625 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
627 if ( !obj.IsNull() ) {
628 TSting2ObjDataMap::iterator ent2Data =
629 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
631 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
632 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
634 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
638 // collect objects entries to be published
639 TColStd_SequenceOfAsciiString aObjListToPublish;
641 // iterates on functions till critical (that requiers publication of objects)
642 Handle(TDataStd_TreeNode) aNode, aRoot;
643 Handle(GEOM_Function) aFunction;
644 TDF_LabelMap aCheckedFuncMap;
645 std::set< TCollection_AsciiString > anIgnoreObjMap;
647 TCollection_AsciiString aFuncScript;
649 // Mantis issue 0020768
650 Standard_Integer objectCounter = 0;
651 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
652 TIntToListIntMap aRefMap;
654 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
655 TDataStd_ChildNodeIterator Itr(aRoot);
656 for (; Itr.More(); Itr.Next()) {
658 aFunction = GEOM_Function::GetFunction(aNode->Label());
659 if (aFunction.IsNull()) {
660 MESSAGE ( "Null function !!!!" );
663 bool isDumpCollected = false;
664 TCollection_AsciiString aCurScript, anAfterScript;
665 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
666 isPublished, aCheckedFuncMap, anIgnoreObjMap,
669 // add function description before dump
670 if (!aCurScript.IsEmpty())
672 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
673 aFuncScript.Length() > aCurScript.Length() )
674 // avoid repeated SubShape...() command at the end
675 if (aFuncScript.Location( aCurScript,
676 aFuncScript.Length() - aCurScript.Length(),
677 aFuncScript.Length()))
678 continue; // aCurScript is already at the end of aFuncScript
679 aFuncScript += aCurScript;
682 // Fill the map of references.
683 FillMapOfRef(aFunction, aRefMap);
685 if (isDumpCollected ) {
686 // Replace entries by the names
687 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
688 aObjListToPublish, objectCounter, aNameToEntry );
690 // publish collected objects
691 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
692 int i = 1, n = aObjListToPublish.Length();
693 for ( ; i <= n; i++ )
695 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
696 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
697 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
699 // add publishing commands to the script
700 std::set< int > aPublished;
701 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
703 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
704 const TCollection_AsciiString aPublishCmds =
705 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
706 aRefMap, aPublished);
708 aFuncScript += aPublishCmds;
711 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
712 // because they will be published during command execution
713 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
715 indx = anAfterScript.Search( "RestoreSubShapes" );
717 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
718 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
719 i = 1, n = aSeq->Length();
720 for ( ; i <= n; i+=2) {
721 TCollection_AsciiString anEntry =
722 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
723 anIgnoreObjMap.insert(anEntry.ToCString());
727 aObjListToPublish.Clear();
728 aScript += aFuncScript;
731 aFuncScript += anAfterScript;
735 // Replace entries by the names
736 aObjListToPublish.Clear();
737 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
738 objectCounter, aNameToEntry );
740 aScript += aFuncScript;
743 AddObjectColors(aScript, aEntry2ObjData );
745 // Make script to publish in study
746 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
749 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
751 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
752 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
753 ++aStEntry2ObjDataPtrIt)
755 TObjectData* data = aStEntry2ObjDataPtrIt->second;
756 if ( anIgnoreObjMap.count( data->_entry ))
757 continue; // should not be dumped
758 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
759 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
761 // add publishing commands to the script
762 std::set< int > aPublished;
763 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
765 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
766 const TCollection_AsciiString aPublishCmds =
767 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
768 aRefMap, aPublished);
770 aScript += aPublishCmds;
774 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
775 //Add unpublish command if need
776 TCollection_AsciiString unpublishCmd("\n");
778 unpublishCmd += "\t";
779 unpublishCmd += "geompy.hideInStudy(";
781 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
782 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
783 ++aStEntry2ObjDataPtrIt)
785 TObjectData* data = aStEntry2ObjDataPtrIt->second;
786 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
787 aScript += unpublishCmd + data->_pyName + ")";
791 //aScript += "\n\tpass\n";
795 // fill _studyEntry2NameMap and build globalVars
796 TCollection_AsciiString globalVars;
797 _studyEntry2NameMap.Clear();
798 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
799 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
800 ++aStEntry2ObjDataPtrIt)
802 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
803 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
804 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
805 if ( !globalVars.IsEmpty() )
807 globalVars += data->_pyName;
809 if ( isMultiFile && !globalVars.IsEmpty() ) {
810 globalVars.Insert( 1, "\n\tglobal " );
811 aScript.Insert( posToInsertGlobalVars, globalVars );
817 //=======================================================================
818 //function : GetDumpName
820 //=======================================================================
822 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
824 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
825 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
830 //=======================================================================
831 //function : GetAllDumpNames
833 //=======================================================================
835 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
837 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
839 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
840 for (; it.More(); it.Next()) {
841 aRetSeq->Append(it.Value());
847 #define TEXTURE_LABEL_ID 1
848 #define TEXTURE_LABEL_FILE 2
849 #define TEXTURE_LABEL_WIDTH 3
850 #define TEXTURE_LABEL_HEIGHT 4
851 #define TEXTURE_LABEL_DATA 5
853 int GEOM_Engine::addTexture(int theWidth, int theHeight,
854 const Handle(TColStd_HArray1OfByte)& theTexture,
855 const TCollection_AsciiString& theFileName)
857 Handle(TDocStd_Document) aDoc = GetDocument();
858 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
860 // NPAL18604: use existing label to decrease memory usage,
861 // if this label has been freed (object deleted)
862 bool useExisting = false;
864 if (!_freeLabels.empty()) {
866 aChild = _freeLabels.front();
867 _freeLabels.pop_front();
871 aChild = TDF_TagSource::NewChild(aDoc->Main());
874 aChild.ForgetAllAttributes(Standard_True);
875 Handle(TDataStd_TreeNode) node;
876 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
877 node = TDataStd_TreeNode::Set(aChild);
878 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
880 static int aTextureID = 0;
882 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
883 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
884 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
885 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
887 Handle(TDataStd_ByteArray) anAttr =
888 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
889 theTexture.IsNull() ? 0 : theTexture->Lower(),
890 theTexture.IsNull() ? 0 : theTexture->Upper());
891 anAttr->ChangeArray(theTexture);
896 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theTextureID,
897 int& theWidth, int& theHeight,
898 TCollection_AsciiString& theFileName)
900 Handle(TColStd_HArray1OfByte) anArray;
901 theWidth = theHeight = 0;
903 Handle(TDocStd_Document) aDoc = GetDocument();
905 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
907 for (; anIterator.More() && !found; anIterator.Next()) {
908 TDF_Label aTextureLabel = anIterator.Value();
909 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
910 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
911 Handle(TDataStd_Integer) anIdAttr;
912 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
913 anIdAttr->Get() == theTextureID) {
914 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
915 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
916 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
917 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
918 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
919 Handle(TDataStd_ByteArray) aTextureAttr;
920 Handle(TDataStd_Comment) aFileAttr;
921 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
922 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
923 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
924 theWidth = aWidthAttr->Get();
925 theHeight = aHeightAttr->Get();
926 anArray = aTextureAttr->InternalArray();
928 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
929 theFileName = aFileAttr->Get();
937 std::list<int> GEOM_Engine::getAllTextures()
939 std::list<int> id_list;
941 Handle(TDocStd_Document) aDoc = GetDocument();
943 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
944 for (; anIterator.More(); anIterator.Next()) {
945 TDF_Label aTextureLabel = anIterator.Value();
946 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
947 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
948 Handle(TDataStd_Integer) anIdAttr;
949 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
950 id_list.push_back((int)anIdAttr->Get());
956 //===========================================================================
957 // Internal functions
958 //===========================================================================
960 //=============================================================================
962 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
964 //=============================================================================
965 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
967 TCollection_AsciiString aNewDescr;
969 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
970 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
971 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
972 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
973 // "3DSketcher:CMD[:CMD[:CMD...]]"
974 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
976 // Split the command string to separate CMDs
978 TColStd_SequenceOfAsciiString aSequence;
979 if (aCommand.Length()) {
980 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
981 while (aToken.Length() > 0) {
982 aSequence.Append(aToken);
983 aToken = aCommand.Token(":", ++icmd);
987 if (aSequence.Length() > 0) {
991 aNewDescr += "\nsk = geompy.Sketcher3D()";
992 int nbCMDs = aSequence.Length();
993 for (icmd = 1; icmd <= nbCMDs; icmd++) {
996 TCollection_AsciiString aCMD = aSequence.Value(icmd);
998 // Split the CMD into string values
999 TColStd_SequenceOfAsciiString aStrVals;
1001 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1002 while (aToken.Length() > 0) {
1003 aStrVals.Append(aToken);
1004 aToken = aCMD.Token(" ", ++ival);
1007 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1008 if (aCMDpref == "TT") {
1009 aNewDescr += "sk.addPointsAbsolute(";
1010 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1012 else if (aCMDpref == "T") {
1013 aNewDescr += "sk.addPointsRelative(";
1014 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1016 else if (aCMDpref == "WW") {
1017 aNewDescr += "sk.close()";
1019 else if (aCMDpref.Value(1) == 'O'){
1020 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1022 if (aCMDpref.Value(4) == 'C')
1023 aNewDescr += "sk.addPointRadiusAngleH";
1025 aNewDescr += "sk.addPointRadiusAngles";
1026 if (aCMDpref.Value(5) == 'A')
1027 aNewDescr += "Absolute(";
1029 aNewDescr += "Relative(";
1030 aNewDescr += aStrVals.Value(4) + ", " +
1031 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1034 aNewDescr += "\n\t";
1035 aNewDescr += aResult + " = sk.wire()";
1037 } // Make3DSketcherCommand
1038 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1039 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1040 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1041 aCommand = aCommand.Token("]", 1);
1043 aNewDescr += "\n\t";
1044 aNewDescr += "\nsk = geompy.Sketcher3D()";
1045 aNewDescr += "\n\t";
1046 aNewDescr += "sk.addPointsAbsolute(";
1047 aNewDescr += aCommand + ")";
1048 aNewDescr += "\n\t";
1049 aNewDescr += aResult + " = sk.wire()";
1053 aNewDescr += "\n\t";
1054 aNewDescr += aSubStr;
1061 //=============================================================================
1063 * ProcessFunction: Dump function description into script
1065 //=============================================================================
1066 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1067 TCollection_AsciiString& theScript,
1068 TCollection_AsciiString& theAfterScript,
1069 const TVariablesList& theVariables,
1070 const bool theIsPublished,
1071 TDF_LabelMap& theProcessed,
1072 std::set<TCollection_AsciiString>& theIgnoreObjs,
1073 bool& theIsDumpCollected)
1075 theIsDumpCollected = false;
1076 if (theFunction.IsNull()) return false;
1078 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1080 // pass functions, that depends on nonexisting ones
1081 bool doNotProcess = false;
1082 TDF_LabelSequence aSeq;
1083 theFunction->GetDependency(aSeq);
1084 Standard_Integer aLen = aSeq.Length();
1085 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1086 TDF_Label aRefLabel = aSeq.Value(i);
1087 Handle(TDF_Reference) aRef;
1088 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1089 doNotProcess = true;
1092 if (aRef.IsNull() || aRef->Get().IsNull()) {
1093 doNotProcess = true;
1096 Handle(TDataStd_TreeNode) aT;
1097 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1098 doNotProcess = true;
1101 TDF_Label aDepLabel = aT->Label();
1102 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1104 if (aFunction.IsNull()) doNotProcess = true;
1105 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1112 TCollection_AsciiString anObjEntry;
1113 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1114 theIgnoreObjs.insert(anObjEntry);
1117 theProcessed.Add(theFunction->GetEntry());
1119 TCollection_AsciiString aDescr = theFunction->GetDescription();
1120 if(aDescr.Length() == 0) return false;
1122 //Check if its internal function which doesn't requires dumping
1123 if(aDescr == "None") return false;
1125 //Check the very specific case of RestoreShape function,
1126 //which is not dumped, but the result can be published by the user.
1127 //We do not publish such objects to decrease danger of dumped script failure.
1128 if(aDescr.Value(1) == '#') {
1129 TCollection_AsciiString anObjEntry;
1130 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1131 theIgnoreObjs.insert(anObjEntry);
1135 // 0020001 PTv, check for critical functions, which require dump of objects
1138 // currently, there is only one function "RestoreGivenSubShapes",
1139 // later this check could be replaced by iterations on list of such functions
1140 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1141 theIsDumpCollected = true;
1142 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1143 theIsDumpCollected = true;
1146 //Replace parameter by notebook variables
1147 ReplaceVariables(aDescr,theVariables);
1149 //Process sketcher functions, replacing string command by calls to Sketcher interface
1150 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1151 Sketcher_Profile aProfile( aDescr.ToCString());
1152 // Make new command for SketcherOnPlane and for Sketcher
1153 aDescr = aProfile.GetDump();
1155 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1156 aDescr = MakeCommandfor3DSketcher ( aDescr );
1159 if ( theIsDumpCollected ) {
1161 bool isBefore = true;
1162 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1163 while (!aSubStr.IsEmpty()) {
1165 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1166 aSubStr.Search( "RestoreSubShapes" ) == -1)
1167 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1169 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1170 aSubStr = aDescr.Token("\n\t", i++);
1174 theScript += "\n\t";
1175 theScript += aDescr;
1180 //=============================================================================
1182 * GetTag: Returns the tag from entry
1184 //=============================================================================
1185 int GetTag(const TCollection_AsciiString &theEntry)
1187 const int aGeomObjDepth = 3;
1188 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1193 //=============================================================================
1195 * FillMapOfRef: Fill the map of references
1197 //=============================================================================
1198 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1199 TIntToListIntMap &theRefMap)
1201 TDF_LabelSequence aSeq;
1202 TCollection_AsciiString anObjEntry;
1205 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1206 anObjTag = GetTag(anObjEntry);
1207 theFunction->GetDependency(aSeq);
1209 const Standard_Integer aLen = aSeq.Length();
1212 for (i = 1; i <= aLen; i++) {
1213 TDF_Label aRefLabel = aSeq.Value(i);
1214 Handle(TDF_Reference) aRef;
1216 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1217 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1218 Handle(TDataStd_TreeNode) aT;
1220 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1221 TDF_Label aDepLabel = aT->Label();
1222 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1224 if (!aRefFunct.IsNull()) {
1225 // Get entry of the referenced object.
1226 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1228 const int aRefTag = GetTag(anObjEntry);
1230 if (anObjTag != aRefTag) {
1231 // Avoid making references for operations without copy.
1232 theRefMap[anObjTag].push_back(aRefTag);
1241 //=============================================================================
1243 * FindEntries: Returns a sequence of start/end positions of entries in the string
1245 //=============================================================================
1246 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1248 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1249 Standard_Integer aLen = theString.Length();
1250 Standard_Boolean isFound = Standard_False;
1252 const char* arr = theString.ToCString();
1253 Standard_Integer i = 0, j;
1256 int c = (int)arr[i];
1258 if(c >= 48 && c <= 57) { //Is digit?
1260 isFound = Standard_False;
1261 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1263 if(c == 58) isFound = Standard_True;
1266 if(isFound && arr[j-2] != 58) { // last char should be a diggit
1267 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1278 //=============================================================================
1280 * ReplaceVariables: Replace parameters of the function by variales from
1283 //=============================================================================
1284 void ReplaceVariables(TCollection_AsciiString& theCommand,
1285 const TVariablesList& theVariables)
1288 cout<<"Command : "<<theCommand<<endl;
1291 cout<<"All Entries:"<<endl;
1292 TVariablesList::const_iterator it = theVariables.begin();
1293 for(;it != theVariables.end();it++)
1294 cout<<"\t'"<<(*it).first<<"'"<<endl;
1297 //Additional case - multi-row commands
1298 int aCommandIndex = 1;
1299 while( aCommandIndex < 10 ) { // tmp check
1300 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1301 if( aCommand.Length() == 0 )
1305 cout<<"Sub-command : "<<aCommand<<endl;
1307 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1308 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1310 //Get Entry of the result object
1311 TCollection_AsciiString anEntry;
1312 if( aCommand.Search("=") != -1 ) // command returns an object
1313 anEntry = aCommand.Token("=",1);
1314 else { // command modifies the object
1315 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1316 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1317 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1319 //Remove white spaces
1320 anEntry.RightAdjust();
1321 anEntry.LeftAdjust();
1323 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1325 if ( anEntry.IsEmpty() ) {
1330 //Check if result is list of entries - enough to get the first entry in this case
1332 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1333 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1335 TCollection_AsciiString aSeparator(COMMA);
1336 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1337 anEntry.Remove( 1, 1 );
1338 anEntry.RightAdjust();
1339 anEntry.LeftAdjust();
1341 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1344 //Find variables used for object construction
1345 ObjectStates* aStates = 0;
1346 TVariablesList::const_iterator it = theVariables.find(anEntry);
1347 if( it != theVariables.end() )
1348 aStates = (*it).second;
1352 cout<<"Valiables list empty!!!"<<endl;
1357 TState aVariables = aStates->GetCurrectState();
1360 cout<<"Variables from SObject:"<<endl;
1361 for (int i = 0; i < aVariables.size();i++)
1362 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1365 //Calculate total number of parameters
1366 Standard_Integer aTotalNbParams = 1;
1367 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1371 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1373 Standard_Integer aFirstParam = aNbEntries;
1375 //Replace parameters by variables
1376 Standard_Integer aStartPos = 0;
1377 Standard_Integer aEndPos = 0;
1379 TCollection_AsciiString aVar, aReplacedVar;
1380 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1381 //Replace first parameter (bettwen '(' character and first ',' character)
1382 if(i == aFirstParam)
1384 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1385 if(aTotalNbParams - aNbEntries > 0 )
1386 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1388 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1390 //Replace last parameter (bettwen ',' character and ')' character)
1391 else if(i == aTotalNbParams)
1393 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1394 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1396 //Replace other parameters (bettwen two ',' characters)
1397 else if(i != aFirstParam && i != aTotalNbParams )
1399 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1400 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1403 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1405 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1407 if ( aStartPos == aEndPos )
1408 continue; // PAL20889: for "[]"
1411 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1413 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1418 cout<<"Variable: '"<< aVar <<"'"<<endl;
1420 // specific case for sketcher
1421 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1422 Standard_Integer aNbSections = 1;
1423 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1427 int aStartSectionPos = 0, aEndSectionPos = 0;
1428 TCollection_AsciiString aSection, aReplacedSection;
1429 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1430 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1431 if( aSectionIndex != aNbSections )
1432 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1434 aEndSectionPos = aVar.Length();
1436 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1438 cout<<"aSection: "<<aSection<<endl;
1440 Standard_Integer aNbParams = 1;
1441 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1445 int aStartParamPos = 0, aEndParamPos = 0;
1446 TCollection_AsciiString aParameter, aReplacedParameter;
1447 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1448 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1449 if( aParamIndex != aNbParams )
1450 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1452 aEndParamPos = aSection.Length() + 1;
1455 cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1457 if ( aStartParamPos == aEndParamPos)
1460 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1462 cout<<"aParameter: "<<aParameter<<endl;
1464 if(iVar >= aVariables.size())
1467 aReplacedParameter = aVariables[iVar].myVariable;
1468 if(aReplacedParameter.IsEmpty()) {
1473 if(aVariables[iVar].isVariable) {
1474 aReplacedParameter.InsertBefore(1,"'");
1475 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1479 cout<<"aSection before : "<<aSection<<endl;
1480 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1481 aSection.Insert(aStartParamPos, aReplacedParameter);
1483 cout<<"aSection after : "<<aSection<<endl<<endl;
1487 cout<<"aVar before : "<<aVar<<endl;
1488 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1489 aVar.Insert(aStartSectionPos, aSection);
1491 cout<<"aVar after : "<<aVar<<endl<<endl;
1495 cout<<"aCommand before : "<<aCommand<<endl;
1496 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1497 aCommand.Insert(aStartPos, aVar);
1499 cout<<"aCommand after : "<<aCommand<<endl;
1502 } // end of specific case for sketcher
1504 //If parameter is entry or 'None', skip it
1505 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1508 if(iVar >= aVariables.size())
1511 aReplacedVar = aVariables[iVar].myVariable;
1512 if(aReplacedVar.IsEmpty()) {
1517 if(aVariables[iVar].isVariable) {
1518 aReplacedVar.InsertBefore(1,"\"");
1519 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1522 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1523 aCommand.Insert(aStartPos, aReplacedVar);
1527 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1528 theCommand.Insert(aStartCommandPos, aCommand);
1532 aStates->IncrementState();
1536 cout<<"Command : "<<theCommand<<endl;
1539 //=============================================================================
1541 * ReplaceEntriesByNames: Replace object entries by their names
1543 //=============================================================================
1544 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1545 TSting2ObjDataMap& aEntry2ObjData,
1546 const bool theIsPublished,
1547 TColStd_SequenceOfAsciiString& theObjListToPublish,
1548 Standard_Integer& objectCounter,
1549 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1551 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1552 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1553 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1555 //Replace entries by the names
1556 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1557 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1558 if (aLen == 0) anUpdatedScript = theScript;
1560 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1561 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1562 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1563 theObjListToPublish.Append( anEntry );
1565 TObjectData& data = aEntry2ObjData[ anEntry ];
1566 if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1567 if ( !data._name.IsEmpty() ) { // published object
1568 data._pyName = data._name;
1569 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1573 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1574 } while(aNameToEntry.IsBound(data._pyName));
1578 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1580 anUpdatedScript += data._pyName;
1581 aStart = aSeq->Value(i+1) + 1;
1584 //Add final part of the script
1585 if (aLen && aSeq->Value(aLen) < aScriptLength)
1586 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1588 theScript = anUpdatedScript;
1591 //=============================================================================
1593 * AddObjectColors: Add color to objects
1595 //=============================================================================
1596 void AddObjectColors (TCollection_AsciiString& theScript,
1597 const TSting2ObjDataMap& theEntry2ObjData)
1599 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1600 Handle(TDocStd_Document) aDoc = engine->GetDocument();
1602 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1603 for (anEntryToNameIt = theEntry2ObjData.begin();
1604 anEntryToNameIt!= theEntry2ObjData.end();
1607 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1608 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1611 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1615 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1619 bool anAutoColor = obj->GetAutoColor();
1622 TCollection_AsciiString aCommand( "\n\t" );
1623 aCommand += aName + ".SetAutoColor(1)";
1624 theScript += aCommand.ToCString();
1627 GEOM_Object::Color aColor = obj->GetColor();
1628 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1630 TCollection_AsciiString aCommand( "\n\t" );
1631 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1632 theScript += aCommand.ToCString();
1635 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1636 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1637 TCollection_AsciiString aCommand( "\n\t" );
1638 aCommand += aName + ".SetMarkerStd(";
1639 switch (aMarkerType) {
1640 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1641 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1642 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1643 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1644 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1645 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1646 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1647 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1648 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1649 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1650 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1651 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1652 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1653 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1656 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1658 case 1: aCommand += "GEOM.MS_10"; break;
1659 case 2: aCommand += "GEOM.MS_15"; break;
1660 case 3: aCommand += "GEOM.MS_20"; break;
1661 case 4: aCommand += "GEOM.MS_25"; break;
1662 case 5: aCommand += "GEOM.MS_30"; break;
1663 case 6: aCommand += "GEOM.MS_35"; break;
1664 case 7: aCommand += "GEOM.MS_40"; break;
1665 case 8: aCommand += "GEOM.MS_45"; break;
1666 case 9: aCommand += "GEOM.MS_50"; break;
1667 case 10: aCommand += "GEOM.MS_55"; break;
1668 case 11: aCommand += "GEOM.MS_60"; break;
1669 case 12: aCommand += "GEOM.MS_65"; break;
1670 case 13: aCommand += "GEOM.MS_70"; break;
1671 default: aCommand += "GEOM.MS_NONE"; break;
1674 theScript += aCommand.ToCString();
1676 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1677 int aMarkerTextureID = obj->GetMarkerTexture();
1678 if (aMarkerTextureID >= 0) {
1679 TCollection_AsciiString aCommand( "\n\t" );
1680 aCommand += aName + ".SetMarkerTexture(texture_map[";
1681 aCommand += aMarkerTextureID;
1683 theScript += aCommand.ToCString();
1689 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1691 TCollection_AsciiString stream;
1692 if (!aData.IsNull()) {
1693 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1694 Standard_Byte byte = aData->Value(i);
1695 TCollection_AsciiString strByte = "";
1696 for (int j = 0; j < 8; j++)
1697 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1704 void AddTextures (TCollection_AsciiString& theScript)
1706 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1707 std::list<int> allTextures = engine->getAllTextures();
1708 std::list<int>::const_iterator it;
1710 if (allTextures.size() > 0) {
1711 theScript += "\n\ttexture_map = {}\n";
1713 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1714 if (*it <= 0) continue;
1715 Standard_Integer aWidth, aHeight;
1716 TCollection_AsciiString aFileName;
1717 Handle(TColStd_HArray1OfByte) aTexture =
1718 engine->getTexture(*it, aWidth, aHeight, aFileName);
1719 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1720 TCollection_AsciiString aCommand = "\n\t";
1721 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1722 if (aFileName != "" ) {
1723 aCommand += "geompy.LoadTexture(\"";
1724 aCommand += aFileName.ToCString();
1728 aCommand += "geompy.AddTexture(";
1729 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1730 aCommand += pack_data(aTexture);
1733 theScript += aCommand;
1740 //=============================================================================
1742 * PublishObject: publish object in study script
1744 //=============================================================================
1745 void PublishObject (TObjectData& theObjectData,
1746 TSting2ObjDataMap& theEntry2ObjData,
1747 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1748 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1749 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1750 std::set< TCollection_AsciiString>& theIgnoreMap)
1752 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1753 if ( theObjectData._studyEntry.IsEmpty() )
1754 return; // was not published
1755 if ( theIgnoreMap.count( theObjectData._entry ) )
1756 return; // not to publish
1758 TCollection_AsciiString aCommand("\n\tgeompy.");
1760 // find a father entry
1761 TObjectData* aFatherData = 0;
1762 TCollection_AsciiString aFatherStudyEntry =
1763 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1764 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1765 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1766 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1767 aFatherData = stEntry2DataPtr->second;
1769 // treat multiply published object
1770 if ( theObjectData._pyName.IsEmpty() )
1772 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1773 if ( data0._pyName.IsEmpty() ) return; // something wrong
1775 theObjectData._pyName = theObjectData._name;
1776 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1778 TCollection_AsciiString aCreationCommand("\n\t");
1779 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1781 // store aCreationCommand before publishing commands
1782 int tag = GetTag(theObjectData._entry);
1783 theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1787 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1788 aCommand += "addToStudyInFather( ";
1789 aCommand += aFatherData->_pyName + ", ";
1792 aCommand += "addToStudy( ";
1794 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1796 // bind a command to the study entry
1797 int tag = GetTag(theObjectData._entry);
1798 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1800 theObjectData._studyEntry.Clear(); // not to publish any more
1803 //================================================================================
1805 * \brief Returns the string of publishing commands. Take into account that
1806 * references should be published prior to the objects refer to them.
1808 //================================================================================
1809 TCollection_AsciiString GetPublishCommands
1811 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1812 const TIntToListIntMap &theMapRefs,
1813 std::set< int > &thePublished)
1815 TCollection_AsciiString aResult;
1817 if (!thePublished.count(theTag)) {
1818 // This object is not published yet.
1819 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1820 theEntryToCmdMap.find(theTag);
1822 if (anIt != theEntryToCmdMap.end()) {
1823 // There is a pubish cmd.
1824 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1826 if (aRefIt != theMapRefs.end()) {
1827 // Recursively publish all references.
1828 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1830 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1831 const TCollection_AsciiString aRefCmd = GetPublishCommands
1832 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1838 // Add the object command.
1839 aResult += anIt->second;
1842 thePublished.insert(theTag);
1848 //================================================================================
1850 * \brief Constructor
1852 //================================================================================
1853 ObjectStates::ObjectStates()
1858 //================================================================================
1862 //================================================================================
1863 ObjectStates::~ObjectStates()
1867 //================================================================================
1869 * \brief Return current object state
1870 * \retval state - Object state (vector of notebook variable)
1872 //================================================================================
1873 TState ObjectStates::GetCurrectState() const
1875 if(_states.size() > _dumpstate)
1876 return _states[_dumpstate];
1880 //================================================================================
1882 * \brief Add new object state
1883 * \param theState - Object state (vector of notebook variable)
1885 //================================================================================
1886 void ObjectStates::AddState(const TState &theState)
1888 _states.push_back(theState);
1891 //================================================================================
1893 * \brief Increment object state
1895 //================================================================================
1896 void ObjectStates::IncrementState()