1 // Copyright (C) 2005 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License.
9 // This library is distributed in the hope that it will be useful
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Lesser General Public License for more details.
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #pragma warning( disable:4786 )
24 #include "GEOM_Engine.hxx"
26 #include "GEOM_Solver.hxx"
27 #include "GEOM_Function.hxx"
28 #include "GEOM_ISubShape.hxx"
29 #include "GEOM_SubShapeDriver.hxx"
30 #include "GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient.hxx"
31 #include "GEOM_PythonDump.hxx"
33 #include "utilities.h"
35 #include <TDF_Tool.hxx>
36 #include <TDF_Data.hxx>
37 #include <TDF_LabelSequence.hxx>
38 #include <TDataStd_Integer.hxx>
39 #include <TDataStd_ChildNodeIterator.hxx>
40 #include <TFunction_Driver.hxx>
41 #include <TFunction_DriverTable.hxx>
44 #include <TopTools_IndexedMapOfShape.hxx>
46 #include <TCollection_AsciiString.hxx>
47 #include <TCollection_ExtendedString.hxx>
48 #include <TColStd_SequenceOfAsciiString.hxx>
49 #include <TColStd_MapOfTransient.hxx>
50 #include <TColStd_HSequenceOfInteger.hxx>
52 #include <Interface_DataMapIteratorOfDataMapOfIntegerTransient.hxx>
53 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
58 #include <Standard_Failure.hxx>
59 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
61 static GEOM_Engine* TheEngine = NULL;
63 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
65 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
66 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
67 anID+=(TCollection_AsciiString("_")+anEntry);
71 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
73 TCollection_AsciiString anID(theDocID);
74 anID+=(TCollection_AsciiString("_")+theEntry);
78 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
80 TCollection_AsciiString aDocID = theID.Token("_");
81 if(aDocID.Length() < 1) return -1;
82 return aDocID.IntegerValue();
85 void ProcessFunction(Handle(GEOM_Function)& theFunction,
86 TCollection_AsciiString& theScript,
87 TColStd_MapOfTransient& theProcessed);
89 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
91 //=============================================================================
95 //=============================================================================
96 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
99 //=============================================================================
103 //=============================================================================
104 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
106 //=============================================================================
110 //=============================================================================
111 GEOM_Engine::GEOM_Engine()
113 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
115 _OCAFApp = new GEOM_Application();
122 GEOM_Engine::~GEOM_Engine()
124 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
125 for(; It.More(); It.Next())
127 RemoveObject(Handle(GEOM_Object)::DownCast(It.Value()));
130 //Close all documents not closed
131 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
134 _mapIDDocument.Clear();
138 //=============================================================================
142 //=============================================================================
143 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
145 Handle(TDocStd_Document) aDoc;
146 if(!_mapIDDocument.IsBound(theDocID)) {
147 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
148 aDoc->SetUndoLimit(_UndoLimit);
149 _mapIDDocument.Bind(theDocID, aDoc);
150 TDataStd_Integer::Set(aDoc->Main(), theDocID);
153 return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
156 //=============================================================================
160 //=============================================================================
161 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
163 if(theDocument.IsNull()) return -1;
164 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
165 if(anItr.Value() == theDocument) return anItr.Key();
171 //=============================================================================
175 //=============================================================================
176 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
178 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
179 if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
182 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
183 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
184 Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
186 _objects.Bind(anID, anObject);
191 //=============================================================================
195 //=============================================================================
196 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
198 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
199 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
201 // NPAL18604: use existing label to decrease memory usage,
202 // if this label has been freed (object deleted)
203 bool useExisting = false;
205 if (!_lastCleared.IsNull()) {
206 if (_lastCleared.Root() == aDoc->Main().Root()) {
208 aChild = _lastCleared;
209 _lastCleared.Nullify();
214 aChild = TDF_TagSource::NewChild(aDoc->Main());
217 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
219 //Put an object in the map of created objects
220 TCollection_AsciiString anID = BuildIDFromObject(anObject);
221 if(_objects.IsBound(anID)) _objects.UnBind(anID);
222 _objects.Bind(anID, anObject);
227 //=============================================================================
231 //=============================================================================
232 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
233 Handle(TColStd_HArray1OfInteger) theIndices,
234 bool isStandaloneOperation)
236 if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
238 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
239 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
241 // NPAL18604: use existing label to decrease memory usage,
242 // if this label has been freed (object deleted)
243 bool useExisting = false;
245 if (!_lastCleared.IsNull()) {
246 if (_lastCleared.Root() == aDoc->Main().Root()) {
248 aChild = _lastCleared;
249 _lastCleared.Nullify();
254 aChild = TDF_TagSource::NewChild(aDoc->Main());
257 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
258 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
259 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
261 GEOM_ISubShape aSSI(aFunction);
262 aSSI.SetMainShape(aMainShape);
263 aSSI.SetIndices(theIndices);
266 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
269 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
270 if (!aSolver.ComputeFunction(aFunction)) {
271 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
275 catch (Standard_Failure) {
276 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
277 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
281 //Put an object in the map of created objects
282 TCollection_AsciiString anID = BuildIDFromObject(anObject);
283 if(_objects.IsBound(anID)) _objects.UnBind(anID);
284 _objects.Bind(anID, anObject);
286 GEOM::TPythonDump pd (aFunction);
288 if (isStandaloneOperation) {
289 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
290 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
291 for (; i <= up - 1; i++) {
292 pd << theIndices->Value(i) << ", ";
294 pd << theIndices->Value(up) << "])";
302 //=============================================================================
306 //=============================================================================
307 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
309 if (!theObject) return false;
311 //Remove an object from the map of available objects
312 TCollection_AsciiString anID = BuildIDFromObject(theObject);
313 if (_objects.IsBound(anID)) _objects.UnBind(anID);
315 int nb = theObject->GetNbFunctions();
316 Handle(TDataStd_TreeNode) aNode;
317 for (int i = 1; i<=nb; i++) {
318 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
319 if (aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
323 TDF_Label aLabel = theObject->GetEntry();
324 aLabel.ForgetAllAttributes(Standard_True);
325 _lastCleared = aLabel;
332 //=============================================================================
336 //=============================================================================
337 void GEOM_Engine::Undo(int theDocID)
339 GetDocument(theDocID)->Undo();
342 //=============================================================================
346 //=============================================================================
347 void GEOM_Engine::Redo(int theDocID)
349 GetDocument(theDocID)->Redo();
352 //=============================================================================
356 //=============================================================================
357 bool GEOM_Engine::Save(int theDocID, char* theFileName)
359 if(!_mapIDDocument.IsBound(theDocID)) return false;
360 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
362 _OCAFApp->SaveAs(aDoc, theFileName);
367 //=============================================================================
371 //=============================================================================
372 bool GEOM_Engine::Load(int theDocID, char* theFileName)
374 Handle(TDocStd_Document) aDoc;
375 if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
379 aDoc->SetUndoLimit(_UndoLimit);
381 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
382 _mapIDDocument.Bind(theDocID, aDoc);
384 TDataStd_Integer::Set(aDoc->Main(), theDocID);
389 //=============================================================================
393 //=============================================================================
394 void GEOM_Engine::Close(int theDocID)
396 if (_mapIDDocument.IsBound(theDocID)) {
397 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
399 //Remove all GEOM Objects associated to the given document
400 TColStd_SequenceOfAsciiString aSeq;
401 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It (_objects);
402 for (; It.More(); It.Next()) {
403 TCollection_AsciiString anObjID (It.Key());
404 Standard_Integer anID = ExtractDocID(anObjID);
405 if (theDocID == anID) aSeq.Append(It.Key());
407 for (Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
409 _lastCleared.Nullify();
411 _mapIDDocument.UnBind(theDocID);
412 _OCAFApp->Close(aDoc);
417 //=============================================================================
421 //=============================================================================
422 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
423 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
427 TCollection_AsciiString aScript;
428 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
430 if(aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
432 aScript = "import geompy\n";
433 aScript += "import math\n";
434 aScript += "import SALOMEDS\n\n";
435 aScript += "def RebuildData(theStudy):";
436 aScript += "\n\tgeompy.init_geom(theStudy)";
438 Standard_Integer posToInertGlobalVars = aScript.Length() + 1;
440 Handle(TDataStd_TreeNode) aNode, aRoot;
441 Handle(GEOM_Function) aFunction;
442 TColStd_MapOfTransient aMap;
444 if(aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
445 TDataStd_ChildNodeIterator Itr(aRoot);
446 for(; Itr.More(); Itr.Next()) {
448 aFunction = GEOM_Function::GetFunction(aNode->Label());
449 if(aFunction.IsNull()) {
450 MESSAGE ( "Null function !!!!" );
453 ProcessFunction(aFunction, aScript, aMap);
457 Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
458 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
459 // build maps entry <-> studyEntry
460 for (anEntryToNameIt.Initialize( theObjectNames );
461 anEntryToNameIt.More();
462 anEntryToNameIt.Next())
464 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
465 // look for an object by entry
467 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
468 if ( L.IsNull() ) continue;
469 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
471 if ( !obj.IsNull() ) {
472 TCollection_AsciiString aStudyEntry (obj->GetAuxData());
473 aEntry2StEntry.Bind( aEntry, aStudyEntry);
474 aStEntry2Entry.Bind( aStudyEntry, aEntry );
478 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
479 Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
480 Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
482 //Replace entries by the names
483 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
484 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
485 if(aLen == 0) anUpdatedScript = aScript;
487 for(Standard_Integer i = 1; i <= aLen; i+=2) {
488 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
489 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
490 if(theObjectNames.IsBound(anEntry)) {
491 aName = theObjectNames.Find(anEntry);
492 // check validity of aName
493 bool isValidName = true;
494 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
495 aName.Insert( 1, 'a' );
498 int p, p2=1; // replace not allowed chars
499 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
500 aName.SetValue(p, '_');
504 if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
505 { // diff objects have same name - make a new name by appending a digit
506 TCollection_AsciiString aName2;
507 Standard_Integer i = 0;
509 aName2 = aName + "_" + ++i;
510 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
514 if ( !isValidName ) {
516 anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
517 theObjectNames( anEntry ) = aName;
522 aName = aBaseName + TCollection_AsciiString(++objectCounter);
523 } while(aNameToEntry.IsBound(aName));
524 theObjectNames.Bind(anEntry, aName);
526 aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
528 anUpdatedScript += aName;
529 aStart = aSeq->Value(i+1) + 1;
532 //Add final part of the script
533 if(aLen && aSeq->Value(aLen) < aScriptLength) anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
536 for (anEntryToNameIt.Initialize( theObjectNames );
537 anEntryToNameIt.More();
538 anEntryToNameIt.Next())
540 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
541 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
544 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
548 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
552 bool anAutoColor = obj->GetAutoColor();
555 TCollection_AsciiString aCommand( "\n\t" );
556 aCommand += aName + ".SetAutoColor(1)";
557 anUpdatedScript += aCommand.ToCString();
560 SALOMEDS::Color aColor = obj->GetColor();
561 if ( aColor.R > 0 || aColor.G > 0 || aColor.B > 0 )
563 TCollection_AsciiString aCommand( "\n\t" );
564 aCommand += aName + ".SetColor(SALOMEDS.Color(" + aColor.R + "," + aColor.G + "," + aColor.B + "))";
565 anUpdatedScript += aCommand.ToCString();
569 // Make script to publish in study
572 std::map< int, std::string > anEntryToCommandMap; // sort publishing commands by object entry
573 for (anEntryToNameIt.Initialize( theObjectNames );
574 anEntryToNameIt.More();
575 anEntryToNameIt.Next())
577 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
578 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
579 if ( !aEntry2StEntry.IsBound( aEntry ))
580 continue; // was not published
581 TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
583 // find a father entry
584 const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
585 TCollection_AsciiString aFatherStudyEntry =
586 aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
587 if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
588 aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
591 if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
592 aCommand += "addToStudyInFather( ";
593 aCommand += theObjectNames( aFatherEntry ) + ", ";
596 aCommand += "addToStudy( ";
597 if ( anEntryToBadName.IsBound( aEntry ))
598 aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
600 aCommand += aName + ", \"" + aName + "\" )";
602 // bind a command to the last digit of the entry
604 aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
605 anEntryToCommandMap.insert( std::make_pair( tag, aCommand.ToCString() ));
608 // add publishing commands to the script
609 std::map< int, std::string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
610 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
611 anUpdatedScript += (char*)anEntryToCommand->second.c_str();
615 anUpdatedScript += "\n\tpass\n";
618 // fill _studyEntry2NameMap and build globalVars
619 TCollection_AsciiString globalVars;
620 _studyEntry2NameMap.Clear();
621 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
622 for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
623 aStEntryToEntryIt.More();
624 aStEntryToEntryIt.Next() )
626 const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
627 _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
628 if ( !globalVars.IsEmpty() )
632 if ( !globalVars.IsEmpty() ) {
633 globalVars.Insert( 1, "\n\tglobal " );
634 anUpdatedScript.Insert( posToInertGlobalVars, globalVars );
637 return anUpdatedScript;
640 //=======================================================================
641 //function : GetDumpName
643 //=======================================================================
645 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
647 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
648 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
653 //=======================================================================
654 //function : GetAllDumpNames
656 //=======================================================================
658 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
660 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
662 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
663 for (; it.More(); it.Next()) {
664 aRetSeq->Append(it.Value());
671 //===========================================================================
672 // Internal functions
673 //===========================================================================
674 void ProcessFunction(Handle(GEOM_Function)& theFunction,
675 TCollection_AsciiString& theScript,
676 TColStd_MapOfTransient& theProcessed)
678 if(theFunction.IsNull() || theProcessed.Contains(theFunction)) return;
681 TDF_LabelSequence aSeq;
682 theFunction->GetDependency(aSeq);
683 Standard_Integer aLen = aSeq.Length();
684 for(Standard_Integer i = 1; i<= aLen; i++) {
685 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aSeq.Value(i));
686 if(aFunction.IsNull()) continue;
687 ProcessFunction(aFunction, theScript, theProcessed);
691 TCollection_AsciiString aDescr = theFunction->GetDescription();
692 if(aDescr.Length() == 0) {
693 //cout << "Warning: the function has no description" << endl;
696 //Check if its internal function which doesn't requires dumping
697 if(aDescr == "None") return;
702 theProcessed.Add(theFunction);
706 //=============================================================================
708 * FindEntries: Returns a sequence of start/end positions of entries in the string
710 //=============================================================================
711 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
713 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
714 Standard_Integer aLen = theString.Length();
715 Standard_Boolean isFound = Standard_False;
717 char* arr = theString.ToCString();
718 Standard_Integer i = 0, j;
723 if(c >= 48 && c <= 57) { //Is digit?
725 isFound = Standard_False;
726 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
728 if(c == 58) isFound = Standard_True;
731 if(isFound && arr[j-2] != 58) { // last char should be a diggit
732 aSeq->Append(i+1); // +1 because AsciiString starts from 1