1 // Copyright (C) 2007-2020 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 return _OCAFApp->SaveAs( _document, aFileName.c_str() ) == PCDM_SS_OK;
525 //=============================================================================
529 //=============================================================================
530 bool GEOM_Engine::Load(const char* theFileName)
532 #if defined(WIN32) && defined(UNICODE)
533 std::wstring aFileName = Kernel_Utils::utf8_decode_s(theFileName);
535 std::string aFileName = theFileName;
537 Handle(TDocStd_Document) aDoc;
538 if (_OCAFApp->Open(aFileName.c_str(), aDoc) != PCDM_RS_OK) {
542 // Replace old document format by the new one.
543 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
544 aDoc->ChangeStorageFormat("BinOcaf");
547 aDoc->SetUndoLimit(_UndoLimit);
554 //=============================================================================
558 //=============================================================================
559 void GEOM_Engine::Close()
562 //Remove all GEOM Objects associated to the document
563 TColStd_SequenceOfAsciiString aSeq;
564 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
565 for (; It.More(); It.Next()) {
566 aSeq.Append(It.Key());
568 for (Standard_Integer i=1; i<=aSeq.Length(); i++) {
569 _objects.UnBind(aSeq.Value(i));
572 // Forget free labels for document
575 _OCAFApp->Close(_document);
580 //=============================================================================
584 //=============================================================================
585 TCollection_AsciiString GEOM_Engine::DumpPython(std::vector<TObjectData>& theObjectData,
586 TVariablesList theVariables,
591 // Set "C" numeric locale to save numbers correctly
592 Kernel_Utils::Localizer loc;
594 TCollection_AsciiString aScript;
595 Handle(TDocStd_Document) aDoc = GetDocument();
599 TCollection_AsciiString anEmptyScript;
601 anEmptyScript = "def RebuildData(): pass\n";
602 return anEmptyScript;
606 aScript = "import salome\n";
608 aScript += "import GEOM\n";
609 aScript += "from salome.geom import geomBuilder\n";
610 aScript += "import math\n";
611 aScript += "import SALOMEDS\n\n";
613 aScript += "def RebuildData():";
615 aScript += "\n\tgeompy = geomBuilder.New()\n";
617 AddTextures(aScript);
619 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
621 // a map containing copies of TObjectData from theObjectData
622 TSting2ObjDataMap aEntry2ObjData;
623 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
624 // occurs when several StudyEntries correspond to one Entry
625 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
627 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
628 for (unsigned i = 0; i < theObjectData.size(); ++i )
630 TObjectData& data = theObjectData[i];
631 // look for an object by entry
633 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
634 if ( L.IsNull() ) continue;
635 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
637 if ( !obj.IsNull() ) {
638 TSting2ObjDataMap::iterator ent2Data =
639 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
641 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
642 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
644 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
648 // collect objects entries to be published
649 TColStd_SequenceOfAsciiString aObjListToPublish;
651 // iterates on functions till critical (that requiers publication of objects)
652 Handle(TDataStd_TreeNode) aNode, aRoot;
653 Handle(GEOM_Function) aFunction;
654 TDF_LabelMap aCheckedFuncMap;
655 std::set< TCollection_AsciiString > anIgnoreObjMap;
657 TCollection_AsciiString aFuncScript;
659 // Mantis issue 0020768
660 Standard_Integer objectCounter = 0;
661 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
662 TIntToListIntMap aRefMap;
664 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
665 TDataStd_ChildNodeIterator Itr(aRoot);
666 for (; Itr.More(); Itr.Next()) {
668 aFunction = GEOM_Function::GetFunction(aNode->Label());
669 if (aFunction.IsNull()) {
670 MESSAGE ( "Null function !!!!" );
673 bool isDumpCollected = false;
674 TCollection_AsciiString aCurScript, anAfterScript;
675 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
676 isPublished, aCheckedFuncMap, anIgnoreObjMap,
679 // add function description before dump
680 if (!aCurScript.IsEmpty())
682 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
683 aFuncScript.Length() > aCurScript.Length() )
684 // avoid repeated SubShape...() command at the end
685 if (aFuncScript.Location( aCurScript,
686 aFuncScript.Length() - aCurScript.Length(),
687 aFuncScript.Length()))
688 continue; // aCurScript is already at the end of aFuncScript
689 aFuncScript += aCurScript;
692 // Fill the map of references.
693 FillMapOfRef(aFunction, aRefMap);
695 if (isDumpCollected ) {
696 // Replace entries by the names
697 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
698 aObjListToPublish, objectCounter, aNameToEntry );
700 // publish collected objects
701 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
702 int i = 1, n = aObjListToPublish.Length();
703 for ( ; i <= n; i++ )
705 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
706 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
707 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
709 // add publishing commands to the script
710 std::set< int > aPublished;
711 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
713 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
714 const TCollection_AsciiString aPublishCmds =
715 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
716 aRefMap, aPublished);
718 aFuncScript += aPublishCmds;
721 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
722 // because they will be published during command execution
723 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
725 indx = anAfterScript.Search( "RestoreSubShapes" );
727 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
728 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
729 i = 1, n = aSeq->Length();
730 for ( ; i <= n; i+=2) {
731 TCollection_AsciiString anEntry =
732 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
733 anIgnoreObjMap.insert(anEntry.ToCString());
737 aObjListToPublish.Clear();
738 aScript += aFuncScript;
741 aFuncScript += anAfterScript;
745 // Replace entries by the names
746 aObjListToPublish.Clear();
747 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
748 objectCounter, aNameToEntry );
750 aScript += aFuncScript;
753 AddObjectColors(aScript, aEntry2ObjData );
755 // Make script to publish in study
756 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
759 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
761 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
762 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
763 ++aStEntry2ObjDataPtrIt)
765 TObjectData* data = aStEntry2ObjDataPtrIt->second;
766 if ( anIgnoreObjMap.count( data->_entry ))
767 continue; // should not be dumped
768 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
769 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
771 // add publishing commands to the script
772 std::set< int > aPublished;
773 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
775 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
776 const TCollection_AsciiString aPublishCmds =
777 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
778 aRefMap, aPublished);
780 aScript += aPublishCmds;
784 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
785 //Add unpublish command if need
786 TCollection_AsciiString unpublishCmd("\n");
788 unpublishCmd += "\t";
789 unpublishCmd += "geompy.hideInStudy(";
791 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
792 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
793 ++aStEntry2ObjDataPtrIt)
795 TObjectData* data = aStEntry2ObjDataPtrIt->second;
796 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
797 aScript += unpublishCmd + data->_pyName + ")";
801 //aScript += "\n\tpass\n";
805 // fill _studyEntry2NameMap and build globalVars
806 TCollection_AsciiString globalVars;
807 _studyEntry2NameMap.Clear();
808 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
809 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
810 ++aStEntry2ObjDataPtrIt)
812 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
813 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
814 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
815 if ( !globalVars.IsEmpty() )
817 globalVars += data->_pyName;
819 if ( isMultiFile && !globalVars.IsEmpty() ) {
820 globalVars.Insert( 1, "\n\tglobal " );
821 aScript.Insert( posToInsertGlobalVars, globalVars );
824 // VSR 29/08/2017: 0023327, 0023428: eliminate unnecessary lines in Python dump
825 #ifndef DUMP_SUBSHAPE_IDS
832 //=======================================================================
833 //function : GetDumpName
835 //=======================================================================
837 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
839 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
840 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
845 //=======================================================================
846 //function : GetAllDumpNames
848 //=======================================================================
850 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
852 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
854 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
855 for (; it.More(); it.Next()) {
856 aRetSeq->Append(it.Value());
862 #define TEXTURE_LABEL_ID 1
863 #define TEXTURE_LABEL_FILE 2
864 #define TEXTURE_LABEL_WIDTH 3
865 #define TEXTURE_LABEL_HEIGHT 4
866 #define TEXTURE_LABEL_DATA 5
868 int GEOM_Engine::addTexture(int theWidth, int theHeight,
869 const Handle(TColStd_HArray1OfByte)& theTexture,
870 const TCollection_AsciiString& theFileName)
872 Handle(TDocStd_Document) aDoc = GetDocument();
873 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
875 // NPAL18604: use existing label to decrease memory usage,
876 // if this label has been freed (object deleted)
877 bool useExisting = false;
879 if (!_freeLabels.empty()) {
881 aChild = _freeLabels.front();
882 _freeLabels.pop_front();
886 aChild = TDF_TagSource::NewChild(aDoc->Main());
889 aChild.ForgetAllAttributes(Standard_True);
890 Handle(TDataStd_TreeNode) node;
891 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
892 node = TDataStd_TreeNode::Set(aChild);
893 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
895 static int aTextureID = 0;
897 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
898 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
899 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
900 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
902 Handle(TDataStd_ByteArray) anAttr =
903 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
904 theTexture.IsNull() ? 0 : theTexture->Lower(),
905 theTexture.IsNull() ? 0 : theTexture->Upper());
906 anAttr->ChangeArray(theTexture);
911 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theTextureID,
912 int& theWidth, int& theHeight,
913 TCollection_AsciiString& theFileName)
915 Handle(TColStd_HArray1OfByte) anArray;
916 theWidth = theHeight = 0;
918 Handle(TDocStd_Document) aDoc = GetDocument();
920 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
922 for (; anIterator.More() && !found; anIterator.Next()) {
923 TDF_Label aTextureLabel = anIterator.Value();
924 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
925 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
926 Handle(TDataStd_Integer) anIdAttr;
927 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
928 anIdAttr->Get() == theTextureID) {
929 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
930 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
931 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
932 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
933 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
934 Handle(TDataStd_ByteArray) aTextureAttr;
935 Handle(TDataStd_Comment) aFileAttr;
936 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
937 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
938 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
939 theWidth = aWidthAttr->Get();
940 theHeight = aHeightAttr->Get();
941 anArray = aTextureAttr->InternalArray();
943 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
944 theFileName = aFileAttr->Get();
952 std::list<int> GEOM_Engine::getAllTextures()
954 std::list<int> id_list;
956 Handle(TDocStd_Document) aDoc = GetDocument();
958 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
959 for (; anIterator.More(); anIterator.Next()) {
960 TDF_Label aTextureLabel = anIterator.Value();
961 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
962 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
963 Handle(TDataStd_Integer) anIdAttr;
964 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
965 id_list.push_back((int)anIdAttr->Get());
971 //===========================================================================
972 // Internal functions
973 //===========================================================================
975 //=============================================================================
977 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
979 //=============================================================================
980 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
982 TCollection_AsciiString aNewDescr;
984 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
985 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
986 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
987 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
988 // "3DSketcher:CMD[:CMD[:CMD...]]"
989 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
991 // Split the command string to separate CMDs
993 TColStd_SequenceOfAsciiString aSequence;
994 if (aCommand.Length()) {
995 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
996 while (aToken.Length() > 0) {
997 aSequence.Append(aToken);
998 aToken = aCommand.Token(":", ++icmd);
1002 if (aSequence.Length() > 0) {
1004 aNewDescr += "\n\t";
1006 aNewDescr += "\nsk = geompy.Sketcher3D()";
1007 int nbCMDs = aSequence.Length();
1008 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1009 aNewDescr += "\n\t";
1011 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1013 // Split the CMD into string values
1014 TColStd_SequenceOfAsciiString aStrVals;
1016 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1017 while (aToken.Length() > 0) {
1018 aStrVals.Append(aToken);
1019 aToken = aCMD.Token(" ", ++ival);
1022 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1023 if (aCMDpref == "TT") {
1024 aNewDescr += "sk.addPointsAbsolute(";
1025 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1027 else if (aCMDpref == "T") {
1028 aNewDescr += "sk.addPointsRelative(";
1029 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1031 else if (aCMDpref == "WW") {
1032 aNewDescr += "sk.close()";
1034 else if (aCMDpref.Value(1) == 'O'){
1035 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1037 if (aCMDpref.Value(4) == 'C')
1038 aNewDescr += "sk.addPointRadiusAngleH";
1040 aNewDescr += "sk.addPointRadiusAngles";
1041 if (aCMDpref.Value(5) == 'A')
1042 aNewDescr += "Absolute(";
1044 aNewDescr += "Relative(";
1045 aNewDescr += aStrVals.Value(4) + ", " +
1046 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1049 aNewDescr += "\n\t";
1050 aNewDescr += aResult + " = sk.wire()";
1052 } // Make3DSketcherCommand
1053 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1054 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1055 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1056 aCommand = aCommand.Token("]", 1);
1058 aNewDescr += "\n\t";
1059 aNewDescr += "\nsk = geompy.Sketcher3D()";
1060 aNewDescr += "\n\t";
1061 aNewDescr += "sk.addPointsAbsolute(";
1062 aNewDescr += aCommand + ")";
1063 aNewDescr += "\n\t";
1064 aNewDescr += aResult + " = sk.wire()";
1068 aNewDescr += "\n\t";
1069 aNewDescr += aSubStr;
1076 //=============================================================================
1078 * ProcessFunction: Dump function description into script
1080 //=============================================================================
1081 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1082 TCollection_AsciiString& theScript,
1083 TCollection_AsciiString& theAfterScript,
1084 const TVariablesList& theVariables,
1085 const bool theIsPublished,
1086 TDF_LabelMap& theProcessed,
1087 std::set<TCollection_AsciiString>& theIgnoreObjs,
1088 bool& theIsDumpCollected)
1090 theIsDumpCollected = false;
1091 if (theFunction.IsNull()) return false;
1093 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1095 // pass functions, that depends on nonexisting ones
1096 bool doNotProcess = false;
1097 TDF_LabelSequence aSeq;
1098 theFunction->GetDependency(aSeq);
1099 Standard_Integer aLen = aSeq.Length();
1100 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1101 TDF_Label aRefLabel = aSeq.Value(i);
1102 Handle(TDF_Reference) aRef;
1103 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1104 doNotProcess = true;
1107 if (aRef.IsNull() || aRef->Get().IsNull()) {
1108 doNotProcess = true;
1111 Handle(TDataStd_TreeNode) aT;
1112 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1113 doNotProcess = true;
1116 TDF_Label aDepLabel = aT->Label();
1117 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1119 if (aFunction.IsNull()) doNotProcess = true;
1120 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1127 TCollection_AsciiString anObjEntry;
1128 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1129 theIgnoreObjs.insert(anObjEntry);
1132 theProcessed.Add(theFunction->GetEntry());
1134 TCollection_AsciiString aDescr = theFunction->GetDescription();
1135 if(aDescr.Length() == 0) return false;
1137 //Check if its internal function which doesn't requires dumping
1138 if(aDescr == "None") return false;
1140 //Check the very specific case of RestoreShape function,
1141 //which is not dumped, but the result can be published by the user.
1142 //We do not publish such objects to decrease danger of dumped script failure.
1143 if(aDescr.Value(1) == '#') {
1144 TCollection_AsciiString anObjEntry;
1145 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1146 theIgnoreObjs.insert(anObjEntry);
1150 // 0020001 PTv, check for critical functions, which require dump of objects
1153 // currently, there is only one function "RestoreGivenSubShapes",
1154 // later this check could be replaced by iterations on list of such functions
1155 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1156 theIsDumpCollected = true;
1157 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1158 theIsDumpCollected = true;
1161 //Replace parameter by notebook variables
1162 ReplaceVariables(aDescr,theVariables);
1164 //Process sketcher functions, replacing string command by calls to Sketcher interface
1165 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1166 Sketcher_Profile aProfile( aDescr.ToCString());
1167 // Make new command for SketcherOnPlane and for Sketcher
1168 aDescr = aProfile.GetDump();
1170 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1171 aDescr = MakeCommandfor3DSketcher ( aDescr );
1174 if ( theIsDumpCollected ) {
1176 bool isBefore = true;
1177 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1178 while (!aSubStr.IsEmpty()) {
1180 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1181 aSubStr.Search( "RestoreSubShapes" ) == -1)
1182 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1184 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1185 aSubStr = aDescr.Token("\n\t", i++);
1189 theScript += "\n\t";
1190 theScript += aDescr;
1195 //=============================================================================
1197 * GetTag: Returns the tag from entry
1199 //=============================================================================
1200 int GetTag(const TCollection_AsciiString &theEntry)
1202 const int aGeomObjDepth = 3;
1203 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1208 //=============================================================================
1210 * FillMapOfRef: Fill the map of references
1212 //=============================================================================
1213 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1214 TIntToListIntMap &theRefMap)
1216 TDF_LabelSequence aSeq;
1217 TCollection_AsciiString anObjEntry;
1220 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1221 anObjTag = GetTag(anObjEntry);
1222 theFunction->GetDependency(aSeq);
1224 const Standard_Integer aLen = aSeq.Length();
1227 for (i = 1; i <= aLen; i++) {
1228 TDF_Label aRefLabel = aSeq.Value(i);
1229 Handle(TDF_Reference) aRef;
1231 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1232 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1233 Handle(TDataStd_TreeNode) aT;
1235 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1236 TDF_Label aDepLabel = aT->Label();
1237 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1239 if (!aRefFunct.IsNull()) {
1240 // Get entry of the referenced object.
1241 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1243 const int aRefTag = GetTag(anObjEntry);
1245 if (anObjTag != aRefTag) {
1246 // Avoid making references for operations without copy.
1247 theRefMap[anObjTag].push_back(aRefTag);
1256 //=============================================================================
1258 * FindEntries: Returns a sequence of start/end positions of entries in the string
1260 //=============================================================================
1261 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1263 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1264 Standard_Integer aLen = theString.Length();
1265 Standard_Boolean isFound = Standard_False;
1267 const char* arr = theString.ToCString();
1268 Standard_Integer i = 0, j;
1271 int c = (int)arr[i];
1273 if(c >= 48 && c <= 57) { //Is digit?
1275 isFound = Standard_False;
1276 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1278 if(c == 58) isFound = Standard_True;
1281 if(isFound && arr[j-2] != 58) { // last char should be a digit
1282 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1293 //=============================================================================
1295 * ReplaceVariables: Replace parameters of the function by variales from
1298 //=============================================================================
1299 void ReplaceVariables(TCollection_AsciiString& theCommand,
1300 const TVariablesList& theVariables)
1303 std::cout<<"Command : "<<theCommand<<std::endl;
1306 std::cout<<"All Entries:"<<std::endl;
1307 TVariablesList::const_iterator it = theVariables.begin();
1308 for(;it != theVariables.end();it++)
1309 std::cout<<"\t'"<<(*it).first<<"'"<<std::endl;
1312 //Additional case - multi-row commands
1313 int aCommandIndex = 1;
1314 while( aCommandIndex < 10 ) { // tmp check
1315 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1316 if( aCommand.Length() == 0 )
1320 std::cout<<"Sub-command : "<<aCommand<<std::endl;
1322 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1323 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1325 //Get Entry of the result object
1326 TCollection_AsciiString anEntry;
1327 if( aCommand.Search("=") != -1 ) // command returns an object
1328 anEntry = aCommand.Token("=",1);
1329 else { // command modifies the object
1330 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1331 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1332 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1334 //Remove white spaces
1335 anEntry.RightAdjust();
1336 anEntry.LeftAdjust();
1338 std::cout<<"Result entry : '" <<anEntry<<"'"<<std::endl;
1340 if ( anEntry.IsEmpty() ) {
1345 //Check if result is list of entries - enough to get the first entry in this case
1347 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1348 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1350 TCollection_AsciiString aSeparator(COMMA);
1351 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1352 anEntry.Remove( 1, 1 );
1353 anEntry.RightAdjust();
1354 anEntry.LeftAdjust();
1356 std::cout<<"Sub-entry : '" <<anEntry<<"'"<<std::endl;
1359 //Find variables used for object construction
1360 ObjectStates* aStates = 0;
1361 TVariablesList::const_iterator it = theVariables.find(anEntry);
1362 if( it != theVariables.end() )
1363 aStates = (*it).second;
1367 std::cout<<"Valiables list empty!!!"<<std::endl;
1372 TState aVariables = aStates->GetCurrectState();
1375 std::cout<<"Variables from SObject:"<<std::endl;
1376 for (size_t i = 0; i < aVariables.size();i++)
1377 std::cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<std::endl;
1380 //Calculate total number of parameters
1381 Standard_Integer aTotalNbParams = 1;
1382 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1386 std::cout<<"aTotalNbParams = "<<aTotalNbParams<<std::endl;
1388 Standard_Integer aFirstParam = aNbEntries;
1390 //Replace parameters by variables
1391 Standard_Integer aStartPos = 0;
1392 Standard_Integer aEndPos = 0;
1394 TCollection_AsciiString aVar, aReplacedVar;
1395 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1396 //Replace first parameter (bettwen '(' character and first ',' character)
1397 if(i == aFirstParam)
1399 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1400 if(aTotalNbParams - aNbEntries > 0 )
1401 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1403 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1405 //Replace last parameter (bettwen ',' character and ')' character)
1406 else if(i == aTotalNbParams)
1408 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1409 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1411 //Replace other parameters (bettwen two ',' characters)
1412 else if(i != aFirstParam && i != aTotalNbParams )
1414 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1415 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1417 if (aStartPos == 0 || aEndPos == 0)
1420 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1422 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1424 if ( aStartPos == aEndPos )
1425 continue; // PAL20889: for "[]"
1428 std::cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<std::endl;
1430 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1435 std::cout<<"Variable: '"<< aVar <<"'"<<std::endl;
1437 // specific case for sketcher
1438 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1439 Standard_Integer aNbSections = 1;
1440 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1444 int aStartSectionPos = 0, aEndSectionPos = 0;
1445 TCollection_AsciiString aSection, aReplacedSection;
1446 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1447 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1448 if( aSectionIndex != aNbSections )
1449 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1451 aEndSectionPos = aVar.Length();
1453 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1455 std::cout<<"aSection: "<<aSection<<std::endl;
1457 Standard_Integer aNbParams = 1;
1458 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1462 int aStartParamPos = 0, aEndParamPos = 0;
1463 TCollection_AsciiString aParameter, aReplacedParameter;
1464 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1465 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1466 if( aParamIndex != aNbParams )
1467 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1469 aEndParamPos = aSection.Length() + 1;
1472 std::cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<std::endl;
1474 if ( aStartParamPos == aEndParamPos)
1477 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1479 std::cout<<"aParameter: "<<aParameter<<std::endl;
1481 if(iVar >= aVariables.size())
1484 aReplacedParameter = aVariables[iVar].myVariable;
1485 if(aReplacedParameter.IsEmpty()) {
1490 if(aVariables[iVar].isVariable) {
1491 aReplacedParameter.InsertBefore(1,"'");
1492 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1496 std::cout<<"aSection before : "<<aSection<< std::endl;
1497 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1498 aSection.Insert(aStartParamPos, aReplacedParameter);
1500 std::cout<<"aSection after : "<<aSection<<std::endl<<std::endl;
1504 std::cout<<"aVar before : "<<aVar<<std::endl;
1505 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1506 aVar.Insert(aStartSectionPos, aSection);
1508 std::cout<<"aVar after : "<<aVar<<std::endl<<std::endl;
1512 std::cout<<"aCommand before : "<<aCommand<<std::endl;
1513 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1514 aCommand.Insert(aStartPos, aVar);
1516 std::cout<<"aCommand after : "<<aCommand<<std::endl;
1519 } // end of specific case for sketcher
1521 //If parameter is entry or 'None', skip it
1522 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1525 if(iVar >= aVariables.size())
1528 aReplacedVar = aVariables[iVar].myVariable;
1529 if(aReplacedVar.IsEmpty()) {
1534 if(aVariables[iVar].isVariable) {
1535 aReplacedVar.InsertBefore(1,"\"");
1536 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1539 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1540 aCommand.Insert(aStartPos, aReplacedVar);
1544 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1545 theCommand.Insert(aStartCommandPos, aCommand);
1549 aStates->IncrementState();
1553 std::cout<<"Command : "<<theCommand<<std::endl;
1556 //=============================================================================
1558 * ReplaceEntriesByNames: Replace object entries by their names
1560 //=============================================================================
1561 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1562 TSting2ObjDataMap& aEntry2ObjData,
1563 const bool /*theIsPublished*/,
1564 TColStd_SequenceOfAsciiString& theObjListToPublish,
1565 Standard_Integer& objectCounter,
1566 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1568 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1569 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1570 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1572 //Replace entries by the names
1573 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1574 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1575 if (aLen == 0) anUpdatedScript = theScript;
1577 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1578 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1579 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1580 theObjListToPublish.Append( anEntry );
1582 TObjectData& data = aEntry2ObjData[ anEntry ];
1583 if ( data._pyName.IsEmpty() ) { // encountered for the 1st time
1584 if ( !data._name.IsEmpty() ) { // published object
1585 data._pyName = data._name;
1586 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1590 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1591 } while(aNameToEntry.IsBound(data._pyName));
1595 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1597 anUpdatedScript += data._pyName;
1598 aStart = aSeq->Value(i+1) + 1;
1601 //Add final part of the script
1602 if (aLen && aSeq->Value(aLen) < aScriptLength)
1603 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1605 theScript = anUpdatedScript;
1608 //=============================================================================
1610 * AddObjectColors: Add color to objects
1612 //=============================================================================
1613 void AddObjectColors (TCollection_AsciiString& theScript,
1614 const TSting2ObjDataMap& theEntry2ObjData)
1616 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1617 Handle(TDocStd_Document) aDoc = engine->GetDocument();
1619 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1620 for (anEntryToNameIt = theEntry2ObjData.begin();
1621 anEntryToNameIt!= theEntry2ObjData.end();
1624 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1625 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1628 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1632 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1636 bool anAutoColor = obj->GetAutoColor();
1639 TCollection_AsciiString aCommand( "\n\t" );
1640 aCommand += aName + ".SetAutoColor(1)";
1641 theScript += aCommand.ToCString();
1644 GEOM_Object::Color aColor = obj->GetColor();
1645 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1647 TCollection_AsciiString aCommand( "\n\t" );
1648 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1649 theScript += aCommand.ToCString();
1652 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1653 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1654 TCollection_AsciiString aCommand( "\n\t" );
1655 aCommand += aName + ".SetMarkerStd(";
1656 switch (aMarkerType) {
1657 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1658 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1659 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1660 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1661 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1662 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1663 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1664 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1665 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1666 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1667 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1668 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1669 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1670 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1673 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1675 case 1: aCommand += "GEOM.MS_10"; break;
1676 case 2: aCommand += "GEOM.MS_15"; break;
1677 case 3: aCommand += "GEOM.MS_20"; break;
1678 case 4: aCommand += "GEOM.MS_25"; break;
1679 case 5: aCommand += "GEOM.MS_30"; break;
1680 case 6: aCommand += "GEOM.MS_35"; break;
1681 case 7: aCommand += "GEOM.MS_40"; break;
1682 case 8: aCommand += "GEOM.MS_45"; break;
1683 case 9: aCommand += "GEOM.MS_50"; break;
1684 case 10: aCommand += "GEOM.MS_55"; break;
1685 case 11: aCommand += "GEOM.MS_60"; break;
1686 case 12: aCommand += "GEOM.MS_65"; break;
1687 case 13: aCommand += "GEOM.MS_70"; break;
1688 default: aCommand += "GEOM.MS_NONE"; break;
1691 theScript += aCommand.ToCString();
1693 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1694 int aMarkerTextureID = obj->GetMarkerTexture();
1695 if (aMarkerTextureID >= 0) {
1696 TCollection_AsciiString aCommand( "\n\t" );
1697 aCommand += aName + ".SetMarkerTexture(texture_map[";
1698 aCommand += aMarkerTextureID;
1700 theScript += aCommand.ToCString();
1706 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1708 TCollection_AsciiString stream;
1709 if (!aData.IsNull()) {
1710 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1711 Standard_Byte byte = aData->Value(i);
1712 TCollection_AsciiString strByte = "";
1713 for (int j = 0; j < 8; j++)
1714 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1721 void AddTextures (TCollection_AsciiString& theScript)
1723 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1724 std::list<int> allTextures = engine->getAllTextures();
1725 std::list<int>::const_iterator it;
1727 if (allTextures.size() > 0) {
1728 theScript += "\n\ttexture_map = {}\n";
1730 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1731 if (*it <= 0) continue;
1732 Standard_Integer aWidth, aHeight;
1733 TCollection_AsciiString aFileName;
1734 Handle(TColStd_HArray1OfByte) aTexture =
1735 engine->getTexture(*it, aWidth, aHeight, aFileName);
1736 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1737 TCollection_AsciiString aCommand = "\n\t";
1738 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1739 if (aFileName != "" ) {
1740 aCommand += "geompy.LoadTexture(\"";
1741 aCommand += aFileName.ToCString();
1745 aCommand += "geompy.AddTexture(";
1746 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1747 aCommand += pack_data(aTexture);
1750 theScript += aCommand;
1757 //=============================================================================
1759 * PublishObject: publish object in study script
1761 //=============================================================================
1762 void PublishObject (TObjectData& theObjectData,
1763 TSting2ObjDataMap& theEntry2ObjData,
1764 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1765 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1766 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1767 std::set< TCollection_AsciiString>& theIgnoreMap)
1769 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1770 if ( theObjectData._studyEntry.IsEmpty() )
1771 return; // was not published
1772 if ( theIgnoreMap.count( theObjectData._entry ) )
1773 return; // not to publish
1775 TCollection_AsciiString aCommand("\n\tgeompy.");
1777 // find a father entry
1778 TObjectData* aFatherData = 0;
1779 TCollection_AsciiString aFatherStudyEntry =
1780 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1781 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1782 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1783 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1784 aFatherData = stEntry2DataPtr->second;
1786 // treat multiply published object
1787 if ( theObjectData._pyName.IsEmpty() )
1789 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1790 if ( data0._pyName.IsEmpty() ) return; // something wrong
1792 theObjectData._pyName = theObjectData._name;
1793 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1795 TCollection_AsciiString aCreationCommand("\n\t");
1796 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1798 // store aCreationCommand before publishing commands
1799 int tag = GetTag(theObjectData._entry);
1800 theEntryToCmdMap.insert( std::make_pair( tag + -2*theEntry2ObjData.size(), aCreationCommand ));
1804 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1805 aCommand += "addToStudyInFather( ";
1806 aCommand += aFatherData->_pyName + ", ";
1809 aCommand += "addToStudy( ";
1811 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1813 // bind a command to the study entry
1814 int tag = GetTag(theObjectData._entry);
1815 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1817 theObjectData._studyEntry.Clear(); // not to publish any more
1820 //================================================================================
1822 * \brief Returns the string of publishing commands. Take into account that
1823 * references should be published prior to the objects refer to them.
1825 //================================================================================
1826 TCollection_AsciiString GetPublishCommands
1828 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1829 const TIntToListIntMap &theMapRefs,
1830 std::set< int > &thePublished)
1832 TCollection_AsciiString aResult;
1834 if (!thePublished.count(theTag)) {
1835 // This object is not published yet.
1836 thePublished.insert(theTag);
1838 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1839 theEntryToCmdMap.find(theTag);
1841 if (anIt != theEntryToCmdMap.end()) {
1842 // There is a pubish cmd.
1843 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1845 if (aRefIt != theMapRefs.end()) {
1846 // Recursively publish all references.
1847 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1849 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1850 const TCollection_AsciiString aRefCmd = GetPublishCommands
1851 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1857 // Add the object command.
1858 aResult += anIt->second;
1865 void Prettify(TCollection_AsciiString& theScript)
1867 TCollection_AsciiString output;
1868 static std::list<TCollection_AsciiString> ToRemove;
1869 if (ToRemove.empty()) {
1870 ToRemove.push_back("geompy.SubShapeAllIDs");
1871 ToRemove.push_back("geompy.SubShapeAllSortedCentresIDs");
1872 ToRemove.push_back("geompy.SubShapeAllSortedIDs");
1873 ToRemove.push_back("geompy.GetFreeFacesIDs");
1874 ToRemove.push_back("geompy.GetShapesOnBoxIDs");
1875 ToRemove.push_back("geompy.GetShapesOnShapeIDs");
1876 ToRemove.push_back("geompy.GetShapesOnPlaneIDs");
1877 ToRemove.push_back("geompy.GetShapesOnPlaneWithLocationIDs");
1878 ToRemove.push_back("geompy.GetShapesOnCylinderIDs");
1879 ToRemove.push_back("geompy.GetShapesOnCylinderWithLocationIDs");
1880 ToRemove.push_back("geompy.GetShapesOnSphereIDs");
1881 ToRemove.push_back("geompy.GetShapesOnQuadrangleIDs");
1882 ToRemove.push_back("geompy.GetSameIDs");
1886 while (start <= theScript.Length()) {
1887 int end = theScript.Location("\n", start, theScript.Length());
1888 if (end == -1) end = theScript.Length();
1889 TCollection_AsciiString line = theScript.SubString(start, end);
1891 for (std::list<TCollection_AsciiString>::const_iterator it = ToRemove.begin(); it != ToRemove.end() && !found; ++it)
1892 found = line.Search( *it ) != -1;
1899 //OK @@@@@@@@@@@@@@@@@@@@@@@@@@@
1902 //================================================================================
1904 * \brief Constructor
1906 //================================================================================
1907 ObjectStates::ObjectStates()
1912 //================================================================================
1916 //================================================================================
1917 ObjectStates::~ObjectStates()
1921 //================================================================================
1923 * \brief Return current object state
1924 * \retval state - Object state (vector of notebook variable)
1926 //================================================================================
1927 TState ObjectStates::GetCurrectState() const
1929 if((int)_states.size() > _dumpstate)
1930 return _states[_dumpstate];
1934 //================================================================================
1936 * \brief Add new object state
1937 * \param theState - Object state (vector of notebook variable)
1939 //================================================================================
1940 void ObjectStates::AddState(const TState &theState)
1942 _states.push_back(theState);
1945 //================================================================================
1947 * \brief Increment object state
1949 //================================================================================
1950 void ObjectStates::IncrementState()