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_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
60 static GEOM_Engine* TheEngine = NULL;
62 static TCollection_AsciiString BuildIDFromObject(Handle(GEOM_Object)& theObject)
64 TCollection_AsciiString anID(theObject->GetDocID()), anEntry;
65 TDF_Tool::Entry(theObject->GetEntry(), anEntry);
66 anID+=(TCollection_AsciiString("_")+anEntry);
70 static TCollection_AsciiString BuildID(Standard_Integer theDocID, char* theEntry)
72 TCollection_AsciiString anID(theDocID);
73 anID+=(TCollection_AsciiString("_")+theEntry);
77 static Standard_Integer ExtractDocID(TCollection_AsciiString& theID)
79 TCollection_AsciiString aDocID = theID.Token("_");
80 if(aDocID.Length() < 1) return -1;
81 return aDocID.IntegerValue();
84 void ProcessFunction(Handle(GEOM_Function)& theFunction,
85 TCollection_AsciiString& theScript,
86 TColStd_MapOfTransient& theProcessed);
88 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString);
90 //=============================================================================
94 //=============================================================================
95 GEOM_Engine* GEOM_Engine::GetEngine() { return TheEngine; }
98 //=============================================================================
102 //=============================================================================
103 void GEOM_Engine::SetEngine(GEOM_Engine* theEngine) { TheEngine = theEngine; }
105 //=============================================================================
109 //=============================================================================
110 GEOM_Engine::GEOM_Engine()
112 TFunction_DriverTable::Get()->AddDriver(GEOM_Object::GetSubShapeID(), new GEOM_SubShapeDriver());
114 _OCAFApp = new GEOM_Application();
118 //=============================================================================
122 //=============================================================================
123 Handle(TDocStd_Document) GEOM_Engine::GetDocument(int theDocID)
125 Handle(TDocStd_Document) aDoc;
126 if(!_mapIDDocument.IsBound(theDocID)) {
127 _OCAFApp->NewDocument("SALOME_GEOM", aDoc);
128 aDoc->SetUndoLimit(_UndoLimit);
129 _mapIDDocument.Bind(theDocID, aDoc);
130 TDataStd_Integer::Set(aDoc->Main(), theDocID);
133 return Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
136 //=============================================================================
140 //=============================================================================
141 int GEOM_Engine::GetDocID(Handle(TDocStd_Document) theDocument)
143 if(theDocument.IsNull()) return -1;
144 for(Interface_DataMapIteratorOfDataMapOfIntegerTransient anItr(_mapIDDocument); anItr.More(); anItr.Next())
145 if(anItr.Value() == theDocument) return anItr.Key();
151 //=============================================================================
155 //=============================================================================
156 Handle(GEOM_Object) GEOM_Engine::GetObject(int theDocID, char* theEntry)
158 TCollection_AsciiString anID = BuildID(theDocID, theEntry);
159 if(_objects.IsBound(anID)) return Handle(GEOM_Object)::DownCast(_objects(anID));
162 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
163 TDF_Tool::Label(aDoc->Main().Data(), theEntry, aLabel, Standard_True);
164 Handle(GEOM_Object) anObject = new GEOM_Object(aLabel);
166 _objects.Bind(anID, anObject);
171 //=============================================================================
175 //=============================================================================
176 Handle(GEOM_Object) GEOM_Engine::AddObject(int theDocID, int theType)
178 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
179 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
181 TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
182 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, theType);
184 //Put an object in the map of created objects
185 TCollection_AsciiString anID = BuildIDFromObject(anObject);
186 if(_objects.IsBound(anID)) _objects.UnBind(anID);
187 _objects.Bind(anID, anObject);
192 //=============================================================================
196 //=============================================================================
197 Handle(GEOM_Object) GEOM_Engine::AddSubShape(Handle(GEOM_Object) theMainShape,
198 Handle(TColStd_HArray1OfInteger) theIndices,
199 bool isStandaloneOperation)
201 if(theMainShape.IsNull() || theIndices.IsNull()) return NULL;
203 Handle(TDocStd_Document) aDoc = GetDocument(theMainShape->GetDocID());
204 Handle(TDataStd_TreeNode) aRoot = TDataStd_TreeNode::Set(aDoc->Main());
206 TDF_Label aChild = TDF_TagSource::NewChild(aDoc->Main());
208 Handle(GEOM_Function) aMainShape = theMainShape->GetLastFunction();
209 Handle(GEOM_Object) anObject = new GEOM_Object(aChild, 28); //28 is SUBSHAPE type
210 Handle(GEOM_Function) aFunction = anObject->AddFunction(GEOM_Object::GetSubShapeID(), 1);
212 GEOM_ISubShape aSSI(aFunction);
213 aSSI.SetMainShape(aMainShape);
214 aSSI.SetIndices(theIndices);
217 GEOM_Solver aSolver (GEOM_Engine::GetEngine());
218 if (!aSolver.ComputeFunction(aFunction)) {
219 MESSAGE("GEOM_Engine::AddSubShape Error: Can't build a sub shape");
223 catch (Standard_Failure) {
224 Handle(Standard_Failure) aFail = Standard_Failure::Caught();
225 MESSAGE("GEOM_Engine::AddSubShape Error: " << aFail->GetMessageString());
229 //Put an object in the map of created objects
230 TCollection_AsciiString anID = BuildIDFromObject(anObject);
231 if(_objects.IsBound(anID)) _objects.UnBind(anID);
232 _objects.Bind(anID, anObject);
234 GEOM::TPythonDump pd (aFunction);
236 if (isStandaloneOperation) {
237 pd << anObject << " = geompy.GetSubShape(" << theMainShape << ", [";
238 Standard_Integer i = theIndices->Lower(), up = theIndices->Upper();
239 for (; i <= up - 1; i++) {
240 pd << theIndices->Value(i) << ", ";
242 pd << theIndices->Value(up) << "])";
250 //=============================================================================
254 //=============================================================================
255 bool GEOM_Engine::RemoveObject(Handle(GEOM_Object) theObject)
257 if(!theObject) return false;
259 //Remove an object from the map of available objects
260 TCollection_AsciiString anID = BuildIDFromObject(theObject);
261 if(_objects.IsBound(anID)) _objects.UnBind(anID);
263 int nb = theObject->GetNbFunctions();
264 Handle(TDataStd_TreeNode) aNode;
265 for(int i = 1; i<=nb; i++) {
266 Handle(GEOM_Function) aFunction = theObject->GetFunction(i);
267 if(aFunction->GetEntry().FindAttribute(GEOM_Function::GetFunctionTreeID(), aNode))
271 TDF_Label aLabel = theObject->GetEntry();
272 aLabel.ForgetAllAttributes(Standard_True);
279 //=============================================================================
283 //=============================================================================
284 void GEOM_Engine::Undo(int theDocID)
286 GetDocument(theDocID)->Undo();
289 //=============================================================================
293 //=============================================================================
294 void GEOM_Engine::Redo(int theDocID)
296 GetDocument(theDocID)->Redo();
299 //=============================================================================
303 //=============================================================================
304 bool GEOM_Engine::Save(int theDocID, char* theFileName)
306 if(!_mapIDDocument.IsBound(theDocID)) return false;
307 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
309 _OCAFApp->SaveAs(aDoc, theFileName);
314 //=============================================================================
318 //=============================================================================
319 bool GEOM_Engine::Load(int theDocID, char* theFileName)
321 Handle(TDocStd_Document) aDoc;
322 if(_OCAFApp->Open(theFileName, aDoc) != CDF_RS_OK) {
326 aDoc->SetUndoLimit(_UndoLimit);
328 if(_mapIDDocument.IsBound(theDocID)) _mapIDDocument.UnBind(theDocID);
329 _mapIDDocument.Bind(theDocID, aDoc);
331 TDataStd_Integer::Set(aDoc->Main(), theDocID);
336 //=============================================================================
340 //=============================================================================
341 void GEOM_Engine::Close(int theDocID)
343 if(_mapIDDocument.IsBound(theDocID)) {
344 Handle(TDocStd_Document) aDoc = Handle(TDocStd_Document)::DownCast(_mapIDDocument(theDocID));
346 //Remove all GEOM Objects associated to the given document
347 TColStd_SequenceOfAsciiString aSeq;
348 GEOM_DataMapIteratorOfDataMapOfAsciiStringTransient It(_objects);
349 for(; It.More(); It.Next()) {
350 TCollection_AsciiString anObjID(It.Key());
351 Standard_Integer anID = ExtractDocID(anObjID);
352 if(theDocID == anID) aSeq.Append(It.Key());
354 for(Standard_Integer i=1; i<=aSeq.Length(); i++) _objects.UnBind(aSeq.Value(i));
356 _mapIDDocument.UnBind(theDocID);
357 _OCAFApp->Close(aDoc);
362 //=============================================================================
366 //=============================================================================
367 TCollection_AsciiString GEOM_Engine::DumpPython(int theDocID,
368 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
372 TCollection_AsciiString aScript;
373 Handle(TDocStd_Document) aDoc = GetDocument(theDocID);
375 if(aDoc.IsNull()) return TCollection_AsciiString("def RebuildData(theStudy): pass\n");
377 aScript = "import geompy\n";
378 aScript += "import math\n\n";
379 aScript += "def RebuildData(theStudy):";
380 aScript += "\n\tgeompy.init_geom(theStudy)";
382 Standard_Integer posToInertGlobalVars = aScript.Length() + 1;
384 Handle(TDataStd_TreeNode) aNode, aRoot;
385 Handle(GEOM_Function) aFunction;
386 TColStd_MapOfTransient aMap;
388 if(aDoc->Main().FindAttribute(GEOM_Function::GetFunctionTreeID(), aRoot)) {
389 TDataStd_ChildNodeIterator Itr(aRoot);
390 for(; Itr.More(); Itr.Next()) {
392 aFunction = GEOM_Function::GetFunction(aNode->Label());
393 if(aFunction.IsNull()) {
394 cout << "Null function !!!!" << endl;
397 ProcessFunction(aFunction, aScript, aMap);
401 Resource_DataMapOfAsciiStringAsciiString aEntry2StEntry, aStEntry2Entry;
402 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString anEntryToNameIt;
403 // build maps entry <-> studyEntry
404 for (anEntryToNameIt.Initialize( theObjectNames );
405 anEntryToNameIt.More();
406 anEntryToNameIt.Next())
408 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
409 // look for an object by entry
411 TDF_Tool::Label( aDoc->GetData(), aEntry, L );
412 if ( L.IsNull() ) continue;
413 Handle(GEOM_Object) obj = GEOM_Object::GetObject( L );
415 if ( !obj.IsNull() ) {
416 TCollection_AsciiString aStudyEntry (obj->GetAuxData());
417 aEntry2StEntry.Bind( aEntry, aStudyEntry);
418 aStEntry2Entry.Bind( aStudyEntry, aEntry );
422 Handle(TColStd_HSequenceOfInteger) aSeq = FindEntries(aScript);
423 Standard_Integer aLen = aSeq->Length(), objectCounter = 0, aStart = 1, aScriptLength = aScript.Length();
424 Resource_DataMapOfAsciiStringAsciiString aNameToEntry, anEntryToBadName;
426 //Replace entries by the names
427 TCollection_AsciiString anUpdatedScript, anEntry, aName, aBaseName("geomObj_"),
428 allowedChars ("qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM0987654321_");
429 if(aLen == 0) anUpdatedScript = aScript;
431 for(Standard_Integer i = 1; i <= aLen; i+=2) {
432 anUpdatedScript += aScript.SubString(aStart, aSeq->Value(i)-1);
433 anEntry = aScript.SubString(aSeq->Value(i), aSeq->Value(i+1));
434 if(theObjectNames.IsBound(anEntry)) {
435 aName = theObjectNames.Find(anEntry);
436 // check validity of aName
437 bool isValidName = true;
438 if ( aName.IsIntegerValue() ) { // aName must not start with a digit
439 aName.Insert( 1, 'a' );
442 int p, p2=1; // replace not allowed chars
443 while ((p = aName.FirstLocationNotInSet(allowedChars, p2, aName.Length()))) {
444 aName.SetValue(p, '_');
448 if ( aNameToEntry.IsBound( aName ) && anEntry != aNameToEntry( aName ))
449 { // diff objects have same name - make a new name by appending a digit
450 TCollection_AsciiString aName2;
451 Standard_Integer i = 0;
453 aName2 = aName + "_" + ++i;
454 } while ( aNameToEntry.IsBound( aName2 ) && anEntry != aNameToEntry( aName2 ));
458 if ( !isValidName ) {
460 anEntryToBadName.Bind( anEntry, theObjectNames.Find(anEntry) );
461 theObjectNames( anEntry ) = aName;
466 aName = aBaseName + TCollection_AsciiString(++objectCounter);
467 } while(aNameToEntry.IsBound(aName));
468 theObjectNames.Bind(anEntry, aName);
470 aNameToEntry.Bind(aName, anEntry); // to detect same name of diff objects
472 anUpdatedScript += aName;
473 aStart = aSeq->Value(i+1) + 1;
476 //Add final part of the script
477 if(aLen && aSeq->Value(aLen) < aScriptLength) anUpdatedScript += aScript.SubString(aSeq->Value(aLen)+1, aScriptLength); // mkr : IPAL11865
479 // Make script to publish in study
482 map< int, string > anEntryToCommandMap; // sort publishing commands by object entry
483 for (anEntryToNameIt.Initialize( theObjectNames );
484 anEntryToNameIt.More();
485 anEntryToNameIt.Next())
487 const TCollection_AsciiString& aEntry = anEntryToNameIt.Key();
488 const TCollection_AsciiString& aName = anEntryToNameIt.Value();
489 if ( !aEntry2StEntry.IsBound( aEntry ))
490 continue; // was not published
491 TCollection_AsciiString aCommand("\n\tgeompy."), aFatherEntry;
493 // find a father entry
494 const TCollection_AsciiString& aStudyEntry = aEntry2StEntry( aEntry );
495 TCollection_AsciiString aFatherStudyEntry =
496 aStudyEntry.SubString( 1, aStudyEntry.SearchFromEnd(":") - 1 );
497 if ( aStEntry2Entry.IsBound( aFatherStudyEntry ))
498 aFatherEntry = aStEntry2Entry( aFatherStudyEntry );
501 if ( !aFatherEntry.IsEmpty() && theObjectNames.IsBound( aFatherEntry )) {
502 aCommand += "addToStudyInFather( ";
503 aCommand += theObjectNames( aFatherEntry ) + ", ";
506 aCommand += "addToStudy( ";
507 if ( anEntryToBadName.IsBound( aEntry ))
508 aCommand += aName + ", \"" + anEntryToBadName( aEntry ) + "\" )";
510 aCommand += aName + ", \"" + aName + "\" )";
512 // bind a command to the last digit of the entry
514 aEntry.SubString( aEntry.SearchFromEnd(":")+1, aEntry.Length() ).IntegerValue();
515 anEntryToCommandMap.insert( make_pair( tag, aCommand.ToCString() ));
518 // add publishing commands to the script
519 map< int, string >::iterator anEntryToCommand = anEntryToCommandMap.begin();
520 for ( ; anEntryToCommand != anEntryToCommandMap.end(); ++anEntryToCommand ) {
521 anUpdatedScript += (char*)anEntryToCommand->second.c_str();
525 anUpdatedScript += "\n\tpass\n";
528 // fill _studyEntry2NameMap and build globalVars
529 TCollection_AsciiString globalVars;
530 _studyEntry2NameMap.Clear();
531 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString aStEntryToEntryIt;
532 for (aStEntryToEntryIt.Initialize( aStEntry2Entry );
533 aStEntryToEntryIt.More();
534 aStEntryToEntryIt.Next() )
536 const TCollection_AsciiString & name = theObjectNames( aStEntryToEntryIt.Value() );
537 _studyEntry2NameMap.Bind (aStEntryToEntryIt.Key(), name );
538 if ( !globalVars.IsEmpty() )
542 if ( !globalVars.IsEmpty() ) {
543 globalVars.Insert( 1, "\n\tglobal " );
544 anUpdatedScript.Insert( posToInertGlobalVars, globalVars );
547 return anUpdatedScript;
550 //=======================================================================
551 //function : GetDumpName
553 //=======================================================================
555 const char* GEOM_Engine::GetDumpName (const char* theStudyEntry) const
557 if ( _studyEntry2NameMap.IsBound( (char*)theStudyEntry ))
558 return _studyEntry2NameMap( (char*)theStudyEntry ).ToCString();
563 //=======================================================================
564 //function : GetAllDumpNames
566 //=======================================================================
568 Handle(TColStd_HSequenceOfAsciiString) GEOM_Engine::GetAllDumpNames() const
570 Handle(TColStd_HSequenceOfAsciiString) aRetSeq = new TColStd_HSequenceOfAsciiString;
572 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString it (_studyEntry2NameMap);
573 for (; it.More(); it.Next()) {
574 aRetSeq->Append(it.Value());
581 //===========================================================================
582 // Internal functions
583 //===========================================================================
584 void ProcessFunction(Handle(GEOM_Function)& theFunction,
585 TCollection_AsciiString& theScript,
586 TColStd_MapOfTransient& theProcessed)
588 if(theFunction.IsNull() || theProcessed.Contains(theFunction)) return;
591 TDF_LabelSequence aSeq;
592 theFunction->GetDependency(aSeq);
593 Standard_Integer aLen = aSeq.Length();
594 for(Standard_Integer i = 1; i<= aLen; i++) {
595 Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(aSeq.Value(i));
596 if(aFunction.IsNull()) continue;
597 ProcessFunction(aFunction, theScript, theProcessed);
601 TCollection_AsciiString aDescr = theFunction->GetDescription();
602 if(aDescr.Length() == 0) {
603 //cout << "Warning: the function has no description" << endl;
606 //Check if its internal function which doesn't requires dumping
607 if(aDescr == "None") return;
612 theProcessed.Add(theFunction);
616 //=============================================================================
618 * FindEntries: Returns a sequence of start/end positions of entries in the string
620 //=============================================================================
621 Handle(TColStd_HSequenceOfInteger) FindEntries(TCollection_AsciiString& theString)
623 Handle(TColStd_HSequenceOfInteger) aSeq = new TColStd_HSequenceOfInteger;
624 Standard_Integer aLen = theString.Length();
625 Standard_Boolean isFound = Standard_False;
627 char* arr = theString.ToCString();
628 Standard_Integer i = 0, j;
633 if(c >= 48 && c <= 57) { //Is digit?
635 isFound = Standard_False;
636 while((j < aLen) && ((c >= 48 && c <= 57) || c == 58) ) { //Check if it is an entry
638 if(c == 58) isFound = Standard_True;
641 if(isFound && arr[j-2] != 58) { // last char should be a diggit
642 aSeq->Append(i+1); // +1 because AsciiString starts from 1