1 // Copyright (C) 2007-2019 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>
41 #include <TDF_Tool.hxx>
42 #include <TDF_Data.hxx>
43 #include <TDF_Reference.hxx>
44 #include <TDF_LabelSequence.hxx>
45 #include <TDataStd_Integer.hxx>
46 #include <TDataStd_ChildNodeIterator.hxx>
47 #include <TFunction_Driver.hxx>
48 #include <TFunction_DriverTable.hxx>
49 #include <TDataStd_ByteArray.hxx>
50 #include <TDataStd_UAttribute.hxx>
51 #include <TDF_ChildIterator.hxx>
52 #include <TDataStd_Comment.hxx>
55 #include <TopTools_IndexedMapOfShape.hxx>
57 #include <TCollection_AsciiString.hxx>
58 #include <TCollection_ExtendedString.hxx>
59 #include <TColStd_SequenceOfAsciiString.hxx>
60 #include <TColStd_MapOfTransient.hxx>
61 #include <TColStd_HSequenceOfInteger.hxx>
63 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
65 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
67 #include <BinDrivers.hxx>
68 #include <StdDrivers_DocumentRetrievalDriver.hxx>
69 #include <PCDM_StorageDriver.hxx>
73 #include <Standard_Failure.hxx>
74 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
79 #define O_SQR_BRACKET '['
80 #define C_SQR_BRACKET ']'
81 #define PY_NULL "None"
84 static int MYDEBUG = 0;
87 static int MYDEBUG = 0;
90 // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump
91 // Next macro, when defined, causes appearing of SubShapeAllIDs(), SubShapeAllSortedIDs(), GetSameIDs()
92 // and other such commands in Python dump.
93 // See also GEOMImpl_IShapesOperations.cxx.
94 // ---------------------------------------
95 // #define DUMP_SUBSHAPE_IDS
96 // ---------------------------------------
98 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
99 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
100 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
101 typedef std::map< int, std::list < int > > TIntToListIntMap;
103 static GEOM_Engine* TheEngine = NULL;
106 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
108 TCollection_AsciiString anEntry;
109 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
113 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
114 TCollection_AsciiString& theScript,
115 TCollection_AsciiString& theAfterScript,
116 const TVariablesList& theVariables,
117 const bool theIsPublished,
118 TDF_LabelMap& theProcessed,
119 std::set<TCollection_AsciiString>& theIgnoreObjs,
120 bool& theIsDumpCollected);
122 static int GetTag(const TCollection_AsciiString &theEntry);
124 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
125 TIntToListIntMap &theRefMap);
127 void ReplaceVariables(TCollection_AsciiString& theCommand,
128 const TVariablesList& theVariables);
130 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
132 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
133 TSting2ObjDataMap& aEntry2ObjData,
134 const bool theIsPublished,
135 TColStd_SequenceOfAsciiString& theObjListToPublish,
136 Standard_Integer& objectCounter,
137 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
139 void AddObjectColors (TCollection_AsciiString& theScript,
140 const TSting2ObjDataMap& theEntry2ObjData);
142 void AddTextures (TCollection_AsciiString& theScript);
144 void PublishObject (TObjectData& theObjectData,
145 TSting2ObjDataMap& theEntry2ObjData,
146 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
147 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
148 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
149 std::set<TCollection_AsciiString>& theMapOfPublished);
151 static TCollection_AsciiString GetPublishCommands
153 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
154 const TIntToListIntMap &theMapRefs,
155 std::set< int > &thePublished);
157 void Prettify(TCollection_AsciiString& theScript);
159 //================================================================================
161 * \brief Fix up the name of python variable
163 //================================================================================
165 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
166 const TCollection_AsciiString& anEntry,
167 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
169 const TCollection_AsciiString allowedChars
170 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
172 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
173 pyName.Insert( 1, 'a' );
175 int p, p2=1; // replace not allowed chars
176 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
177 pyName.SetValue(p, '_');
180 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
181 { // diff objects have same name - make a new name by appending a digit
182 TCollection_AsciiString aName2;
183 Standard_Integer i = 0;
185 aName2 = pyName + "_" + ++i;
186 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
191 //=======================================================================
192 //function : GetTextureGUID
194 //=======================================================================
195 const Standard_GUID& GEOM_Engine::GetTextureGUID()
197 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
201 //=============================================================================
205 //=============================================================================
206 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
208 //=============================================================================
212 //=============================================================================
213 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
215 //=============================================================================
219 //=============================================================================
220 GEOM_Engine::GEOM_Engine()
222 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
224 _OCAFApp = new GEOM_Application();
225 _OCAFApp->DefineFormat("SALOME_GEOM", "GEOM Document Version 1.0", "sgd",
226 new StdDrivers_DocumentRetrievalDriver, 0);
227 BinDrivers::DefineFormat(_OCAFApp);
234 GEOM_Engine::~GEOM_Engine()
236 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
237 std::list< Handle(GEOM_Object) > objs;
238 for(; It.More(); It.Next())
239 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
240 std::list< Handle(GEOM_Object) >::iterator objit;
241 for(objit = objs.begin(); objit != objs.end(); ++objit)
242 RemoveObject(*objit);
249 //=============================================================================
253 //=============================================================================
254 Handle(TDocStd_Document) GEOM_Engine::GetDocument(bool force)
256 Handle(TDocStd_Document) aDoc;
261 _OCAFApp->NewDocument("BinOcaf", aDoc);
262 aDoc->SetUndoLimit(_UndoLimit);
268 //=============================================================================
272 //=============================================================================
274 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(const char* theEntry, bool force)
276 Handle(GEOM_BaseObject) anObject;
278 if (_objects.IsBound(theEntry)) {
279 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(theEntry));
282 Handle(TDocStd_Document) aDoc = GetDocument(force);
283 if ( !aDoc.IsNull()) {
285 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
286 if ( !aLabel.IsNull() ) {
287 int objType = GEOM_BaseObject::GetType( aLabel );
289 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
290 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
291 default: anObject = new GEOM_Object (aLabel);
293 _objects.Bind(theEntry, anObject);
301 //=============================================================================
305 //=============================================================================
307 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theType)
309 Handle(TDocStd_Document) aDoc = GetDocument();
310 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
312 // NPAL18604: use existing label to decrease memory usage,
313 // if this label has been freed (object deleted)
314 bool useExisting = false;
316 if (!_freeLabels.empty()) {
318 aChild = _freeLabels.front();
319 _freeLabels.pop_front();
323 aChild = TDF_TagSource::NewChild(aDoc->Main());
326 Handle(GEOM_BaseObject) anObject;
328 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
329 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
330 default: anObject = new GEOM_Object (aChild, theType);
333 //Put an object in the map of created objects
334 TCollection_AsciiString anID = BuildIDFromObject(anObject);
335 if(_objects.IsBound(anID)) _objects.UnBind(anID);
336 _objects.Bind(anID, anObject);
341 //================================================================================
343 * \brief Adds a new object of the type theType in the OCAF document
345 //================================================================================
347 Handle(GEOM_Object) GEOM_Engine::AddObject(int theType)
349 return Handle(GEOM_Object)::DownCast( AddBaseObject(theType) );
352 //=============================================================================
356 //=============================================================================
358 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
359 Handle(TColStd_HArray1OfInteger) theIndices,
360 bool isStandaloneOperation)
362 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
364 Handle(TDocStd_Document) aDoc = GetDocument();
365 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
367 // NPAL18604: use existing label to decrease memory usage,
368 // if this label has been freed (object deleted)
369 bool useExisting = false;
371 if (!_freeLabels.empty()) {
373 aChild = _freeLabels.front();
374 _freeLabels.pop_front();
378 aChild = TDF_TagSource::NewChild(aDoc->Main());
381 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
382 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
383 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
385 GEOM_ISubShape aSSI (aFunction);
386 aSSI.SetMainShape(aMainShape);
387 aSSI.SetIndices(theIndices);
391 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
392 if (!aSolver.ComputeFunction(aFunction)) {
393 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
397 catch (Standard_Failure& aFail) {
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 TDF_Label aLabel = theObject->GetEntry();
439 if ( aLabel == aLabel.Root() )
440 return false; // already removed object
442 //Remove an object from the map of available objects
443 TCollection_AsciiString anID = BuildIDFromObject(theObject);
444 if (_objects.IsBound(anID)) {
445 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
446 if ( anObject != theObject )
447 anObject->_label = anObject->_label.Root();
448 _objects.UnBind(anID);
451 // If sub-shape, remove it from the list of sub-shapes of its main shape
452 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
453 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
454 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
455 GEOM_ISubShape aSSI (aFunction);
456 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
457 //If main shape is not null, then remove
458 if(!aMainShape.IsNull())
459 aMainShape->RemoveSubShapeReference(aFunction);
462 int nb = theObject->GetNbFunctions();
463 Handle(TDataStd_TreeNode) aNode;
464 for (int i = 1; i <= nb; i++) {
465 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
466 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
470 aLabel.ForgetAllAttributes(Standard_True);
472 // Remember the label to reuse it then
473 if ( _freeLabels.empty() || _freeLabels.back() != aLabel )
474 _freeLabels.push_back(aLabel);
476 // we can't explicitly delete theObject. At least prevent its functioning
477 // as an alive object when aLabel is reused for a new object
478 theObject->_label = aLabel.Root();
479 theObject->_ior.Clear();
480 theObject->_parameters.Clear();;
487 //=============================================================================
491 //=============================================================================
492 void GEOM_Engine::Undo()
494 GetDocument()->Undo();
497 //=============================================================================
501 //=============================================================================
502 void GEOM_Engine::Redo()
504 GetDocument()->Redo();
507 //=============================================================================
511 //=============================================================================
512 bool GEOM_Engine::Save(const char* theFileName)
514 if(!_document) return false;
516 #if defined(WIN32) && defined(UNICODE)
517 std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName);
519 std::string aFileName = theFileName;
522 _OCAFApp->SaveAs( _document, aFileName.c_str() );
527 //=============================================================================
531 //=============================================================================
532 bool GEOM_Engine::Load(const char* theFileName)
534 #if defined(WIN32) && defined(UNICODE)
535 std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName);
537 std::string aFileName = theFileName;
539 Handle(TDocStd_Document) aDoc;
540 if (_OCAFApp->Open(aFileName.c_str(), aDoc) != PCDM_RS_OK) {
544 // Replace old document format by the new one.
545 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
546 aDoc->ChangeStorageFormat("BinOcaf");
549 aDoc->SetUndoLimit(_UndoLimit);
556 //=============================================================================
560 //=============================================================================
561 void GEOM_Engine::Close()
564 //Remove all GEOM Objects associated to the document
565 TColStd_SequenceOfAsciiString aSeq;
566 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
567 for (; It.More(); It.Next()) {
568 aSeq.Append(It.Key());
570 for (Standard_Integer i=1; i<=aSeq.Length(); i++) {
571 _objects.UnBind(aSeq.Value(i));
574 // Forget free labels for document
577 _OCAFApp->Close(_document);
582 //=============================================================================
586 //=============================================================================
587 TCollection_AsciiString GEOM_Engine::DumpPython(std::vector<TObjectData>& theObjectData,
588 TVariablesList theVariables,
593 // Set "C" numeric locale to save numbers correctly
594 Kernel_Utils::Localizer loc;
596 TCollection_AsciiString aScript;
597 Handle(TDocStd_Document) aDoc = GetDocument();
601 TCollection_AsciiString anEmptyScript;
603 anEmptyScript = "def RebuildData(): pass\n";
604 return anEmptyScript;
608 aScript = "import salome\n";
610 aScript += "import GEOM\n";
611 aScript += "from salome.geom import geomBuilder\n";
612 aScript += "import math\n";
613 aScript += "import SALOMEDS\n\n";
615 aScript += "def RebuildData():";
617 aScript += "\n\tgeompy = geomBuilder.New()\n";
619 AddTextures(aScript);
621 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
623 // a map containing copies of TObjectData from theObjectData
624 TSting2ObjDataMap aEntry2ObjData;
625 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
626 // occurs when several StudyEntries correspond to one Entry
627 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
629 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
630 for (unsigned i = 0; i < theObjectData.size(); ++i )
632 TObjectData& data = theObjectData[i];
633 // look for an object by entry
635 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
636 if ( L.IsNull() ) continue;
637 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
639 if ( !obj.IsNull() ) {
640 TSting2ObjDataMap::iterator ent2Data =
641 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
643 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
644 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
646 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
650 // collect objects entries to be published
651 TColStd_SequenceOfAsciiString aObjListToPublish;
653 // iterates on functions till critical (that requiers publication of objects)
654 Handle(TDataStd_TreeNode) aNode, aRoot;
655 Handle(GEOM_Function) aFunction;
656 TDF_LabelMap aCheckedFuncMap;
657 std::set< TCollection_AsciiString > anIgnoreObjMap;
659 TCollection_AsciiString aFuncScript;
661 // Mantis issue 0020768
662 Standard_Integer objectCounter = 0;
663 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
664 TIntToListIntMap aRefMap;
666 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
667 TDataStd_ChildNodeIterator Itr(aRoot);
668 for (; Itr.More(); Itr.Next()) {
670 aFunction = GEOM_Function::GetFunction(aNode->Label());
671 if (aFunction.IsNull()) {
672 MESSAGE ( "Null function !!!!" );
675 bool isDumpCollected = false;
676 TCollection_AsciiString aCurScript, anAfterScript;
677 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
678 isPublished, aCheckedFuncMap, anIgnoreObjMap,
681 // add function description before dump
682 if (!aCurScript.IsEmpty())
684 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
685 aFuncScript.Length() > aCurScript.Length() )
686 // avoid repeated SubShape...() command at the end
687 if (aFuncScript.Location( aCurScript,
688 aFuncScript.Length() - aCurScript.Length(),
689 aFuncScript.Length()))
690 continue; // aCurScript is already at the end of aFuncScript
691 aFuncScript += aCurScript;
694 // Fill the map of references.
695 FillMapOfRef(aFunction, aRefMap);
697 if (isDumpCollected ) {
698 // Replace entries by the names
699 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
700 aObjListToPublish, objectCounter, aNameToEntry );
702 // publish collected objects
703 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
704 int i = 1, n = aObjListToPublish.Length();
705 for ( ; i <= n; i++ )
707 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
708 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
709 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
711 // add publishing commands to the script
712 std::set< int > aPublished;
713 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
715 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
716 const TCollection_AsciiString aPublishCmds =
717 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
718 aRefMap, aPublished);
720 aFuncScript += aPublishCmds;
723 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
724 // because they will be published during command execution
725 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
727 indx = anAfterScript.Search( "RestoreSubShapes" );
729 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
730 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
731 i = 1, n = aSeq->Length();
732 for ( ; i <= n; i+=2) {
733 TCollection_AsciiString anEntry =
734 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
735 anIgnoreObjMap.insert(anEntry.ToCString());
739 aObjListToPublish.Clear();
740 aScript += aFuncScript;
743 aFuncScript += anAfterScript;
747 // Replace entries by the names
748 aObjListToPublish.Clear();
749 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
750 objectCounter, aNameToEntry );
752 aScript += aFuncScript;
755 AddObjectColors(aScript, aEntry2ObjData );
757 // Make script to publish in study
758 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
761 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
763 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
764 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
765 ++aStEntry2ObjDataPtrIt)
767 TObjectData* data = aStEntry2ObjDataPtrIt->second;
768 if ( anIgnoreObjMap.count( data->_entry ))
769 continue; // should not be dumped
770 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
771 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
773 // add publishing commands to the script
774 std::set< int > aPublished;
775 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
777 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
778 const TCollection_AsciiString aPublishCmds =
779 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
780 aRefMap, aPublished);
782 aScript += aPublishCmds;
786 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
787 //Add unpublish command if need
788 TCollection_AsciiString unpublishCmd("\n");
790 unpublishCmd += "\t";
791 unpublishCmd += "geompy.hideInStudy(";
793 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
794 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
795 ++aStEntry2ObjDataPtrIt)
797 TObjectData* data = aStEntry2ObjDataPtrIt->second;
798 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
799 aScript += unpublishCmd + data->_pyName + ")";
803 //aScript += "\n\tpass\n";
807 // fill _studyEntry2NameMap and build globalVars
808 TCollection_AsciiString globalVars;
809 _studyEntry2NameMap.Clear();
810 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
811 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
812 ++aStEntry2ObjDataPtrIt)
814 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
815 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
816 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
817 if ( !globalVars.IsEmpty() )
819 globalVars += data->_pyName;
821 if ( isMultiFile && !globalVars.IsEmpty() ) {
822 globalVars.Insert( 1, "\n\tglobal " );
823 aScript.Insert( posToInsertGlobalVars, globalVars );
826 // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump
827 #ifndef DUMP_SUBSHAPE_IDS
834 //=======================================================================
835 //function : GetDumpName
837 //=======================================================================
839 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
841 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
842 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
847 //=======================================================================
848 //function : GetAllDumpNames
850 //=======================================================================
852 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
854 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
856 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
857 for (; it.More(); it.Next()) {
858 aRetSeq->Append(it.Value());
864 #define TEXTURE_LABEL_ID 1
865 #define TEXTURE_LABEL_FILE 2
866 #define TEXTURE_LABEL_WIDTH 3
867 #define TEXTURE_LABEL_HEIGHT 4
868 #define TEXTURE_LABEL_DATA 5
870 int GEOM_Engine::addTexture(int theWidth, int theHeight,
871 const Handle(TColStd_HArray1OfByte)& theTexture,
872 const TCollection_AsciiString& theFileName)
874 Handle(TDocStd_Document) aDoc = GetDocument();
875 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
877 // NPAL18604: use existing label to decrease memory usage,
878 // if this label has been freed (object deleted)
879 bool useExisting = false;
881 if (!_freeLabels.empty()) {
883 aChild = _freeLabels.front();
884 _freeLabels.pop_front();
888 aChild = TDF_TagSource::NewChild(aDoc->Main());
891 aChild.ForgetAllAttributes(Standard_True);
892 Handle(TDataStd_TreeNode) node;
893 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
894 node = TDataStd_TreeNode::Set(aChild);
895 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
897 static int aTextureID = 0;
899 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
900 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
901 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
902 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
904 Handle(TDataStd_ByteArray) anAttr =
905 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
906 theTexture.IsNull() ? 0 : theTexture->Lower(),
907 theTexture.IsNull() ? 0 : theTexture->Upper());
908 anAttr->ChangeArray(theTexture);
913 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theTextureID,
914 int& theWidth, int& theHeight,
915 TCollection_AsciiString& theFileName)
917 Handle(TColStd_HArray1OfByte) anArray;
918 theWidth = theHeight = 0;
920 Handle(TDocStd_Document) aDoc = GetDocument();
922 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
924 for (; anIterator.More() && !found; anIterator.Next()) {
925 TDF_Label aTextureLabel = anIterator.Value();
926 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
927 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
928 Handle(TDataStd_Integer) anIdAttr;
929 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
930 anIdAttr->Get() == theTextureID) {
931 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
932 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
933 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
934 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
935 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
936 Handle(TDataStd_ByteArray) aTextureAttr;
937 Handle(TDataStd_Comment) aFileAttr;
938 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
939 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
940 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
941 theWidth = aWidthAttr->Get();
942 theHeight = aHeightAttr->Get();
943 anArray = aTextureAttr->InternalArray();
945 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
946 theFileName = aFileAttr->Get();
954 std::list<int> GEOM_Engine::getAllTextures()
956 std::list<int> id_list;
958 Handle(TDocStd_Document) aDoc = GetDocument();
960 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
961 for (; anIterator.More(); anIterator.Next()) {
962 TDF_Label aTextureLabel = anIterator.Value();
963 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
964 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
965 Handle(TDataStd_Integer) anIdAttr;
966 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
967 id_list.push_back((int)anIdAttr->Get());
973 //===========================================================================
974 // Internal functions
975 //===========================================================================
977 //=============================================================================
979 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
981 //=============================================================================
982 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
984 TCollection_AsciiString aNewDescr;
986 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
987 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
988 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
989 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
990 // "3DSketcher:CMD[:CMD[:CMD...]]"
991 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
993 // Split the command string to separate CMDs
995 TColStd_SequenceOfAsciiString aSequence;
996 if (aCommand.Length()) {
997 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
998 while (aToken.Length() > 0) {
999 aSequence.Append(aToken);
1000 aToken = aCommand.Token(":", ++icmd);
1004 if (aSequence.Length() > 0) {
1006 aNewDescr += "\n\t";
1008 aNewDescr += "\nsk = geompy.Sketcher3D()";
1009 int nbCMDs = aSequence.Length();
1010 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1011 aNewDescr += "\n\t";
1013 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1015 // Split the CMD into string values
1016 TColStd_SequenceOfAsciiString aStrVals;
1018 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1019 while (aToken.Length() > 0) {
1020 aStrVals.Append(aToken);
1021 aToken = aCMD.Token(" ", ++ival);
1024 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1025 if (aCMDpref == "TT") {
1026 aNewDescr += "sk.addPointsAbsolute(";
1027 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1029 else if (aCMDpref == "T") {
1030 aNewDescr += "sk.addPointsRelative(";
1031 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1033 else if (aCMDpref == "WW") {
1034 aNewDescr += "sk.close()";
1036 else if (aCMDpref.Value(1) == 'O'){
1037 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1039 if (aCMDpref.Value(4) == 'C')
1040 aNewDescr += "sk.addPointRadiusAngleH";
1042 aNewDescr += "sk.addPointRadiusAngles";
1043 if (aCMDpref.Value(5) == 'A')
1044 aNewDescr += "Absolute(";
1046 aNewDescr += "Relative(";
1047 aNewDescr += aStrVals.Value(4) + ", " +
1048 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1051 aNewDescr += "\n\t";
1052 aNewDescr += aResult + " = sk.wire()";
1054 } // Make3DSketcherCommand
1055 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1056 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1057 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1058 aCommand = aCommand.Token("]", 1);
1060 aNewDescr += "\n\t";
1061 aNewDescr += "\nsk = geompy.Sketcher3D()";
1062 aNewDescr += "\n\t";
1063 aNewDescr += "sk.addPointsAbsolute(";
1064 aNewDescr += aCommand + ")";
1065 aNewDescr += "\n\t";
1066 aNewDescr += aResult + " = sk.wire()";
1070 aNewDescr += "\n\t";
1071 aNewDescr += aSubStr;
1078 //=============================================================================
1080 * ProcessFunction: Dump function description into script
1082 //=============================================================================
1083 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1084 TCollection_AsciiString& theScript,
1085 TCollection_AsciiString& theAfterScript,
1086 const TVariablesList& theVariables,
1087 const bool theIsPublished,
1088 TDF_LabelMap& theProcessed,
1089 std::set<TCollection_AsciiString>& theIgnoreObjs,
1090 bool& theIsDumpCollected)
1092 theIsDumpCollected = false;
1093 if (theFunction.IsNull()) return false;
1095 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1097 // pass functions, that depends on nonexisting ones
1098 bool doNotProcess = false;
1099 TDF_LabelSequence aSeq;
1100 theFunction->GetDependency(aSeq);
1101 Standard_Integer aLen = aSeq.Length();
1102 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1103 TDF_Label aRefLabel = aSeq.Value(i);
1104 Handle(TDF_Reference) aRef;
1105 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1106 doNotProcess = true;
1109 if (aRef.IsNull() || aRef->Get().IsNull()) {
1110 doNotProcess = true;
1113 Handle(TDataStd_TreeNode) aT;
1114 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1115 doNotProcess = true;
1118 TDF_Label aDepLabel = aT->Label();
1119 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1121 if (aFunction.IsNull()) doNotProcess = true;
1122 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1129 TCollection_AsciiString anObjEntry;
1130 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1131 theIgnoreObjs.insert(anObjEntry);
1134 theProcessed.Add(theFunction->GetEntry());
1136 TCollection_AsciiString aDescr = theFunction->GetDescription();
1137 if(aDescr.Length() == 0) return false;
1139 //Check if its internal function which doesn't requires dumping
1140 if(aDescr == "None") return false;
1142 //Check the very specific case of RestoreShape function,
1143 //which is not dumped, but the result can be published by the user.
1144 //We do not publish such objects to decrease danger of dumped script failure.
1145 if(aDescr.Value(1) == '#') {
1146 TCollection_AsciiString anObjEntry;
1147 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1148 theIgnoreObjs.insert(anObjEntry);
1152 // 0020001 PTv, check for critical functions, which require dump of objects
1155 // currently, there is only one function "RestoreGivenSubShapes",
1156 // later this check could be replaced by iterations on list of such functions
1157 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1158 theIsDumpCollected = true;
1159 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1160 theIsDumpCollected = true;
1163 //Replace parameter by notebook variables
1164 ReplaceVariables(aDescr,theVariables);
1166 //Process sketcher functions, replacing string command by calls to Sketcher interface
1167 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1168 Sketcher_Profile aProfile( aDescr.ToCString());
1169 // Make new command for SketcherOnPlane and for Sketcher
1170 aDescr = aProfile.GetDump();
1172 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1173 aDescr = MakeCommandfor3DSketcher ( aDescr );
1176 if ( theIsDumpCollected ) {
1178 bool isBefore = true;
1179 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1180 while (!aSubStr.IsEmpty()) {
1182 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1183 aSubStr.Search( "RestoreSubShapes" ) == -1)
1184 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1186 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1187 aSubStr = aDescr.Token("\n\t", i++);
1191 theScript += "\n\t";
1192 theScript += aDescr;
1197 //=============================================================================
1199 * GetTag: Returns the tag from entry
1201 //=============================================================================
1202 int GetTag(const TCollection_AsciiString &theEntry)
1204 const int aGeomObjDepth = 3;
1205 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1210 //=============================================================================
1212 * FillMapOfRef: Fill the map of references
1214 //=============================================================================
1215 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1216 TIntToListIntMap &theRefMap)
1218 TDF_LabelSequence aSeq;
1219 TCollection_AsciiString anObjEntry;
1222 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1223 anObjTag = GetTag(anObjEntry);
1224 theFunction->GetDependency(aSeq);
1226 const Standard_Integer aLen = aSeq.Length();
1229 for (i = 1; i <= aLen; i++) {
1230 TDF_Label aRefLabel = aSeq.Value(i);
1231 Handle(TDF_Reference) aRef;
1233 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1234 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1235 Handle(TDataStd_TreeNode) aT;
1237 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1238 TDF_Label aDepLabel = aT->Label();
1239 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1241 if (!aRefFunct.IsNull()) {
1242 // Get entry of the referenced object.
1243 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1245 const int aRefTag = GetTag(anObjEntry);
1247 if (anObjTag != aRefTag) {
1248 // Avoid making references for operations without copy.
1249 theRefMap[anObjTag].push_back(aRefTag);
1258 //=============================================================================
1260 * FindEntries: Returns a sequence of start/end positions of entries in the string
1262 //=============================================================================
1263 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1265 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1266 Standard_Integer aLen = theString.Length();
1267 Standard_Boolean isFound = Standard_False;
1269 const char* arr = theString.ToCString();
1270 Standard_Integer i = 0, j;
1273 int c = (int)arr[i];
1275 if(c >= 48 && c <= 57) { //Is digit?
1277 isFound = Standard_False;
1278 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1280 if(c == 58) isFound = Standard_True;
1283 if(isFound && arr[j-2] != 58) { // last char should be a digit
1284 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1295 //=============================================================================
1297 * ReplaceVariables: Replace parameters of the function by variales from
1300 //=============================================================================
1301 void ReplaceVariables(TCollection_AsciiString& theCommand,
1302 const TVariablesList& theVariables)
1305 std::cout<<"Command : "<<theCommand<<std::endl;
1308 std::cout<<"All Entries:"<<std::endl;
1309 TVariablesList::const_iterator it = theVariables.begin();
1310 for(;it != theVariables.end();it++)
1311 std::cout<<"\t'"<<(*it).first<<"'"<<std::endl;
1314 //Additional case - multi-row commands
1315 int aCommandIndex = 1;
1316 while( aCommandIndex < 10 ) { // tmp check
1317 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1318 if( aCommand.Length() == 0 )
1322 std::cout<<"Sub-command : "<<aCommand<<std::endl;
1324 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1325 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1327 //Get Entry of the result object
1328 TCollection_AsciiString anEntry;
1329 if( aCommand.Search("=") != -1 ) // command returns an object
1330 anEntry = aCommand.Token("=",1);
1331 else { // command modifies the object
1332 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1333 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1334 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1336 //Remove white spaces
1337 anEntry.RightAdjust();
1338 anEntry.LeftAdjust();
1340 std::cout<<"Result entry : '" <<anEntry<<"'"<<std::endl;
1342 if ( anEntry.IsEmpty() ) {
1347 //Check if result is list of entries - enough to get the first entry in this case
1349 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1350 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1352 TCollection_AsciiString aSeparator(COMMA);
1353 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1354 anEntry.Remove( 1, 1 );
1355 anEntry.RightAdjust();
1356 anEntry.LeftAdjust();
1358 std::cout<<"Sub-entry : '" <<anEntry<<"'"<<std::endl;
1361 //Find variables used for object construction
1362 ObjectStates* aStates = 0;
1363 TVariablesList::const_iterator it = theVariables.find(anEntry);
1364 if( it != theVariables.end() )
1365 aStates = (*it).second;
1369 std::cout<<"Valiables list empty!!!"<<std::endl;
1374 TState aVariables = aStates->GetCurrectState();
1377 std::cout<<"Variables from SObject:"<<std::endl;
1378 for (size_t i = 0; i < aVariables.size();i++)
1379 std::cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<std::endl;
1382 //Calculate total number of parameters
1383 Standard_Integer aTotalNbParams = 1;
1384 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1388 std::cout<<"aTotalNbParams = "<<aTotalNbParams<<std::endl;
1390 Standard_Integer aFirstParam = aNbEntries;
1392 //Replace parameters by variables
1393 Standard_Integer aStartPos = 0;
1394 Standard_Integer aEndPos = 0;
1396 TCollection_AsciiString aVar, aReplacedVar;
1397 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1398 //Replace first parameter (bettwen '(' character and first ',' character)
1399 if(i == aFirstParam)
1401 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1402 if(aTotalNbParams - aNbEntries > 0 )
1403 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1405 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1407 //Replace last parameter (bettwen ',' character and ')' character)
1408 else if(i == aTotalNbParams)
1410 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1411 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1413 //Replace other parameters (bettwen two ',' characters)
1414 else if(i != aFirstParam && i != aTotalNbParams )
1416 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1417 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1419 if (aStartPos == 0 || aEndPos == 0)
1422 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1424 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1426 if ( aStartPos == aEndPos )
1427 continue; // PAL20889: for "[]"
1430 std::cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<std::endl;
1432 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1437 std::cout<<"Variable: '"<< aVar <<"'"<<std::endl;
1439 // specific case for sketcher
1440 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1441 Standard_Integer aNbSections = 1;
1442 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1446 int aStartSectionPos = 0, aEndSectionPos = 0;
1447 TCollection_AsciiString aSection, aReplacedSection;
1448 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1449 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1450 if( aSectionIndex != aNbSections )
1451 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1453 aEndSectionPos = aVar.Length();
1455 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1457 std::cout<<"aSection: "<<aSection<<std::endl;
1459 Standard_Integer aNbParams = 1;
1460 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1464 int aStartParamPos = 0, aEndParamPos = 0;
1465 TCollection_AsciiString aParameter, aReplacedParameter;
1466 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1467 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1468 if( aParamIndex != aNbParams )
1469 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1471 aEndParamPos = aSection.Length() + 1;
1474 std::cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<std::endl;
1476 if ( aStartParamPos == aEndParamPos)
1479 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1481 std::cout<<"aParameter: "<<aParameter<<std::endl;
1483 if(iVar >= aVariables.size())
1486 aReplacedParameter = aVariables[iVar].myVariable;
1487 if(aReplacedParameter.IsEmpty()) {
1492 if(aVariables[iVar].isVariable) {
1493 aReplacedParameter.InsertBefore(1,"'");
1494 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1498 std::cout<<"aSection before : "<<aSection<< std::endl;
1499 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1500 aSection.Insert(aStartParamPos, aReplacedParameter);
1502 std::cout<<"aSection after : "<<aSection<<std::endl<<std::endl;
1506 std::cout<<"aVar before : "<<aVar<<std::endl;
1507 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1508 aVar.Insert(aStartSectionPos, aSection);
1510 std::cout<<"aVar after : "<<aVar<<std::endl<<std::endl;
1514 std::cout<<"aCommand before : "<<aCommand<<std::endl;
1515 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1516 aCommand.Insert(aStartPos, aVar);
1518 std::cout<<"aCommand after : "<<aCommand<<std::endl;
1521 } // end of specific case for sketcher
1523 //If parameter is entry or 'None', skip it
1524 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1527 if(iVar >= aVariables.size())
1530 aReplacedVar = aVariables[iVar].myVariable;
1531 if(aReplacedVar.IsEmpty()) {
1536 if(aVariables[iVar].isVariable) {
1537 aReplacedVar.InsertBefore(1,"\"");
1538 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1541 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1542 aCommand.Insert(aStartPos, aReplacedVar);
1546 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1547 theCommand.Insert(aStartCommandPos, aCommand);
1551 aStates->IncrementState();
1555 std::cout<<"Command : "<<theCommand<<std::endl;
1558 //=============================================================================
1560 * ReplaceEntriesByNames: Replace object entries by their names
1562 //=============================================================================
1563 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1564 TSting2ObjDataMap& aEntry2ObjData,
1565 const bool theIsPublished,
1566 TColStd_SequenceOfAsciiString& theObjListToPublish,
1567 Standard_Integer& objectCounter,
1568 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1570 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1571 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1572 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1574 //Replace entries by the names
1575 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1576 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1577 if (aLen == 0) anUpdatedScript = theScript;
1579 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1580 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1581 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1582 theObjListToPublish.Append( anEntry );
1584 TObjectData& data = aEntry2ObjData[ anEntry ];
1585 if ( data._pyName.IsEmpty() ) { // encountered for the 1st time
1586 if ( !data._name.IsEmpty() ) { // published object
1587 data._pyName = data._name;
1588 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1592 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1593 } while(aNameToEntry.IsBound(data._pyName));
1597 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1599 anUpdatedScript += data._pyName;
1600 aStart = aSeq->Value(i+1) + 1;
1603 //Add final part of the script
1604 if (aLen && aSeq->Value(aLen) < aScriptLength)
1605 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1607 theScript = anUpdatedScript;
1610 //=============================================================================
1612 * AddObjectColors: Add color to objects
1614 //=============================================================================
1615 void AddObjectColors (TCollection_AsciiString& theScript,
1616 const TSting2ObjDataMap& theEntry2ObjData)
1618 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1619 Handle(TDocStd_Document) aDoc = engine->GetDocument();
1621 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1622 for (anEntryToNameIt = theEntry2ObjData.begin();
1623 anEntryToNameIt!= theEntry2ObjData.end();
1626 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1627 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1630 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1634 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1638 bool anAutoColor = obj->GetAutoColor();
1641 TCollection_AsciiString aCommand( "\n\t" );
1642 aCommand += aName + ".SetAutoColor(1)";
1643 theScript += aCommand.ToCString();
1646 GEOM_Object::Color aColor = obj->GetColor();
1647 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1649 TCollection_AsciiString aCommand( "\n\t" );
1650 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1651 theScript += aCommand.ToCString();
1654 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1655 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1656 TCollection_AsciiString aCommand( "\n\t" );
1657 aCommand += aName + ".SetMarkerStd(";
1658 switch (aMarkerType) {
1659 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1660 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1661 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1662 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1663 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1664 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1665 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1666 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1667 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1668 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1669 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1670 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1671 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1672 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1675 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1677 case 1: aCommand += "GEOM.MS_10"; break;
1678 case 2: aCommand += "GEOM.MS_15"; break;
1679 case 3: aCommand += "GEOM.MS_20"; break;
1680 case 4: aCommand += "GEOM.MS_25"; break;
1681 case 5: aCommand += "GEOM.MS_30"; break;
1682 case 6: aCommand += "GEOM.MS_35"; break;
1683 case 7: aCommand += "GEOM.MS_40"; break;
1684 case 8: aCommand += "GEOM.MS_45"; break;
1685 case 9: aCommand += "GEOM.MS_50"; break;
1686 case 10: aCommand += "GEOM.MS_55"; break;
1687 case 11: aCommand += "GEOM.MS_60"; break;
1688 case 12: aCommand += "GEOM.MS_65"; break;
1689 case 13: aCommand += "GEOM.MS_70"; break;
1690 default: aCommand += "GEOM.MS_NONE"; break;
1693 theScript += aCommand.ToCString();
1695 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1696 int aMarkerTextureID = obj->GetMarkerTexture();
1697 if (aMarkerTextureID >= 0) {
1698 TCollection_AsciiString aCommand( "\n\t" );
1699 aCommand += aName + ".SetMarkerTexture(texture_map[";
1700 aCommand += aMarkerTextureID;
1702 theScript += aCommand.ToCString();
1708 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1710 TCollection_AsciiString stream;
1711 if (!aData.IsNull()) {
1712 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1713 Standard_Byte byte = aData->Value(i);
1714 TCollection_AsciiString strByte = "";
1715 for (int j = 0; j < 8; j++)
1716 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1723 void AddTextures (TCollection_AsciiString& theScript)
1725 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1726 std::list<int> allTextures = engine->getAllTextures();
1727 std::list<int>::const_iterator it;
1729 if (allTextures.size() > 0) {
1730 theScript += "\n\ttexture_map = {}\n";
1732 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1733 if (*it <= 0) continue;
1734 Standard_Integer aWidth, aHeight;
1735 TCollection_AsciiString aFileName;
1736 Handle(TColStd_HArray1OfByte) aTexture =
1737 engine->getTexture(*it, aWidth, aHeight, aFileName);
1738 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1739 TCollection_AsciiString aCommand = "\n\t";
1740 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1741 if (aFileName != "" ) {
1742 aCommand += "geompy.LoadTexture(\"";
1743 aCommand += aFileName.ToCString();
1747 aCommand += "geompy.AddTexture(";
1748 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1749 aCommand += pack_data(aTexture);
1752 theScript += aCommand;
1759 //=============================================================================
1761 * PublishObject: publish object in study script
1763 //=============================================================================
1764 void PublishObject (TObjectData& theObjectData,
1765 TSting2ObjDataMap& theEntry2ObjData,
1766 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1767 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1768 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1769 std::set< TCollection_AsciiString>& theIgnoreMap)
1771 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1772 if ( theObjectData._studyEntry.IsEmpty() )
1773 return; // was not published
1774 if ( theIgnoreMap.count( theObjectData._entry ) )
1775 return; // not to publish
1777 TCollection_AsciiString aCommand("\n\tgeompy.");
1779 // find a father entry
1780 TObjectData* aFatherData = 0;
1781 TCollection_AsciiString aFatherStudyEntry =
1782 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1783 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1784 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1785 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1786 aFatherData = stEntry2DataPtr->second;
1788 // treat multiply published object
1789 if ( theObjectData._pyName.IsEmpty() )
1791 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1792 if ( data0._pyName.IsEmpty() ) return; // something wrong
1794 theObjectData._pyName = theObjectData._name;
1795 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1797 TCollection_AsciiString aCreationCommand("\n\t");
1798 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1800 // store aCreationCommand before publishing commands
1801 int tag = GetTag(theObjectData._entry);
1802 theEntryToCmdMap.insert( std::make_pair( tag + -2*theEntry2ObjData.size(), aCreationCommand ));
1806 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1807 aCommand += "addToStudyInFather( ";
1808 aCommand += aFatherData->_pyName + ", ";
1811 aCommand += "addToStudy( ";
1813 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1815 // bind a command to the study entry
1816 int tag = GetTag(theObjectData._entry);
1817 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1819 theObjectData._studyEntry.Clear(); // not to publish any more
1822 //================================================================================
1824 * \brief Returns the string of publishing commands. Take into account that
1825 * references should be published prior to the objects refer to them.
1827 //================================================================================
1828 TCollection_AsciiString GetPublishCommands
1830 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1831 const TIntToListIntMap &theMapRefs,
1832 std::set< int > &thePublished)
1834 TCollection_AsciiString aResult;
1836 if (!thePublished.count(theTag)) {
1837 // This object is not published yet.
1838 thePublished.insert(theTag);
1840 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1841 theEntryToCmdMap.find(theTag);
1843 if (anIt != theEntryToCmdMap.end()) {
1844 // There is a pubish cmd.
1845 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1847 if (aRefIt != theMapRefs.end()) {
1848 // Recursively publish all references.
1849 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1851 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1852 const TCollection_AsciiString aRefCmd = GetPublishCommands
1853 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1859 // Add the object command.
1860 aResult += anIt->second;
1867 void Prettify(TCollection_AsciiString& theScript)
1869 TCollection_AsciiString output;
1870 static std::list<TCollection_AsciiString> ToRemove;
1871 if (ToRemove.empty()) {
1872 ToRemove.push_back("geompy.SubShapeAllIDs");
1873 ToRemove.push_back("geompy.SubShapeAllSortedCentresIDs");
1874 ToRemove.push_back("geompy.SubShapeAllSortedIDs");
1875 ToRemove.push_back("geompy.GetFreeFacesIDs");
1876 ToRemove.push_back("geompy.GetShapesOnBoxIDs");
1877 ToRemove.push_back("geompy.GetShapesOnShapeIDs");
1878 ToRemove.push_back("geompy.GetShapesOnPlaneIDs");
1879 ToRemove.push_back("geompy.GetShapesOnPlaneWithLocationIDs");
1880 ToRemove.push_back("geompy.GetShapesOnCylinderIDs");
1881 ToRemove.push_back("geompy.GetShapesOnCylinderWithLocationIDs");
1882 ToRemove.push_back("geompy.GetShapesOnSphereIDs");
1883 ToRemove.push_back("geompy.GetShapesOnQuadrangleIDs");
1884 ToRemove.push_back("geompy.GetSameIDs");
1888 while (start <= theScript.Length()) {
1889 int end = theScript.Location("\n", start, theScript.Length());
1890 if (end == -1) end = theScript.Length();
1891 TCollection_AsciiString line = theScript.SubString(start, end);
1893 for (std::list<TCollection_AsciiString>::const_iterator it = ToRemove.begin(); it != ToRemove.end() && !found; ++it)
1894 found = line.Search( *it ) != -1;
1901 //OK @@@@@@@@@@@@@@@@@@@@@@@@@@@
1904 //================================================================================
1906 * \brief Constructor
1908 //================================================================================
1909 ObjectStates::ObjectStates()
1914 //================================================================================
1918 //================================================================================
1919 ObjectStates::~ObjectStates()
1923 //================================================================================
1925 * \brief Return current object state
1926 * \retval state - Object state (vector of notebook variable)
1928 //================================================================================
1929 TState ObjectStates::GetCurrectState() const
1931 if((int)_states.size() > _dumpstate)
1932 return _states[_dumpstate];
1936 //================================================================================
1938 * \brief Add new object state
1939 * \param theState - Object state (vector of notebook variable)
1941 //================================================================================
1942 void ObjectStates::AddState(const TState &theState)
1944 _states.push_back(theState);
1947 //================================================================================
1949 * \brief Increment object state
1951 //================================================================================
1952 void ObjectStates::IncrementState()