1 // Copyright (C) 2007-2012 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.
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
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
34 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
36 #include "SMESH_Gen_i.hxx"
37 /* SALOME headers that include CORBA headers that include windows.h
38 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
39 * that declare methods named GetObject - to apply the same rules of GetObject renaming
40 * and thus to avoid mess with GetObject symbol on Windows */
42 #include <LDOMParser.hxx>
51 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
52 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
53 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
54 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
55 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
56 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
57 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
63 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
64 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
68 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
71 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
84 using SMESH::TPythonDump;
87 * \brief Container of commands into which the initial script is split.
88 * It also contains data coresponding to SMESH_Gen contents
90 static Handle(_pyGen) theGen;
92 static TCollection_AsciiString theEmptyString;
94 //#define DUMP_CONVERSION
96 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
97 #undef DUMP_CONVERSION
103 //================================================================================
105 * \brief Set of TCollection_AsciiString initialized by C array of C strings
107 //================================================================================
109 struct TStringSet: public set<TCollection_AsciiString>
112 * \brief Filling. The last string must be ""
114 void Insert(const char* names[]) {
115 for ( int i = 0; names[i][0] ; ++i )
116 insert( (char*) names[i] );
119 * \brief Check if a string is in
121 bool Contains(const TCollection_AsciiString& name ) {
122 return find( name ) != end();
126 //================================================================================
128 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
129 * Odd items of the C array are map keys, and even items are values
131 //================================================================================
133 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
136 * \brief Filling. The last string must be ""
138 void Insert(const char* names_values[]) {
139 for ( int i = 0; names_values[i][0] ; i += 2 )
140 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
143 * \brief Check if a string is in
145 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
146 map< _AString, _AString >::iterator it = find( name );
147 return it == end() ? "" : it->second;
151 //================================================================================
153 * \brief Returns a mesh by object
155 //================================================================================
157 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
161 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
162 return Handle(_pyMesh)::DownCast( obj );
163 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
164 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
165 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
166 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
168 return Handle(_pyMesh)();
171 //================================================================================
173 * \brief Check if objects used as args have been created by previous commands
175 //================================================================================
177 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
179 // either comment or erase a command including NotPublishedObjectName()
180 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
182 bool isResultPublished = false;
183 for ( int i = 0; i < cmd->GetNbResultValues(); i++ )
185 _pyID objID = cmd->GetResultValue( i+1 );
186 if ( cmd->IsStudyEntry( objID ))
187 isResultPublished = (! theGen->IsNotPublished( objID ));
188 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
190 if ( isResultPublished )
196 // check if an Object was created in the script
198 const _pyID& obj = cmd->GetObject();
199 const bool isMethodCall = cmd->IsMethodCall();
200 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
202 comment = "not created Object";
203 theGen->ObjectCreationRemoved( obj );
205 // check if a command has not created args
206 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
208 const _pyID& arg = cmd->GetArg( iArg );
209 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
211 list< _pyID > idList = cmd->GetStudyEntries( arg );
212 list< _pyID >::iterator id = idList.begin();
213 for ( ; id != idList.end(); ++id )
214 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
216 comment += *id + " has not been yet created";
219 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
220 // comment += arg + " has not been yet created";
222 // treat result objects
223 const _pyID& result = cmd->GetResultValue();
224 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
226 list< _pyID > idList = cmd->GetStudyEntries( result );
227 list< _pyID >::iterator id = idList.begin();
228 for ( ; id != idList.end(); ++id )
230 if ( comment.IsEmpty() )
231 presentObjects.insert( *id );
233 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
235 if ( idList.empty() && cmd->IsID( result ))
236 presentObjects.insert( result );
238 // comment the command
239 if ( !comment.IsEmpty() )
242 cmd->GetString() += " ### ";
243 cmd->GetString() += comment;
247 //================================================================================
249 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
251 //================================================================================
253 void fixFunctorType( TCollection_AsciiString& Type,
254 TCollection_AsciiString& Compare,
255 TCollection_AsciiString& UnaryOp,
256 TCollection_AsciiString& BinaryOp )
258 // The problem is that dumps of old studies created using filters becomes invalid
259 // when new items are inserted in the enum SMESH::FunctorType since values
260 // of this enum are dumped as integer values.
261 // This function corrects enum values of old studies given as args (Type,Compare,...)
262 // We can find out how to correct them by value of BinaryOp which can have only two
263 // values: FT_Undefined or FT_LogicalNOT.
264 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
265 // where PythonDump appeared
266 // v 3.0.0: FT_Undefined == 25
267 // v 3.1.0: FT_Undefined == 26, new items:
269 // v 4.1.2: FT_Undefined == 27, new items:
270 // - FT_BelongToGenSurface = 17
271 // v 5.1.1: FT_Undefined == 32, new items:
272 // - FT_FreeNodes = 10
273 // - FT_FreeFaces = 11
274 // - FT_LinearOrQuadratic = 23
275 // - FT_GroupColor = 24
276 // - FT_ElemGeomType = 25
277 // v 5.1.5: FT_Undefined == 33, new items:
278 // - FT_CoplanarFaces = 26
279 // v 6.2.0: FT_Undefined == 39, new items:
280 // - FT_MaxElementLength2D = 8
281 // - FT_MaxElementLength3D = 9
282 // - FT_BareBorderVolume = 25
283 // - FT_BareBorderFace = 26
284 // - FT_OverConstrainedVolume = 27
285 // - FT_OverConstrainedFace = 28
286 // v 6.5.0: FT_Undefined == 43, new items:
287 // - FT_EqualNodes = 14
288 // - FT_EqualEdges = 15
289 // - FT_EqualFaces = 16
290 // - FT_EqualVolumes = 17
291 // v 6.6.0: FT_Undefined == 44, new items:
292 // - FT_BallDiameter = 37
293 // v 6.7.1: FT_Undefined == 45, new items:
294 // - FT_EntityType = 36
295 // v 7.3.0: FT_Undefined == 46, new items:
296 // - FT_ConnectedElements = 39
298 // It's necessary to continue recording this history and to fill
299 // undef2newItems (see below) accordingly.
301 typedef map< int, vector< int > > TUndef2newItems;
302 static TUndef2newItems undef2newItems;
303 if ( undef2newItems.empty() )
305 undef2newItems[ 26 ].push_back( 7 );
306 undef2newItems[ 27 ].push_back( 17 );
307 { int items[] = { 10, 11, 23, 24, 25 };
308 undef2newItems[ 32 ].assign( items, items+5 ); }
309 undef2newItems[ 33 ].push_back( 26 );
310 { int items[] = { 8, 9, 25, 26, 27, 28 };
311 undef2newItems[ 39 ].assign( items, items+6 ); }
312 { int items[] = { 14, 15, 16, 17 };
313 undef2newItems[ 43 ].assign( items, items+4 ); }
316 int iType = Type.IntegerValue();
317 int iCompare = Compare.IntegerValue();
318 int iUnaryOp = UnaryOp.IntegerValue();
319 int iBinaryOp = BinaryOp.IntegerValue();
321 // find out integer value of FT_Undefined at the moment of dump
322 int oldUndefined = iBinaryOp;
323 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
326 // apply history to args
327 TUndef2newItems::const_iterator undef_items =
328 undef2newItems.upper_bound( oldUndefined );
329 if ( undef_items != undef2newItems.end() )
331 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
332 for ( ; undef_items != undef2newItems.end(); ++undef_items )
334 const vector< int > & addedItems = undef_items->second;
335 for ( size_t i = 0; i < addedItems.size(); ++i )
336 for ( int iArg = 0; iArg < 4; ++iArg )
338 int& arg = *pArg[iArg];
339 if ( arg >= addedItems[i] )
343 Type = TCollection_AsciiString( iType );
344 Compare = TCollection_AsciiString( iCompare );
345 UnaryOp = TCollection_AsciiString( iUnaryOp );
346 BinaryOp = TCollection_AsciiString( iBinaryOp );
350 //================================================================================
352 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
353 * arguments of a given command by a list "[x,y,z]" if the list is accesible
356 //================================================================================
358 void StructToList( Handle( _pyCommand)& theCommand )
360 static TStringSet methodsAcceptingList;
361 if ( methodsAcceptingList.empty() ) {
362 const char * methodNames[] = {
363 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
364 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
365 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
366 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
367 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
368 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
369 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
370 "Translate","TranslateMakeGroups","TranslateMakeMesh",
371 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
372 "ExtrusionAlongPathX","ExtrusionAlongPathObjX"
373 ,"" }; // <- mark of the end
374 methodsAcceptingList.Insert( methodNames );
376 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
378 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
380 const _AString & arg = theCommand->GetArg( i );
381 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
382 arg.Search( "SMESH.DirStruct" ) == 1 )
384 Handle(_pyCommand) workCmd = new _pyCommand( arg );
385 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
387 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
389 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
391 _AString newArg = "[ ";
392 newArg += ( workCmd->GetArg( 1 ) + ", " +
393 workCmd->GetArg( 2 ) + ", " +
394 workCmd->GetArg( 3 ) + " ]");
395 theCommand->SetArg( i, newArg );
401 //================================================================================
403 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
404 * a list "[id1,id2]" if the list is an accesible type of argument.
406 //================================================================================
408 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
410 static TStringSet methodsAcceptingList;
411 if ( methodsAcceptingList.empty() ) {
412 const char * methodNames[] = {
413 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
414 "ExportCGNS","ExportGMF",
415 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
416 "ScaleMakeGroups","Scale","ScaleMakeMesh",
417 "FindCoincidentNodesOnPartBut","DoubleElements"
418 ,"" }; // <- mark of the end
419 methodsAcceptingList.Insert( methodNames );
421 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
423 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
425 _pyCommand argCmd( theCommand->GetArg( i ));
426 if ( argCmd.GetMethod() == "GetIDSource" &&
427 argCmd.GetNbArgs() == 2 )
429 theCommand->SetArg( i, argCmd.GetArg( 1 ));
436 //================================================================================
438 * \brief Convert a python script using commands of smesh.py
439 * \param theScript - Input script
440 * \param theEntry2AccessorMethod - returns method names to access to
441 * objects wrapped with python class
442 * \param theObjectNames - names of objects
443 * \param theRemovedObjIDs - entries of objects whose created commands were removed
444 * \param theHistoricalDump - true means to keep all commands, false means
445 * to exclude commands relating to objects removed from study
446 * \retval TCollection_AsciiString - Convertion result
448 //================================================================================
450 TCollection_AsciiString
451 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
452 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
453 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
454 std::set< TCollection_AsciiString >& theRemovedObjIDs,
455 SALOMEDS::Study_ptr& theStudy,
456 const bool theToKeepAllCommands)
458 theGen = new _pyGen( theEntry2AccessorMethod,
462 theToKeepAllCommands );
464 // split theScript into separate commands
466 SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
468 int from = 1, end = theScript.Length(), to;
469 while ( from < end && ( to = theScript.Location( "\n", from, end )))
472 // cut out and store a command
473 aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
477 aNoteBook->ReplaceVariables();
479 TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
483 // split theScript into separate commands
484 from = 1, end = aNoteScript.Length();
485 while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
488 // cut out and store a command
489 theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
495 #ifdef DUMP_CONVERSION
496 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
499 // clean commmands of removed objects depending on myIsPublished flag
500 theGen->ClearCommands();
502 // reorder commands after conversion
503 list< Handle(_pyCommand) >::iterator cmd;
506 orderChanges = false;
507 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
508 if ( (*cmd)->SetDependentCmdsAfter() )
510 } while ( orderChanges );
512 // concat commands back into a script
513 TCollection_AsciiString aScript, aPrevCmd;
514 set<_pyID> createdObjects;
515 createdObjects.insert( "smeshBuilder" );
516 createdObjects.insert( "smesh" );
517 createdObjects.insert( "theStudy" );
518 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
520 #ifdef DUMP_CONVERSION
521 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
523 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
524 CheckObjectPresence( *cmd, createdObjects );
525 if ( !(*cmd)->IsEmpty() ) {
526 aPrevCmd = (*cmd)->GetString();
540 //================================================================================
542 * \brief _pyGen constructor
544 //================================================================================
546 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
547 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
548 std::set< TCollection_AsciiString >& theRemovedObjIDs,
549 SALOMEDS::Study_ptr& theStudy,
550 const bool theToKeepAllCommands)
551 : _pyObject( new _pyCommand( "", 0 )),
553 myID2AccessorMethod( theEntry2AccessorMethod ),
554 myObjectNames( theObjectNames ),
555 myRemovedObjIDs( theRemovedObjIDs ),
557 myToKeepAllCommands( theToKeepAllCommands ),
558 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
559 myGeomIDNb(0), myGeomIDIndex(-1)
561 // make that GetID() to return TPythonDump::SMESHGenName()
562 GetCreationCmd()->Clear();
563 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
564 GetCreationCmd()->GetString() += "=";
566 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
567 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
571 SALOMEDS::SComponent_var geomComp = theStudy->FindComponent("GEOM");
572 if ( geomComp->_is_nil() ) return;
573 CORBA::String_var entry = geomComp->GetID();
576 // find a SMESH entry
578 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
579 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
580 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
583 // find 1st difference between smeshID and geomID
584 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
585 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
586 if ( geomID.Value( i ) != smeshID.Value( i ))
588 myGeomIDNb = geomID.Value( i );
594 //================================================================================
596 * \brief name of SMESH_Gen in smesh.py
598 //================================================================================
600 const char* _pyGen::AccessorMethod() const
602 return SMESH_2smeshpy::GenName();
605 //================================================================================
607 * \brief Convert a command using a specific converter
608 * \param theCommand - the command to convert
610 //================================================================================
612 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
614 // store theCommand in the sequence
615 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
617 Handle(_pyCommand) aCommand = myCommands.back();
618 #ifdef DUMP_CONVERSION
619 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
622 const _pyID& objID = aCommand->GetObject();
624 if ( objID.IsEmpty() )
627 // Prevent moving a command creating a sub-mesh to the end of the script
628 // if the sub-mesh is used in theCommand as argument
629 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
631 // PlaceSubmeshAfterItsCreation( aCommand );
634 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
635 //StructToList( aCommand );
637 // not to erase _pySelfEraser's etc. used as args in some commands
639 #ifdef USE_STRING_FAMILY
641 if ( myKeepAgrCmdsIDs.IsIn( theCommand, objID ))
643 Handle(_pyObject) obj = FindObject( objID );
646 obj->AddArgCmd( aCommand );
647 //cout << objID << " found in " << theCommand << endl;
651 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
652 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
653 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
655 Handle(_pyObject) obj = FindObject( *id );
657 obj->AddArgCmd( aCommand );
662 // Find an object to process theCommand
665 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
667 this->Process( aCommand );
668 //addFilterUser( aCommand, theGen ); // protect filters from clearing
672 // SMESH_Mesh method?
673 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
674 if ( id_mesh != myMeshes.end() )
676 //id_mesh->second->AddProcessedCmd( aCommand );
678 // check for mesh editor object
679 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
680 _pyID editorID = aCommand->GetResultValue();
681 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
682 myMeshEditors.insert( make_pair( editorID, editor ));
685 // check for SubMesh objects
686 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
687 _pyID subMeshID = aCommand->GetResultValue();
688 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
689 CheckObjectIsReCreated( subMesh );
690 myObjects.insert( make_pair( subMeshID, subMesh ));
693 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
694 //GetIDSourceToList( aCommand );
696 //addFilterUser( aCommand, theGen ); // protect filters from clearing
698 id_mesh->second->Process( aCommand );
699 id_mesh->second->AddProcessedCmd( aCommand );
703 // SMESH_MeshEditor method?
704 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
705 if ( id_editor != myMeshEditors.end() )
707 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
708 //GetIDSourceToList( aCommand );
710 //addFilterUser( aCommand, theGen ); // protect filters from clearing
712 const TCollection_AsciiString& method = aCommand->GetMethod();
714 // some commands of SMESH_MeshEditor create meshes and groups
715 _pyID meshID, groups;
716 if ( method.Search("MakeMesh") != -1 )
717 meshID = aCommand->GetResultValue();
718 else if ( method == "MakeBoundaryMesh")
719 meshID = aCommand->GetResultValue(1);
720 else if ( method == "MakeBoundaryElements")
721 meshID = aCommand->GetResultValue(2);
723 if ( method.Search("MakeGroups") != -1 ||
724 method == "ExtrusionAlongPathX" ||
725 method == "ExtrusionAlongPathObjX" ||
726 method == "DoubleNodeGroupNew" ||
727 method == "DoubleNodeGroupsNew" ||
728 method == "DoubleNodeElemGroupNew" ||
729 method == "DoubleNodeElemGroupsNew"||
730 method == "DoubleNodeElemGroup2New"||
731 method == "DoubleNodeElemGroups2New"
733 groups = aCommand->GetResultValue();
734 else if ( method == "MakeBoundaryMesh" )
735 groups = aCommand->GetResultValue(2);
736 else if ( method == "MakeBoundaryElements")
737 groups = aCommand->GetResultValue(3);
738 else if ( method == "Create0DElementsOnAllNodes" &&
739 aCommand->GetArg(2).Length() > 2 ) // group name != ''
740 groups = aCommand->GetResultValue();
742 id_editor->second->Process( aCommand );
743 id_editor->second->AddProcessedCmd( aCommand );
746 if ( !meshID.IsEmpty() &&
747 !myMeshes.count( meshID ) &&
748 aCommand->IsStudyEntry( meshID ))
750 _AString processedCommand = aCommand->GetString();
751 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
752 CheckObjectIsReCreated( mesh );
753 myMeshes.insert( make_pair( meshID, mesh ));
755 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
758 if ( !groups.IsEmpty() )
760 if ( !aCommand->IsStudyEntry( meshID ))
761 meshID = id_editor->second->GetMesh();
762 Handle(_pyMesh) mesh = myMeshes[ meshID ];
764 list< _pyID > idList = aCommand->GetStudyEntries( groups );
765 list< _pyID >::iterator grID = idList.begin();
766 for ( ; grID != idList.end(); ++grID )
767 if ( !myObjects.count( *grID ))
769 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
771 if ( !mesh.IsNull() ) mesh->AddGroup( group );
775 } // SMESH_MeshEditor methods
777 // SMESH_Hypothesis method?
778 Handle(_pyHypothesis) hyp = FindHyp( objID );
779 if ( !hyp.IsNull() && !hyp->IsAlgo() )
781 hyp->Process( aCommand );
782 hyp->AddProcessedCmd( aCommand );
786 // aFilterManager.CreateFilter() ?
787 if ( aCommand->GetMethod() == "CreateFilter" )
789 // Set a more human readable name to a filter
790 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
791 _pyID newID, filterID = aCommand->GetResultValue();
792 int pos = filterID.Search( "0x" );
794 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
796 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
799 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
800 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
802 // create _pySelfEraser for functors
803 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
804 functor->IgnoreOwnCalls(); // to erase if not used as an argument
805 AddObject( functor );
808 // other object method?
809 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
810 if ( id_obj != myObjects.end() ) {
811 id_obj->second->Process( aCommand );
812 id_obj->second->AddProcessedCmd( aCommand );
816 // Add access to a wrapped mesh
817 AddMeshAccessorMethod( aCommand );
819 // Add access to a wrapped algorithm
820 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
822 // PAL12227. PythonDump was not updated at proper time; result is
823 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
824 // TypeError: __init__() takes exactly 11 arguments (10 given)
825 const char wrongCommand[] = "SMESH.Filter.Criterion(";
826 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
828 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
829 // there must be 10 arguments, 5-th arg ThresholdID is missing,
830 const int wrongNbArgs = 9, missingArg = 5;
831 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
833 for ( int i = wrongNbArgs; i > missingArg; --i )
834 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
835 tmpCmd.SetArg( missingArg, "''");
836 aCommand->GetString().Trunc( beg - 1 );
837 aCommand->GetString() += tmpCmd.GetString();
840 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
842 // instead of "SMESH.Filter.Criterion(
843 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
844 // 1 2 3 4 5 6 7 8 9 10
845 // in order to avoid the problem of type mismatch of long and FunctorType
846 const TCollection_AsciiString
847 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
848 TCollection_AsciiString
849 Type = aCommand->GetArg(1), // long
850 Compare = aCommand->GetArg(2), // long
851 Threshold = aCommand->GetArg(3), // double
852 ThresholdStr = aCommand->GetArg(4), // string
853 ThresholdID = aCommand->GetArg(5), // string
854 UnaryOp = aCommand->GetArg(6), // long
855 BinaryOp = aCommand->GetArg(7), // long
856 Tolerance = aCommand->GetArg(8), // double
857 TypeOfElement = aCommand->GetArg(9), // ElementType
858 Precision = aCommand->GetArg(10); // long
859 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
860 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
861 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
862 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
863 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
865 if ( Compare == "SMESH.FT_EqualTo" )
868 aCommand->RemoveArgs();
869 aCommand->SetObject( SMESH_2smeshpy::GenName() );
870 aCommand->SetMethod( "GetCriterion" );
872 aCommand->SetArg( 1, TypeOfElement );
873 aCommand->SetArg( 2, Type );
874 aCommand->SetArg( 3, Compare );
876 if ( Threshold.IsIntegerValue() )
878 int iGeom = Threshold.IntegerValue();
879 if ( Type == "SMESH.FT_ElemGeomType" )
881 // set SMESH.GeometryType instead of a numerical Threshold
882 const int nbTypes = SMESH::Geom_POLYHEDRA+1;
883 const char* types[nbTypes] = {
884 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
885 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
887 if ( -1 < iGeom && iGeom < nbTypes )
888 Threshold = SMESH + types[ iGeom ];
891 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
892 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
893 else if ( ThresholdStr.Length() != 2 )
894 aCommand->SetArg( 4, ThresholdStr );
895 else if ( ThresholdID.Length() != 2 )
896 aCommand->SetArg( 4, ThresholdID );
898 aCommand->SetArg( 4, Threshold );
899 // find the last not default arg
901 if ( Tolerance == dfltTol ) {
903 if ( BinaryOp == dfltFunctor ) {
905 if ( UnaryOp == dfltFunctor )
909 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
910 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
911 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
912 if ( Precision != dfltPreci )
914 TCollection_AsciiString crit = aCommand->GetResultValue();
915 aCommand->GetString() += "; ";
916 aCommand->GetString() += crit + ".Precision = " + Precision;
922 //================================================================================
924 * \brief Convert the command or remember it for later conversion
925 * \param theCommand - The python command calling a method of SMESH_Gen
927 //================================================================================
929 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
931 // there are methods to convert:
932 // CreateMesh( shape )
933 // Concatenate( [mesh1, ...], ... )
934 // CreateHypothesis( theHypType, theLibName )
935 // Compute( mesh, geom )
936 // Evaluate( mesh, geom )
938 TCollection_AsciiString method = theCommand->GetMethod();
940 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
942 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
946 if ( method == "CreateMeshesFromUNV" ||
947 method == "CreateMeshesFromSTL" ||
948 method == "CopyMesh" ) // command result is a mesh
950 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
954 if( method == "CreateMeshesFromMED" ||
955 method == "CreateMeshesFromSAUV"||
956 method == "CreateMeshesFromCGNS" ||
957 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
959 for ( int ind = 0; ind < theCommand->GetNbResultValues(); ind++ )
961 _pyID meshID = theCommand->GetResultValue(ind+1);
962 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
963 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
966 if ( method == "CreateMeshesFromGMF" )
968 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
969 // CreateMeshesFromGMF( theFileName )
970 _AString file = theCommand->GetArg(1);
971 theCommand->RemoveArgs();
972 theCommand->SetArg( 1, file );
976 // CreateHypothesis()
977 if ( method == "CreateHypothesis" )
979 // issue 199929, remove standard library name (default parameter)
980 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
981 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
982 // keep the first argument
983 TCollection_AsciiString arg = theCommand->GetArg( 1 );
984 theCommand->RemoveArgs();
985 theCommand->SetArg( 1, arg );
988 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
989 CheckObjectIsReCreated( hyp );
990 myHypos.insert( make_pair( hyp->GetID(), hyp ));
995 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
996 if ( method == "Compute" )
998 const _pyID& meshID = theCommand->GetArg( 1 );
999 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1000 if ( id_mesh != myMeshes.end() ) {
1001 theCommand->SetObject( meshID );
1002 theCommand->RemoveArgs();
1003 id_mesh->second->Process( theCommand );
1004 id_mesh->second->AddProcessedCmd( theCommand );
1009 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1010 if ( method == "Evaluate" )
1012 const _pyID& meshID = theCommand->GetArg( 1 );
1013 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1014 if ( id_mesh != myMeshes.end() ) {
1015 theCommand->SetObject( meshID );
1016 _pyID geom = theCommand->GetArg( 2 );
1017 theCommand->RemoveArgs();
1018 theCommand->SetArg( 1, geom );
1019 id_mesh->second->AddProcessedCmd( theCommand );
1024 // objects erasing creation command if no more its commands invoked:
1025 // SMESH_Pattern, FilterManager
1026 if ( method == "GetPattern" ||
1027 method == "CreateFilterManager" ||
1028 method == "CreateMeasurements" )
1030 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1031 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
1032 theCommand->Clear(); // already created
1034 // Concatenate( [mesh1, ...], ... )
1035 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1037 if ( method == "ConcatenateWithGroups" ) {
1038 theCommand->SetMethod( "Concatenate" );
1039 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1041 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1043 AddMeshAccessorMethod( theCommand );
1045 else if ( method == "SetName" ) // SetName(obj,name)
1047 // store theCommand as one of object commands to erase it along with the object
1048 const _pyID& objID = theCommand->GetArg( 1 );
1049 Handle(_pyObject) obj = FindObject( objID );
1050 if ( !obj.IsNull() )
1051 obj->AddProcessedCmd( theCommand );
1054 // Replace name of SMESH_Gen
1056 // names of SMESH_Gen methods fully equal to methods defined in smesh.py
1057 static TStringSet smeshpyMethods;
1058 if ( smeshpyMethods.empty() ) {
1059 const char * names[] =
1060 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1061 "GetPattern","GetSubShapesId",
1062 "" }; // <- mark of array end
1063 smeshpyMethods.Insert( names );
1065 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1066 // smeshgen.Method() --> smesh.Method()
1067 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1069 // smeshgen.Method() --> smesh.smesh.Method()
1070 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1073 //================================================================================
1075 * \brief Convert the remembered commands
1077 //================================================================================
1079 void _pyGen::Flush()
1081 // create an empty command
1082 myLastCommand = new _pyCommand();
1084 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1085 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1086 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1088 if ( IsToKeepAllCommands() ) // historical dump
1090 // set myIsPublished = true to all objects
1091 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1092 id_mesh->second->SetRemovedFromStudy( false );
1093 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1094 id_hyp->second->SetRemovedFromStudy( false );
1095 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1096 id_obj->second->SetRemovedFromStudy( false );
1100 // let hypotheses find referred objects in order to prevent clearing
1101 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1102 list< Handle(_pyMesh) > fatherMeshes;
1103 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1104 if ( !id_hyp->second.IsNull() )
1105 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1107 // set myIsPublished = false to all objects depending on
1108 // meshes built on a removed geometry
1109 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1110 if ( id_mesh->second->IsNotGeomPublished() )
1111 id_mesh->second->SetRemovedFromStudy( true );
1114 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1115 if ( ! id_mesh->second.IsNull() )
1116 id_mesh->second->Flush();
1119 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1120 if ( !id_hyp->second.IsNull() ) {
1121 id_hyp->second->Flush();
1122 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1123 if ( !id_hyp->second->IsWrapped() )
1124 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1127 // Flush other objects
1128 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1129 if ( ! id_obj->second.IsNull() )
1130 id_obj->second->Flush();
1132 myLastCommand->SetOrderNb( ++myNbCommands );
1133 myCommands.push_back( myLastCommand );
1136 //================================================================================
1138 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1139 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1141 //================================================================================
1143 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1145 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1146 for ( ; id_obj != myObjects.end(); ++id_obj )
1148 if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1149 for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1151 const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1152 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1154 list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1155 list< _pyID >::iterator id = idList.begin();
1156 for ( ; id != idList.end(); ++id )
1157 if ( id_obj->first == *id )
1158 // _pySubMesh::Process() does what we need
1159 Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1164 //================================================================================
1166 * \brief Clean commmands of removed objects depending on myIsPublished flag
1168 //================================================================================
1170 void _pyGen::ClearCommands()
1172 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1173 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1174 id_mesh->second->ClearCommands();
1176 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1177 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1178 if ( !id_hyp->second.IsNull() )
1179 id_hyp->second->ClearCommands();
1181 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1182 for ( ; id_obj != myObjects.end(); ++id_obj )
1183 id_obj->second->ClearCommands();
1186 //================================================================================
1188 * \brief Release mutual handles of objects
1190 //================================================================================
1194 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1195 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1196 id_mesh->second->Free();
1199 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1200 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1201 id_ed->second->Free();
1202 myMeshEditors.clear();
1204 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1205 for ( ; id_obj != myObjects.end(); ++id_obj )
1206 id_obj->second->Free();
1209 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1210 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1211 if ( !id_hyp->second.IsNull() )
1212 id_hyp->second->Free();
1215 myFile2ExportedMesh.clear();
1217 //myKeepAgrCmdsIDs.Print();
1220 //================================================================================
1222 * \brief Add access method to mesh that is an argument
1223 * \param theCmd - command to add access method
1224 * \retval bool - true if added
1226 //================================================================================
1228 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1231 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1232 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1233 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1239 //================================================================================
1241 * \brief Add access method to algo that is an object or an argument
1242 * \param theCmd - command to add access method
1243 * \retval bool - true if added
1245 //================================================================================
1247 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1250 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1251 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1252 if ( !id_hyp->second.IsNull() &&
1253 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1254 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1255 id_hyp->second->AccessorMethod() ))
1261 //================================================================================
1263 * \brief Find hypothesis by ID (entry)
1264 * \param theHypID - The hypothesis ID
1265 * \retval Handle(_pyHypothesis) - The found hypothesis
1267 //================================================================================
1269 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1271 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1272 if ( id_hyp != myHypos.end() &&
1273 !id_hyp->second.IsNull() &&
1274 theHypID == id_hyp->second->GetID() )
1275 return id_hyp->second;
1276 return Handle(_pyHypothesis)();
1279 //================================================================================
1281 * \brief Find algorithm able to create a hypothesis
1282 * \param theGeom - The shape ID the algorithm was created on
1283 * \param theMesh - The mesh ID that created the algorithm
1284 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1285 * \retval Handle(_pyHypothesis) - The found algo
1287 //================================================================================
1289 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1290 const Handle(_pyHypothesis)& theHypothesis )
1292 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1293 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1294 if ( !id_hyp->second.IsNull() &&
1295 id_hyp->second->IsAlgo() &&
1296 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1297 id_hyp->second->GetGeom() == theGeom &&
1298 id_hyp->second->GetMesh() == theMesh )
1299 return id_hyp->second;
1300 return Handle(_pyHypothesis)();
1303 //================================================================================
1305 * \brief Find subMesh by ID (entry)
1306 * \param theSubMeshID - The subMesh ID
1307 * \retval Handle(_pySubMesh) - The found subMesh
1309 //================================================================================
1311 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1313 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1314 if ( id_subMesh != myObjects.end() )
1315 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1316 return Handle(_pySubMesh)();
1320 //================================================================================
1322 * \brief Change order of commands in the script
1323 * \param theCmd1 - One command
1324 * \param theCmd2 - Another command
1326 //================================================================================
1328 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1330 list< Handle(_pyCommand) >::iterator pos1, pos2;
1331 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1332 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1333 myCommands.insert( pos1, theCmd2 );
1334 myCommands.insert( pos2, theCmd1 );
1335 myCommands.erase( pos1 );
1336 myCommands.erase( pos2 );
1338 int nb1 = theCmd1->GetOrderNb();
1339 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1340 theCmd2->SetOrderNb( nb1 );
1341 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1342 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1345 //================================================================================
1347 * \brief Set one command after the other
1348 * \param theCmd - Command to move
1349 * \param theAfterCmd - Command ater which to insert the first one
1351 //================================================================================
1353 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1355 setNeighbourCommand( theCmd, theAfterCmd, true );
1358 //================================================================================
1360 * \brief Set one command before the other
1361 * \param theCmd - Command to move
1362 * \param theBeforeCmd - Command before which to insert the first one
1364 //================================================================================
1366 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1368 setNeighbourCommand( theCmd, theBeforeCmd, false );
1371 //================================================================================
1373 * \brief Set one command before or after the other
1374 * \param theCmd - Command to move
1375 * \param theOtherCmd - Command ater or before which to insert the first one
1377 //================================================================================
1379 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1380 Handle(_pyCommand)& theOtherCmd,
1381 const bool theIsAfter )
1383 list< Handle(_pyCommand) >::iterator pos;
1384 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1385 myCommands.erase( pos );
1386 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1387 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1390 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1391 (*pos)->SetOrderNb( i++ );
1394 //================================================================================
1396 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1398 //================================================================================
1400 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1402 // No more needed after adding _pyObject::myArgCommands
1404 // const char filterPrefix[] = "aFilter0x";
1405 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1408 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1410 // const _AString & arg = theCommand->GetArg( i );
1411 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1412 // if ( arg.Search( filterPrefix ) != 1 )
1415 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1416 // if ( !filter.IsNull() )
1418 // filter->AddUser( user );
1419 // if ( !filter->GetNewID().IsEmpty() )
1420 // theCommand->SetArg( i, filter->GetNewID() );
1425 //================================================================================
1427 * \brief Set command be last in list of commands
1428 * \param theCmd - Command to be last
1430 //================================================================================
1432 Handle(_pyCommand)& _pyGen::GetLastCommand()
1434 return myLastCommand;
1437 //================================================================================
1439 * \brief Set method to access to object wrapped with python class
1440 * \param theID - The wrapped object entry
1441 * \param theMethod - The accessor method
1443 //================================================================================
1445 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1447 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1450 //================================================================================
1452 * \brief Generated new ID for object and assign with existing name
1453 * \param theID - ID of existing object
1455 //================================================================================
1457 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1462 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1464 while ( myObjectNames.IsBound( aNewID ) );
1466 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1467 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1468 : _pyID( "A" ) + aNewID );
1472 //================================================================================
1474 * \brief Stores theObj in myObjects
1476 //================================================================================
1478 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1480 if ( theObj.IsNull() ) return;
1482 CheckObjectIsReCreated( theObj );
1484 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1485 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1487 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1488 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1491 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1494 //================================================================================
1496 * \brief Erases an existing object with the same ID. This method should be called
1497 * before storing theObj in _pyGen
1499 //================================================================================
1501 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1503 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1506 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1507 Handle(_pyObject) existing =
1508 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1509 if ( !existing.IsNull() && existing != theObj )
1511 existing->SetRemovedFromStudy( true );
1512 existing->ClearCommands();
1515 if ( myHypos.count( theObj->GetID() ))
1516 myHypos.erase( theObj->GetID() );
1518 else if ( myMeshes.count( theObj->GetID() ))
1520 myMeshes.erase( theObj->GetID() );
1522 else if ( myObjects.count( theObj->GetID() ))
1524 myObjects.erase( theObj->GetID() );
1529 //================================================================================
1531 * \brief Re-register an object with other ID to make it Process() commands of
1532 * other object having this ID
1534 //================================================================================
1536 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1538 if ( theObj.IsNull() ) return;
1540 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1541 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1543 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1544 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1547 myObjects.insert( make_pair( theID, theObj ));
1550 //================================================================================
1552 * \brief Finds a _pyObject by ID
1554 //================================================================================
1556 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1559 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1560 if ( id_obj != myObjects.end() )
1561 return id_obj->second;
1564 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1565 if ( id_obj != myMeshes.end() )
1566 return id_obj->second;
1569 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1570 // if ( id_obj != myMeshEditors.end() )
1571 // return id_obj->second;
1573 return Handle(_pyObject)();
1576 //================================================================================
1578 * \brief Check if a study entry is under GEOM component
1580 //================================================================================
1582 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1586 return ( myGeomIDIndex <= theObjID.Length() &&
1587 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1588 _pyCommand::IsStudyEntry( theObjID ));
1593 //================================================================================
1595 * \brief Returns true if an object is not present in a study
1597 //================================================================================
1599 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1601 if ( theObjID.IsEmpty() ) return false;
1603 if ( myObjectNames.IsBound( theObjID ))
1604 return false; // SMESH object is in study
1606 // either the SMESH object is not in study or it is a GEOM object
1607 if ( IsGeomObject( theObjID ))
1609 SALOMEDS::SObject_var so = myStudy->FindObjectID( theObjID.ToCString() );
1610 if ( so->_is_nil() ) return true;
1611 CORBA::Object_var obj = so->GetObject();
1612 return CORBA::is_nil( obj );
1614 return true; // SMESH object not in study
1617 //================================================================================
1619 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1620 * this object is not dumped
1621 * \param [in] theObjID - entry of the object whose creation command was eliminated
1623 //================================================================================
1625 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1627 myRemovedObjIDs.insert( theObjID );
1630 //================================================================================
1632 * \brief Return reader of hypotheses of plugins
1634 //================================================================================
1636 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1638 if (myHypReader.IsNull() )
1639 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1645 //================================================================================
1647 * \brief Mesh created by SMESH_Gen
1649 //================================================================================
1651 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1652 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1654 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1655 myGeomNotInStudy = true;
1657 // convert my creation command --> smeshpy.Mesh(...)
1658 Handle(_pyCommand) creationCmd = GetCreationCmd();
1659 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1660 creationCmd->SetMethod( "Mesh" );
1661 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1664 //================================================================================
1666 * \brief Mesh created by SMESH_MeshEditor
1668 //================================================================================
1670 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1671 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1673 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1675 // this mesh depends on the exported mesh
1676 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1677 if ( !file.IsEmpty() )
1679 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1680 addFatherMesh( exportData.myMesh );
1681 if ( !exportData.myLastComputeCmd.IsNull() )
1683 // restore cleared Compute() by which the exported mesh was generated
1684 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1685 // protect that Compute() cmd from clearing
1686 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1687 exportData.myMesh->myLastComputeCmd.Nullify();
1691 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1693 // this mesh depends on concatenated meshes
1694 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1695 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1696 list< _pyID >::iterator meshID = idList.begin();
1697 for ( ; meshID != idList.end(); ++meshID )
1698 addFatherMesh( *meshID );
1700 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1702 // this mesh depends on a copied IdSource
1703 const _pyID& objID = theCreationCmd->GetArg( 1 );
1704 addFatherMesh( objID );
1706 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1707 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1708 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1710 // this mesh depends on a source mesh
1711 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1712 const _pyID& meshID = theCreationCmd->GetObject();
1713 addFatherMesh( meshID );
1716 // convert my creation command
1717 Handle(_pyCommand) creationCmd = GetCreationCmd();
1718 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1719 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1722 //================================================================================
1724 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1725 * \param theCommand - Engine method called for this mesh
1727 //================================================================================
1729 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1731 // some methods of SMESH_Mesh interface needs special conversion
1732 // to methods of Mesh python class
1734 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1735 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1736 // 2. AddHypothesis(geom, hyp)
1737 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1738 // 3. CreateGroupFromGEOM(type, name, grp)
1739 // --> in Mesh.Group(grp, name="")
1740 // 4. ExportToMED(f, auto_groups, version)
1741 // --> in Mesh.ExportMED( f, auto_groups, version )
1744 const TCollection_AsciiString& method = theCommand->GetMethod();
1745 // ----------------------------------------------------------------------
1746 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1748 if ( !theGen->IsToKeepAllCommands() ) // !historical
1750 list< Handle(_pyHypothesis) >::iterator hyp;
1751 if ( !myLastComputeCmd.IsNull() )
1753 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1754 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1756 myLastComputeCmd->Clear();
1758 myLastComputeCmd = theCommand;
1760 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1761 (*hyp)->MeshComputed( myLastComputeCmd );
1765 // ----------------------------------------------------------------------
1766 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1768 if ( !theGen->IsToKeepAllCommands() ) // !historical
1771 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1772 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1773 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1775 if ( !myLastComputeCmd.IsNull() )
1777 list< Handle(_pyHypothesis) >::iterator hyp;
1778 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1779 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1781 myLastComputeCmd->Clear();
1784 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1785 for ( ; e != myEditors.end(); ++e )
1787 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1788 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1789 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1790 if ( !(*cmd)->IsEmpty() )
1792 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1796 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1799 // ----------------------------------------------------------------------
1800 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1801 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1802 if ( !subMesh.IsNull() ) {
1803 subMesh->SetCreator( this );
1804 mySubmeshes.push_back( subMesh );
1807 // ----------------------------------------------------------------------
1808 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1809 myAddHypCmds.push_back( theCommand );
1811 const _pyID& hypID = theCommand->GetArg( 2 );
1812 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1813 if ( !hyp.IsNull() ) {
1814 myHypos.push_back( hyp );
1815 if ( hyp->GetMesh().IsEmpty() )
1816 hyp->SetMesh( this->GetID() );
1819 // ----------------------------------------------------------------------
1820 else if ( method == "CreateGroup" ||
1821 method == "CreateGroupFromGEOM" ||
1822 method == "CreateGroupFromFilter" )
1824 Handle(_pyGroup) group = new _pyGroup( theCommand );
1825 myGroups.push_back( group );
1826 theGen->AddObject( group );
1828 // ----------------------------------------------------------------------
1829 // update list of groups
1830 else if ( method == "GetGroups" )
1832 bool allGroupsRemoved = true;
1833 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1834 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1835 list< _pyID >::iterator grID = idList.begin();
1836 const int nbGroupsBefore = myGroups.size();
1837 Handle(_pyObject) obj;
1838 for ( ; grID != idList.end(); ++grID )
1840 obj = theGen->FindObject( *grID );
1843 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1844 theGen->AddObject( group );
1845 myGroups.push_back( group );
1848 if ( !obj->CanClear() )
1849 allGroupsRemoved = false;
1851 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1852 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1854 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1856 // check if the preceding command is Compute();
1857 // if GetGroups() is just after Compute(), this can mean that the groups
1858 // were created by some algorithm and hence Compute() should not be discarded
1859 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1860 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1861 while ( (*cmd)->GetMethod() == "GetGroups" )
1863 if ( myLastComputeCmd == (*cmd))
1864 // protect last Compute() from clearing by the next Compute()
1865 myLastComputeCmd.Nullify();
1868 // ----------------------------------------------------------------------
1869 // notify a group about full removal
1870 else if ( method == "RemoveGroupWithContents" ||
1871 method == "RemoveGroup")
1873 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1874 const _pyID groupID = theCommand->GetArg( 1 );
1875 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1876 if ( !grp.IsNull() )
1878 if ( method == "RemoveGroupWithContents" )
1879 grp->RemovedWithContents();
1880 // to clear RemoveGroup() if the group creation is cleared
1881 grp->AddProcessedCmd( theCommand );
1885 // ----------------------------------------------------------------------
1886 else if ( theCommand->MethodStartsFrom( "Export" ))
1888 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1889 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1891 theCommand->SetMethod( "ExportMED" );
1892 if ( theCommand->GetNbArgs() == 5 )
1894 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1895 _AString autoDimension = theCommand->GetArg( 5 );
1896 theCommand->SetArg( 5, "None" );
1897 theCommand->SetArg( 6, autoDimension );
1900 else if ( method == "ExportCGNS" )
1901 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1902 _pyID partID = theCommand->GetArg( 1 );
1903 int nbArgs = theCommand->GetNbArgs();
1904 for ( int i = 2; i <= nbArgs; ++i )
1905 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1906 theCommand->SetArg( nbArgs, partID );
1908 else if ( method == "ExportGMF" )
1909 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1910 _pyID partID = theCommand->GetArg( 1 );
1911 _AString file = theCommand->GetArg( 2 );
1912 theCommand->RemoveArgs();
1913 theCommand->SetArg( 1, file );
1914 theCommand->SetArg( 2, partID );
1916 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1917 { // ExportPartTo*(part, ...) -> Export*(..., part)
1919 // remove "PartTo" from the method
1920 TCollection_AsciiString newMethod = method;
1921 newMethod.Remove( 7, 6 );
1922 theCommand->SetMethod( newMethod );
1923 // make the 1st arg be the last one (or last but one for ExportMED())
1924 _pyID partID = theCommand->GetArg( 1 );
1925 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1926 for ( int i = 2; i <= nbArgs; ++i )
1927 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1928 theCommand->SetArg( nbArgs, partID );
1930 // remember file name
1931 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1932 ExportedMeshData( this, myLastComputeCmd ));
1934 // ----------------------------------------------------------------------
1935 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1937 _pyID hypID = theCommand->GetArg( 2 );
1938 _pyID geomID = theCommand->GetArg( 1 );
1939 bool isLocal = ( geomID != GetGeom() );
1941 // check if this mesh still has corresponding addition command
1942 Handle(_pyCommand) addCmd;
1943 list< Handle(_pyCommand) >::iterator cmd;
1944 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1945 for ( int i = 0; i < 2; ++i )
1947 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1948 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1950 bool sameHyp = true;
1951 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1952 sameHyp = false; // other hyp
1953 if ( (*cmd)->GetNbArgs() == 2 &&
1954 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1955 sameHyp = false; // other geom
1956 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1957 sameHyp = false; // other geom
1961 cmd = addHypCmds.erase( cmd );
1962 if ( !theGen->IsToKeepAllCommands() ) {
1964 theCommand->Clear();
1973 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1974 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1975 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1976 _pyID geom = theCommand->GetArg( 1 );
1977 theCommand->RemoveArgs();
1978 theCommand->SetArg( 1, hypID );
1979 if ( geom != GetGeom() )
1980 theCommand->SetArg( 2, geom );
1982 // remove hyp from myHypos
1983 myHypos.remove( hyp );
1985 // check for SubMesh order commands
1986 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1988 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1989 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1990 // commands are moved at the end of the script
1991 TCollection_AsciiString subIDs =
1992 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1993 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1994 list< _pyID >::iterator subID = idList.begin();
1995 for ( ; subID != idList.end(); ++subID )
1997 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1998 if ( !subMesh.IsNull() )
1999 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2002 // add accessor method if necessary
2005 if ( NeedMeshAccess( theCommand ))
2006 // apply theCommand to the mesh wrapped by smeshpy mesh
2007 AddMeshAccess( theCommand );
2011 //================================================================================
2013 * \brief Return True if addition of accesor method is needed
2015 //================================================================================
2017 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2019 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2020 // so no conversion is needed for them at all:
2021 static TStringSet sameMethods;
2022 if ( sameMethods.empty() ) {
2023 const char * names[] =
2024 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2025 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2026 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2027 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2028 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2029 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2030 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2031 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2032 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2033 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2034 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2035 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2036 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2037 ,"" }; // <- mark of end
2038 sameMethods.Insert( names );
2041 return !sameMethods.Contains( theCommand->GetMethod() );
2044 //================================================================================
2046 * \brief Convert creation and addition of all algos and hypos
2048 //================================================================================
2050 void _pyMesh::Flush()
2053 // get the meshes this mesh depends on via hypotheses
2054 list< Handle(_pyMesh) > fatherMeshes;
2055 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2056 for ( ; hyp != myHypos.end(); ++hyp )
2057 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2058 myGeomNotInStudy = true;
2060 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2061 for ( ; m != fatherMeshes.end(); ++m )
2062 addFatherMesh( *m );
2063 // if ( removedGeom )
2064 // SetRemovedFromStudy(); // as reffered geometry not in study
2066 if ( myGeomNotInStudy )
2069 list < Handle(_pyCommand) >::iterator cmd;
2071 // try to convert algo addition like this:
2072 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2073 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2075 Handle(_pyCommand) addCmd = *cmd;
2077 _pyID algoID = addCmd->GetArg( 2 );
2078 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2079 if ( algo.IsNull() || !algo->IsAlgo() )
2082 // check and create new algorithm instance if it is already wrapped
2083 if ( algo->IsWrapped() ) {
2084 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2085 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2086 TCollection_AsciiString( " = " ) + theGen->GetID() +
2087 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2088 TCollection_AsciiString( "\" )" );
2090 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2091 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2092 if ( !newAlgo.IsNull() ) {
2093 newAlgo->Assign( algo, this->GetID() );
2094 newAlgo->SetCreationCmd( newCmd );
2096 // set algorithm creation
2097 theGen->SetCommandBefore( newCmd, addCmd );
2098 myHypos.push_back( newAlgo );
2099 if ( !myLastComputeCmd.IsNull() &&
2100 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2101 newAlgo->MeshComputed( myLastComputeCmd );
2106 _pyID geom = addCmd->GetArg( 1 );
2107 bool isLocalAlgo = ( geom != GetGeom() );
2110 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2112 // wrapped algo is created after mesh creation
2113 GetCreationCmd()->AddDependantCmd( addCmd );
2115 if ( isLocalAlgo ) {
2116 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2117 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2118 TCollection_AsciiString( "geom=" ) + geom );
2119 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2120 list < Handle(_pySubMesh) >::iterator smIt;
2121 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2122 Handle(_pySubMesh) subMesh = *smIt;
2123 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2124 if ( geom == subCmd->GetArg( 1 )) {
2125 subCmd->SetObject( algo->GetID() );
2126 subCmd->RemoveArgs();
2127 subMesh->SetCreator( algo );
2132 else // KO - ALGO was already created
2134 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2135 addCmd->RemoveArgs();
2136 addCmd->SetArg( 1, algoID );
2138 addCmd->SetArg( 2, geom );
2139 myNotConvertedAddHypCmds.push_back( addCmd );
2143 // try to convert hypo addition like this:
2144 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2145 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2147 Handle(_pyCommand) addCmd = *cmd;
2148 _pyID hypID = addCmd->GetArg( 2 );
2149 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2150 if ( hyp.IsNull() || hyp->IsAlgo() )
2152 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2154 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2155 _pyID geom = addCmd->GetArg( 1 );
2156 addCmd->RemoveArgs();
2157 addCmd->SetArg( 1, hypID );
2158 if ( geom != GetGeom() )
2159 addCmd->SetArg( 2, geom );
2160 myNotConvertedAddHypCmds.push_back( addCmd );
2164 myAddHypCmds.clear();
2165 mySubmeshes.clear();
2168 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2169 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2173 //================================================================================
2175 * \brief Sets myIsPublished of me and of all objects depending on me.
2177 //================================================================================
2179 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2181 _pyObject::SetRemovedFromStudy(isRemoved);
2183 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2184 for ( ; sm != mySubmeshes.end(); ++sm )
2185 (*sm)->SetRemovedFromStudy(isRemoved);
2187 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2188 for ( ; gr != myGroups.end(); ++gr )
2189 (*gr)->SetRemovedFromStudy(isRemoved);
2191 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2192 for ( ; m != myChildMeshes.end(); ++m )
2193 (*m)->SetRemovedFromStudy(isRemoved);
2195 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2196 for ( ; e != myEditors.end(); ++e )
2197 (*e)->SetRemovedFromStudy(isRemoved);
2200 //================================================================================
2202 * \brief Return true if none of myChildMeshes is in study
2204 //================================================================================
2206 bool _pyMesh::CanClear()
2211 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2212 for ( ; m != myChildMeshes.end(); ++m )
2213 if ( !(*m)->CanClear() )
2219 //================================================================================
2221 * \brief Clear my commands and commands of mesh editor
2223 //================================================================================
2225 void _pyMesh::ClearCommands()
2231 // mark all sub-objects as not removed, except child meshes
2232 list< Handle(_pyMesh) > children;
2233 children.swap( myChildMeshes );
2234 SetRemovedFromStudy( false );
2235 children.swap( myChildMeshes );
2239 _pyObject::ClearCommands();
2241 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2242 for ( ; sm != mySubmeshes.end(); ++sm )
2243 (*sm)->ClearCommands();
2245 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2246 for ( ; gr != myGroups.end(); ++gr )
2247 (*gr)->ClearCommands();
2249 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2250 for ( ; e != myEditors.end(); ++e )
2251 (*e)->ClearCommands();
2254 //================================================================================
2256 * \brief Add a father mesh by ID
2258 //================================================================================
2260 void _pyMesh::addFatherMesh( const _pyID& meshID )
2262 if ( !meshID.IsEmpty() && meshID != GetID() )
2263 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2266 //================================================================================
2268 * \brief Add a father mesh
2270 //================================================================================
2272 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2274 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2276 //myFatherMeshes.push_back( mesh );
2277 mesh->myChildMeshes.push_back( this );
2279 // protect last Compute() from clearing by the next Compute()
2280 mesh->myLastComputeCmd.Nullify();
2284 //================================================================================
2286 * \brief MeshEditor convert its commands to ones of mesh
2288 //================================================================================
2290 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2291 _pyObject( theCreationCmd )
2293 myMesh = theCreationCmd->GetObject();
2294 myCreationCmdStr = theCreationCmd->GetString();
2295 theCreationCmd->Clear();
2297 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2298 if ( !mesh.IsNull() )
2299 mesh->AddEditor( this );
2302 //================================================================================
2304 * \brief convert its commands to ones of mesh
2306 //================================================================================
2308 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2310 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2311 // commands calling these methods are converted to calls of Mesh methods without
2312 // additional modifs, only object is changed from MeshEditor to Mesh.
2313 static TStringSet sameMethods;
2314 if ( sameMethods.empty() ) {
2315 const char * names[] = {
2316 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2317 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2318 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2319 "MoveNode", "MoveClosestNodeToPoint",
2320 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2321 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2322 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2323 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2324 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2325 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2326 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2327 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2328 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2329 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2330 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2331 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2332 "GetLastCreatedElems",
2333 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2334 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2335 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2336 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2337 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2338 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2339 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2340 ,"" }; // <- mark of the end
2341 sameMethods.Insert( names );
2344 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2345 TStringMap diffMethods;
2346 if ( diffMethods.empty() ) {
2347 const char * orig2newName[] = {
2348 // original name --------------> new name
2349 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2350 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2351 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2352 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2353 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2354 ""};// <- mark of the end
2355 diffMethods.Insert( orig2newName );
2358 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2359 // only by last two arguments
2360 static TStringSet diffLastTwoArgsMethods;
2361 if (diffLastTwoArgsMethods.empty() ) {
2362 const char * names[] = {
2363 "MirrorMakeGroups","MirrorObjectMakeGroups",
2364 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2365 "RotateMakeGroups","RotateObjectMakeGroups",
2366 ""};// <- mark of the end
2367 diffLastTwoArgsMethods.Insert( names );
2370 // only a method name is to change?
2371 const TCollection_AsciiString & method = theCommand->GetMethod();
2372 bool isPyMeshMethod = sameMethods.Contains( method );
2373 if ( !isPyMeshMethod )
2375 TCollection_AsciiString newMethod = diffMethods.Value( method );
2376 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2377 theCommand->SetMethod( newMethod );
2379 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2380 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2382 isPyMeshMethod = true;
2383 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2384 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2387 if ( !isPyMeshMethod )
2389 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2390 // functions with the flag "theMakeGroups = True" like:
2391 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2392 int pos = method.Search("MakeGroups");
2395 isPyMeshMethod = true;
2396 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2397 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2399 // 1. Remove "MakeGroups" from the Command
2400 TCollection_AsciiString aMethod = theCommand->GetMethod();
2401 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2404 pos = pos-2; //Remove "0D" from the Command too
2405 aMethod.Trunc(pos-1);
2406 theCommand->SetMethod(aMethod);
2408 // 2. And add last "True" argument(s)
2409 while(nbArgsToAdd--)
2410 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2411 if( is0DmethId || is0DmethObj )
2412 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2416 // ExtrusionSweep0D() -> ExtrusionSweep()
2417 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2418 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2419 method == "ExtrusionSweepObject0D" ))
2421 isPyMeshMethod = true;
2422 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2423 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2424 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2427 // DoubleNode...New(...) -> DoubleNode...(...,True)
2428 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2429 method == "DoubleNodeElemGroupsNew" ||
2430 method == "DoubleNodeGroupNew" ||
2431 method == "DoubleNodeGroupsNew" ||
2432 method == "DoubleNodeElemGroup2New" ||
2433 method == "DoubleNodeElemGroups2New"))
2435 isPyMeshMethod = true;
2436 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2437 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2438 if ( excessLen == 3 )
2440 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2442 else if ( theCommand->GetArg(4) == "0" ||
2443 theCommand->GetArg(5) == "0" )
2445 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2446 // Group = DoubleNodeGroup2New(,,,False, True)
2447 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2448 theCommand->SetResultValue( groupID );
2451 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2452 // FindElementsByPoint(x, y, z, elementType, meshPart)
2453 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2455 isPyMeshMethod = true;
2456 theCommand->SetMethod( "FindElementsByPoint" );
2457 // make the 1st arg be the last one
2458 _pyID partID = theCommand->GetArg( 1 );
2459 int nbArgs = theCommand->GetNbArgs();
2460 for ( int i = 2; i <= nbArgs; ++i )
2461 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2462 theCommand->SetArg( nbArgs, partID );
2464 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2465 if ( !isPyMeshMethod && method == "Reorient2D" )
2467 isPyMeshMethod = true;
2468 _AString mesh = theCommand->GetArg( 1 );
2469 _AString dir = theCommand->GetArg( 2 );
2470 _AString face = theCommand->GetArg( 3 );
2471 _AString point = theCommand->GetArg( 4 );
2472 theCommand->RemoveArgs();
2473 theCommand->SetArg( 1, mesh );
2474 theCommand->SetArg( 2, dir );
2475 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2476 theCommand->SetArg( 3, point );
2478 theCommand->SetArg( 3, face );
2481 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2483 isPyMeshMethod = true;
2484 int crit_arg = theCommand->GetNbArgs();
2485 const _AString& crit = theCommand->GetArg(crit_arg);
2486 if (crit.Search("MaxElementLength2D") != -1)
2487 theCommand->SetArg(crit_arg, "");
2490 if ( isPyMeshMethod )
2492 theCommand->SetObject( myMesh );
2496 // editor creation command is needed only if any editor function is called
2497 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2498 if ( !myCreationCmdStr.IsEmpty() ) {
2499 GetCreationCmd()->GetString() = myCreationCmdStr;
2500 myCreationCmdStr.Clear();
2505 //================================================================================
2507 * \brief Return true if my mesh can be removed
2509 //================================================================================
2511 bool _pyMeshEditor::CanClear()
2513 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2514 return mesh.IsNull() ? true : mesh->CanClear();
2517 //================================================================================
2519 * \brief _pyHypothesis constructor
2520 * \param theCreationCmd -
2522 //================================================================================
2524 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2525 _pyObject( theCreationCmd ), myCurCrMethod(0)
2527 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2530 //================================================================================
2532 * \brief Creates algorithm or hypothesis
2533 * \param theCreationCmd - The engine command creating a hypothesis
2534 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2536 //================================================================================
2538 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2540 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2541 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2543 Handle(_pyHypothesis) hyp, algo;
2546 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2547 if ( hypTypeQuoted.IsEmpty() )
2550 TCollection_AsciiString hypType =
2551 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2553 algo = new _pyAlgorithm( theCreationCmd );
2554 hyp = new _pyHypothesis( theCreationCmd );
2556 if ( hypType == "NumberOfSegments" ) {
2557 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2558 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2559 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2560 hyp->AddArgMethod( "SetNumberOfSegments" );
2561 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2562 hyp->AddArgMethod( "SetScaleFactor" );
2563 hyp->AddArgMethod( "SetReversedEdges" );
2564 // same for ""CompositeSegment_1D:
2565 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2566 hyp->AddArgMethod( "SetNumberOfSegments" );
2567 hyp->AddArgMethod( "SetScaleFactor" );
2568 hyp->AddArgMethod( "SetReversedEdges" );
2570 else if ( hypType == "SegmentLengthAroundVertex" ) {
2571 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2572 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2573 hyp->AddArgMethod( "SetLength" );
2574 // same for ""CompositeSegment_1D:
2575 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2576 hyp->AddArgMethod( "SetLength" );
2578 else if ( hypType == "LayerDistribution2D" ) {
2579 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2580 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2582 else if ( hypType == "LayerDistribution" ) {
2583 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2584 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2586 else if ( hypType == "CartesianParameters3D" ) {
2587 hyp = new _pyComplexParamHypo( theCreationCmd );
2588 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2589 for ( int iArg = 0; iArg < 4; ++iArg )
2590 hyp->setCreationArg( iArg+1, "[]");
2594 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2597 return algo->IsValid() ? algo : hyp;
2600 //================================================================================
2602 * \brief Returns true if addition of this hypothesis to a given mesh can be
2603 * wrapped into hypothesis creation
2605 //================================================================================
2607 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2609 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2611 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2612 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2618 //================================================================================
2620 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2621 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2622 * \param theAlgo - The algo that can create this hypo
2623 * \retval bool - false if the command cant be converted
2625 //================================================================================
2627 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2628 const _pyID& theMesh)
2630 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2632 if ( !IsWrappable( theMesh ))
2635 myGeom = theCmd->GetArg( 1 );
2637 Handle(_pyHypothesis) algo;
2639 // find algo created on myGeom in theMesh
2640 algo = theGen->FindAlgo( myGeom, theMesh, this );
2641 if ( algo.IsNull() )
2643 // attach hypothesis creation command to be after algo creation command
2644 // because it can be new created instance of algorithm
2645 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2649 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2650 theCmd->SetResultValue( GetID() );
2651 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2652 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2653 // set args (geom will be set by _pyMesh calling this method)
2654 theCmd->RemoveArgs();
2655 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2656 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2657 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2659 theCmd->SetArg( i+1, "[]");
2661 // set a new creation command
2662 GetCreationCmd()->Clear();
2663 // replace creation command by wrapped instance
2664 // please note, that hypothesis attaches to algo creation command (see upper)
2665 SetCreationCmd( theCmd );
2668 // clear commands setting arg values
2669 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2670 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2673 // set unknown arg commands after hypo creation
2674 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2675 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2676 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2677 afterCmd->AddDependantCmd( *cmd );
2683 //================================================================================
2685 * \brief Remember hypothesis parameter values
2686 * \param theCommand - The called hypothesis method
2688 //================================================================================
2690 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2692 ASSERT( !myIsAlgo );
2693 if ( !theGen->IsToKeepAllCommands() )
2694 rememberCmdOfParameter( theCommand );
2696 bool usedCommand = false;
2697 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2698 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2700 CreationMethod& crMethod = type2meth->second;
2701 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2702 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2704 myArgCommands.push_back( theCommand );
2706 while ( crMethod.myArgs.size() < i+1 )
2707 crMethod.myArgs.push_back( "[]" );
2708 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2713 myUnusedCommands.push_back( theCommand );
2716 //================================================================================
2718 * \brief Finish conversion
2720 //================================================================================
2722 void _pyHypothesis::Flush()
2726 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2727 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2728 // Add access to a wrapped mesh
2729 theGen->AddMeshAccessorMethod( *cmd );
2730 // Add access to a wrapped algorithm
2731 theGen->AddAlgoAccessorMethod( *cmd );
2733 cmd = myUnusedCommands.begin();
2734 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2735 // Add access to a wrapped mesh
2736 theGen->AddMeshAccessorMethod( *cmd );
2737 // Add access to a wrapped algorithm
2738 theGen->AddAlgoAccessorMethod( *cmd );
2741 // forget previous hypothesis modifications
2742 myArgCommands.clear();
2743 myUnusedCommands.clear();
2746 //================================================================================
2748 * \brief clear creation, arg and unkown commands
2750 //================================================================================
2752 void _pyHypothesis::ClearAllCommands()
2754 GetCreationCmd()->Clear();
2755 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2756 for ( ; cmd != myArgCommands.end(); ++cmd )
2758 cmd = myUnusedCommands.begin();
2759 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2764 //================================================================================
2766 * \brief Assign fields of theOther to me except myIsWrapped
2768 //================================================================================
2770 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2771 const _pyID& theMesh )
2773 // myCreationCmd = theOther->myCreationCmd;
2774 myIsAlgo = theOther->myIsAlgo;
2775 myIsWrapped = false;
2776 myGeom = theOther->myGeom;
2778 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2779 myAccumulativeMethods = theOther->myAccumulativeMethods;
2780 //myUnusedCommands = theOther->myUnusedCommands;
2781 // init myCurCrMethod
2782 GetCreationMethod( theOther->GetAlgoType() );
2785 //================================================================================
2787 * \brief Analyze my erasability depending on myReferredObjs
2789 //================================================================================
2791 bool _pyHypothesis::CanClear()
2795 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2796 for ( ; obj != myReferredObjs.end(); ++obj )
2797 if ( (*obj)->CanClear() )
2804 //================================================================================
2806 * \brief Clear my commands depending on usage by meshes
2808 //================================================================================
2810 void _pyHypothesis::ClearCommands()
2812 // if ( !theGen->IsToKeepAllCommands() )
2814 // bool isUsed = false;
2815 // int lastComputeOrder = 0;
2816 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2817 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2818 // if ( ! (*cmd)->IsEmpty() )
2821 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2822 // lastComputeOrder = (*cmd)->GetOrderNb();
2826 // SetRemovedFromStudy( true );
2830 // // clear my commands invoked after lastComputeOrder
2831 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2832 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2834 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2835 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2836 // // cmds.back()->Clear();
2840 _pyObject::ClearCommands();
2843 //================================================================================
2845 * \brief Find arguments that are objects like mesh, group, geometry
2846 * \param meshes - referred meshes (directly or indirrectly)
2847 * \retval bool - false if a referred geometry is not in the study
2849 //================================================================================
2851 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2853 if ( IsAlgo() ) return true;
2855 bool geomPublished = true;
2856 vector< _AString > args;
2857 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2858 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2860 CreationMethod& crMethod = type2meth->second;
2861 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2863 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2864 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2865 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2866 args.push_back( (*cmd)->GetArg( nb ));
2869 for ( size_t i = 0; i < args.size(); ++i )
2871 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2872 if ( idList.empty() && !args[ i ].IsEmpty() )
2873 idList.push_back( args[ i ]);
2874 list< _pyID >::iterator id = idList.begin();
2875 for ( ; id != idList.end(); ++id )
2877 Handle(_pyObject) obj = theGen->FindObject( *id );
2878 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2881 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2882 geomPublished = false;
2886 myReferredObjs.push_back( obj );
2887 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2888 if ( !mesh.IsNull() )
2889 meshes.push_back( mesh );
2890 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2891 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2892 obj->SetRemovedFromStudy( false );
2896 return geomPublished;
2899 //================================================================================
2901 * \brief Remember theCommand setting a parameter
2903 //================================================================================
2905 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2907 // parameters are discriminated by method name
2908 _AString method = theCommand->GetMethod();
2909 if ( myAccumulativeMethods.count( method ))
2910 return; // this method adds values and not override the previus value
2912 // discriminate commands setting different parameters via one method
2913 // by passing parameter names like e.g. SetOption("size", "0.2")
2914 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2915 theCommand->GetNbArgs() > 1 )
2917 // mangle method by appending a 1st textual arg
2918 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2920 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2921 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2922 if ( !isalpha( arg.Value(2))) continue;
2927 // parameters are discriminated by method name
2928 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2929 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2931 cmds.back()->Clear(); // previous parameter value has not been used
2932 cmds.back() = theCommand;
2936 cmds.push_back( theCommand );
2940 //================================================================================
2942 * \brief Return true if a setting parameter command ha been used to compute mesh
2944 //================================================================================
2946 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2947 _pyCommand::TAddr avoidComputeAddr ) const
2949 bool isUsed = false;
2950 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2951 myComputeAddr2Cmds.begin();
2952 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2954 if ( addr2cmds->first == avoidComputeAddr ) continue;
2955 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2956 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2961 //================================================================================
2963 * \brief Save commands setting parameters as they are used for a mesh computation
2965 //================================================================================
2967 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2969 myComputeCmds.push_back( theComputeCmd );
2970 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2972 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2973 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2974 savedCmds.push_back( m2c->second.back() );
2977 //================================================================================
2979 * \brief Clear commands setting parameters as a mesh computed using them is cleared
2981 //================================================================================
2983 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2985 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2987 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2988 for ( ; cmd != savedCmds.end(); ++cmd )
2990 // check if a cmd has been used to compute another mesh
2991 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2993 // check if a cmd is a sole command setting its parameter;
2994 // don't use method name for search as it can change
2995 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2996 m2cmds = myMeth2Commands.begin();
2997 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2999 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3000 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3001 if ( cmdIt != cmds.end() )
3003 if ( cmds.back() != *cmd )
3005 cmds.erase( cmdIt );
3012 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3015 //================================================================================
3017 * \brief Sets an argNb-th argument of current creation command
3018 * \param argNb - argument index countered from 1
3020 //================================================================================
3022 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3024 if ( myCurCrMethod )
3026 while ( myCurCrMethod->myArgs.size() < argNb )
3027 myCurCrMethod->myArgs.push_back( "None" );
3028 if ( arg.IsEmpty() )
3029 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3031 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3036 //================================================================================
3038 * \brief Remember hypothesis parameter values
3039 * \param theCommand - The called hypothesis method
3041 //================================================================================
3043 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3045 if ( GetAlgoType() == "Cartesian_3D" )
3047 // CartesianParameters3D hyp
3049 if ( theCommand->GetMethod() == "SetSizeThreshold" )
3051 setCreationArg( 4, theCommand->GetArg( 1 ));
3052 myArgCommands.push_back( theCommand );
3055 if ( theCommand->GetMethod() == "SetGrid" ||
3056 theCommand->GetMethod() == "SetGridSpacing" )
3058 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3059 int iArg = axis.Value(1) - '0';
3060 if ( theCommand->GetMethod() == "SetGrid" )
3062 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3066 myCurCrMethod->myArgs[ iArg ] = "[ ";
3067 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3068 myCurCrMethod->myArgs[ iArg ] += ", ";
3069 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3070 myCurCrMethod->myArgs[ iArg ] += "]";
3072 myArgCommands.push_back( theCommand );
3073 rememberCmdOfParameter( theCommand );
3078 if( theCommand->GetMethod() == "SetLength" )
3080 // NOW it is OBSOLETE
3081 // ex: hyp.SetLength(start, 1)
3082 // hyp.SetLength(end, 0)
3083 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3084 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3085 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3086 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3088 CreationMethod& crMethod = type2meth->second;
3089 while ( crMethod.myArgs.size() < i+1 )
3090 crMethod.myArgs.push_back( "[]" );
3091 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3093 myArgCommands.push_back( theCommand );
3097 _pyHypothesis::Process( theCommand );
3100 //================================================================================
3102 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3104 //================================================================================
3106 void _pyComplexParamHypo::Flush()
3110 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3111 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3112 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3117 //================================================================================
3119 * \brief Convert methods of 1D hypotheses to my own methods
3120 * \param theCommand - The called hypothesis method
3122 //================================================================================
3124 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3126 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3129 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3130 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3131 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3133 // TCollection_AsciiString cmd =
3134 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3135 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3136 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3139 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3141 // // 1D hypo is already set, so distribution changes and the old
3142 // // 1D hypo is thrown away
3143 // my1dHyp->ClearAllCommands();
3146 // //my1dHyp->SetRemovedFromStudy( false );
3148 // if ( !myArgCommands.empty() )
3149 // myArgCommands.back()->Clear();
3150 myCurCrMethod->myArgs.push_back( hyp1dID );
3151 myArgCommands.push_back( theCommand );
3154 //================================================================================
3157 * \param theAdditionCmd - command to be converted
3158 * \param theMesh - mesh instance
3159 * \retval bool - status
3161 //================================================================================
3163 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3164 const _pyID& theMesh)
3166 myIsWrapped = false;
3168 if ( my1dHyp.IsNull() )
3171 // set "SetLayerDistribution()" after addition cmd
3172 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3174 _pyID geom = theAdditionCmd->GetArg( 1 );
3176 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3177 if ( !algo.IsNull() )
3179 my1dHyp->SetMesh( theMesh );
3180 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3181 algo->GetAlgoType().ToCString());
3182 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3185 // clear "SetLayerDistribution()" cmd
3186 myArgCommands.back()->Clear();
3188 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3190 // find RadialPrism algo created on <geom> for theMesh
3191 GetCreationCmd()->SetObject( algo->GetID() );
3192 GetCreationCmd()->SetMethod( myAlgoMethod );
3193 GetCreationCmd()->RemoveArgs();
3194 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3200 //================================================================================
3204 //================================================================================
3206 void _pyLayerDistributionHypo::Flush()
3208 // as creation of 1D hyp was written later then it's edition,
3209 // we need to find all it's edition calls and process them
3210 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3212 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3214 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3215 if ( hyp1dID.IsEmpty() ) continue;
3217 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3219 // make a new name for 1D hyp = "HypType" + "_Distribution"
3221 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3223 if ( prevNewName.IsEmpty() ) continue;
3224 newName = prevNewName;
3228 if ( hyp1d->IsWrapped() ) {
3229 newName = hyp1d->GetCreationCmd()->GetMethod();
3232 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3233 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3235 newName += "_Distribution";
3236 prevNewName = newName;
3238 hyp1d->GetCreationCmd()->SetResultValue( newName );
3240 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3241 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3242 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3243 const _pyID& objID = (*cmdIt)->GetObject();
3244 if ( objID == hyp1dID ) {
3245 if ( !hyp1d.IsNull() )
3247 hyp1d->Process( *cmdIt );
3248 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3250 ( *cmdIt )->SetObject( newName );
3253 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3254 (*cmd)->SetArg( 1, newName );
3258 //================================================================================
3260 * \brief additionally to Addition2Creation, clears SetDistrType() command
3261 * \param theCmd - AddHypothesis() command
3262 * \param theMesh - mesh to which a hypothesis is added
3263 * \retval bool - convertion result
3265 //================================================================================
3267 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3268 const _pyID& theMesh)
3270 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3271 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3272 bool scaleDistrType = false;
3273 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3274 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3275 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3276 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3277 scaleDistrType = true;
3280 else if ( !scaleDistrType ) {
3281 // distribution type changed: remove scale factor from args
3282 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3283 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3285 CreationMethod& crMethod = type2meth->second;
3286 if ( crMethod.myArgs.size() == 2 )
3287 crMethod.myArgs.pop_back();
3294 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3297 //================================================================================
3299 * \brief remove repeated commands defining distribution
3301 //================================================================================
3303 void _pyNumberOfSegmentsHyp::Flush()
3305 // find number of the last SetDistrType() command
3306 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3307 int distrTypeNb = 0;
3308 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3309 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3310 if ( cmd != myUnusedCommands.rbegin() )
3311 distrTypeNb = (*cmd)->GetOrderNb();
3313 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3316 // clear commands before the last SetDistrType()
3317 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3318 set< int > treatedCmdNbs; // avoid treating same cmd twice
3319 for ( int i = 0; i < 2; ++i ) {
3320 set<TCollection_AsciiString> uniqueMethods;
3321 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3322 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3324 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3325 continue;// avoid treating same cmd twice
3326 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3327 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3328 if ( !clear || method == "SetNumberOfSegments" ) {
3329 bool isNewInSet = uniqueMethods.insert( method ).second;
3330 clear = !isNewInSet;
3339 //================================================================================
3341 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3342 * into regular1D.LengthNearVertex( length, vertex )
3343 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3344 * \param theMesh - The mesh needing this hypo
3345 * \retval bool - false if the command cant be converted
3347 //================================================================================
3349 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3350 const _pyID& theMeshID)
3352 if ( IsWrappable( theMeshID )) {
3354 _pyID vertex = theCmd->GetArg( 1 );
3356 // the problem here is that segment algo will not be found
3357 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3358 // geometry where segment algorithm is assigned
3359 Handle(_pyHypothesis) algo;
3360 _pyID geom = vertex;
3361 while ( algo.IsNull() && !geom.IsEmpty()) {
3362 // try to find geom as a father of <vertex>
3363 geom = FatherID( geom );
3364 algo = theGen->FindAlgo( geom, theMeshID, this );
3366 if ( algo.IsNull() )
3367 return false; // also possible to find geom as brother of veretex...
3368 // set geom instead of vertex
3369 theCmd->SetArg( 1, geom );
3371 // set vertex as a second arg
3372 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3373 setCreationArg( 2, vertex );
3375 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3376 // theMeshID.LengthNearVertex( length, vertex )
3377 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3382 //================================================================================
3384 * \brief _pyAlgorithm constructor
3385 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3387 //================================================================================
3389 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3390 : _pyHypothesis( theCreationCmd )
3395 //================================================================================
3397 * \brief Convert the command adding an algorithm to mesh
3398 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3399 * \param theMesh - The mesh needing this algo
3400 * \retval bool - false if the command cant be converted
3402 //================================================================================
3404 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3405 const _pyID& theMeshID)
3407 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3408 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3409 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3415 //================================================================================
3417 * \brief Return starting position of a part of python command
3418 * \param thePartIndex - The index of command part
3419 * \retval int - Part position
3421 //================================================================================
3423 int _pyCommand::GetBegPos( int thePartIndex )
3427 if ( myBegPos.Length() < thePartIndex )
3429 ASSERT( thePartIndex > 0 );
3430 return myBegPos( thePartIndex );
3433 //================================================================================
3435 * \brief Store starting position of a part of python command
3436 * \param thePartIndex - The index of command part
3437 * \param thePosition - Part position
3439 //================================================================================
3441 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3443 while ( myBegPos.Length() < thePartIndex )
3444 myBegPos.Append( UNKNOWN );
3445 ASSERT( thePartIndex > 0 );
3446 myBegPos( thePartIndex ) = thePosition;
3449 //================================================================================
3451 * \brief Returns whitespace symbols at the line beginning
3452 * \retval TCollection_AsciiString - result
3454 //================================================================================
3456 TCollection_AsciiString _pyCommand::GetIndentation()
3459 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3460 GetWord( myString, end, true );
3462 end = GetBegPos( RESULT_IND );
3463 return myString.SubString( 1, end - 1 );
3466 //================================================================================
3468 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3469 * \retval const TCollection_AsciiString & - ResultValue substring
3471 //================================================================================
3473 const TCollection_AsciiString & _pyCommand::GetResultValue()
3475 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3477 SetBegPos( RESULT_IND, EMPTY );
3478 int begPos, endPos = myString.Location( "=", 1, Length() );
3482 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3483 if ( begPos < endPos )
3485 SetBegPos( RESULT_IND, begPos );
3487 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3488 myRes = myString.SubString( begPos, endPos );
3495 //================================================================================
3497 * \brief Return number of python command result value ResultValue = Obj.Meth()
3499 //================================================================================
3501 int _pyCommand::GetNbResultValues()
3505 int endPos = myString.Location( "=", 1, Length() );
3506 while ( begPos < endPos )
3508 _AString str = GetWord( myString, begPos, true );
3509 begPos = begPos+ str.Length();
3516 //================================================================================
3518 * \brief Return substring of python command looking like
3519 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3520 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3522 //================================================================================
3523 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3526 if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3527 ++begPos; // skip [, else the whole list is returned
3528 int endPos = myString.Location( "=", 1, Length() );
3530 while ( begPos < endPos) {
3531 _AString result = GetWord( myString, begPos, true );
3532 begPos = begPos + result.Length();
3535 result.RemoveAll('[');
3536 result.RemoveAll(']');
3542 return theEmptyString;
3545 //================================================================================
3547 * \brief Return substring of python command looking like ResVal = Object.Meth()
3548 * \retval const TCollection_AsciiString & - Object substring
3550 //================================================================================
3552 const TCollection_AsciiString & _pyCommand::GetObject()
3554 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3557 int begPos = GetBegPos( RESULT_IND );
3559 begPos = myString.Location( "=", 1, Length() ) + 1;
3560 // is '=' in the string argument (for example, name) or not
3561 int nb1 = 0; // number of ' character at the left of =
3562 int nb2 = 0; // number of " character at the left of =
3563 for ( int i = 1; i < begPos-1; i++ ) {
3564 if ( myString.Value( i )=='\'' )
3566 else if ( myString.Value( i )=='"' )
3569 // if number of ' or " is not divisible by 2,
3570 // then get an object at the start of the command
3571 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3575 begPos += myRes.Length();
3577 myObj = GetWord( myString, begPos, true );
3578 if ( begPos != EMPTY )
3580 // check if object is complex,
3581 // so far consider case like "smesh.Method()"
3582 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3583 //if ( bracketPos==0 ) bracketPos = Length();
3584 int dotPos = begPos+myObj.Length();
3585 while ( dotPos+1 < bracketPos ) {
3586 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3591 if ( dotPos > begPos+myObj.Length() )
3592 myObj = myString.SubString( begPos, dotPos-1 );
3595 // 1st word after '=' is an object
3596 // else // no method -> no object
3602 SetBegPos( OBJECT_IND, begPos );
3608 //================================================================================
3610 * \brief Return substring of python command looking like ResVal = Obj.Method()
3611 * \retval const TCollection_AsciiString & - Method substring
3613 //================================================================================
3615 const TCollection_AsciiString & _pyCommand::GetMethod()
3617 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3620 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3621 bool forward = true;
3623 begPos = myString.Location( "(", 1, Length() ) - 1;
3627 myMeth = GetWord( myString, begPos, forward );
3628 SetBegPos( METHOD_IND, begPos );
3634 //================================================================================
3636 * \brief Returns true if there are brackets after the method
3638 //================================================================================
3640 bool _pyCommand::IsMethodCall()
3642 if ( GetMethod().IsEmpty() )
3644 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3645 return ( s[0] == '(' || s[1] == '(' );
3648 //================================================================================
3650 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3651 * \retval const TCollection_AsciiString & - Arg<index> substring
3653 //================================================================================
3655 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3657 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3661 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3663 pos = myString.Location( "(", 1, Length() );
3667 // we are at or before '(', skip it if present
3669 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3670 if ( pos > Length() )
3674 SetBegPos( ARG1_IND, 0 ); // even no '('
3675 return theEmptyString;
3679 list< TCollection_AsciiString > separatorStack( 1, ",)");
3680 bool ignoreNesting = false;
3682 while ( pos <= Length() )
3684 const char chr = myString.Value( pos );
3686 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3688 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3690 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3692 TCollection_AsciiString arg;
3693 if ( pos-1 >= prevPos ) {
3694 arg = myString.SubString( prevPos, pos-1 );
3695 arg.RightAdjust(); // remove spaces
3698 if ( !arg.IsEmpty() || chr == ',' )
3700 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3701 myArgs.Append( arg );
3707 else // end of nesting args found
3709 separatorStack.pop_back();
3710 ignoreNesting = false;
3713 else if ( !ignoreNesting )
3716 case '(' : separatorStack.push_back(")"); break;
3717 case '[' : separatorStack.push_back("]"); break;
3718 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3719 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3726 if ( myArgs.Length() < index )
3727 return theEmptyString;
3728 return myArgs( index );
3731 //================================================================================
3733 * \brief Check if char is a word part
3734 * \param c - The character to check
3735 * \retval bool - The check result
3737 //================================================================================
3739 static inline bool isWord(const char c, const bool dotIsWord)
3742 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3745 //================================================================================
3747 * \brief Looks for a word in the string and returns word's beginning
3748 * \param theString - The input string
3749 * \param theStartPos - The position to start the search, returning word's beginning
3750 * \param theForward - The search direction
3751 * \retval TCollection_AsciiString - The found word
3753 //================================================================================
3755 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3757 const bool theForward,
3758 const bool dotIsWord )
3760 int beg = theStartPos, end = theStartPos;
3761 theStartPos = EMPTY;
3762 if ( beg < 1 || beg > theString.Length() )
3763 return theEmptyString;
3765 if ( theForward ) { // search forward
3767 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3769 if ( beg > theString.Length() )
3770 return theEmptyString; // no word found
3773 char begChar = theString.Value( beg );
3774 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3775 char endChar = ( begChar == '[' ) ? ']' : begChar;
3776 // end is at the corresponding quoting mark or bracket
3777 while ( end < theString.Length() &&
3778 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3782 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3787 else { // search backward
3789 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3792 return theEmptyString; // no word found
3794 char endChar = theString.Value( end );
3795 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3796 char begChar = ( endChar == ']' ) ? '[' : endChar;
3797 // beg is at the corresponding quoting mark
3799 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3803 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3809 //cout << theString << " ---- " << beg << " - " << end << endl;
3810 return theString.SubString( beg, end );
3813 //================================================================================
3815 * \brief Returns true if the string looks like a study entry
3817 //================================================================================
3819 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3821 if ( str.Length() < 5 ) return false;
3823 int nbColons = 0, isColon;
3824 for ( int i = 1; i <= str.Length(); ++i )
3826 char c = str.Value(i);
3827 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3829 nbColons += isColon;
3831 return nbColons > 2 && str.Length()-nbColons > 2;
3834 //================================================================================
3836 * \brief Returns true if the string looks like an object ID but not like a list,
3837 * string, command etc.
3839 //================================================================================
3841 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3843 if ( str.Length() < 1 ) return false;
3845 if ( isdigit( str.Value( 1 )))
3846 return IsStudyEntry( str );
3848 for ( int i = 1; i <= str.Length(); ++i )
3849 if ( !isalnum( str.Value( i )) && !str.Value( i ) != '_' )
3855 //================================================================================
3857 * \brief Finds entries in a sting
3859 //================================================================================
3861 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3863 std::list< _pyID > resList;
3865 while ( ++pos <= str.Length() )
3867 if ( !isdigit( str.Value( pos ))) continue;
3868 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3871 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3872 _pyID entry = str.SubString( pos, end-1 );
3874 if ( IsStudyEntry( entry ))
3875 resList.push_back( entry );
3880 //================================================================================
3882 * \brief Look for position where not space char is
3883 * \param theString - The string
3884 * \param thePos - The position to search from and which returns result
3885 * \retval bool - false if there are only space after thePos in theString
3887 //================================================================================
3889 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3891 if ( thePos < 1 || thePos > theString.Length() )
3894 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3897 return thePos <= theString.Length();
3900 //================================================================================
3902 * \brief Modify a part of the command
3903 * \param thePartIndex - The index of the part
3904 * \param thePart - The new part string
3905 * \param theOldPart - The old part
3907 //================================================================================
3909 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3910 TCollection_AsciiString& theOldPart)
3912 int pos = GetBegPos( thePartIndex );
3913 if ( pos <= Length() && theOldPart != thePart)
3915 TCollection_AsciiString seperator;
3917 pos = GetBegPos( thePartIndex + 1 );
3918 if ( pos < 1 ) return;
3919 switch ( thePartIndex ) {
3920 case RESULT_IND: seperator = " = "; break;
3921 case OBJECT_IND: seperator = "."; break;
3922 case METHOD_IND: seperator = "()"; break;
3926 myString.Remove( pos, theOldPart.Length() );
3927 if ( !seperator.IsEmpty() )
3928 myString.Insert( pos , seperator );
3929 myString.Insert( pos, thePart );
3930 // update starting positions of the following parts
3931 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3932 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3933 if ( myBegPos( i ) > 0 )
3934 myBegPos( i ) += posDelta;
3936 theOldPart = thePart;
3940 //================================================================================
3942 * \brief Set agrument
3943 * \param index - The argument index, it counts from 1
3944 * \param theArg - The argument string
3946 //================================================================================
3948 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3951 int argInd = ARG1_IND + index - 1;
3952 int pos = GetBegPos( argInd );
3953 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3955 // find a closing parenthesis
3956 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3957 int lastArgInd = GetNbArgs();
3958 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3959 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3964 while ( pos > 0 && myString.Value( pos ) != ')' )
3967 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3971 while ( myArgs.Length() < index ) {
3972 if ( myArgs.Length() )
3973 myString.Insert( pos++, "," );
3974 myArgs.Append("None");
3975 myString.Insert( pos, myArgs.Last() );
3976 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3977 pos += myArgs.Last().Length();
3980 SetPart( argInd, theArg, myArgs( index ));
3983 //================================================================================
3985 * \brief Empty arg list
3987 //================================================================================
3989 void _pyCommand::RemoveArgs()
3991 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3992 myString.Trunc( pos );
3995 if ( myBegPos.Length() >= ARG1_IND )
3996 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3999 //================================================================================
4001 * \brief Comment a python command
4003 //================================================================================
4005 void _pyCommand::Comment()
4007 if ( IsEmpty() ) return;
4010 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4011 if ( i <= Length() )
4013 myString.Insert( i, "#" );
4014 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4016 int begPos = GetBegPos( iPart + 1 );
4017 if ( begPos != UNKNOWN )
4018 SetBegPos( iPart + 1, begPos + 1 );
4023 //================================================================================
4025 * \brief Set dependent commands after this one
4027 //================================================================================
4029 bool _pyCommand::SetDependentCmdsAfter() const
4031 bool orderChanged = false;
4032 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4033 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4034 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4035 orderChanged = true;
4036 theGen->SetCommandAfter( *cmd, this );
4037 (*cmd)->SetDependentCmdsAfter();
4040 return orderChanged;
4042 //================================================================================
4044 * \brief Insert accessor method after theObjectID
4045 * \param theObjectID - id of the accessed object
4046 * \param theAcsMethod - name of the method giving access to the object
4047 * \retval bool - false if theObjectID is not found in the command string
4049 //================================================================================
4051 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4053 if ( !theAcsMethod )
4055 // start object search from the object, i.e. ignore result
4057 int beg = GetBegPos( OBJECT_IND );
4058 if ( beg < 1 || beg > Length() )
4061 while (( beg = myString.Location( theObjectID, beg, Length() )))
4063 // check that theObjectID is not just a part of a longer ID
4064 int afterEnd = beg + theObjectID.Length();
4065 Standard_Character c = myString.Value( afterEnd );
4066 if ( !isalnum( c ) && c != ':' ) {
4067 // check if accessor method already present
4069 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4071 int oldLen = Length();
4072 myString.Insert( afterEnd, (char*) theAcsMethod );
4073 myString.Insert( afterEnd, "." );
4074 // update starting positions of the parts following the modified one
4075 int posDelta = Length() - oldLen;
4076 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4077 if ( myBegPos( i ) > afterEnd )
4078 myBegPos( i ) += posDelta;
4083 beg = afterEnd; // is a part - next search
4088 //================================================================================
4090 * \brief Creates pyObject
4092 //================================================================================
4094 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4095 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4100 //================================================================================
4102 * \brief Set up myID and myIsPublished
4104 //================================================================================
4106 void _pyObject::setID(const _pyID& theID)
4109 myIsPublished = !theGen->IsNotPublished( GetID() );
4112 //================================================================================
4114 * \brief Clear myCreationCmd and myProcessedCmds
4116 //================================================================================
4118 void _pyObject::ClearCommands()
4123 if ( !myCreationCmd.IsNull() )
4124 myCreationCmd->Clear();
4126 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4127 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4131 //================================================================================
4133 * \brief Return method name giving access to an interaface object wrapped by python class
4134 * \retval const char* - method name
4136 //================================================================================
4138 const char* _pyObject::AccessorMethod() const
4142 //================================================================================
4144 * \brief Return ID of a father
4146 //================================================================================
4148 _pyID _pyObject::FatherID(const _pyID & childID)
4150 int colPos = childID.SearchFromEnd(':');
4152 return childID.SubString( 1, colPos-1 );
4156 //================================================================================
4158 * \brief SelfEraser erases creation command if no more it's commands invoked
4160 //================================================================================
4162 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4163 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4165 myIsPublished = true; // prevent clearing as a not published
4166 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4169 //================================================================================
4171 * \brief SelfEraser erases creation command if no more it's commands invoked
4173 //================================================================================
4175 void _pySelfEraser::Flush()
4177 bool toErase = false;
4178 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4181 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4182 for ( ; cmd != myArgCmds.end(); ++cmd )
4183 nbArgUses += !(*cmd)->IsEmpty();
4184 toErase = ( nbArgUses < 1 );
4188 int nbCalls = GetNbCalls();
4191 // ignore cleared commands
4192 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4193 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4194 for ( ; cmd != cmds.end(); ++cmd )
4195 nbCalls -= (*cmd)->IsEmpty();
4197 toErase = ( nbCalls < 1 );
4201 myIsPublished = false;
4202 _pyObject::ClearCommands();
4206 //================================================================================
4208 * \brief _pySubMesh constructor
4210 //================================================================================
4212 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4213 _pyObject(theCreationCmd)
4215 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4216 if ( toKeepAgrCmds )
4217 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4220 //================================================================================
4222 * \brief Return true if a sub-mesh can be used as argument of the given method
4224 //================================================================================
4226 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4229 // // names of all methods where a sub-mesh can be used as argument
4230 // static TStringSet methods;
4231 // if ( methods.empty() ) {
4232 // const char * names[] = {
4233 // // methods of SMESH_Gen
4235 // // methods of SMESH_Group
4237 // // methods of SMESH_Measurements
4239 // // methods of SMESH_Mesh
4240 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4242 // // methods of SMESH_MeshEditor
4243 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4244 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4245 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4246 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4247 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4248 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4249 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4250 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4251 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4252 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4253 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4254 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4255 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4256 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4257 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4258 // "" }; // <- mark of end
4259 // methods.Insert( names );
4261 // return methods.Contains( theMethodName );
4264 //================================================================================
4266 * \brief count invoked commands
4268 //================================================================================
4270 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4272 _pyObject::Process(theCommand); // count calls of Process()
4275 //================================================================================
4277 * \brief Move creation command depending on invoked commands
4279 //================================================================================
4281 void _pySubMesh::Flush()
4283 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4284 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4285 else if ( !myCreator.IsNull() )
4286 // move to be just after creator
4287 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4289 // move sub-mesh usage after creation cmd
4290 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4291 for ( ; cmd != myArgCmds.end(); ++cmd )
4292 if ( !(*cmd)->IsEmpty() )
4293 GetCreationCmd()->AddDependantCmd( *cmd );
4296 //================================================================================
4298 * \brief Creates _pyGroup
4300 //================================================================================
4302 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4303 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4305 if ( !id.IsEmpty() )
4308 myCanClearCreationCmd = true;
4310 const _AString& method = theCreationCmd->GetMethod();
4311 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4313 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4315 // ----------------------------------------------------------------------
4316 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4318 _pyID geom = theCreationCmd->GetArg( 3 );
4319 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4320 // next if(){...} section is commented
4321 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4322 // theCreationCmd->SetMethod( "Group" );
4323 // theCreationCmd->RemoveArgs();
4324 // theCreationCmd->SetArg( 1, geom );
4327 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4328 _pyID type = theCreationCmd->GetArg( 1 );
4329 _pyID name = theCreationCmd->GetArg( 2 );
4330 theCreationCmd->SetMethod( "GroupOnGeom" );
4331 theCreationCmd->RemoveArgs();
4332 theCreationCmd->SetArg( 1, geom );
4333 theCreationCmd->SetArg( 2, name );
4334 theCreationCmd->SetArg( 3, type );
4337 else if ( method == "CreateGroupFromFilter" )
4339 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4340 theCreationCmd->SetMethod( "GroupOnFilter" );
4342 _pyID filterID = theCreationCmd->GetArg(3);
4343 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4344 if ( !filter.IsNull())
4346 if ( !filter->GetNewID().IsEmpty() )
4347 theCreationCmd->SetArg( 3, filter->GetNewID() );
4348 //filter->AddUser( this );
4352 else if ( method == "GetGroups" )
4354 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4358 // theCreationCmd does something else apart from creation of this group
4359 // and thus it can't be cleared if this group is removed
4360 myCanClearCreationCmd = false;
4364 //================================================================================
4366 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4369 //================================================================================
4371 bool _pyGroup::CanClear()
4376 if ( !myCanClearCreationCmd &&
4377 !myCreationCmd.IsNull() &&
4378 myCreationCmd->GetMethod() == "GetGroups" )
4380 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4381 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4382 list< _pyID >::iterator grID = idList.begin();
4383 if ( GetID() == *grID )
4385 myCanClearCreationCmd = true;
4386 list< Handle(_pyGroup ) > groups;
4387 for ( ; grID != idList.end(); ++grID )
4389 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4390 if ( group.IsNull() ) continue;
4391 groups.push_back( group );
4392 if ( group->IsInStudy() )
4393 myCanClearCreationCmd = false;
4395 // set myCanClearCreationCmd == true to all groups
4396 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4397 for ( ; group != groups.end(); ++group )
4398 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4402 return myCanClearCreationCmd;
4405 //================================================================================
4407 * \brief set myCanClearCreationCmd = true if the main action of the creation
4408 * command is discarded
4410 //================================================================================
4412 void _pyGroup::RemovedWithContents()
4414 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4415 // via a created group
4416 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4417 // myCanClearCreationCmd = true;
4420 //================================================================================
4422 * \brief To convert creation of a group by filter
4424 //================================================================================
4426 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4428 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4429 // group = mesh.CreateEmptyGroup( elemType, groupName )
4430 // aFilter.SetMesh(mesh)
4431 // nbAdd = group.AddFrom( aFilter )
4432 Handle(_pyFilter) filter;
4433 if ( theCommand->GetMethod() == "AddFrom" )
4435 _pyID idSource = theCommand->GetArg(1);
4436 // check if idSource is a filter
4437 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4438 if ( !filter.IsNull() )
4440 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4441 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4442 while ( *cmdIt != theCommand ) ++cmdIt;
4443 while ( (*cmdIt)->GetOrderNb() != 1 )
4445 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4446 if ((setMeshCmd->GetObject() == idSource ||
4447 setMeshCmd->GetObject() == filter->GetNewID() )
4449 setMeshCmd->GetMethod() == "SetMesh")
4451 setMeshCmd->Clear();
4455 // replace 3 commands by one
4456 theCommand->Clear();
4457 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4458 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4459 if ( !filter->GetNewID().IsEmpty() )
4460 idSource = filter->GetNewID();
4461 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4462 makeGroupCmd->SetArg( 1, name );
4463 makeGroupCmd->SetArg( 2, idSource );
4464 filter->AddArgCmd( makeGroupCmd );
4467 else if ( theCommand->GetMethod() == "SetFilter" )
4469 // set new name of a filter or clear the command if the same filter is set
4470 _pyID filterID = theCommand->GetArg(1);
4471 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4472 if ( !myFilter.IsNull() && filter == myFilter )
4473 theCommand->Clear();
4474 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4475 theCommand->SetArg( 1, filter->GetNewID() );
4478 else if ( theCommand->GetMethod() == "GetFilter" )
4480 // GetFilter() returns a filter with other ID, make myFilter process
4481 // calls of the returned filter
4482 if ( !myFilter.IsNull() )
4484 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4485 theCommand->Clear();
4489 // if ( !filter.IsNull() )
4490 // filter->AddUser( this );
4492 theGen->AddMeshAccessorMethod( theCommand );
4495 //================================================================================
4497 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4499 //================================================================================
4501 void _pyGroup::Flush()
4503 if ( !theGen->IsToKeepAllCommands() &&
4504 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4506 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4510 //================================================================================
4512 * \brief Constructor of _pyFilter
4514 //================================================================================
4516 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4517 :_pyObject(theCreationCmd), myNewID( newID )
4519 //myIsPublished = true; // prevent clearing as a not published
4520 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4523 //================================================================================
4525 * \brief To convert creation of a filter by criteria and
4526 * to replace an old name by a new one
4528 //================================================================================
4530 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4532 if ( theCommand->GetObject() == GetID() )
4533 _pyObject::Process(theCommand); // count commands
4535 if ( !myNewID.IsEmpty() )
4536 theCommand->SetObject( myNewID );
4538 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4539 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4540 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4541 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4542 theCommand->GetMethod() == "SetCriteria")
4544 // aFilter.SetCriteria(aCriteria) ->
4545 // aFilter = smesh.GetFilterFromCriteria(criteria)
4546 if ( myNewID.IsEmpty() )
4547 theCommand->SetResultValue( GetID() );
4549 theCommand->SetResultValue( myNewID );
4550 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4551 theCommand->SetMethod( "GetFilterFromCriteria" );
4553 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4554 GetCreationCmd()->Clear();
4555 GetCreationCmd()->GetString() = theCommand->GetString();
4556 theCommand->Clear();
4557 theCommand->AddDependantCmd( GetCreationCmd() );
4559 else if ( theCommand->GetMethod() == "SetMesh" )
4561 if ( myMesh == theCommand->GetArg( 1 ))
4562 theCommand->Clear();
4564 myMesh = theCommand->GetArg( 1 );
4565 theGen->AddMeshAccessorMethod( theCommand );
4569 //================================================================================
4571 * \brief Set new filter name to the creation command and to myArgCmds
4573 //================================================================================
4575 void _pyFilter::Flush()
4577 if ( myNewID.IsEmpty() ) return;
4579 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4580 for ( ; cmd != myArgCmds.end(); ++cmd )
4581 if ( !(*cmd)->IsEmpty() )
4583 _AString cmdStr = (*cmd)->GetString();
4584 _AString id = GetID();
4585 int pos = cmdStr.Search( id );
4588 cmdStr.Remove( pos, id.Length() );
4589 cmdStr.Insert( pos, myNewID );
4592 (*cmd)->GetString() = cmdStr;
4595 if ( !GetCreationCmd()->IsEmpty() )
4596 GetCreationCmd()->SetResultValue( myNewID );
4599 //================================================================================
4601 * \brief Return true if all my users can be cleared
4603 //================================================================================
4605 bool _pyObject::CanClear()
4607 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4608 for ( ; cmd != myArgCmds.end(); ++cmd )
4609 if ( !(*cmd)->IsEmpty() )
4611 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4612 if ( !obj.IsNull() && !obj->CanClear() )
4615 return ( !myIsPublished );
4618 //================================================================================
4620 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4622 //================================================================================
4624 _pyHypothesisReader::_pyHypothesisReader()
4626 // Get paths to xml files of plugins
4627 vector< string > xmlPaths;
4629 if ( const char* meshersList = getenv("SMESH_MeshersList") )
4631 string meshers = meshersList, plugin;
4632 string::size_type from = 0, pos;
4633 while ( from < meshers.size() )
4635 // cut off plugin name
4636 pos = meshers.find( ':', from );
4637 if ( pos != string::npos )
4638 plugin = meshers.substr( from, pos-from );
4640 plugin = meshers.substr( from ), pos = meshers.size();
4643 // get PLUGIN_ROOT_DIR path
4644 string rootDirVar, pluginSubDir = plugin;
4645 if ( plugin == "StdMeshers" )
4646 rootDirVar = "SMESH", pluginSubDir = "smesh";
4648 for ( pos = 0; pos < plugin.size(); ++pos )
4649 rootDirVar += toupper( plugin[pos] );
4650 rootDirVar += "_ROOT_DIR";
4652 const char* rootDir = getenv( rootDirVar.c_str() );
4653 if ( !rootDir || strlen(rootDir) == 0 )
4655 rootDirVar = plugin + "_ROOT_DIR"; // HexoticPLUGIN_ROOT_DIR
4656 rootDir = getenv( rootDirVar.c_str() );
4657 if ( !rootDir || strlen(rootDir) == 0 ) continue;
4660 // get a separator from rootDir
4661 for ( pos = strlen( rootDir )-1; pos >= 0 && sep.empty(); --pos )
4662 if ( rootDir[pos] == '/' || rootDir[pos] == '\\' )
4668 if (sep.empty() ) sep = "\\";
4670 if (sep.empty() ) sep = "/";
4673 // get a path to resource file
4674 string xmlPath = rootDir;
4675 if ( xmlPath[ xmlPath.size()-1 ] != sep[0] )
4677 xmlPath += "share" + sep + "salome" + sep + "resources" + sep;
4678 for ( pos = 0; pos < pluginSubDir.size(); ++pos )
4679 xmlPath += tolower( pluginSubDir[pos] );
4680 xmlPath += sep + plugin + ".xml";
4683 fileOK = (GetFileAttributes(xmlPath.c_str()) != INVALID_FILE_ATTRIBUTES);
4685 fileOK = (access(xmlPath.c_str(), F_OK) == 0);
4688 xmlPaths.push_back( xmlPath );
4693 LDOMParser xmlParser;
4694 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4696 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4700 INFOS( xmlParser.GetError(data) );
4703 // <algorithm type="Regular_1D"
4704 // label-id="Wire discretisation"
4707 // <algo>Regular_1D=Segment()</algo>
4708 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4710 LDOM_Document xmlDoc = xmlParser.getDocument();
4711 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4712 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4714 LDOM_Node algoNode = algoNodeList.item( i );
4715 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4716 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4717 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4719 _AString text, algoType, method, arg;
4720 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4722 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4723 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4724 text = textNode.getNodeValue();
4725 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4726 algoType = algoCmd->GetResultValue();
4727 method = algoCmd->GetMethod();
4728 arg = algoCmd->GetArg(1);
4729 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4731 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4732 algo->SetConvMethodAndType( method, algoType );
4733 if ( !arg.IsEmpty() )
4734 algo->setCreationArg( 1, arg );
4736 myType2Hyp[ algoType ] = algo;
4740 if ( algoType.IsEmpty() ) continue;
4742 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4744 Handle( _pyHypothesis ) hyp;
4745 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4747 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4748 LDOM_Node textNode = pyHypoNode.getFirstChild();
4749 text = textNode.getNodeValue();
4750 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4751 hypType = hypoCmd->GetResultValue();
4752 method = hypoCmd->GetMethod();
4753 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4755 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4756 if ( type2hyp == myType2Hyp.end() )
4757 hyp = new _pyHypothesis( hypoCmd );
4759 hyp = type2hyp->second;
4760 hyp->SetConvMethodAndType( method, algoType );
4761 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4763 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4764 _AString argMethod = argCmd.GetMethod();
4765 _AString argNbText = argCmd.GetArg( 1 );
4766 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4767 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4769 hyp->AddArgMethod( argMethod,
4770 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4772 myType2Hyp[ hypType ] = hyp;
4776 // <hypothesis type="BLSURF_Parameters"
4780 // <accumulative-methods>
4781 // SetEnforcedVertex,
4782 // SetEnforcedVertexNamed
4783 // </accumulative-methods>
4787 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4788 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4790 LDOM_Node hypNode = hypNodeList.item( i );
4791 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4792 _AString hypType = hypElem.getAttribute("type");
4793 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4794 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4796 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4797 if ( type2hyp == myType2Hyp.end() ) continue;
4799 LDOM_Node methNode = methNodeList.item( 0 );
4800 LDOM_Node textNode = methNode.getFirstChild();
4801 _AString text = textNode.getNodeValue();
4805 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4806 pos += method.Length();
4807 type2hyp->second->AddAccumulativeMethod( method );
4809 while ( !method.IsEmpty() );
4812 } // loop on xmlPaths
4815 //================================================================================
4817 * \brief Returns a new hypothesis initialized according to the read information
4819 //================================================================================
4821 Handle(_pyHypothesis)
4822 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4823 const Handle(_pyCommand)& creationCmd) const
4825 Handle(_pyHypothesis) resHyp, sampleHyp;
4827 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4828 if ( type2hyp != myType2Hyp.end() )
4829 sampleHyp = type2hyp->second;
4831 if ( sampleHyp.IsNull() )
4833 resHyp = new _pyHypothesis(creationCmd);
4837 if ( sampleHyp->IsAlgo() )
4838 resHyp = new _pyAlgorithm( creationCmd );
4840 resHyp = new _pyHypothesis(creationCmd);
4841 resHyp->Assign( sampleHyp, _pyID() );
4846 //================================================================================
4848 * \brief Adds an object ID to some family of IDs with a common prefix
4849 * \param [in] str - the object ID
4850 * \return bool - \c false if \a str does not have the same prefix as \a this family
4851 * (for internal usage)
4853 //================================================================================
4855 bool _pyStringFamily::Add( const char* str )
4857 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4858 return false; // expected prefix is missing
4860 str += _prefix.Length(); // skip _prefix
4862 // try to add to some of child falimies
4863 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4864 for ( ; itSub != _subFams.end(); ++itSub )
4865 if ( itSub->Add( str ))
4868 // no suitable family found - add str to _strings or create a new child family
4870 // look for a proper place within sorted _strings
4871 std::list< _AString >::iterator itStr = _strings.begin();
4872 while ( itStr != _strings.end() && itStr->IsLess( str ))
4874 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4875 return true; // same ID already kept
4877 const int minPrefixSize = 4;
4879 // count "smaller" strings with the same prefix
4880 std::list< _AString >::iterator itLess = itStr; --itLess;
4882 for ( ; itLess != _strings.end(); --itLess )
4883 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4888 // count "greater" strings with the same prefix
4889 std::list< _AString >::iterator itMore = itStr;
4891 for ( ; itMore != _strings.end(); ++itMore )
4892 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4897 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4899 // look for a maximal prefix length
4900 // int lessPrefSize = 3, morePrefSize = 3;
4901 // if ( nbLess > 0 )
4902 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4904 // if ( nbMore > 0 )
4905 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4907 // int prefixSize = 3;
4908 // if ( nbLess == 0 )
4909 // prefixSize = morePrefSize;
4910 // else if ( nbMore == 0 )
4911 // prefixSize = lessPrefSize;
4913 // prefixSize = Min( lessPrefSize, morePrefSize );
4914 int prefixSize = minPrefixSize;
4915 _AString newPrefix ( str, prefixSize );
4917 // look for a proper place within _subFams sorted by _prefix
4918 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
4919 if ( !itSub->_prefix.IsLess( newPrefix ))
4922 // add the new _pyStringFamily
4923 itSub = _subFams.insert( itSub, _pyStringFamily());
4924 _pyStringFamily& newSubFam = *itSub;
4925 newSubFam._prefix = newPrefix;
4927 // pass this->_strings to newSubFam._strings
4928 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
4929 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4930 newSubFam._strings.push_back( str + prefixSize );
4931 for ( ; nbMore > 0; --nbMore, ++itStr )
4932 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4934 _strings.erase( itLess, ++itMore );
4936 else // to few string to make a family fot them
4938 _strings.insert( itStr, str );
4943 //================================================================================
4945 * \brief Finds an object ID in the command
4946 * \param [in] longStr - the command string
4947 * \param [out] subStr - the found object ID
4948 * \return bool - \c true if the object ID found
4950 //================================================================================
4952 bool _pyStringFamily::IsIn( const _AString& longStr, _AString& subStr )
4954 const char* s = longStr.ToCString();
4957 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4959 for ( ; itSub != _subFams.end(); ++itSub )
4961 if (( pos = longStr.Search( itSub->_prefix )-1) > 6-1 ) // 6 = strlen("a=b.c(")
4962 if (( len = itSub->isIn( s + pos + itSub->_prefix.Length() )) >= 0 )
4964 subStr = _AString( s + pos, len + itSub->_prefix.Length() );
4968 // look among _strings
4969 std::list< _AString >::iterator itStr = _strings.begin();
4970 for ( ; itStr != _strings.end(); ++itStr )
4971 if ( longStr.Search( *itStr ) > itStr->Length() )
4979 //================================================================================
4981 * \brief Return remainder length of the object ID after my _prefix
4982 * \param [in] str - remainder of the command after my _prefix
4983 * \return int - length of the object ID or -1 if not found
4985 //================================================================================
4987 int _pyStringFamily::isIn( const char* str )
4989 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4991 for ( ; itSub != _subFams.end(); ++itSub )
4993 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
4996 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
4997 return itSub->_prefix.Length() + len;
5002 if ( !_strings.empty() )
5004 std::list< _AString >::iterator itStr = _strings.begin();
5005 bool firstEmpty = itStr->IsEmpty();
5008 for ( ; itStr != _strings.end(); ++itStr )
5010 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5012 return itStr->Length();
5023 //================================================================================
5027 //================================================================================
5029 void _pyStringFamily::Print( int level )
5031 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5032 std::list< _AString >::iterator itStr = _strings.begin();
5033 for ( ; itStr != _strings.end(); ++itStr )
5034 cout << *itStr << " | ";
5036 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5037 for ( ; itSub != _subFams.end(); ++itSub )
5038 itSub->Print( level + 1 );
5040 cout << string( 70, '-' ) << endl;