1 // Copyright (C) 2007-2022 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 "utilities.h"
39 #include <Basics_Utils.hxx>
40 #include <Basics_OCCTVersion.hxx>
42 #include <TDF_Tool.hxx>
43 #include <TDF_Data.hxx>
44 #include <TDF_Reference.hxx>
45 #include <TDF_LabelSequence.hxx>
46 #include <TDataStd_Integer.hxx>
47 #include <TDataStd_ChildNodeIterator.hxx>
48 #include <TFunction_Driver.hxx>
49 #include <TFunction_DriverTable.hxx>
50 #include <TDataStd_ByteArray.hxx>
51 #include <TDataStd_UAttribute.hxx>
52 #include <TDF_ChildIterator.hxx>
53 #include <TDataStd_Comment.hxx>
56 #include <TopTools_IndexedMapOfShape.hxx>
58 #include <TCollection_AsciiString.hxx>
59 #include <TCollection_ExtendedString.hxx>
60 #include <TColStd_SequenceOfAsciiString.hxx>
61 #include <TColStd_MapOfTransient.hxx>
62 #include <TColStd_HSequenceOfInteger.hxx>
64 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
66 #if OCC_VERSION_LARGE < 0x07050000
67 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
70 #include <BinDrivers.hxx>
71 #include <StdDrivers_DocumentRetrievalDriver.hxx>
72 #include <PCDM_StorageDriver.hxx>
76 #include <Standard_Failure.hxx>
77 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
82 #define O_SQR_BRACKET '['
83 #define C_SQR_BRACKET ']'
84 #define PY_NULL "None"
86 // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump
87 // Next macro, when defined, causes appearing of SubShapeAllIDs(), SubShapeAllSortedIDs(), GetSameIDs()
88 // and other such commands in Python dump.
89 // See also GEOMImpl_IShapesOperations.cxx.
90 // ---------------------------------------
91 // #define DUMP_SUBSHAPE_IDS
92 // ---------------------------------------
94 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
95 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
96 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
97 typedef std::map< int, std::list < int > > TIntToListIntMap;
99 static GEOM_Engine* TheEngine = NULL;
102 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
104 TCollection_AsciiString anEntry;
105 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
109 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
110 TCollection_AsciiString& theScript,
111 TCollection_AsciiString& theAfterScript,
112 const TVariablesList& theVariables,
113 const bool /*theIsPublished*/,
114 TDF_LabelMap& theProcessed,
115 std::set<TCollection_AsciiString>& theIgnoreObjs,
116 bool& theIsDumpCollected);
118 static int GetTag(const TCollection_AsciiString &theEntry);
120 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
121 TIntToListIntMap &theRefMap);
123 void ReplaceVariables(TCollection_AsciiString& theCommand,
124 const TVariablesList& theVariables);
126 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
128 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
129 TSting2ObjDataMap& aEntry2ObjData,
130 const bool theIsPublished,
131 TColStd_SequenceOfAsciiString& theObjListToPublish,
132 Standard_Integer& objectCounter,
133 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
135 void AddObjectColors (TCollection_AsciiString& theScript,
136 const TSting2ObjDataMap& theEntry2ObjData);
138 void AddTextures (TCollection_AsciiString& theScript);
140 void PublishObject (TObjectData& theObjectData,
141 TSting2ObjDataMap& theEntry2ObjData,
142 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
143 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
144 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
145 std::set<TCollection_AsciiString>& theMapOfPublished);
147 static TCollection_AsciiString GetPublishCommands
149 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
150 const TIntToListIntMap &theMapRefs,
151 std::set< int > &thePublished);
153 void Prettify(TCollection_AsciiString& theScript);
155 //================================================================================
157 * \brief Fix up the name of python variable
159 //================================================================================
161 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
162 const TCollection_AsciiString& anEntry,
163 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
165 const TCollection_AsciiString allowedChars
166 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
168 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
169 pyName.Insert( 1, 'a' );
171 int p, p2=1; // replace not allowed chars
172 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
173 pyName.SetValue(p, '_');
176 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
177 { // diff objects have same name - make a new name by appending a digit
178 TCollection_AsciiString aName2;
179 Standard_Integer i = 0;
181 aName2 = pyName + "_" + ++i;
182 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
187 //=======================================================================
188 //function : GetTextureGUID
190 //=======================================================================
191 const Standard_GUID& GEOM_Engine::GetTextureGUID()
193 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
197 //=============================================================================
201 //=============================================================================
202 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
204 //=============================================================================
208 //=============================================================================
209 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
211 //=============================================================================
215 //=============================================================================
216 GEOM_Engine::GEOM_Engine()
218 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
220 _OCAFApp = new GEOM_Application();
221 _OCAFApp->DefineFormat("SALOME_GEOM", "GEOM Document Version 1.0", "sgd",
222 new StdDrivers_DocumentRetrievalDriver, 0);
223 BinDrivers::DefineFormat(_OCAFApp);
230 GEOM_Engine::~GEOM_Engine()
232 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
233 std::list< Handle(GEOM_Object) > objs;
234 for(; It.More(); It.Next())
235 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
236 std::list< Handle(GEOM_Object) >::iterator objit;
237 for(objit = objs.begin(); objit != objs.end(); ++objit)
238 RemoveObject(*objit);
245 //=============================================================================
249 //=============================================================================
250 Handle(TDocStd_Document) GEOM_Engine::GetDocument(bool force)
252 Handle(TDocStd_Document) aDoc;
257 _OCAFApp->NewDocument("BinOcaf", aDoc);
258 aDoc->SetUndoLimit(_UndoLimit);
264 //=============================================================================
268 //=============================================================================
270 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(const char* theEntry, bool force)
272 Handle(GEOM_BaseObject) anObject;
274 if (_objects.IsBound(theEntry)) {
275 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(theEntry));
278 Handle(TDocStd_Document) aDoc = GetDocument(force);
279 if ( !aDoc.IsNull()) {
281 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
282 if ( !aLabel.IsNull() ) {
283 int objType = GEOM_BaseObject::GetType( aLabel );
285 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
286 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
287 default: anObject = new GEOM_Object (aLabel);
289 _objects.Bind(theEntry, anObject);
297 //=============================================================================
301 //=============================================================================
303 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theType)
305 Handle(TDocStd_Document) aDoc = GetDocument();
306 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
308 // NPAL18604: use existing label to decrease memory usage,
309 // if this label has been freed (object deleted)
310 bool useExisting = false;
312 if (!_freeLabels.empty()) {
314 aChild = _freeLabels.front();
315 _freeLabels.pop_front();
319 aChild = TDF_TagSource::NewChild(aDoc->Main());
322 Handle(GEOM_BaseObject) anObject;
324 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
325 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
326 default: anObject = new GEOM_Object (aChild, theType);
329 //Put an object in the map of created objects
330 TCollection_AsciiString anID = BuildIDFromObject(anObject);
331 if(_objects.IsBound(anID)) _objects.UnBind(anID);
332 _objects.Bind(anID, anObject);
337 //================================================================================
339 * \brief Adds a new object of the type theType in the OCAF document
341 //================================================================================
343 Handle(GEOM_Object) GEOM_Engine::AddObject(int theType)
345 return Handle(GEOM_Object)::DownCast( AddBaseObject(theType) );
348 //=============================================================================
352 //=============================================================================
354 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
355 Handle(TColStd_HArray1OfInteger) theIndices,
356 bool isStandaloneOperation)
358 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
360 Handle(TDocStd_Document) aDoc = GetDocument();
361 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
363 // NPAL18604: use existing label to decrease memory usage,
364 // if this label has been freed (object deleted)
365 bool useExisting = false;
367 if (!_freeLabels.empty()) {
369 aChild = _freeLabels.front();
370 _freeLabels.pop_front();
374 aChild = TDF_TagSource::NewChild(aDoc->Main());
377 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
378 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
379 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
381 GEOM_ISubShape aSSI (aFunction);
382 aSSI.SetMainShape(aMainShape);
383 aSSI.SetIndices(theIndices);
387 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
388 if (!aSolver.ComputeFunction(aFunction)) {
389 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
393 catch (Standard_Failure& aFail) {
394 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail.GetMessageString());
398 // Put an object in the map of created objects
399 TCollection_AsciiString anID = BuildIDFromObject(anObject);
400 if (_objects.IsBound(anID)) _objects.UnBind(anID);
401 _objects.Bind(anID, anObject);
403 // Put this sub-shape in the list of sub-shapes of theMainShape
404 aMainShape->AddSubShapeReference(aFunction);
406 GEOM::TPythonDump pd (aFunction);
408 if (isStandaloneOperation) {
409 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
410 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
411 for (; i <= up - 1; i++) {
412 pd << theIndices->Value(i) << ", ";
414 pd << theIndices->Value(up) << "])";
422 //=============================================================================
426 //=============================================================================
427 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
429 if (theObject.IsNull()) return false;
432 return false; // document is closed...
434 TDF_Label aLabel = theObject->GetEntry();
435 if ( aLabel == aLabel.Root() )
436 return false; // already removed object
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 aLabel.ForgetAllAttributes(Standard_True);
468 // Remember the label to reuse it then
469 if ( _freeLabels.empty() || _freeLabels.back() != aLabel )
470 _freeLabels.push_back(aLabel);
472 // we can't explicitly delete theObject. At least prevent its functioning
473 // as an alive object when aLabel is reused for a new object
474 theObject->_label = aLabel.Root();
475 theObject->_ior.Clear();
476 theObject->_parameters.Clear();;
483 //=============================================================================
487 //=============================================================================
488 void GEOM_Engine::Undo()
490 GetDocument()->Undo();
493 //=============================================================================
497 //=============================================================================
498 void GEOM_Engine::Redo()
500 GetDocument()->Redo();
503 //=============================================================================
507 //=============================================================================
508 bool GEOM_Engine::Save(const char* theFileName)
510 if(!_document) return false;
512 #if defined(WIN32) && defined(UNICODE)
513 std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName);
515 std::string aFileName = theFileName;
518 return _OCAFApp->SaveAs( _document, aFileName.c_str() ) == PCDM_SS_OK;
521 //=============================================================================
525 //=============================================================================
526 bool GEOM_Engine::Load(const char* theFileName)
528 #if defined(WIN32) && defined(UNICODE)
529 std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName);
531 std::string aFileName = theFileName;
533 Handle(TDocStd_Document) aDoc;
534 if (_OCAFApp->Open(aFileName.c_str(), aDoc) != PCDM_RS_OK) {
538 // Replace old document format by the new one.
539 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
540 aDoc->ChangeStorageFormat("BinOcaf");
543 aDoc->SetUndoLimit(_UndoLimit);
550 //=============================================================================
554 //=============================================================================
555 void GEOM_Engine::Close()
558 //Remove all GEOM Objects associated to the document
559 TColStd_SequenceOfAsciiString aSeq;
560 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
561 for (; It.More(); It.Next()) {
562 aSeq.Append(It.Key());
564 for (Standard_Integer i=1; i<=aSeq.Length(); i++) {
565 _objects.UnBind(aSeq.Value(i));
568 // Forget free labels for document
571 _OCAFApp->Close(_document);
576 //=============================================================================
580 //=============================================================================
581 TCollection_AsciiString GEOM_Engine::DumpPython(std::vector<TObjectData>& theObjectData,
582 TVariablesList theVariables,
587 // Set "C" numeric locale to save numbers correctly
588 Kernel_Utils::Localizer loc;
590 TCollection_AsciiString aScript;
591 Handle(TDocStd_Document) aDoc = GetDocument();
595 TCollection_AsciiString anEmptyScript;
597 anEmptyScript = "def RebuildData(): pass\n";
598 return anEmptyScript;
602 aScript = "import salome\n";
604 aScript += "import GEOM\n";
605 aScript += "from salome.geom import geomBuilder\n";
606 aScript += "import math\n";
607 aScript += "import SALOMEDS\n\n";
609 aScript += "def RebuildData():";
611 aScript += "\n\tgeompy = geomBuilder.New()\n";
613 AddTextures(aScript);
615 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
617 // a map containing copies of TObjectData from theObjectData
618 TSting2ObjDataMap aEntry2ObjData;
619 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
620 // occurs when several StudyEntries correspond to one Entry
621 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
623 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
624 for (unsigned i = 0; i < theObjectData.size(); ++i )
626 TObjectData& data = theObjectData[i];
627 // look for an object by entry
629 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
630 if ( L.IsNull() ) continue;
631 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
633 if ( !obj.IsNull() ) {
634 TSting2ObjDataMap::iterator ent2Data =
635 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
637 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
638 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
640 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
644 // collect objects entries to be published
645 TColStd_SequenceOfAsciiString aObjListToPublish;
647 // iterates on functions till critical (that requiers publication of objects)
648 Handle(TDataStd_TreeNode) aNode, aRoot;
649 Handle(GEOM_Function) aFunction;
650 TDF_LabelMap aCheckedFuncMap;
651 std::set< TCollection_AsciiString > anIgnoreObjMap;
653 TCollection_AsciiString aFuncScript;
655 // Mantis issue 0020768
656 Standard_Integer objectCounter = 0;
657 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
658 TIntToListIntMap aRefMap;
660 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
661 TDataStd_ChildNodeIterator Itr(aRoot);
662 for (; Itr.More(); Itr.Next()) {
664 aFunction = GEOM_Function::GetFunction(aNode->Label());
665 if (aFunction.IsNull()) {
666 MESSAGE ( "Null function !!!!" );
669 bool isDumpCollected = false;
670 TCollection_AsciiString aCurScript, anAfterScript;
671 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
672 isPublished, aCheckedFuncMap, anIgnoreObjMap,
675 // add function description before dump
676 if (!aCurScript.IsEmpty())
678 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
679 aFuncScript.Length() > aCurScript.Length() )
680 // avoid repeated SubShape...() command at the end
681 if (aFuncScript.Location( aCurScript,
682 aFuncScript.Length() - aCurScript.Length(),
683 aFuncScript.Length()))
684 continue; // aCurScript is already at the end of aFuncScript
685 aFuncScript += aCurScript;
688 // Fill the map of references.
689 FillMapOfRef(aFunction, aRefMap);
691 if (isDumpCollected ) {
692 // Replace entries by the names
693 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
694 aObjListToPublish, objectCounter, aNameToEntry );
696 // publish collected objects
697 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
698 int i = 1, n = aObjListToPublish.Length();
699 for ( ; i <= n; i++ )
701 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
702 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
703 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
705 // add publishing commands to the script
706 std::set< int > aPublished;
707 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
709 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
710 const TCollection_AsciiString aPublishCmds =
711 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
712 aRefMap, aPublished);
714 aFuncScript += aPublishCmds;
717 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
718 // because they will be published during command execution
719 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
721 indx = anAfterScript.Search( "RestoreSubShapes" );
723 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
724 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
725 i = 1, n = aSeq->Length();
726 for ( ; i <= n; i+=2) {
727 TCollection_AsciiString anEntry =
728 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
729 anIgnoreObjMap.insert(anEntry.ToCString());
733 aObjListToPublish.Clear();
734 aScript += aFuncScript;
737 aFuncScript += anAfterScript;
741 // Replace entries by the names
742 aObjListToPublish.Clear();
743 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
744 objectCounter, aNameToEntry );
746 aScript += aFuncScript;
749 AddObjectColors(aScript, aEntry2ObjData );
751 // Make script to publish in study
752 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
755 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
757 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
758 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
759 ++aStEntry2ObjDataPtrIt)
761 TObjectData* data = aStEntry2ObjDataPtrIt->second;
762 if ( anIgnoreObjMap.count( data->_entry ))
763 continue; // should not be dumped
764 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
765 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
767 // add publishing commands to the script
768 std::set< int > aPublished;
769 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
771 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
772 const TCollection_AsciiString aPublishCmds =
773 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
774 aRefMap, aPublished);
776 aScript += aPublishCmds;
780 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
781 //Add unpublish command if need
782 TCollection_AsciiString unpublishCmd("\n");
784 unpublishCmd += "\t";
785 unpublishCmd += "geompy.hideInStudy(";
787 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
788 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
789 ++aStEntry2ObjDataPtrIt)
791 TObjectData* data = aStEntry2ObjDataPtrIt->second;
792 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
793 aScript += unpublishCmd + data->_pyName + ")";
797 //aScript += "\n\tpass\n";
801 // fill _studyEntry2NameMap and build globalVars
802 TCollection_AsciiString globalVars;
803 _studyEntry2NameMap.Clear();
804 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
805 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
806 ++aStEntry2ObjDataPtrIt)
808 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
809 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
810 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
811 if ( !globalVars.IsEmpty() )
813 globalVars += data->_pyName;
815 if ( isMultiFile && !globalVars.IsEmpty() ) {
816 globalVars.Insert( 1, "\n\tglobal " );
817 aScript.Insert( posToInsertGlobalVars, globalVars );
820 // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump
821 #ifndef DUMP_SUBSHAPE_IDS
828 //=======================================================================
829 //function : GetDumpName
831 //=======================================================================
833 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
835 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
836 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
841 //=======================================================================
842 //function : GetAllDumpNames
844 //=======================================================================
846 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
848 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
850 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
851 for (; it.More(); it.Next()) {
852 aRetSeq->Append(it.Value());
858 #define TEXTURE_LABEL_ID 1
859 #define TEXTURE_LABEL_FILE 2
860 #define TEXTURE_LABEL_WIDTH 3
861 #define TEXTURE_LABEL_HEIGHT 4
862 #define TEXTURE_LABEL_DATA 5
864 int GEOM_Engine::addTexture(int theWidth, int theHeight,
865 const Handle(TColStd_HArray1OfByte)& theTexture,
866 const TCollection_AsciiString& theFileName)
868 Handle(TDocStd_Document) aDoc = GetDocument();
869 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
871 // NPAL18604: use existing label to decrease memory usage,
872 // if this label has been freed (object deleted)
873 bool useExisting = false;
875 if (!_freeLabels.empty()) {
877 aChild = _freeLabels.front();
878 _freeLabels.pop_front();
882 aChild = TDF_TagSource::NewChild(aDoc->Main());
885 aChild.ForgetAllAttributes(Standard_True);
886 Handle(TDataStd_TreeNode) node;
887 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
888 node = TDataStd_TreeNode::Set(aChild);
889 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
891 static int aTextureID = 0;
893 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
894 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
895 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
896 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
898 Handle(TDataStd_ByteArray) anAttr =
899 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
900 theTexture.IsNull() ? 0 : theTexture->Lower(),
901 theTexture.IsNull() ? 0 : theTexture->Upper());
902 anAttr->ChangeArray(theTexture);
907 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theTextureID,
908 int& theWidth, int& theHeight,
909 TCollection_AsciiString& theFileName)
911 Handle(TColStd_HArray1OfByte) anArray;
912 theWidth = theHeight = 0;
914 Handle(TDocStd_Document) aDoc = GetDocument();
916 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
918 for (; anIterator.More() && !found; anIterator.Next()) {
919 TDF_Label aTextureLabel = anIterator.Value();
920 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
921 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
922 Handle(TDataStd_Integer) anIdAttr;
923 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
924 anIdAttr->Get() == theTextureID) {
925 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
926 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
927 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
928 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
929 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
930 Handle(TDataStd_ByteArray) aTextureAttr;
931 Handle(TDataStd_Comment) aFileAttr;
932 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
933 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
934 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
935 theWidth = aWidthAttr->Get();
936 theHeight = aHeightAttr->Get();
937 anArray = aTextureAttr->InternalArray();
939 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
940 theFileName = aFileAttr->Get();
948 std::list<int> GEOM_Engine::getAllTextures()
950 std::list<int> id_list;
952 Handle(TDocStd_Document) aDoc = GetDocument();
954 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
955 for (; anIterator.More(); anIterator.Next()) {
956 TDF_Label aTextureLabel = anIterator.Value();
957 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
958 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
959 Handle(TDataStd_Integer) anIdAttr;
960 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
961 id_list.push_back((int)anIdAttr->Get());
967 //===========================================================================
968 // Internal functions
969 //===========================================================================
971 //=============================================================================
973 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
975 //=============================================================================
976 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
978 TCollection_AsciiString aNewDescr;
980 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
981 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
982 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
983 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
984 // "3DSketcher:CMD[:CMD[:CMD...]]"
985 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
987 // Split the command string to separate CMDs
989 TColStd_SequenceOfAsciiString aSequence;
990 if (aCommand.Length()) {
991 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
992 while (aToken.Length() > 0) {
993 aSequence.Append(aToken);
994 aToken = aCommand.Token(":", ++icmd);
998 if (aSequence.Length() > 0) {
1000 aNewDescr += "\n\t";
1002 aNewDescr += "\nsk = geompy.Sketcher3D()";
1003 int nbCMDs = aSequence.Length();
1004 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1005 aNewDescr += "\n\t";
1007 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1009 // Split the CMD into string values
1010 TColStd_SequenceOfAsciiString aStrVals;
1012 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1013 while (aToken.Length() > 0) {
1014 aStrVals.Append(aToken);
1015 aToken = aCMD.Token(" ", ++ival);
1018 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1019 if (aCMDpref == "TT") {
1020 aNewDescr += "sk.addPointsAbsolute(";
1021 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1023 else if (aCMDpref == "T") {
1024 aNewDescr += "sk.addPointsRelative(";
1025 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1027 else if (aCMDpref == "WW") {
1028 aNewDescr += "sk.close()";
1030 else if (aCMDpref.Value(1) == 'O'){
1031 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1033 if (aCMDpref.Value(4) == 'C')
1034 aNewDescr += "sk.addPointRadiusAngleH";
1036 aNewDescr += "sk.addPointRadiusAngles";
1037 if (aCMDpref.Value(5) == 'A')
1038 aNewDescr += "Absolute(";
1040 aNewDescr += "Relative(";
1041 aNewDescr += aStrVals.Value(4) + ", " +
1042 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1045 aNewDescr += "\n\t";
1046 aNewDescr += aResult + " = sk.wire()";
1048 } // Make3DSketcherCommand
1049 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1050 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1051 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1052 aCommand = aCommand.Token("]", 1);
1054 aNewDescr += "\n\t";
1055 aNewDescr += "\nsk = geompy.Sketcher3D()";
1056 aNewDescr += "\n\t";
1057 aNewDescr += "sk.addPointsAbsolute(";
1058 aNewDescr += aCommand + ")";
1059 aNewDescr += "\n\t";
1060 aNewDescr += aResult + " = sk.wire()";
1064 aNewDescr += "\n\t";
1065 aNewDescr += aSubStr;
1072 //=============================================================================
1074 * ProcessFunction: Dump function description into script
1076 //=============================================================================
1077 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1078 TCollection_AsciiString& theScript,
1079 TCollection_AsciiString& theAfterScript,
1080 const TVariablesList& theVariables,
1081 const bool theIsPublished,
1082 TDF_LabelMap& theProcessed,
1083 std::set<TCollection_AsciiString>& theIgnoreObjs,
1084 bool& theIsDumpCollected)
1086 theIsDumpCollected = false;
1087 if (theFunction.IsNull()) return false;
1089 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1091 // pass functions, that depends on nonexisting ones
1092 bool doNotProcess = false;
1093 TDF_LabelSequence aSeq;
1094 theFunction->GetDependency(aSeq);
1095 Standard_Integer aLen = aSeq.Length();
1096 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1097 TDF_Label aRefLabel = aSeq.Value(i);
1098 Handle(TDF_Reference) aRef;
1099 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1100 doNotProcess = true;
1103 if (aRef.IsNull() || aRef->Get().IsNull()) {
1104 doNotProcess = true;
1107 Handle(TDataStd_TreeNode) aT;
1108 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1109 doNotProcess = true;
1112 TDF_Label aDepLabel = aT->Label();
1113 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1115 if (aFunction.IsNull()) doNotProcess = true;
1116 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1123 TCollection_AsciiString anObjEntry;
1124 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1125 theIgnoreObjs.insert(anObjEntry);
1128 theProcessed.Add(theFunction->GetEntry());
1130 TCollection_AsciiString aDescr = theFunction->GetDescription();
1131 if(aDescr.Length() == 0) return false;
1133 //Check if its internal function which doesn't requires dumping
1134 if(aDescr == "None") return false;
1136 //Check the very specific case of RestoreShape function,
1137 //which is not dumped, but the result can be published by the user.
1138 //We do not publish such objects to decrease danger of dumped script failure.
1139 if(aDescr.Value(1) == '#') {
1140 TCollection_AsciiString anObjEntry;
1141 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1142 theIgnoreObjs.insert(anObjEntry);
1146 // 0020001 PTv, check for critical functions, which require dump of objects
1149 // currently, there is only one function "RestoreGivenSubShapes",
1150 // later this check could be replaced by iterations on list of such functions
1151 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1152 theIsDumpCollected = true;
1153 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1154 theIsDumpCollected = true;
1157 //Replace parameter by notebook variables
1158 ReplaceVariables(aDescr,theVariables);
1160 //Process sketcher functions, replacing string command by calls to Sketcher interface
1161 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1162 Sketcher_Profile aProfile( aDescr.ToCString());
1163 // Make new command for SketcherOnPlane and for Sketcher
1164 aDescr = aProfile.GetDump();
1166 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1167 aDescr = MakeCommandfor3DSketcher ( aDescr );
1170 if ( theIsDumpCollected ) {
1172 bool isBefore = true;
1173 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1174 while (!aSubStr.IsEmpty()) {
1176 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1177 aSubStr.Search( "RestoreSubShapes" ) == -1)
1178 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1180 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1181 aSubStr = aDescr.Token("\n\t", i++);
1185 theScript += "\n\t";
1186 theScript += aDescr;
1191 //=============================================================================
1193 * GetTag: Returns the tag from entry
1195 //=============================================================================
1196 int GetTag(const TCollection_AsciiString &theEntry)
1198 const int aGeomObjDepth = 3;
1199 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1204 //=============================================================================
1206 * FillMapOfRef: Fill the map of references
1208 //=============================================================================
1209 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1210 TIntToListIntMap &theRefMap)
1212 TDF_LabelSequence aSeq;
1213 TCollection_AsciiString anObjEntry;
1216 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1217 anObjTag = GetTag(anObjEntry);
1218 theFunction->GetDependency(aSeq);
1220 const Standard_Integer aLen = aSeq.Length();
1223 for (i = 1; i <= aLen; i++) {
1224 TDF_Label aRefLabel = aSeq.Value(i);
1225 Handle(TDF_Reference) aRef;
1227 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1228 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1229 Handle(TDataStd_TreeNode) aT;
1231 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1232 TDF_Label aDepLabel = aT->Label();
1233 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1235 if (!aRefFunct.IsNull()) {
1236 // Get entry of the referenced object.
1237 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1239 const int aRefTag = GetTag(anObjEntry);
1241 if (anObjTag != aRefTag) {
1242 // Avoid making references for operations without copy.
1243 theRefMap[anObjTag].push_back(aRefTag);
1252 //=============================================================================
1254 * FindEntries: Returns a sequence of start/end positions of entries in the string
1256 //=============================================================================
1257 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1259 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1260 Standard_Integer aLen = theString.Length();
1261 Standard_Boolean isFound = Standard_False;
1263 const char* arr = theString.ToCString();
1264 Standard_Integer i = 0, j;
1267 int c = (int)arr[i];
1269 if(c >= 48 && c <= 57) { //Is digit?
1271 isFound = Standard_False;
1272 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1274 if(c == 58) isFound = Standard_True;
1277 if(isFound && arr[j-2] != 58) { // last char should be a digit
1278 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1289 //=============================================================================
1291 * ReplaceVariables: Replace parameters of the function by variales from
1294 //=============================================================================
1295 void ReplaceVariables(TCollection_AsciiString& theCommand,
1296 const TVariablesList& theVariables)
1298 if (SALOME::VerbosityActivated())
1299 std::cout<<"Command : "<<theCommand<<std::endl;
1301 if (SALOME::VerbosityActivated()) {
1302 std::cout<<"All Entries:"<<std::endl;
1303 TVariablesList::const_iterator it = theVariables.begin();
1304 for(;it != theVariables.end();it++)
1305 std::cout<<"\t'"<<(*it).first<<"'"<<std::endl;
1308 //Additional case - multi-row commands
1309 int aCommandIndex = 1;
1310 while( aCommandIndex < 10 ) { // tmp check
1311 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1312 if( aCommand.Length() == 0 )
1315 if (SALOME::VerbosityActivated())
1316 std::cout<<"Sub-command : "<<aCommand<<std::endl;
1318 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1319 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1321 //Get Entry of the result object
1322 TCollection_AsciiString anEntry;
1323 if( aCommand.Search("=") != -1 ) // command returns an object
1324 anEntry = aCommand.Token("=",1);
1325 else { // command modifies the object
1326 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1327 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1328 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1330 //Remove white spaces
1331 anEntry.RightAdjust();
1332 anEntry.LeftAdjust();
1333 if(SALOME::VerbosityActivated())
1334 std::cout<<"Result entry : '" <<anEntry<<"'"<<std::endl;
1336 if ( anEntry.IsEmpty() ) {
1341 //Check if result is list of entries - enough to get the first entry in this case
1343 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1344 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1346 TCollection_AsciiString aSeparator(COMMA);
1347 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1348 anEntry.Remove( 1, 1 );
1349 anEntry.RightAdjust();
1350 anEntry.LeftAdjust();
1351 if(SALOME::VerbosityActivated())
1352 std::cout<<"Sub-entry : '" <<anEntry<<"'"<<std::endl;
1355 //Find variables used for object construction
1356 ObjectStates* aStates = 0;
1357 TVariablesList::const_iterator it = theVariables.find(anEntry);
1358 if( it != theVariables.end() )
1359 aStates = (*it).second;
1362 if(SALOME::VerbosityActivated())
1363 std::cout<<"Valiables list empty!!!"<<std::endl;
1368 TState aVariables = aStates->GetCurrectState();
1370 if(SALOME::VerbosityActivated()) {
1371 std::cout<<"Variables from SObject:"<<std::endl;
1372 for (size_t i = 0; i < aVariables.size();i++)
1373 std::cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<std::endl;
1376 //Calculate total number of parameters
1377 Standard_Integer aTotalNbParams = 1;
1378 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1381 if(SALOME::VerbosityActivated())
1382 std::cout<<"aTotalNbParams = "<<aTotalNbParams<<std::endl;
1384 Standard_Integer aFirstParam = aNbEntries;
1386 //Replace parameters by variables
1387 Standard_Integer aStartPos = 0;
1388 Standard_Integer aEndPos = 0;
1390 TCollection_AsciiString aVar, aReplacedVar;
1391 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1392 //Replace first parameter (bettwen '(' character and first ',' character)
1393 if(i == aFirstParam)
1395 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1396 if(aTotalNbParams - aNbEntries > 0 )
1397 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1399 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1401 //Replace last parameter (bettwen ',' character and ')' character)
1402 else if(i == aTotalNbParams)
1404 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1405 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1407 //Replace other parameters (bettwen two ',' characters)
1408 else if(i != aFirstParam && i != aTotalNbParams )
1410 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1411 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1413 if (aStartPos == 0 || aEndPos == 0)
1416 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1418 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1420 if ( aStartPos == aEndPos )
1421 continue; // PAL20889: for "[]"
1423 if(SALOME::VerbosityActivated())
1424 std::cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<std::endl;
1426 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1430 if(SALOME::VerbosityActivated())
1431 std::cout<<"Variable: '"<< aVar <<"'"<<std::endl;
1433 // specific case for sketcher
1434 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1435 Standard_Integer aNbSections = 1;
1436 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1440 int aStartSectionPos = 0, aEndSectionPos = 0;
1441 TCollection_AsciiString aSection, aReplacedSection;
1442 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1443 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1444 if( aSectionIndex != aNbSections )
1445 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1447 aEndSectionPos = aVar.Length();
1449 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1450 if(SALOME::VerbosityActivated())
1451 std::cout<<"aSection: "<<aSection<<std::endl;
1453 Standard_Integer aNbParams = 1;
1454 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1458 int aStartParamPos = 0, aEndParamPos = 0;
1459 TCollection_AsciiString aParameter, aReplacedParameter;
1460 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1461 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1462 if( aParamIndex != aNbParams )
1463 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1465 aEndParamPos = aSection.Length() + 1;
1467 if(SALOME::VerbosityActivated())
1468 std::cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<std::endl;
1470 if ( aStartParamPos == aEndParamPos)
1473 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1474 if(SALOME::VerbosityActivated())
1475 std::cout<<"aParameter: "<<aParameter<<std::endl;
1477 if(iVar >= aVariables.size())
1480 aReplacedParameter = aVariables[iVar].myVariable;
1481 if(aReplacedParameter.IsEmpty()) {
1486 if(aVariables[iVar].isVariable) {
1487 aReplacedParameter.InsertBefore(1,"'");
1488 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1491 if(SALOME::VerbosityActivated())
1492 std::cout<<"aSection before : "<<aSection<< std::endl;
1493 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1494 aSection.Insert(aStartParamPos, aReplacedParameter);
1495 if(SALOME::VerbosityActivated())
1496 std::cout<<"aSection after : "<<aSection<<std::endl<<std::endl;
1500 if(SALOME::VerbosityActivated())
1501 std::cout<<"aVar before : "<<aVar<<std::endl;
1503 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1504 aVar.Insert(aStartSectionPos, aSection);
1506 if(SALOME::VerbosityActivated())
1507 std::cout<<"aVar after : "<<aVar<<std::endl<<std::endl;
1510 if(SALOME::VerbosityActivated())
1511 std::cout<<"aCommand before : "<<aCommand<<std::endl;
1512 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1513 aCommand.Insert(aStartPos, aVar);
1514 if(SALOME::VerbosityActivated())
1515 std::cout<<"aCommand after : "<<aCommand<<std::endl;
1518 } // end of specific case for sketcher
1520 //If parameter is entry or 'None', skip it
1521 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1524 if(iVar >= aVariables.size())
1527 aReplacedVar = aVariables[iVar].myVariable;
1528 if(aReplacedVar.IsEmpty()) {
1533 if(aVariables[iVar].isVariable) {
1534 aReplacedVar.InsertBefore(1,"\"");
1535 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1538 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1539 aCommand.Insert(aStartPos, aReplacedVar);
1543 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1544 theCommand.Insert(aStartCommandPos, aCommand);
1548 aStates->IncrementState();
1551 if (SALOME::VerbosityActivated())
1552 std::cout<<"Command : "<<theCommand<<std::endl;
1555 //=============================================================================
1557 * ReplaceEntriesByNames: Replace object entries by their names
1559 //=============================================================================
1560 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1561 TSting2ObjDataMap& aEntry2ObjData,
1562 const bool /*theIsPublished*/,
1563 TColStd_SequenceOfAsciiString& theObjListToPublish,
1564 Standard_Integer& objectCounter,
1565 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1567 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1568 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1569 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1571 //Replace entries by the names
1572 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1573 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1574 if (aLen == 0) anUpdatedScript = theScript;
1576 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1577 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1578 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1579 theObjListToPublish.Append( anEntry );
1581 TObjectData& data = aEntry2ObjData[ anEntry ];
1582 if ( data._pyName.IsEmpty() ) { // encountered for the 1st time
1583 if ( !data._name.IsEmpty() ) { // published object
1584 data._pyName = data._name;
1585 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1589 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1590 } while(aNameToEntry.IsBound(data._pyName));
1594 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1596 anUpdatedScript += data._pyName;
1597 aStart = aSeq->Value(i+1) + 1;
1600 //Add final part of the script
1601 if (aLen && aSeq->Value(aLen) < aScriptLength)
1602 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1604 theScript = anUpdatedScript;
1607 //=============================================================================
1609 * AddObjectColors: Add color to objects
1611 //=============================================================================
1612 void AddObjectColors (TCollection_AsciiString& theScript,
1613 const TSting2ObjDataMap& theEntry2ObjData)
1615 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1616 Handle(TDocStd_Document) aDoc = engine->GetDocument();
1618 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1619 for (anEntryToNameIt = theEntry2ObjData.begin();
1620 anEntryToNameIt!= theEntry2ObjData.end();
1623 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1624 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1627 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1631 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1635 bool anAutoColor = obj->GetAutoColor();
1638 TCollection_AsciiString aCommand( "\n\t" );
1639 aCommand += aName + ".SetAutoColor(1)";
1640 theScript += aCommand.ToCString();
1643 GEOM_Object::Color aColor = obj->GetColor();
1644 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1646 TCollection_AsciiString aCommand( "\n\t" );
1647 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1648 theScript += aCommand.ToCString();
1651 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1652 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1653 TCollection_AsciiString aCommand( "\n\t" );
1654 aCommand += aName + ".SetMarkerStd(";
1655 switch (aMarkerType) {
1656 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1657 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1658 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1659 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1660 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1661 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1662 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1663 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1664 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1665 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1666 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1667 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1668 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1669 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1672 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1674 case 1: aCommand += "GEOM.MS_10"; break;
1675 case 2: aCommand += "GEOM.MS_15"; break;
1676 case 3: aCommand += "GEOM.MS_20"; break;
1677 case 4: aCommand += "GEOM.MS_25"; break;
1678 case 5: aCommand += "GEOM.MS_30"; break;
1679 case 6: aCommand += "GEOM.MS_35"; break;
1680 case 7: aCommand += "GEOM.MS_40"; break;
1681 case 8: aCommand += "GEOM.MS_45"; break;
1682 case 9: aCommand += "GEOM.MS_50"; break;
1683 case 10: aCommand += "GEOM.MS_55"; break;
1684 case 11: aCommand += "GEOM.MS_60"; break;
1685 case 12: aCommand += "GEOM.MS_65"; break;
1686 case 13: aCommand += "GEOM.MS_70"; break;
1687 default: aCommand += "GEOM.MS_NONE"; break;
1690 theScript += aCommand.ToCString();
1692 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1693 int aMarkerTextureID = obj->GetMarkerTexture();
1694 if (aMarkerTextureID >= 0) {
1695 TCollection_AsciiString aCommand( "\n\t" );
1696 aCommand += aName + ".SetMarkerTexture(texture_map[";
1697 aCommand += aMarkerTextureID;
1699 theScript += aCommand.ToCString();
1705 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1707 TCollection_AsciiString stream;
1708 if (!aData.IsNull()) {
1709 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1710 Standard_Byte byte = aData->Value(i);
1711 TCollection_AsciiString strByte = "";
1712 for (int j = 0; j < 8; j++)
1713 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1720 void AddTextures (TCollection_AsciiString& theScript)
1722 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1723 std::list<int> allTextures = engine->getAllTextures();
1724 std::list<int>::const_iterator it;
1726 if (allTextures.size() > 0) {
1727 theScript += "\n\ttexture_map = {}\n";
1729 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1730 if (*it <= 0) continue;
1731 Standard_Integer aWidth, aHeight;
1732 TCollection_AsciiString aFileName;
1733 Handle(TColStd_HArray1OfByte) aTexture =
1734 engine->getTexture(*it, aWidth, aHeight, aFileName);
1735 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1736 TCollection_AsciiString aCommand = "\n\t";
1737 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1738 if (aFileName != "" ) {
1739 aCommand += "geompy.LoadTexture(\"";
1740 aCommand += aFileName.ToCString();
1744 aCommand += "geompy.AddTexture(";
1745 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1746 aCommand += pack_data(aTexture);
1749 theScript += aCommand;
1756 //=============================================================================
1758 * PublishObject: publish object in study script
1760 //=============================================================================
1761 void PublishObject (TObjectData& theObjectData,
1762 TSting2ObjDataMap& theEntry2ObjData,
1763 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1764 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1765 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1766 std::set< TCollection_AsciiString>& theIgnoreMap)
1768 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1769 if ( theObjectData._studyEntry.IsEmpty() )
1770 return; // was not published
1771 if ( theIgnoreMap.count( theObjectData._entry ) )
1772 return; // not to publish
1774 TCollection_AsciiString aCommand("\n\tgeompy.");
1776 // find a father entry
1777 TObjectData* aFatherData = 0;
1778 TCollection_AsciiString aFatherStudyEntry =
1779 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1780 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1781 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1782 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1783 aFatherData = stEntry2DataPtr->second;
1785 // treat multiply published object
1786 if ( theObjectData._pyName.IsEmpty() )
1788 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1789 if ( data0._pyName.IsEmpty() ) return; // something wrong
1791 theObjectData._pyName = theObjectData._name;
1792 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1794 TCollection_AsciiString aCreationCommand("\n\t");
1795 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1797 // store aCreationCommand before publishing commands
1798 int tag = GetTag(theObjectData._entry);
1799 theEntryToCmdMap.insert( std::make_pair( tag + -2*theEntry2ObjData.size(), aCreationCommand ));
1803 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1804 aCommand += "addToStudyInFather( ";
1805 aCommand += aFatherData->_pyName + ", ";
1808 aCommand += "addToStudy( ";
1810 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1812 // bind a command to the study entry
1813 int tag = GetTag(theObjectData._entry);
1814 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1816 theObjectData._studyEntry.Clear(); // not to publish any more
1819 //================================================================================
1821 * \brief Returns the string of publishing commands. Take into account that
1822 * references should be published prior to the objects refer to them.
1824 //================================================================================
1825 TCollection_AsciiString GetPublishCommands
1827 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1828 const TIntToListIntMap &theMapRefs,
1829 std::set< int > &thePublished)
1831 TCollection_AsciiString aResult;
1833 if (!thePublished.count(theTag)) {
1834 // This object is not published yet.
1835 thePublished.insert(theTag);
1837 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1838 theEntryToCmdMap.find(theTag);
1840 if (anIt != theEntryToCmdMap.end()) {
1841 // There is a pubish cmd.
1842 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1844 if (aRefIt != theMapRefs.end()) {
1845 // Recursively publish all references.
1846 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1848 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1849 const TCollection_AsciiString aRefCmd = GetPublishCommands
1850 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1856 // Add the object command.
1857 aResult += anIt->second;
1864 void Prettify(TCollection_AsciiString& theScript)
1866 TCollection_AsciiString output;
1867 static std::list<TCollection_AsciiString> ToRemove;
1868 if (ToRemove.empty()) {
1869 ToRemove.push_back("geompy.SubShapeAllIDs");
1870 ToRemove.push_back("geompy.SubShapeAllSortedCentresIDs");
1871 ToRemove.push_back("geompy.SubShapeAllSortedIDs");
1872 ToRemove.push_back("geompy.GetFreeFacesIDs");
1873 ToRemove.push_back("geompy.GetShapesOnBoxIDs");
1874 ToRemove.push_back("geompy.GetShapesOnShapeIDs");
1875 ToRemove.push_back("geompy.GetShapesOnPlaneIDs");
1876 ToRemove.push_back("geompy.GetShapesOnPlaneWithLocationIDs");
1877 ToRemove.push_back("geompy.GetShapesOnCylinderIDs");
1878 ToRemove.push_back("geompy.GetShapesOnCylinderWithLocationIDs");
1879 ToRemove.push_back("geompy.GetShapesOnSphereIDs");
1880 ToRemove.push_back("geompy.GetShapesOnQuadrangleIDs");
1881 ToRemove.push_back("geompy.GetSameIDs");
1885 while (start <= theScript.Length()) {
1886 int end = theScript.Location("\n", start, theScript.Length());
1887 if (end == -1) end = theScript.Length();
1888 TCollection_AsciiString line = theScript.SubString(start, end);
1890 for (std::list<TCollection_AsciiString>::const_iterator it = ToRemove.begin(); it != ToRemove.end() && !found; ++it)
1891 found = line.Search( *it ) != -1;
1898 //OK @@@@@@@@@@@@@@@@@@@@@@@@@@@
1901 //================================================================================
1903 * \brief Constructor
1905 //================================================================================
1906 ObjectStates::ObjectStates()
1911 //================================================================================
1915 //================================================================================
1916 ObjectStates::~ObjectStates()
1920 //================================================================================
1922 * \brief Return current object state
1923 * \retval state - Object state (vector of notebook variable)
1925 //================================================================================
1926 TState ObjectStates::GetCurrectState() const
1928 if((int)_states.size() > _dumpstate)
1929 return _states[_dumpstate];
1933 //================================================================================
1935 * \brief Add new object state
1936 * \param theState - Object state (vector of notebook variable)
1938 //================================================================================
1939 void ObjectStates::AddState(const TState &theState)
1941 _states.push_back(theState);
1944 //================================================================================
1946 * \brief Increment object state
1948 //================================================================================
1949 void ObjectStates::IncrementState()