1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
24 #pragma warning( disable:4786 )
27 #include "GEOM_Engine.hxx"
29 #include "GEOM_Field.hxx"
30 #include "GEOM_Function.hxx"
31 #include "GEOM_ISubShape.hxx"
32 #include "GEOM_PythonDump.hxx"
33 #include "GEOM_Solver.hxx"
34 #include "GEOM_SubShapeDriver.hxx"
35 #include "Sketcher_Profile.hxx"
37 #include <Basics_OCCTVersion.hxx>
39 #include "utilities.h"
41 #include <Basics_Utils.hxx>
43 #include <TDF_Tool.hxx>
44 #include <TDF_Data.hxx>
45 #include <TDF_Reference.hxx>
46 #include <TDF_LabelSequence.hxx>
47 #include <TDataStd_Integer.hxx>
48 #include <TDataStd_ChildNodeIterator.hxx>
49 #include <TFunction_Driver.hxx>
50 #include <TFunction_DriverTable.hxx>
51 #include <TDataStd_ByteArray.hxx>
52 #include <TDataStd_UAttribute.hxx>
53 #include <TDF_ChildIterator.hxx>
54 #include <TDataStd_Comment.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
59 #include <TCollection_AsciiString.hxx>
60 #include <TCollection_ExtendedString.hxx>
61 #include <TColStd_SequenceOfAsciiString.hxx>
62 #include <TColStd_MapOfTransient.hxx>
63 #include <TColStd_HSequenceOfInteger.hxx>
65 #include <TColStd_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
67 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
69 #if OCC_VERSION_LARGE > 0x07000000
70 #include <BinDrivers.hxx>
71 #include <StdDrivers_DocumentRetrievalDriver.hxx>
72 #include <PCDM_StorageDriver.hxx>
77 #include <Standard_Failure.hxx>
78 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
83 #define O_SQR_BRACKET '['
84 #define C_SQR_BRACKET ']'
85 #define PY_NULL "None"
88 static int MYDEBUG = 0;
90 static int MYDEBUG = 0;
93 typedef std::map< TCollection_AsciiString, TCollection_AsciiString > TSting2StringMap;
94 typedef std::map< TCollection_AsciiString, TObjectData > TSting2ObjDataMap;
95 typedef std::map< TCollection_AsciiString, TObjectData* > TSting2ObjDataPtrMap;
96 typedef std::map< int, std::list < int > > TIntToListIntMap;
98 static GEOM_Engine* TheEngine = NULL;
101 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_BaseObject)& theObject)
103 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
104 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
105 anID+=(TCollection_AsciiString("_")+anEntry);
109 static TCollection_AsciiString BuildID(Standard_Integer theDocID, const char* theEntry)
111 TCollection_AsciiString anID(theDocID);
112 anID+=(TCollection_AsciiString("_")+theEntry);
116 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
118 TCollection_AsciiString aDocID = theID.Token("_");
119 if(aDocID.Length() < 1) return -1;
120 return aDocID.IntegerValue();
123 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
124 TCollection_AsciiString& theScript,
125 TCollection_AsciiString& theAfterScript,
126 const TVariablesList& theVariables,
127 const bool theIsPublished,
128 TDF_LabelMap& theProcessed,
129 std::set<TCollection_AsciiString>& theIgnoreObjs,
130 bool& theIsDumpCollected);
132 static int GetTag(const TCollection_AsciiString &theEntry);
134 static void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
135 TIntToListIntMap &theRefMap);
137 void ReplaceVariables(TCollection_AsciiString& theCommand,
138 const TVariablesList& theVariables);
140 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
142 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
143 TSting2ObjDataMap& aEntry2ObjData,
144 const bool theIsPublished,
145 TColStd_SequenceOfAsciiString& theObjListToPublish,
146 Standard_Integer& objectCounter,
147 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry);
149 void AddObjectColors (int theDocID,
150 TCollection_AsciiString& theScript,
151 const TSting2ObjDataMap& theEntry2ObjData);
153 void AddTextures (int theDocID, TCollection_AsciiString& theScript);
155 void PublishObject (TObjectData& theObjectData,
156 TSting2ObjDataMap& theEntry2ObjData,
157 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
158 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
159 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
160 std::set<TCollection_AsciiString>& theMapOfPublished);
162 static TCollection_AsciiString GetPublishCommands
164 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
165 const TIntToListIntMap &theMapRefs,
166 std::set< int > &thePublished);
168 //================================================================================
170 * \brief Fix up the name of python variable
172 //================================================================================
174 void GEOM_Engine::healPyName( TCollection_AsciiString& pyName,
175 const TCollection_AsciiString& anEntry,
176 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
178 const TCollection_AsciiString allowedChars
179 ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
181 if ( pyName.IsIntegerValue() ) { // pyName must not start with a digit
182 pyName.Insert( 1, 'a' );
184 int p, p2=1; // replace not allowed chars
185 while ((p = pyName.FirstLocationNotInSet(allowedChars, p2, pyName.Length()))) {
186 pyName.SetValue(p, '_');
189 if ( aNameToEntry.IsBound( pyName ) && anEntry != aNameToEntry( pyName ))
190 { // diff objects have same name - make a new name by appending a digit
191 TCollection_AsciiString aName2;
192 Standard_Integer i = 0;
194 aName2 = pyName + "_" + ++i;
195 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
200 //=======================================================================
201 //function : GetTextureGUID
203 //=======================================================================
204 const Standard_GUID& GEOM_Engine::GetTextureGUID()
206 static Standard_GUID anID("FF1BBB01-5D14-4df2-980B-3A668264EA17");
210 //=============================================================================
214 //=============================================================================
215 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
217 //=============================================================================
221 //=============================================================================
222 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
224 //=============================================================================
228 //=============================================================================
229 GEOM_Engine::GEOM_Engine()
231 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
233 _OCAFApp = new GEOM_Application();
234 #if OCC_VERSION_LARGE > 0x07000000
235 _OCAFApp->DefineFormat("SALOME_GEOM", "GEOM Document Version 1.0", "sgd",
236 new StdDrivers_DocumentRetrievalDriver, 0);
237 BinDrivers::DefineFormat(_OCAFApp);
245 GEOM_Engine::~GEOM_Engine()
247 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
248 std::list< Handle(GEOM_Object) > objs;
249 for(; It.More(); It.Next())
250 objs.push_back( Handle(GEOM_Object)::DownCast(It.Value()) );
251 std::list< Handle(GEOM_Object) >::iterator objit;
252 for(objit = objs.begin(); objit != objs.end(); ++objit)
253 RemoveObject(*objit);
255 //Close all documents not closed
256 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
257 for (; anItr.More(); anItr.Next())
260 anItr.Initialize( _mapIDDocument ); // anItr becomes invalid at _mapIDDocument.UnBind(docId)
262 _mapIDDocument.Clear();
266 //=============================================================================
270 //=============================================================================
271 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID, bool force)
273 Handle(TDocStd_Document) aDoc;
274 if(_mapIDDocument.IsBound(theDocID)) {
275 aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
278 #if OCC_VERSION_MAJOR > 6
279 _OCAFApp->NewDocument("BinOcaf", aDoc);
281 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
283 aDoc->SetUndoLimit(_UndoLimit);
284 _mapIDDocument.Bind(theDocID, aDoc);
285 TDataStd_Integer::Set(aDoc->Main(), theDocID);
290 //=============================================================================
294 //=============================================================================
295 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
297 if (theDocument.IsNull()) return -1;
298 TColStd_DataMapIteratorOfDataMapOfIntegerTransient anItr (_mapIDDocument);
299 for (; anItr.More(); anItr.Next())
300 if (anItr.Value() == theDocument) return anItr.Key();
305 //=============================================================================
309 //=============================================================================
311 Handle(GEOM_BaseObject) GEOM_Engine::GetObject(int theDocID, const char* theEntry, bool force)
313 Handle(GEOM_BaseObject) anObject;
315 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
317 if (_objects.IsBound(anID)) {
318 anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
321 Handle(TDocStd_Document) aDoc = GetDocument(theDocID, force);
322 if ( !aDoc.IsNull()) {
324 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
325 if ( !aLabel.IsNull() ) {
326 int objType = GEOM_BaseObject::GetType( aLabel );
328 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aLabel); break;
329 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aLabel); break;
330 default: anObject = new GEOM_Object (aLabel);
332 _objects.Bind(anID, anObject);
340 //=============================================================================
344 //=============================================================================
346 Handle(GEOM_BaseObject) GEOM_Engine::AddBaseObject(int theDocID, int theType)
348 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
349 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
351 // NPAL18604: use existing label to decrease memory usage,
352 // if this label has been freed (object deleted)
353 bool useExisting = false;
355 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
356 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
357 if (!aFreeLabels.empty()) {
359 aChild = aFreeLabels.front();
360 aFreeLabels.pop_front();
365 aChild = TDF_TagSource::NewChild(aDoc->Main());
368 Handle(GEOM_BaseObject) anObject;
370 case GEOM_FIELD_OBJTYPE: anObject = new GEOM_Field (aChild, theType); break;
371 case GEOM_FIELD_STEP_OBJTYPE: anObject = new GEOM_FieldStep(aChild, theType); break;
372 default: anObject = new GEOM_Object (aChild, theType);
375 //Put an object in the map of created objects
376 TCollection_AsciiString anID = BuildIDFromObject(anObject);
377 if(_objects.IsBound(anID)) _objects.UnBind(anID);
378 _objects.Bind(anID, anObject);
383 //================================================================================
385 * \brief Adds a new object of the type theType in the OCAF document
387 //================================================================================
389 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
391 return Handle(GEOM_Object)::DownCast( AddBaseObject(theDocID, theType) );
394 //=============================================================================
398 //=============================================================================
400 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
401 Handle(TColStd_HArray1OfInteger) theIndices,
402 bool isStandaloneOperation)
404 if (theMainShape.IsNull() || theIndices.IsNull()) return NULL;
406 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
407 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
409 // NPAL18604: use existing label to decrease memory usage,
410 // if this label has been freed (object deleted)
411 bool useExisting = false;
413 int aDocID = theMainShape->GetDocID();
414 if (_freeLabels.find(aDocID) != _freeLabels.end()) {
415 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
416 if (!aFreeLabels.empty()) {
418 aChild = aFreeLabels.front();
419 aFreeLabels.pop_front();
424 aChild = TDF_TagSource::NewChild(aDoc->Main());
427 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
428 Handle(GEOM_Object) anObject = new GEOM_Object (aChild, 28); //28 is SUBSHAPE type
429 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
431 GEOM_ISubShape aSSI (aFunction);
432 aSSI.SetMainShape(aMainShape);
433 aSSI.SetIndices(theIndices);
437 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
438 if (!aSolver.ComputeFunction(aFunction)) {
439 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
443 catch (Standard_Failure) {
444 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
445 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
449 // Put an object in the map of created objects
450 TCollection_AsciiString anID = BuildIDFromObject(anObject);
451 if (_objects.IsBound(anID)) _objects.UnBind(anID);
452 _objects.Bind(anID, anObject);
454 // Put this sub-shape in the list of sub-shapes of theMainShape
455 aMainShape->AddSubShapeReference(aFunction);
457 GEOM::TPythonDump pd (aFunction);
459 if (isStandaloneOperation) {
460 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
461 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
462 for (; i <= up - 1; i++) {
463 pd << theIndices->Value(i) << ", ";
465 pd << theIndices->Value(up) << "])";
473 //=============================================================================
477 //=============================================================================
478 bool GEOM_Engine::RemoveObject(Handle(GEOM_BaseObject)& theObject)
480 if (theObject.IsNull()) return false;
482 int aDocID = theObject->GetDocID();
483 if(!_mapIDDocument.IsBound(aDocID))
484 return false; // document is closed...
486 //Remove an object from the map of available objects
487 TCollection_AsciiString anID = BuildIDFromObject(theObject);
488 if (_objects.IsBound(anID)) {
489 Handle(GEOM_BaseObject) anObject = Handle(GEOM_BaseObject)::DownCast(_objects(anID));
490 if ( anObject != theObject )
491 anObject->_label = anObject->_label.Root();
492 _objects.UnBind(anID);
495 // If sub-shape, remove it from the list of sub-shapes of its main shape
496 Handle(GEOM_Object) aGO = Handle(GEOM_Object)::DownCast( theObject );
497 if ( !aGO.IsNull() && !aGO->IsMainShape()) {
498 Handle(GEOM_Function) aFunction = theObject->GetFunction(1);
499 GEOM_ISubShape aSSI (aFunction);
500 Handle(GEOM_Function) aMainShape = aSSI.GetMainShape();
501 //If main shape is not null, then remove
502 if(!aMainShape.IsNull())
503 aMainShape->RemoveSubShapeReference(aFunction);
506 int nb = theObject->GetNbFunctions();
507 Handle(TDataStd_TreeNode) aNode;
508 for (int i = 1; i <= nb; i++) {
509 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
510 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
514 TDF_Label aLabel = theObject->GetEntry();
515 aLabel.ForgetAllAttributes(Standard_True);
517 // Remember the label to reuse it then
518 std::list<TDF_Label>& aFreeLabels = _freeLabels[aDocID];
519 if ( aFreeLabels.empty() || aFreeLabels.back() != aLabel )
520 aFreeLabels.push_back(aLabel);
522 // we can't explicitely delete theObject. At least prevent its functioning
523 // as an alive object when aLabel is reused for a new object
524 theObject->_label = aLabel.Root();
525 theObject->_ior.Clear();
526 theObject->_parameters.Clear();
527 theObject->_docID = -1;
534 //=============================================================================
538 //=============================================================================
539 void GEOM_Engine::Undo(int theDocID)
541 GetDocument(theDocID)->Undo();
544 //=============================================================================
548 //=============================================================================
549 void GEOM_Engine::Redo(int theDocID)
551 GetDocument(theDocID)->Redo();
554 //=============================================================================
558 //=============================================================================
559 bool GEOM_Engine::Save(int theDocID, const char* theFileName)
561 if(!_mapIDDocument.IsBound(theDocID)) return false;
562 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
564 _OCAFApp->SaveAs(aDoc, theFileName);
569 //=============================================================================
573 //=============================================================================
574 bool GEOM_Engine::Load(int theDocID, const char* theFileName)
576 Handle(TDocStd_Document) aDoc;
577 if (_OCAFApp->Open(theFileName, aDoc) != PCDM_RS_OK) {
581 #if OCC_VERSION_MAJOR > 6
582 // Replace old document format by the new one.
583 if (aDoc->StorageFormat().IsEqual("SALOME_GEOM")) {
584 aDoc->ChangeStorageFormat("BinOcaf");
588 aDoc->SetUndoLimit(_UndoLimit);
590 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
591 _mapIDDocument.Bind(theDocID, aDoc);
593 TDataStd_Integer::Set(aDoc->Main(), theDocID);
598 //=============================================================================
602 //=============================================================================
603 void GEOM_Engine::Close(int theDocID)
605 if (_mapIDDocument.IsBound(theDocID)) {
606 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
608 //Remove all GEOM Objects associated to the given document
609 TColStd_SequenceOfAsciiString aSeq;
610 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
611 for (; It.More(); It.Next()) {
612 TCollection_AsciiString anObjID (It.Key());
613 Standard_Integer anID = ExtractDocID(anObjID);
614 if (theDocID == anID) aSeq.Append(It.Key());
616 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
618 // Forget free labels for this document
619 TFreeLabelsList::iterator anIt = _freeLabels.find(theDocID);
620 if (anIt != _freeLabels.end()) {
621 _freeLabels.erase(anIt);
624 _mapIDDocument.UnBind(theDocID);
625 _OCAFApp->Close(aDoc);
630 //=============================================================================
634 //=============================================================================
635 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
636 std::vector<TObjectData>& theObjectData,
637 TVariablesList theVariables,
642 // Set "C" numeric locale to save numbers correctly
643 Kernel_Utils::Localizer loc;
645 TCollection_AsciiString aScript;
646 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
650 TCollection_AsciiString anEmptyScript;
652 anEmptyScript = "def RebuildData(theStudy): pass\n";
653 return anEmptyScript;
656 aScript = "import GEOM\n";
657 aScript += "from salome.geom import geomBuilder\n";
658 aScript += "import math\n";
659 aScript += "import SALOMEDS\n\n";
661 aScript += "def RebuildData(theStudy):";
663 aScript += "\n\tgeompy = geomBuilder.New(theStudy)\n";
665 AddTextures(theDocID, aScript);
667 Standard_Integer posToInsertGlobalVars = aScript.Length() + 1;
669 // a map containing copies of TObjectData from theObjectData
670 TSting2ObjDataMap aEntry2ObjData;
671 // contains pointers to TObjectData of either aEntry2ObjData or theObjectData; the latter
672 // occures when several StudyEntries correspond to one Entry
673 TSting2ObjDataPtrMap aStEntry2ObjDataPtr;
675 //Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry, theObjectNames;
676 for (unsigned i = 0; i < theObjectData.size(); ++i )
678 TObjectData& data = theObjectData[i];
679 // look for an object by entry
681 TDF_Tool::Label( aDoc->GetData(), data._entry, L );
682 if ( L.IsNull() ) continue;
683 Handle(GEOM_BaseObject) obj = GEOM_BaseObject::GetObject( L );
685 if ( !obj.IsNull() ) {
686 TSting2ObjDataMap::iterator ent2Data =
687 aEntry2ObjData.insert( std::make_pair( data._entry, data )).first;
689 if ( ent2Data->second._studyEntry == data._studyEntry ) // Entry encounters 1st time
690 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & ent2Data->second ));
692 aStEntry2ObjDataPtr.insert( std::make_pair( data._studyEntry, & data ));
696 // collect objects entries to be published
697 TColStd_SequenceOfAsciiString aObjListToPublish;
699 // iterates on functions till critical (that requiers publication of objects)
700 Handle(TDataStd_TreeNode) aNode, aRoot;
701 Handle(GEOM_Function) aFunction;
702 TDF_LabelMap aCheckedFuncMap;
703 std::set< TCollection_AsciiString > anIgnoreObjMap;
705 TCollection_AsciiString aFuncScript;
707 // Mantis issue 0020768
708 Standard_Integer objectCounter = 0;
709 Resource_DataMapOfAsciiStringAsciiString aNameToEntry;
710 TIntToListIntMap aRefMap;
712 if (aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
713 TDataStd_ChildNodeIterator Itr(aRoot);
714 for (; Itr.More(); Itr.Next()) {
716 aFunction = GEOM_Function::GetFunction(aNode->Label());
717 if (aFunction.IsNull()) {
718 MESSAGE ( "Null function !!!!" );
721 bool isDumpCollected = false;
722 TCollection_AsciiString aCurScript, anAfterScript;
723 if (!ProcessFunction(aFunction, aCurScript, anAfterScript, theVariables,
724 isPublished, aCheckedFuncMap, anIgnoreObjMap,
727 // add function description before dump
728 if (!aCurScript.IsEmpty())
730 if ( aFunction->GetDriverGUID() == GEOM_Object::GetSubShapeID() &&
731 aFuncScript.Length() > aCurScript.Length() )
732 // avoid repeated SubShape...() command at the end
733 if (aFuncScript.Location( aCurScript,
734 aFuncScript.Length() - aCurScript.Length(),
735 aFuncScript.Length()))
736 continue; // aCurScript is already at the end of aFuncScript
737 aFuncScript += aCurScript;
740 // Fill the map of references.
741 FillMapOfRef(aFunction, aRefMap);
743 if (isDumpCollected ) {
744 // Replace entries by the names
745 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished,
746 aObjListToPublish, objectCounter, aNameToEntry );
748 // publish collected objects
749 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by study entry
750 int i = 1, n = aObjListToPublish.Length();
751 for ( ; i <= n; i++ )
753 const TCollection_AsciiString& aEntry = aObjListToPublish.Value(i);
754 PublishObject( aEntry2ObjData[aEntry], aEntry2ObjData, aStEntry2ObjDataPtr,
755 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
757 // add publishing commands to the script
758 std::set< int > aPublished;
759 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
761 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
762 const TCollection_AsciiString aPublishCmds =
763 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
764 aRefMap, aPublished);
766 aFuncScript += aPublishCmds;
769 // PTv, 0020001 add result objects from RestoreGivenSubShapes into ignore list,
770 // because they will be published during command execution
771 int indx = anAfterScript.Search( "RestoreGivenSubShapes" );
773 indx = anAfterScript.Search( "RestoreSubShapes" );
775 TCollection_AsciiString aSubStr = anAfterScript.SubString(1, indx);
776 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aSubStr);
777 i = 1, n = aSeq->Length();
778 for ( ; i <= n; i+=2) {
779 TCollection_AsciiString anEntry =
780 aSubStr.SubString(aSeq->Value(i), aSeq->Value(i+1));
781 anIgnoreObjMap.insert(anEntry.ToCString());
785 aObjListToPublish.Clear();
786 aScript += aFuncScript;
789 aFuncScript += anAfterScript;
793 // Replace entries by the names
794 aObjListToPublish.Clear();
795 ReplaceEntriesByNames( aFuncScript, aEntry2ObjData, isPublished, aObjListToPublish,
796 objectCounter, aNameToEntry );
798 aScript += aFuncScript;
801 AddObjectColors( theDocID, aScript, aEntry2ObjData );
803 // Make script to publish in study
804 TSting2ObjDataPtrMap::iterator aStEntry2ObjDataPtrIt;
807 std::map< int, TCollection_AsciiString > anEntryToCmdMap; // sort publishing commands by object entry
809 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
810 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
811 ++aStEntry2ObjDataPtrIt)
813 TObjectData* data = aStEntry2ObjDataPtrIt->second;
814 if ( anIgnoreObjMap.count( data->_entry ))
815 continue; // should not be dumped
816 PublishObject( *data, aEntry2ObjData, aStEntry2ObjDataPtr,
817 aNameToEntry, anEntryToCmdMap, anIgnoreObjMap );
819 // add publishing commands to the script
820 std::set< int > aPublished;
821 std::map< int, TCollection_AsciiString >::iterator anEntryToCmd = anEntryToCmdMap.begin();
823 for ( ; anEntryToCmd != anEntryToCmdMap.end(); ++anEntryToCmd ) {
824 const TCollection_AsciiString aPublishCmds =
825 GetPublishCommands(anEntryToCmd->first, anEntryToCmdMap,
826 aRefMap, aPublished);
828 aScript += aPublishCmds;
832 //RNV: issue 16219: EDF PAL 469: "RemoveFromStudy" Function
833 //Add unpublish command if need
834 TCollection_AsciiString unpublishCmd("\n");
836 unpublishCmd += "\t";
837 unpublishCmd += "geompy.hideInStudy(";
839 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
840 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
841 ++aStEntry2ObjDataPtrIt)
843 TObjectData* data = aStEntry2ObjDataPtrIt->second;
844 if ( data->_unpublished && !data->_pyName.IsEmpty() ) {
845 aScript += unpublishCmd + data->_pyName + ")";
849 //aScript += "\n\tpass\n";
853 // fill _studyEntry2NameMap and build globalVars
854 TCollection_AsciiString globalVars;
855 _studyEntry2NameMap.Clear();
856 for (aStEntry2ObjDataPtrIt = aStEntry2ObjDataPtr.begin();
857 aStEntry2ObjDataPtrIt != aStEntry2ObjDataPtr.end();
858 ++aStEntry2ObjDataPtrIt)
860 const TCollection_AsciiString& studyEntry = aStEntry2ObjDataPtrIt->first;
861 const TObjectData* data = aStEntry2ObjDataPtrIt->second;
862 _studyEntry2NameMap.Bind ( studyEntry, data->_pyName );
863 if ( !globalVars.IsEmpty() )
865 globalVars += data->_pyName;
867 if ( isMultiFile && !globalVars.IsEmpty() ) {
868 globalVars.Insert( 1, "\n\tglobal " );
869 aScript.Insert( posToInsertGlobalVars, globalVars );
875 //=======================================================================
876 //function : GetDumpName
878 //=======================================================================
880 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
882 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
883 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
888 //=======================================================================
889 //function : GetAllDumpNames
891 //=======================================================================
893 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
895 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
897 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
898 for (; it.More(); it.Next()) {
899 aRetSeq->Append(it.Value());
905 #define TEXTURE_LABEL_ID 1
906 #define TEXTURE_LABEL_FILE 2
907 #define TEXTURE_LABEL_WIDTH 3
908 #define TEXTURE_LABEL_HEIGHT 4
909 #define TEXTURE_LABEL_DATA 5
911 int GEOM_Engine::addTexture(int theDocID, int theWidth, int theHeight,
912 const Handle(TColStd_HArray1OfByte)& theTexture,
913 const TCollection_AsciiString& theFileName)
915 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
916 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
918 // NPAL18604: use existing label to decrease memory usage,
919 // if this label has been freed (object deleted)
920 bool useExisting = false;
922 if (_freeLabels.find(theDocID) != _freeLabels.end()) {
923 std::list<TDF_Label>& aFreeLabels = _freeLabels[theDocID];
924 if (!aFreeLabels.empty()) {
926 aChild = aFreeLabels.front();
927 aFreeLabels.pop_front();
932 aChild = TDF_TagSource::NewChild(aDoc->Main());
935 aChild.ForgetAllAttributes(Standard_True);
936 Handle(TDataStd_TreeNode) node;
937 if ( !aChild.FindAttribute(TDataStd_TreeNode::GetDefaultTreeID(), node ) )
938 node = TDataStd_TreeNode::Set(aChild);
939 TDataStd_UAttribute::Set(aChild, GetTextureGUID());
941 static int aTextureID = 0;
943 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_ID), ++aTextureID);
944 TDataStd_Comment::Set(aChild.FindChild(TEXTURE_LABEL_FILE), theFileName);
945 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_WIDTH), theWidth);
946 TDataStd_Integer::Set(aChild.FindChild(TEXTURE_LABEL_HEIGHT), theHeight);
948 Handle(TDataStd_ByteArray) anAttr =
949 TDataStd_ByteArray::Set(aChild.FindChild(TEXTURE_LABEL_DATA),
950 theTexture.IsNull() ? 0 : theTexture->Lower(),
951 theTexture.IsNull() ? 0 : theTexture->Upper());
952 anAttr->ChangeArray(theTexture);
957 Handle(TColStd_HArray1OfByte) GEOM_Engine::getTexture(int theDocID, int theTextureID,
958 int& theWidth, int& theHeight,
959 TCollection_AsciiString& theFileName)
961 Handle(TColStd_HArray1OfByte) anArray;
962 theWidth = theHeight = 0;
964 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
966 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
968 for (; anIterator.More() && !found; anIterator.Next()) {
969 TDF_Label aTextureLabel = anIterator.Value();
970 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
971 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
972 Handle(TDataStd_Integer) anIdAttr;
973 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr) &&
974 anIdAttr->Get() == theTextureID) {
975 TDF_Label aFileLabel = aTextureLabel.FindChild(TEXTURE_LABEL_FILE, Standard_False);
976 TDF_Label aWidthLabel = aTextureLabel.FindChild(TEXTURE_LABEL_WIDTH, Standard_False);
977 TDF_Label aHeightLabel = aTextureLabel.FindChild(TEXTURE_LABEL_HEIGHT, Standard_False);
978 TDF_Label aDataLabel = aTextureLabel.FindChild(TEXTURE_LABEL_DATA, Standard_False);
979 Handle(TDataStd_Integer) aWidthAttr, aHeightAttr;
980 Handle(TDataStd_ByteArray) aTextureAttr;
981 Handle(TDataStd_Comment) aFileAttr;
982 if (!aWidthLabel.IsNull() && aWidthLabel.FindAttribute(TDataStd_Integer::GetID(), aWidthAttr) &&
983 !aHeightLabel.IsNull() && aHeightLabel.FindAttribute(TDataStd_Integer::GetID(), aHeightAttr) &&
984 !aDataLabel.IsNull() && aDataLabel.FindAttribute(TDataStd_ByteArray::GetID(), aTextureAttr)) {
985 theWidth = aWidthAttr->Get();
986 theHeight = aHeightAttr->Get();
987 anArray = aTextureAttr->InternalArray();
989 if (!aFileLabel.IsNull() && aFileLabel.FindAttribute(TDataStd_Comment::GetID(), aFileAttr))
990 theFileName = aFileAttr->Get();
998 std::list<int> GEOM_Engine::getAllTextures(int theDocID)
1000 std::list<int> id_list;
1002 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
1004 TDF_ChildIterator anIterator(aDoc->Main(), Standard_True);
1005 for (; anIterator.More(); anIterator.Next()) {
1006 TDF_Label aTextureLabel = anIterator.Value();
1007 if (aTextureLabel.IsAttribute( GetTextureGUID())) {
1008 TDF_Label anIDLabel = aTextureLabel.FindChild(TEXTURE_LABEL_ID, Standard_False);
1009 Handle(TDataStd_Integer) anIdAttr;
1010 if(!anIDLabel.IsNull() && anIDLabel.FindAttribute(TDataStd_Integer::GetID(), anIdAttr))
1011 id_list.push_back((int)anIdAttr->Get());
1017 void GEOM_Engine::DocumentModified(const int theDocId, const bool isModified)
1019 if (isModified) _mapModifiedDocs.Add(theDocId);
1020 else _mapModifiedDocs.Remove(theDocId);
1023 bool GEOM_Engine::DocumentModified(const int theDocId)
1025 return _mapModifiedDocs.Contains(theDocId);
1028 //===========================================================================
1029 // Internal functions
1030 //===========================================================================
1032 //=============================================================================
1034 * MakeCommandfor3DSketcher: Make new command for 3DSketcher
1036 //=============================================================================
1037 TCollection_AsciiString MakeCommandfor3DSketcher (const TCollection_AsciiString& theDescr )
1039 TCollection_AsciiString aNewDescr;
1041 TCollection_AsciiString aSubStr = theDescr.Token("\n\t", i);
1042 for (; !aSubStr.IsEmpty(); aSubStr = theDescr.Token("\n\t", i)) {
1043 if (aSubStr.Search( "Make3DSketcherCommand" ) != -1) {
1044 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1045 // "3DSketcher:CMD[:CMD[:CMD...]]"
1046 TCollection_AsciiString aCommand = aSubStr.Token("\"", 2);
1048 // Split the command string to separate CMDs
1050 TColStd_SequenceOfAsciiString aSequence;
1051 if (aCommand.Length()) {
1052 TCollection_AsciiString aToken = aCommand.Token(":", icmd);
1053 while (aToken.Length() > 0) {
1054 aSequence.Append(aToken);
1055 aToken = aCommand.Token(":", ++icmd);
1059 if (aSequence.Length() > 0) {
1061 aNewDescr += "\n\t";
1063 aNewDescr += "\nsk = geompy.Sketcher3D()";
1064 int nbCMDs = aSequence.Length();
1065 for (icmd = 1; icmd <= nbCMDs; icmd++) {
1066 aNewDescr += "\n\t";
1068 TCollection_AsciiString aCMD = aSequence.Value(icmd);
1070 // Split the CMD into string values
1071 TColStd_SequenceOfAsciiString aStrVals;
1073 TCollection_AsciiString aToken = aCMD.Token(" ", ival);
1074 while (aToken.Length() > 0) {
1075 aStrVals.Append(aToken);
1076 aToken = aCMD.Token(" ", ++ival);
1079 TCollection_AsciiString aCMDpref = aStrVals.Value(1);
1080 if (aCMDpref == "TT") {
1081 aNewDescr += "sk.addPointsAbsolute(";
1082 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1084 else if (aCMDpref == "T") {
1085 aNewDescr += "sk.addPointsRelative(";
1086 aNewDescr += aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + aStrVals.Value(4) + ")";
1088 else if (aCMDpref == "WW") {
1089 aNewDescr += "sk.close()";
1091 else if (aCMDpref.Value(1) == 'O'){
1092 TCollection_AsciiString aCMDtrunc = aStrVals.Value(1);
1094 if (aCMDpref.Value(4) == 'C')
1095 aNewDescr += "sk.addPointRadiusAngleH";
1097 aNewDescr += "sk.addPointRadiusAngles";
1098 if (aCMDpref.Value(5) == 'A')
1099 aNewDescr += "Absolute(";
1101 aNewDescr += "Relative(";
1102 aNewDescr += aStrVals.Value(4) + ", " +
1103 aStrVals.Value(2) + ", " + aStrVals.Value(3) + ", " + "\""+aCMDtrunc+"\"" + ")";
1106 aNewDescr += "\n\t";
1107 aNewDescr += aResult + " = sk.wire()";
1109 } // Make3DSketcherCommand
1110 else if (aSubStr.Search( "Make3DSketcher" ) != -1) {
1111 TCollection_AsciiString aResult = aSubStr.Token(" ", 1);
1112 TCollection_AsciiString aCommand = aSubStr.Token("[", 2);
1113 aCommand = aCommand.Token("]", 1);
1115 aNewDescr += "\n\t";
1116 aNewDescr += "\nsk = geompy.Sketcher3D()";
1117 aNewDescr += "\n\t";
1118 aNewDescr += "sk.addPointsAbsolute(";
1119 aNewDescr += aCommand + ")";
1120 aNewDescr += "\n\t";
1121 aNewDescr += aResult + " = sk.wire()";
1125 aNewDescr += "\n\t";
1126 aNewDescr += aSubStr;
1133 //=============================================================================
1135 * ProcessFunction: Dump function description into script
1137 //=============================================================================
1138 bool ProcessFunction(Handle(GEOM_Function)& theFunction,
1139 TCollection_AsciiString& theScript,
1140 TCollection_AsciiString& theAfterScript,
1141 const TVariablesList& theVariables,
1142 const bool theIsPublished,
1143 TDF_LabelMap& theProcessed,
1144 std::set<TCollection_AsciiString>& theIgnoreObjs,
1145 bool& theIsDumpCollected)
1147 theIsDumpCollected = false;
1148 if (theFunction.IsNull()) return false;
1150 if (theProcessed.Contains(theFunction->GetEntry())) return false;
1152 // pass functions, that depends on nonexisting ones
1153 bool doNotProcess = false;
1154 TDF_LabelSequence aSeq;
1155 theFunction->GetDependency(aSeq);
1156 Standard_Integer aLen = aSeq.Length();
1157 for (Standard_Integer i = 1; i <= aLen && !doNotProcess; i++) {
1158 TDF_Label aRefLabel = aSeq.Value(i);
1159 Handle(TDF_Reference) aRef;
1160 if (!aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1161 doNotProcess = true;
1164 if (aRef.IsNull() || aRef->Get().IsNull()) {
1165 doNotProcess = true;
1168 Handle(TDataStd_TreeNode) aT;
1169 if (!TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1170 doNotProcess = true;
1173 TDF_Label aDepLabel = aT->Label();
1174 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aDepLabel);
1176 if (aFunction.IsNull()) doNotProcess = true;
1177 else if (!theProcessed.Contains(aDepLabel)) doNotProcess = true;
1184 TCollection_AsciiString anObjEntry;
1185 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1186 theIgnoreObjs.insert(anObjEntry);
1189 theProcessed.Add(theFunction->GetEntry());
1191 TCollection_AsciiString aDescr = theFunction->GetDescription();
1192 if(aDescr.Length() == 0) return false;
1194 //Check if its internal function which doesn't requires dumping
1195 if(aDescr == "None") return false;
1197 //Check the very specific case of RestoreShape function,
1198 //which is not dumped, but the result can be published by the user.
1199 //We do not publish such objects to decrease danger of dumped script failure.
1200 if(aDescr.Value(1) == '#') {
1201 TCollection_AsciiString anObjEntry;
1202 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1203 theIgnoreObjs.insert(anObjEntry);
1207 // 0020001 PTv, check for critical functions, which require dump of objects
1210 // currently, there is only one function "RestoreGivenSubShapes",
1211 // later this check could be replaced by iterations on list of such functions
1212 if (aDescr.Search( "RestoreGivenSubShapes" ) != -1)
1213 theIsDumpCollected = true;
1214 else if (aDescr.Search( "RestoreSubShapes" ) != -1)
1215 theIsDumpCollected = true;
1218 //Replace parameter by notebook variables
1219 ReplaceVariables(aDescr,theVariables);
1221 //Process sketcher functions, replacing string command by calls to Sketcher interface
1222 if ( ( aDescr.Search( "MakeSketcherOnPlane" ) != -1 ) || ( aDescr.Search( "MakeSketcher" ) != -1 ) ) {
1223 Sketcher_Profile aProfile( aDescr.ToCString());
1224 // Make new command for SketcherOnPlane and for Sketcher
1225 aDescr = aProfile.GetDump();
1227 if (aDescr.Search( "Make3DSketcher" ) != -1) {
1228 aDescr = MakeCommandfor3DSketcher ( aDescr );
1231 if ( theIsDumpCollected ) {
1233 bool isBefore = true;
1234 TCollection_AsciiString aSubStr = aDescr.Token("\n\t", i++);
1235 while (!aSubStr.IsEmpty()) {
1237 aSubStr.Search( "RestoreGivenSubShapes" ) == -1 &&
1238 aSubStr.Search( "RestoreSubShapes" ) == -1)
1239 theScript += TCollection_AsciiString("\n\t") + aSubStr;
1241 theAfterScript += TCollection_AsciiString("\n\t") + aSubStr;
1242 aSubStr = aDescr.Token("\n\t", i++);
1246 theScript += "\n\t";
1247 theScript += aDescr;
1252 //=============================================================================
1254 * GetTag: Returns the tag from entry
1256 //=============================================================================
1257 int GetTag(const TCollection_AsciiString &theEntry)
1259 const int aGeomObjDepth = 3;
1260 const int aTag = theEntry.Token(":", aGeomObjDepth).IntegerValue();
1265 //=============================================================================
1267 * FillMapOfRef: Fill the map of references
1269 //=============================================================================
1270 void FillMapOfRef(const Handle(GEOM_Function) &theFunction,
1271 TIntToListIntMap &theRefMap)
1273 TDF_LabelSequence aSeq;
1274 TCollection_AsciiString anObjEntry;
1277 TDF_Tool::Entry(theFunction->GetOwnerEntry(), anObjEntry);
1278 anObjTag = GetTag(anObjEntry);
1279 theFunction->GetDependency(aSeq);
1281 const Standard_Integer aLen = aSeq.Length();
1284 for (i = 1; i <= aLen; i++) {
1285 TDF_Label aRefLabel = aSeq.Value(i);
1286 Handle(TDF_Reference) aRef;
1288 if (aRefLabel.FindAttribute(TDF_Reference::GetID(), aRef)) {
1289 if (!aRef.IsNull() && !aRef->Get().IsNull()) {
1290 Handle(TDataStd_TreeNode) aT;
1292 if (TDataStd_TreeNode::Find(aRef->Get(), aT)) {
1293 TDF_Label aDepLabel = aT->Label();
1294 Handle(GEOM_Function) aRefFunct = GEOM_Function::GetFunction(aDepLabel);
1296 if (!aRefFunct.IsNull()) {
1297 // Get entry of the referenced object.
1298 TDF_Tool::Entry(aRefFunct->GetOwnerEntry(), anObjEntry);
1300 const int aRefTag = GetTag(anObjEntry);
1302 if (anObjTag != aRefTag) {
1303 // Avoid making references for operations without copy.
1304 theRefMap[anObjTag].push_back(aRefTag);
1313 //=============================================================================
1315 * FindEntries: Returns a sequence of start/end positions of entries in the string
1317 //=============================================================================
1318 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
1320 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
1321 Standard_Integer aLen = theString.Length();
1322 Standard_Boolean isFound = Standard_False;
1324 const char* arr = theString.ToCString();
1325 Standard_Integer i = 0, j;
1328 int c = (int)arr[i];
1330 if(c >= 48 && c <= 57) { //Is digit?
1332 isFound = Standard_False;
1333 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
1335 if(c == 58) isFound = Standard_True;
1338 if(isFound && arr[j-2] != 58) { // last char should be a diggit
1339 aSeq->Append(i+1); // +1 because AsciiString starts from 1
1350 //=============================================================================
1352 * ReplaceVariables: Replace parameters of the function by variales from
1355 //=============================================================================
1356 void ReplaceVariables(TCollection_AsciiString& theCommand,
1357 const TVariablesList& theVariables)
1360 cout<<"Command : "<<theCommand<<endl;
1363 cout<<"All Entries:"<<endl;
1364 TVariablesList::const_iterator it = theVariables.begin();
1365 for(;it != theVariables.end();it++)
1366 cout<<"\t'"<<(*it).first<<"'"<<endl;
1369 //Additional case - multi-row commands
1370 int aCommandIndex = 1;
1371 while( aCommandIndex < 10 ) { // tmp check
1372 TCollection_AsciiString aCommand = theCommand.Token("\n",aCommandIndex);
1373 if( aCommand.Length() == 0 )
1377 cout<<"Sub-command : "<<aCommand<<endl;
1379 Standard_Integer aStartCommandPos = theCommand.Location(aCommand,1,theCommand.Length());
1380 Standard_Integer aEndCommandPos = aStartCommandPos + aCommand.Length();
1382 //Get Entry of the result object
1383 TCollection_AsciiString anEntry;
1384 if( aCommand.Search("=") != -1 ) // command returns an object
1385 anEntry = aCommand.Token("=",1);
1386 else { // command modifies the object
1387 if (int aStartEntryPos = aCommand.Location(1,'(',1,aCommand.Length()))
1388 if (int aEndEntryPos = aCommand.Location(1,',',aStartEntryPos,aCommand.Length()))
1389 anEntry = aCommand.SubString(aStartEntryPos+1, aEndEntryPos-1);
1391 //Remove white spaces
1392 anEntry.RightAdjust();
1393 anEntry.LeftAdjust();
1395 cout<<"Result entry : '" <<anEntry<<"'"<<endl;
1397 if ( anEntry.IsEmpty() ) {
1402 //Check if result is list of entries - enough to get the first entry in this case
1404 if( anEntry.Value( 1 ) == O_SQR_BRACKET && anEntry.Value( anEntry.Length() ) == C_SQR_BRACKET ) {
1405 while(anEntry.Location(aNbEntries,COMMA,1,anEntry.Length()))
1407 TCollection_AsciiString aSeparator(COMMA);
1408 anEntry = anEntry.Token(aSeparator.ToCString(),1);
1409 anEntry.Remove( 1, 1 );
1410 anEntry.RightAdjust();
1411 anEntry.LeftAdjust();
1413 cout<<"Sub-entry : '" <<anEntry<<"'"<<endl;
1416 //Find variables used for object construction
1417 ObjectStates* aStates = 0;
1418 TVariablesList::const_iterator it = theVariables.find(anEntry);
1419 if( it != theVariables.end() )
1420 aStates = (*it).second;
1424 cout<<"Valiables list empty!!!"<<endl;
1429 TState aVariables = aStates->GetCurrectState();
1432 cout<<"Variables from SObject:"<<endl;
1433 for (int i = 0; i < aVariables.size();i++)
1434 cout<<"\t Variable["<<i<<"] = "<<aVariables[i].myVariable<<endl;
1437 //Calculate total number of parameters
1438 Standard_Integer aTotalNbParams = 1;
1439 while(aCommand.Location(aTotalNbParams,COMMA,1,aCommand.Length()))
1443 cout<<"aTotalNbParams = "<<aTotalNbParams<<endl;
1445 Standard_Integer aFirstParam = aNbEntries;
1447 //Replace parameters by variables
1448 Standard_Integer aStartPos = 0;
1449 Standard_Integer aEndPos = 0;
1451 TCollection_AsciiString aVar, aReplacedVar;
1452 for(Standard_Integer i=aFirstParam;i <= aTotalNbParams;i++) {
1453 //Replace first parameter (bettwen '(' character and first ',' character)
1454 if(i == aFirstParam)
1456 aStartPos = aCommand.Location(O_BRACKET, 1, aCommand.Length()) + 1;
1457 if(aTotalNbParams - aNbEntries > 0 )
1458 aEndPos = aCommand.Location(aFirstParam, COMMA, 1, aCommand.Length());
1460 aEndPos = aCommand.Location(C_BRACKET, 1, aCommand.Length());
1462 //Replace last parameter (bettwen ',' character and ')' character)
1463 else if(i == aTotalNbParams)
1465 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1466 aEndPos = aCommand.Location(C_BRACKET, aStartPos , aCommand.Length());
1468 //Replace other parameters (bettwen two ',' characters)
1469 else if(i != aFirstParam && i != aTotalNbParams )
1471 aStartPos = aCommand.Location(i-1, COMMA, 1, aCommand.Length()) + 2;
1472 aEndPos = aCommand.Location(i, COMMA, 1, aCommand.Length());
1475 if( aCommand.Value( aStartPos ) == O_SQR_BRACKET )
1477 if( aCommand.Value( aEndPos-1 ) == C_SQR_BRACKET )
1479 if ( aStartPos == aEndPos )
1480 continue; // PAL20889: for "[]"
1483 cout<<"aStartPos = "<<aStartPos<<", aEndPos = "<<aEndPos<<endl;
1485 aVar = aCommand.SubString(aStartPos, aEndPos-1);
1490 cout<<"Variable: '"<< aVar <<"'"<<endl;
1492 // specific case for sketcher
1493 if(aVar.Location( TCollection_AsciiString("Sketcher:"), 1, aVar.Length() ) != 0) {
1494 Standard_Integer aNbSections = 1;
1495 while( aVar.Location( aNbSections, ':', 1, aVar.Length() ) )
1499 int aStartSectionPos = 0, aEndSectionPos = 0;
1500 TCollection_AsciiString aSection, aReplacedSection;
1501 for(Standard_Integer aSectionIndex = 1; aSectionIndex <= aNbSections; aSectionIndex++) {
1502 aStartSectionPos = aVar.Location( aSectionIndex, ':', 1, aVar.Length() ) + 1;
1503 if( aSectionIndex != aNbSections )
1504 aEndSectionPos = aVar.Location( aSectionIndex + 1, ':', 1, aVar.Length() );
1506 aEndSectionPos = aVar.Length();
1508 aSection = aVar.SubString(aStartSectionPos, aEndSectionPos-1);
1510 cout<<"aSection: "<<aSection<<endl;
1512 Standard_Integer aNbParams = 1;
1513 while( aSection.Location( aNbParams, ' ', 1, aSection.Length() ) )
1517 int aStartParamPos = 0, aEndParamPos = 0;
1518 TCollection_AsciiString aParameter, aReplacedParameter;
1519 for(Standard_Integer aParamIndex = 1; aParamIndex <= aNbParams; aParamIndex++) {
1520 aStartParamPos = aSection.Location( aParamIndex, ' ', 1, aSection.Length() ) + 1;
1521 if( aParamIndex != aNbParams )
1522 aEndParamPos = aSection.Location( aParamIndex + 1, ' ', 1, aSection.Length() );
1524 aEndParamPos = aSection.Length() + 1;
1527 cout<<"aParamIndex: "<<aParamIndex<<" aStartParamPos: " <<aStartParamPos<<" aEndParamPos: "<<aEndParamPos<<endl;
1529 if ( aStartParamPos == aEndParamPos)
1532 aParameter = aSection.SubString(aStartParamPos, aEndParamPos-1);
1534 cout<<"aParameter: "<<aParameter<<endl;
1536 if(iVar >= aVariables.size())
1539 aReplacedParameter = aVariables[iVar].myVariable;
1540 if(aReplacedParameter.IsEmpty()) {
1545 if(aVariables[iVar].isVariable) {
1546 aReplacedParameter.InsertBefore(1,"'");
1547 aReplacedParameter.InsertAfter(aReplacedParameter.Length(),"'");
1551 cout<<"aSection before : "<<aSection<<endl;
1552 aSection.Remove(aStartParamPos, aEndParamPos - aStartParamPos);
1553 aSection.Insert(aStartParamPos, aReplacedParameter);
1555 cout<<"aSection after : "<<aSection<<endl<<endl;
1559 cout<<"aVar before : "<<aVar<<endl;
1560 aVar.Remove(aStartSectionPos, aEndSectionPos - aStartSectionPos);
1561 aVar.Insert(aStartSectionPos, aSection);
1563 cout<<"aVar after : "<<aVar<<endl<<endl;
1567 cout<<"aCommand before : "<<aCommand<<endl;
1568 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1569 aCommand.Insert(aStartPos, aVar);
1571 cout<<"aCommand after : "<<aCommand<<endl;
1574 } // end of specific case for sketcher
1576 //If parameter is entry or 'None', skip it
1577 if(theVariables.find(aVar) != theVariables.end() || aVar.Search(":") != -1 || aVar == PY_NULL)
1580 if(iVar >= aVariables.size())
1583 aReplacedVar = aVariables[iVar].myVariable;
1584 if(aReplacedVar.IsEmpty()) {
1589 if(aVariables[iVar].isVariable) {
1590 aReplacedVar.InsertBefore(1,"\"");
1591 aReplacedVar.InsertAfter(aReplacedVar.Length(),"\"");
1594 aCommand.Remove(aStartPos, aEndPos - aStartPos);
1595 aCommand.Insert(aStartPos, aReplacedVar);
1599 theCommand.Remove(aStartCommandPos, aEndCommandPos - aStartCommandPos);
1600 theCommand.Insert(aStartCommandPos, aCommand);
1604 aStates->IncrementState();
1608 cout<<"Command : "<<theCommand<<endl;
1611 //=============================================================================
1613 * ReplaceEntriesByNames: Replace object entries by their names
1615 //=============================================================================
1616 void ReplaceEntriesByNames (TCollection_AsciiString& theScript,
1617 TSting2ObjDataMap& aEntry2ObjData,
1618 const bool theIsPublished,
1619 TColStd_SequenceOfAsciiString& theObjListToPublish,
1620 Standard_Integer& objectCounter,
1621 Resource_DataMapOfAsciiStringAsciiString& aNameToEntry)
1623 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1624 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(theScript);
1625 Standard_Integer aLen = aSeq->Length(), aStart = 1, aScriptLength = theScript.Length();
1627 //Replace entries by the names
1628 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
1629 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
1630 if (aLen == 0) anUpdatedScript = theScript;
1632 for (Standard_Integer i = 1; i <= aLen; i+=2) {
1633 anUpdatedScript += theScript.SubString(aStart, aSeq->Value(i)-1);
1634 anEntry = theScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
1635 theObjListToPublish.Append( anEntry );
1637 TObjectData& data = aEntry2ObjData[ anEntry ];
1638 if ( data._pyName.IsEmpty() ) { // encounted for the 1st time
1639 if ( !data._name.IsEmpty() ) { // published object
1640 data._pyName = data._name;
1641 engine->healPyName( data._pyName, anEntry, aNameToEntry);
1645 data._pyName = aBaseName + TCollection_AsciiString(++objectCounter);
1646 } while(aNameToEntry.IsBound(data._pyName));
1650 aNameToEntry.Bind(data._pyName, anEntry); // to detect same name of diff objects
1652 anUpdatedScript += data._pyName;
1653 aStart = aSeq->Value(i+1) + 1;
1656 //Add final part of the script
1657 if (aLen && aSeq->Value(aLen) < aScriptLength)
1658 anUpdatedScript += theScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
1660 theScript = anUpdatedScript;
1663 //=============================================================================
1665 * AddObjectColors: Add color to objects
1667 //=============================================================================
1668 void AddObjectColors (int theDocID,
1669 TCollection_AsciiString& theScript,
1670 const TSting2ObjDataMap& theEntry2ObjData)
1672 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1673 Handle(TDocStd_Document) aDoc = engine->GetDocument(theDocID);
1675 TSting2ObjDataMap::const_iterator anEntryToNameIt;
1676 for (anEntryToNameIt = theEntry2ObjData.begin();
1677 anEntryToNameIt!= theEntry2ObjData.end();
1680 const TCollection_AsciiString& aEntry = anEntryToNameIt->first;
1681 const TCollection_AsciiString& aName = anEntryToNameIt->second._pyName;
1684 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
1688 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
1692 bool anAutoColor = obj->GetAutoColor();
1695 TCollection_AsciiString aCommand( "\n\t" );
1696 aCommand += aName + ".SetAutoColor(1)";
1697 theScript += aCommand.ToCString();
1700 GEOM_Object::Color aColor = obj->GetColor();
1701 if ( aColor.R >= 0 && aColor.G >= 0 && aColor.B >= 0 )
1703 TCollection_AsciiString aCommand( "\n\t" );
1704 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
1705 theScript += aCommand.ToCString();
1708 Aspect_TypeOfMarker aMarkerType = obj->GetMarkerType();
1709 if (aMarkerType >= Aspect_TOM_POINT && aMarkerType < Aspect_TOM_USERDEFINED) {
1710 TCollection_AsciiString aCommand( "\n\t" );
1711 aCommand += aName + ".SetMarkerStd(";
1712 switch (aMarkerType) {
1713 case Aspect_TOM_POINT: aCommand += "GEOM.MT_POINT"; break;
1714 case Aspect_TOM_PLUS: aCommand += "GEOM.MT_PLUS"; break;
1715 case Aspect_TOM_STAR: aCommand += "GEOM.MT_STAR"; break;
1716 case Aspect_TOM_X: aCommand += "GEOM.MT_X"; break;
1717 case Aspect_TOM_O: aCommand += "GEOM.MT_O"; break;
1718 case Aspect_TOM_O_POINT: aCommand += "GEOM.MT_O_POINT"; break;
1719 case Aspect_TOM_O_PLUS: aCommand += "GEOM.MT_O_PLUS"; break;
1720 case Aspect_TOM_O_STAR: aCommand += "GEOM.MT_O_STAR"; break;
1721 case Aspect_TOM_O_X: aCommand += "GEOM.MT_O_X"; break;
1722 case Aspect_TOM_RING1: aCommand += "GEOM.MT_RING1"; break;
1723 case Aspect_TOM_RING2: aCommand += "GEOM.MT_RING2"; break;
1724 case Aspect_TOM_RING3: aCommand += "GEOM.MT_RING3"; break;
1725 case Aspect_TOM_BALL: aCommand += "GEOM.MT_BALL"; break;
1726 default: aCommand += "GEOM.MT_NONE"; break; // just for completeness, should not get here
1729 int aSize = (int)( obj->GetMarkerSize()/0.5 ) - 1;
1731 case 1: aCommand += "GEOM.MS_10"; break;
1732 case 2: aCommand += "GEOM.MS_15"; break;
1733 case 3: aCommand += "GEOM.MS_20"; break;
1734 case 4: aCommand += "GEOM.MS_25"; break;
1735 case 5: aCommand += "GEOM.MS_30"; break;
1736 case 6: aCommand += "GEOM.MS_35"; break;
1737 case 7: aCommand += "GEOM.MS_40"; break;
1738 case 8: aCommand += "GEOM.MS_45"; break;
1739 case 9: aCommand += "GEOM.MS_50"; break;
1740 case 10: aCommand += "GEOM.MS_55"; break;
1741 case 11: aCommand += "GEOM.MS_60"; break;
1742 case 12: aCommand += "GEOM.MS_65"; break;
1743 case 13: aCommand += "GEOM.MS_70"; break;
1744 default: aCommand += "GEOM.MS_NONE"; break;
1747 theScript += aCommand.ToCString();
1749 else if (aMarkerType == Aspect_TOM_USERDEFINED) {
1750 int aMarkerTextureID = obj->GetMarkerTexture();
1751 if (aMarkerTextureID >= 0) {
1752 TCollection_AsciiString aCommand( "\n\t" );
1753 aCommand += aName + ".SetMarkerTexture(texture_map[";
1754 aCommand += aMarkerTextureID;
1756 theScript += aCommand.ToCString();
1762 static TCollection_AsciiString pack_data (const Handle(TColStd_HArray1OfByte)& aData)
1764 TCollection_AsciiString stream;
1765 if (!aData.IsNull()) {
1766 for (Standard_Integer i = aData->Lower(); i <= aData->Upper(); i++) {
1767 Standard_Byte byte = aData->Value(i);
1768 TCollection_AsciiString strByte = "";
1769 for (int j = 0; j < 8; j++)
1770 strByte.Prepend((byte & (1<<j)) ? "1" : "0");
1777 void AddTextures (int theDocID, TCollection_AsciiString& theScript)
1779 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1780 std::list<int> allTextures = engine->getAllTextures(theDocID);
1781 std::list<int>::const_iterator it;
1783 if (allTextures.size() > 0) {
1784 theScript += "\n\ttexture_map = {}\n";
1786 for (it = allTextures.begin(); it != allTextures.end(); ++it) {
1787 if (*it <= 0) continue;
1788 Standard_Integer aWidth, aHeight;
1789 TCollection_AsciiString aFileName;
1790 Handle(TColStd_HArray1OfByte) aTexture =
1791 engine->getTexture(theDocID, *it, aWidth, aHeight, aFileName);
1792 if (aWidth > 0 && aHeight > 0 && !aTexture.IsNull() && aTexture->Length() > 0 ) {
1793 TCollection_AsciiString aCommand = "\n\t";
1794 aCommand += "texture_map["; aCommand += *it; aCommand += "] = ";
1795 if (aFileName != "" ) {
1796 aCommand += "geompy.LoadTexture(\"";
1797 aCommand += aFileName.ToCString();
1801 aCommand += "geompy.AddTexture(";
1802 aCommand += aWidth; aCommand += ", "; aCommand += aHeight; aCommand += ", \"";
1803 aCommand += pack_data(aTexture);
1806 theScript += aCommand;
1813 //=============================================================================
1815 * PublishObject: publish object in study script
1817 //=============================================================================
1818 void PublishObject (TObjectData& theObjectData,
1819 TSting2ObjDataMap& theEntry2ObjData,
1820 const TSting2ObjDataPtrMap& theStEntry2ObjDataPtr,
1821 Resource_DataMapOfAsciiStringAsciiString& theNameToEntry,
1822 std::map< int, TCollection_AsciiString >& theEntryToCmdMap,
1823 std::set< TCollection_AsciiString>& theIgnoreMap)
1825 GEOM_Engine* engine = GEOM_Engine::GetEngine();
1826 if ( theObjectData._studyEntry.IsEmpty() )
1827 return; // was not published
1828 if ( theIgnoreMap.count( theObjectData._entry ) )
1829 return; // not to publish
1831 TCollection_AsciiString aCommand("\n\tgeompy.");
1833 // find a father entry
1834 TObjectData* aFatherData = 0;
1835 TCollection_AsciiString aFatherStudyEntry =
1836 theObjectData._studyEntry.SubString( 1, theObjectData._studyEntry.SearchFromEnd(":") - 1 );
1837 TSting2ObjDataPtrMap::const_iterator stEntry2DataPtr =
1838 theStEntry2ObjDataPtr.find( aFatherStudyEntry );
1839 if ( stEntry2DataPtr != theStEntry2ObjDataPtr.end() )
1840 aFatherData = stEntry2DataPtr->second;
1842 // treat multiply published object
1843 if ( theObjectData._pyName.IsEmpty() )
1845 TObjectData& data0 = theEntry2ObjData[ theObjectData._entry ];
1846 if ( data0._pyName.IsEmpty() ) return; // something wrong
1848 theObjectData._pyName = theObjectData._name;
1849 engine->healPyName( theObjectData._pyName, theObjectData._entry, theNameToEntry);
1851 TCollection_AsciiString aCreationCommand("\n\t");
1852 aCreationCommand += theObjectData._pyName + " = " + data0._pyName;
1854 // store aCreationCommand before publishing commands
1855 int tag = GetTag(theObjectData._entry);
1856 theEntryToCmdMap.insert( std::make_pair( tag + 2*theEntry2ObjData.size(), aCreationCommand ));
1860 if ( aFatherData && !aFatherData->_pyName.IsEmpty() ) {
1861 aCommand += "addToStudyInFather( ";
1862 aCommand += aFatherData->_pyName + ", ";
1865 aCommand += "addToStudy( ";
1867 aCommand += theObjectData._pyName + ", '" + theObjectData._name + "' )";
1869 // bind a command to the study entry
1870 int tag = GetTag(theObjectData._entry);
1871 theEntryToCmdMap.insert( std::make_pair( tag, aCommand ));
1873 theObjectData._studyEntry.Clear(); // not to publish any more
1876 //================================================================================
1878 * \brief Returns the string of publishing commands. Take into account that
1879 * references should be published prior to the objects refer to them.
1881 //================================================================================
1882 TCollection_AsciiString GetPublishCommands
1884 const std::map< int, TCollection_AsciiString > &theEntryToCmdMap,
1885 const TIntToListIntMap &theMapRefs,
1886 std::set< int > &thePublished)
1888 TCollection_AsciiString aResult;
1890 if (!thePublished.count(theTag)) {
1891 // This object is not published yet.
1892 std::map< int, TCollection_AsciiString >::const_iterator anIt =
1893 theEntryToCmdMap.find(theTag);
1895 if (anIt != theEntryToCmdMap.end()) {
1896 // There is a pubish cmd.
1897 TIntToListIntMap::const_iterator aRefIt = theMapRefs.find(theTag);
1899 if (aRefIt != theMapRefs.end()) {
1900 // Recursively publish all references.
1901 std::list< int >::const_iterator aRefTagIt = aRefIt->second.begin();
1903 for(; aRefTagIt != aRefIt->second.end(); ++aRefTagIt) {
1904 const TCollection_AsciiString aRefCmd = GetPublishCommands
1905 (*aRefTagIt, theEntryToCmdMap, theMapRefs, thePublished);
1911 // Add the object command.
1912 aResult += anIt->second;
1915 thePublished.insert(theTag);
1921 //================================================================================
1923 * \brief Constructor
1925 //================================================================================
1926 ObjectStates::ObjectStates()
1931 //================================================================================
1935 //================================================================================
1936 ObjectStates::~ObjectStates()
1940 //================================================================================
1942 * \brief Return current object state
1943 * \retval state - Object state (vector of notebook variable)
1945 //================================================================================
1946 TState ObjectStates::GetCurrectState() const
1948 if(_states.size() > _dumpstate)
1949 return _states[_dumpstate];
1953 //================================================================================
1955 * \brief Add new object state
1956 * \param theState - Object state (vector of notebook variable)
1958 //================================================================================
1959 void ObjectStates::AddState(const TState &theState)
1961 _states.push_back(theState);
1964 //================================================================================
1966 * \brief Increment object state
1968 //================================================================================
1969 void ObjectStates::IncrementState()