1 // Copyright (C) 2007-2013 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 <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 const int nbRes = cmd->GetNbResultValues();
187 for ( int i = 0; i < nbRes; i++ )
189 _pyID objID = cmd->GetResultValue( i+1 );
190 if ( cmd->IsStudyEntry( objID ))
191 isResultPublished = (! theGen->IsNotPublished( objID ));
192 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
194 if ( isResultPublished )
200 // check if an Object was created in the script
203 _pyID obj = cmd->GetObject();
204 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
205 // remove an accessor method
206 obj = _pyCommand( obj ).GetObject();
208 const bool isMethodCall = cmd->IsMethodCall();
209 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
211 comment = "not created Object";
212 theGen->ObjectCreationRemoved( obj );
214 // check if a command has not created args
215 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
217 const _pyID& arg = cmd->GetArg( iArg );
218 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
220 list< _pyID > idList = cmd->GetStudyEntries( arg );
221 list< _pyID >::iterator id = idList.begin();
222 for ( ; id != idList.end(); ++id )
223 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
225 comment += *id + " has not been yet created";
228 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
229 // comment += arg + " has not been yet created";
231 // treat result objects
232 const _pyID& result = cmd->GetResultValue();
233 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
235 list< _pyID > idList = cmd->GetStudyEntries( result );
236 list< _pyID >::iterator id = idList.begin();
237 for ( ; id != idList.end(); ++id )
239 if ( comment.IsEmpty() )
240 presentObjects.insert( *id );
242 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
244 if ( idList.empty() && cmd->IsID( result ))
245 presentObjects.insert( result );
247 // comment the command
248 if ( !comment.IsEmpty() )
251 cmd->GetString() += " ### ";
252 cmd->GetString() += comment;
256 //================================================================================
258 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
260 //================================================================================
262 void fixFunctorType( TCollection_AsciiString& Type,
263 TCollection_AsciiString& Compare,
264 TCollection_AsciiString& UnaryOp,
265 TCollection_AsciiString& BinaryOp )
267 // The problem is that dumps of old studies created using filters becomes invalid
268 // when new items are inserted in the enum SMESH::FunctorType since values
269 // of this enum are dumped as integer values.
270 // This function corrects enum values of old studies given as args (Type,Compare,...)
271 // We can find out how to correct them by value of BinaryOp which can have only two
272 // values: FT_Undefined or FT_LogicalNOT.
273 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
274 // where PythonDump appeared
275 // v 3.0.0: FT_Undefined == 25
276 // v 3.1.0: FT_Undefined == 26, new items:
278 // v 4.1.2: FT_Undefined == 27, new items:
279 // - FT_BelongToGenSurface = 17
280 // v 5.1.1: FT_Undefined == 32, new items:
281 // - FT_FreeNodes = 10
282 // - FT_FreeFaces = 11
283 // - FT_LinearOrQuadratic = 23
284 // - FT_GroupColor = 24
285 // - FT_ElemGeomType = 25
286 // v 5.1.5: FT_Undefined == 33, new items:
287 // - FT_CoplanarFaces = 26
288 // v 6.2.0: FT_Undefined == 39, new items:
289 // - FT_MaxElementLength2D = 8
290 // - FT_MaxElementLength3D = 9
291 // - FT_BareBorderVolume = 25
292 // - FT_BareBorderFace = 26
293 // - FT_OverConstrainedVolume = 27
294 // - FT_OverConstrainedFace = 28
295 // v 6.5.0: FT_Undefined == 43, new items:
296 // - FT_EqualNodes = 14
297 // - FT_EqualEdges = 15
298 // - FT_EqualFaces = 16
299 // - FT_EqualVolumes = 17
300 // v 6.6.0: FT_Undefined == 44, new items:
301 // - FT_BallDiameter = 37
302 // v 6.7.1: FT_Undefined == 45, new items:
303 // - FT_EntityType = 36
304 // v 7.3.0: FT_Undefined == 46, new items:
305 // - FT_ConnectedElements = 39
307 // It's necessary to continue recording this history and to fill
308 // undef2newItems (see below) accordingly.
310 typedef map< int, vector< int > > TUndef2newItems;
311 static TUndef2newItems undef2newItems;
312 if ( undef2newItems.empty() )
314 undef2newItems[ 26 ].push_back( 7 );
315 undef2newItems[ 27 ].push_back( 17 );
316 { int items[] = { 10, 11, 23, 24, 25 };
317 undef2newItems[ 32 ].assign( items, items+5 ); }
318 undef2newItems[ 33 ].push_back( 26 );
319 { int items[] = { 8, 9, 25, 26, 27, 28 };
320 undef2newItems[ 39 ].assign( items, items+6 ); }
321 { int items[] = { 14, 15, 16, 17 };
322 undef2newItems[ 43 ].assign( items, items+4 ); }
323 undef2newItems[ 44 ].push_back( 37 );
324 undef2newItems[ 45 ].push_back( 36 );
325 undef2newItems[ 46 ].push_back( 39 );
327 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
330 int iType = Type.IntegerValue();
331 int iCompare = Compare.IntegerValue();
332 int iUnaryOp = UnaryOp.IntegerValue();
333 int iBinaryOp = BinaryOp.IntegerValue();
335 // find out integer value of FT_Undefined at the moment of dump
336 int oldUndefined = iBinaryOp;
337 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
340 // apply history to args
341 TUndef2newItems::const_iterator undef_items =
342 undef2newItems.upper_bound( oldUndefined );
343 if ( undef_items != undef2newItems.end() )
345 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
346 for ( ; undef_items != undef2newItems.end(); ++undef_items )
348 const vector< int > & addedItems = undef_items->second;
349 for ( size_t i = 0; i < addedItems.size(); ++i )
350 for ( int iArg = 0; iArg < 4; ++iArg )
352 int& arg = *pArg[iArg];
353 if ( arg >= addedItems[i] )
357 Type = TCollection_AsciiString( iType );
358 Compare = TCollection_AsciiString( iCompare );
359 UnaryOp = TCollection_AsciiString( iUnaryOp );
360 BinaryOp = TCollection_AsciiString( iBinaryOp );
364 //================================================================================
366 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
367 * arguments of a given command by a list "[x,y,z]" if the list is accesible
370 //================================================================================
372 void StructToList( Handle( _pyCommand)& theCommand )
374 static TStringSet methodsAcceptingList;
375 if ( methodsAcceptingList.empty() ) {
376 const char * methodNames[] = {
377 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
378 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
379 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
380 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
381 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
382 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
383 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
384 "Translate","TranslateMakeGroups","TranslateMakeMesh",
385 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
386 "ExtrusionAlongPathX","ExtrusionAlongPathObjX"
387 ,"" }; // <- mark of the end
388 methodsAcceptingList.Insert( methodNames );
390 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
392 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
394 const _AString & arg = theCommand->GetArg( i );
395 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
396 arg.Search( "SMESH.DirStruct" ) == 1 )
398 Handle(_pyCommand) workCmd = new _pyCommand( arg );
399 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
401 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
403 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
405 _AString newArg = "[ ";
406 newArg += ( workCmd->GetArg( 1 ) + ", " +
407 workCmd->GetArg( 2 ) + ", " +
408 workCmd->GetArg( 3 ) + " ]");
409 theCommand->SetArg( i, newArg );
415 //================================================================================
417 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
418 * a list "[id1,id2]" if the list is an accesible type of argument.
420 //================================================================================
422 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
424 static TStringSet methodsAcceptingList;
425 if ( methodsAcceptingList.empty() ) {
426 const char * methodNames[] = {
427 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
428 "ExportCGNS","ExportGMF",
429 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
430 "ScaleMakeGroups","Scale","ScaleMakeMesh",
431 "FindCoincidentNodesOnPartBut","DoubleElements"
432 ,"" }; // <- mark of the end
433 methodsAcceptingList.Insert( methodNames );
435 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
437 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
439 _pyCommand argCmd( theCommand->GetArg( i ));
440 if ( argCmd.GetMethod() == "GetIDSource" &&
441 argCmd.GetNbArgs() == 2 )
443 theCommand->SetArg( i, argCmd.GetArg( 1 ));
450 //================================================================================
452 * \brief Convert a python script using commands of smeshBuilder.py
453 * \param theScriptLines - Lines of the input script
454 * \param theEntry2AccessorMethod - returns method names to access to
455 * objects wrapped with python class
456 * \param theObjectNames - names of objects
457 * \param theRemovedObjIDs - entries of objects whose created commands were removed
458 * \param theHistoricalDump - true means to keep all commands, false means
459 * to exclude commands relating to objects removed from study
460 * \retval TCollection_AsciiString - Convertion result
462 //================================================================================
465 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
466 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
467 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
468 std::set< TCollection_AsciiString >& theRemovedObjIDs,
469 SALOMEDS::Study_ptr& theStudy,
470 const bool theToKeepAllCommands)
472 std::list< TCollection_AsciiString >::iterator lineIt;
473 // process notebook variables
475 SMESH_NoteBook aNoteBook;
477 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
478 aNoteBook.AddCommand( *lineIt );
480 theScriptLines.clear();
482 aNoteBook.ReplaceVariables();
484 aNoteBook.GetResultLines( theScriptLines );
487 // convert to smeshBuilder.py API
489 theGen = new _pyGen( theEntry2AccessorMethod,
493 theToKeepAllCommands );
495 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
496 theGen->AddCommand( *lineIt );
498 theScriptLines.clear();
502 #ifdef DUMP_CONVERSION
503 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
506 // clean commmands of removed objects depending on myIsPublished flag
507 theGen->ClearCommands();
509 // reorder commands after conversion
510 list< Handle(_pyCommand) >::iterator cmd;
513 orderChanges = false;
514 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
515 if ( (*cmd)->SetDependentCmdsAfter() )
517 } while ( orderChanges );
519 // concat commands back into a script
520 TCollection_AsciiString aPrevCmd;
521 set<_pyID> createdObjects;
522 createdObjects.insert( "smeshBuilder" );
523 createdObjects.insert( "smesh" );
524 createdObjects.insert( "theStudy" );
525 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
527 #ifdef DUMP_CONVERSION
528 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
530 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
531 CheckObjectPresence( *cmd, createdObjects );
532 if ( !(*cmd)->IsEmpty() ) {
533 aPrevCmd = (*cmd)->GetString();
534 theScriptLines.push_back( aPrevCmd );
543 //================================================================================
545 * \brief _pyGen constructor
547 //================================================================================
549 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
550 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
551 std::set< TCollection_AsciiString >& theRemovedObjIDs,
552 SALOMEDS::Study_ptr& theStudy,
553 const bool theToKeepAllCommands)
554 : _pyObject( new _pyCommand( "", 0 )),
556 myID2AccessorMethod( theEntry2AccessorMethod ),
557 myObjectNames( theObjectNames ),
558 myRemovedObjIDs( theRemovedObjIDs ),
560 myToKeepAllCommands( theToKeepAllCommands ),
561 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
562 myGeomIDNb(0), myGeomIDIndex(-1)
564 // make that GetID() to return TPythonDump::SMESHGenName()
565 GetCreationCmd()->Clear();
566 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
567 GetCreationCmd()->GetString() += "=";
569 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
570 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
574 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
575 if ( geomComp->_is_nil() ) return;
576 CORBA::String_var entry = geomComp->GetID();
579 // find a SMESH entry
581 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
582 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
583 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
586 // find 1st difference between smeshID and geomID
587 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
588 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
589 if ( geomID.Value( i ) != smeshID.Value( i ))
591 myGeomIDNb = geomID.Value( i );
597 //================================================================================
599 * \brief name of SMESH_Gen in smeshBuilder.py
601 //================================================================================
603 const char* _pyGen::AccessorMethod() const
605 return SMESH_2smeshpy::GenName();
608 //================================================================================
610 * \brief Convert a command using a specific converter
611 * \param theCommand - the command to convert
613 //================================================================================
615 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
617 // store theCommand in the sequence
618 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
620 Handle(_pyCommand) aCommand = myCommands.back();
621 #ifdef DUMP_CONVERSION
622 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
625 const _pyID& objID = aCommand->GetObject();
627 if ( objID.IsEmpty() )
630 // Prevent moving a command creating a sub-mesh to the end of the script
631 // if the sub-mesh is used in theCommand as argument
632 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
634 // PlaceSubmeshAfterItsCreation( aCommand );
637 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
638 StructToList( aCommand );
640 const TCollection_AsciiString& method = aCommand->GetMethod();
642 // not to erase _pySelfEraser's etc. used as args in some commands
644 #ifdef USE_STRING_FAMILY
645 std::list<_pyID> objIDs;
646 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
648 std::list<_pyID>::iterator objID = objIDs.begin();
649 for ( ; objID != objIDs.end(); ++objID )
651 Handle(_pyObject) obj = FindObject( *objID );
654 obj->AddArgCmd( aCommand );
655 //cout << objID << " found in " << theCommand << endl;
660 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
661 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
662 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
664 Handle(_pyObject) obj = FindObject( *id );
666 obj->AddArgCmd( aCommand );
671 // Find an object to process theCommand
674 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
676 this->Process( aCommand );
677 //addFilterUser( aCommand, theGen ); // protect filters from clearing
681 // SMESH_Mesh method?
682 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
683 if ( id_mesh != myMeshes.end() )
685 //id_mesh->second->AddProcessedCmd( aCommand );
687 // check for mesh editor object
688 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
689 _pyID editorID = aCommand->GetResultValue();
690 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
691 myMeshEditors.insert( make_pair( editorID, editor ));
694 // check for SubMesh objects
695 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
696 _pyID subMeshID = aCommand->GetResultValue();
697 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
698 AddObject( subMesh );
701 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
702 GetIDSourceToList( aCommand );
704 //addFilterUser( aCommand, theGen ); // protect filters from clearing
706 id_mesh->second->Process( aCommand );
707 id_mesh->second->AddProcessedCmd( aCommand );
711 // SMESH_MeshEditor method?
712 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
713 if ( id_editor != myMeshEditors.end() )
715 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
716 GetIDSourceToList( aCommand );
718 //addFilterUser( aCommand, theGen ); // protect filters from clearing
720 // some commands of SMESH_MeshEditor create meshes and groups
721 _pyID meshID, groups;
722 if ( method.Search("MakeMesh") != -1 )
723 meshID = aCommand->GetResultValue();
724 else if ( method == "MakeBoundaryMesh")
725 meshID = aCommand->GetResultValue(1);
726 else if ( method == "MakeBoundaryElements")
727 meshID = aCommand->GetResultValue(2);
729 if ( method.Search("MakeGroups") != -1 ||
730 method == "ExtrusionAlongPathX" ||
731 method == "ExtrusionAlongPathObjX" ||
732 method == "DoubleNodeGroupNew" ||
733 method == "DoubleNodeGroupsNew" ||
734 method == "DoubleNodeElemGroupNew" ||
735 method == "DoubleNodeElemGroupsNew"||
736 method == "DoubleNodeElemGroup2New"||
737 method == "DoubleNodeElemGroups2New"
739 groups = aCommand->GetResultValue();
740 else if ( method == "MakeBoundaryMesh" )
741 groups = aCommand->GetResultValue(2);
742 else if ( method == "MakeBoundaryElements")
743 groups = aCommand->GetResultValue(3);
744 else if ( method == "Create0DElementsOnAllNodes" &&
745 aCommand->GetArg(2).Length() > 2 ) // group name != ''
746 groups = aCommand->GetResultValue();
748 id_editor->second->Process( aCommand );
749 id_editor->second->AddProcessedCmd( aCommand );
752 if ( !meshID.IsEmpty() &&
753 !myMeshes.count( meshID ) &&
754 aCommand->IsStudyEntry( meshID ))
756 _AString processedCommand = aCommand->GetString();
757 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
758 CheckObjectIsReCreated( mesh );
759 myMeshes.insert( make_pair( meshID, mesh ));
761 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
764 if ( !groups.IsEmpty() )
766 if ( !aCommand->IsStudyEntry( meshID ))
767 meshID = id_editor->second->GetMesh();
768 Handle(_pyMesh) mesh = myMeshes[ meshID ];
770 list< _pyID > idList = aCommand->GetStudyEntries( groups );
771 list< _pyID >::iterator grID = idList.begin();
772 for ( ; grID != idList.end(); ++grID )
773 if ( !myObjects.count( *grID ))
775 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
777 if ( !mesh.IsNull() ) mesh->AddGroup( group );
781 } // SMESH_MeshEditor methods
783 // SMESH_Hypothesis method?
784 Handle(_pyHypothesis) hyp = FindHyp( objID );
785 if ( !hyp.IsNull() && !hyp->IsAlgo() )
787 hyp->Process( aCommand );
788 hyp->AddProcessedCmd( aCommand );
792 // aFilterManager.CreateFilter() ?
793 if ( aCommand->GetMethod() == "CreateFilter" )
795 // Set a more human readable name to a filter
796 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
797 _pyID newID, filterID = aCommand->GetResultValue();
798 int pos = filterID.Search( "0x" );
800 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
802 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
805 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
806 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
808 // create _pySelfEraser for functors
809 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
810 functor->IgnoreOwnCalls(); // to erase if not used as an argument
811 AddObject( functor );
814 // other object method?
815 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
816 if ( id_obj != myObjects.end() ) {
817 id_obj->second->Process( aCommand );
818 id_obj->second->AddProcessedCmd( aCommand );
822 // Add access to a wrapped mesh
823 AddMeshAccessorMethod( aCommand );
825 // Add access to a wrapped algorithm
826 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
828 // PAL12227. PythonDump was not updated at proper time; result is
829 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
830 // TypeError: __init__() takes exactly 11 arguments (10 given)
831 const char wrongCommand[] = "SMESH.Filter.Criterion(";
832 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
834 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
835 // there must be 10 arguments, 5-th arg ThresholdID is missing,
836 const int wrongNbArgs = 9, missingArg = 5;
837 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
839 for ( int i = wrongNbArgs; i > missingArg; --i )
840 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
841 tmpCmd.SetArg( missingArg, "''");
842 aCommand->GetString().Trunc( beg - 1 );
843 aCommand->GetString() += tmpCmd.GetString();
846 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
848 // instead of "SMESH.Filter.Criterion(
849 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
850 // 1 2 3 4 5 6 7 8 9 10
851 // in order to avoid the problem of type mismatch of long and FunctorType
852 const TCollection_AsciiString
853 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
854 TCollection_AsciiString
855 Type = aCommand->GetArg(1), // long
856 Compare = aCommand->GetArg(2), // long
857 Threshold = aCommand->GetArg(3), // double
858 ThresholdStr = aCommand->GetArg(4), // string
859 ThresholdID = aCommand->GetArg(5), // string
860 UnaryOp = aCommand->GetArg(6), // long
861 BinaryOp = aCommand->GetArg(7), // long
862 Tolerance = aCommand->GetArg(8), // double
863 TypeOfElement = aCommand->GetArg(9), // ElementType
864 Precision = aCommand->GetArg(10); // long
865 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
866 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
867 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
868 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
869 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
871 if ( Compare == "SMESH.FT_EqualTo" )
874 aCommand->RemoveArgs();
875 aCommand->SetObject( SMESH_2smeshpy::GenName() );
876 aCommand->SetMethod( "GetCriterion" );
878 aCommand->SetArg( 1, TypeOfElement );
879 aCommand->SetArg( 2, Type );
880 aCommand->SetArg( 3, Compare );
882 if ( Threshold.IsIntegerValue() )
884 int iGeom = Threshold.IntegerValue();
885 if ( Type == "SMESH.FT_ElemGeomType" )
887 // set SMESH.GeometryType instead of a numerical Threshold
888 const int nbTypes = SMESH::Geom_BALL+1;
889 const char* types[nbTypes] = {
890 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
891 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
892 "Geom_POLYHEDRA", "Geom_BALL" };
893 if ( -1 < iGeom && iGeom < nbTypes )
894 Threshold = SMESH + types[ iGeom ];
896 if (Type == "SMESH.FT_EntityType")
898 // set SMESH.EntityType instead of a numerical Threshold
899 const int nbTypes = SMESH::Entity_Ball+1;
900 const char* types[nbTypes] = {
901 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
902 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
903 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
904 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
905 "Entity_Pyramid", "Entity_Quad_Pyramid",
906 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
907 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
908 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
909 if ( -1 < iGeom && iGeom < nbTypes )
910 Threshold = SMESH + types[ iGeom ];
913 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
914 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
915 else if ( ThresholdStr.Length() != 2 )
916 aCommand->SetArg( 4, ThresholdStr );
917 else if ( ThresholdID.Length() != 2 )
918 aCommand->SetArg( 4, ThresholdID );
920 aCommand->SetArg( 4, Threshold );
921 // find the last not default arg
923 if ( Tolerance == dfltTol ) {
925 if ( BinaryOp == dfltFunctor ) {
927 if ( UnaryOp == dfltFunctor )
931 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
932 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
933 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
934 if ( Precision != dfltPreci )
936 TCollection_AsciiString crit = aCommand->GetResultValue();
937 aCommand->GetString() += "; ";
938 aCommand->GetString() += crit + ".Precision = " + Precision;
944 //================================================================================
946 * \brief Convert the command or remember it for later conversion
947 * \param theCommand - The python command calling a method of SMESH_Gen
949 //================================================================================
951 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
953 // there are methods to convert:
954 // CreateMesh( shape )
955 // Concatenate( [mesh1, ...], ... )
956 // CreateHypothesis( theHypType, theLibName )
957 // Compute( mesh, geom )
958 // Evaluate( mesh, geom )
960 TCollection_AsciiString method = theCommand->GetMethod();
962 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
964 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
968 if ( method == "CreateMeshesFromUNV" ||
969 method == "CreateMeshesFromSTL" ||
970 method == "CopyMesh" ) // command result is a mesh
972 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
976 if( method == "CreateMeshesFromMED" ||
977 method == "CreateMeshesFromSAUV"||
978 method == "CreateMeshesFromCGNS" ||
979 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
981 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
982 std::list< _pyID >::iterator meshID = meshIDs.begin();
983 for ( ; meshID != meshIDs.end(); ++meshID )
985 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
988 if ( method == "CreateMeshesFromGMF" )
990 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
991 // CreateMeshesFromGMF( theFileName )
992 _AString file = theCommand->GetArg(1);
993 theCommand->RemoveArgs();
994 theCommand->SetArg( 1, file );
998 // CreateHypothesis()
999 if ( method == "CreateHypothesis" )
1001 // issue 199929, remove standard library name (default parameter)
1002 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1003 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1004 // keep the first argument
1005 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1006 theCommand->RemoveArgs();
1007 theCommand->SetArg( 1, arg );
1010 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1011 CheckObjectIsReCreated( hyp );
1012 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1017 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1018 if ( method == "Compute" )
1020 const _pyID& meshID = theCommand->GetArg( 1 );
1021 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1022 if ( id_mesh != myMeshes.end() ) {
1023 theCommand->SetObject( meshID );
1024 theCommand->RemoveArgs();
1025 id_mesh->second->Process( theCommand );
1026 id_mesh->second->AddProcessedCmd( theCommand );
1031 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1032 if ( method == "Evaluate" )
1034 const _pyID& meshID = theCommand->GetArg( 1 );
1035 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1036 if ( id_mesh != myMeshes.end() ) {
1037 theCommand->SetObject( meshID );
1038 _pyID geom = theCommand->GetArg( 2 );
1039 theCommand->RemoveArgs();
1040 theCommand->SetArg( 1, geom );
1041 id_mesh->second->AddProcessedCmd( theCommand );
1046 // objects erasing creation command if no more its commands invoked:
1047 // SMESH_Pattern, FilterManager
1048 if ( method == "GetPattern" ||
1049 method == "CreateFilterManager" ||
1050 method == "CreateMeasurements" )
1052 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1053 if ( !AddObject( obj ) )
1054 theCommand->Clear(); // already created
1056 // Concatenate( [mesh1, ...], ... )
1057 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1059 if ( method == "ConcatenateWithGroups" ) {
1060 theCommand->SetMethod( "Concatenate" );
1061 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1063 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1065 AddMeshAccessorMethod( theCommand );
1067 else if ( method == "SetName" ) // SetName(obj,name)
1069 // store theCommand as one of object commands to erase it along with the object
1070 const _pyID& objID = theCommand->GetArg( 1 );
1071 Handle(_pyObject) obj = FindObject( objID );
1072 if ( !obj.IsNull() )
1073 obj->AddProcessedCmd( theCommand );
1076 // Replace name of SMESH_Gen
1078 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1079 static TStringSet smeshpyMethods;
1080 if ( smeshpyMethods.empty() ) {
1081 const char * names[] =
1082 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1083 "GetPattern","GetSubShapesId",
1084 "" }; // <- mark of array end
1085 smeshpyMethods.Insert( names );
1087 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1088 // smeshgen.Method() --> smesh.Method()
1089 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1091 // smeshgen.Method() --> smesh.Method()
1092 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1095 //================================================================================
1097 * \brief Convert the remembered commands
1099 //================================================================================
1101 void _pyGen::Flush()
1103 // create an empty command
1104 myLastCommand = new _pyCommand();
1106 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1107 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1108 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1110 if ( IsToKeepAllCommands() ) // historical dump
1112 // set myIsPublished = true to all objects
1113 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1114 id_mesh->second->SetRemovedFromStudy( false );
1115 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1116 id_hyp->second->SetRemovedFromStudy( false );
1117 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1118 id_obj->second->SetRemovedFromStudy( false );
1122 // let hypotheses find referred objects in order to prevent clearing
1123 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1124 list< Handle(_pyMesh) > fatherMeshes;
1125 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1126 if ( !id_hyp->second.IsNull() )
1127 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1129 // set myIsPublished = false to all objects depending on
1130 // meshes built on a removed geometry
1131 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1132 if ( id_mesh->second->IsNotGeomPublished() )
1133 id_mesh->second->SetRemovedFromStudy( true );
1136 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1137 if ( ! id_mesh->second.IsNull() )
1138 id_mesh->second->Flush();
1141 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1142 if ( !id_hyp->second.IsNull() ) {
1143 id_hyp->second->Flush();
1144 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1145 if ( !id_hyp->second->IsWrapped() )
1146 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1149 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1150 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1151 for ( ; robj != myOrderedObjects.rend(); ++robj )
1152 if ( ! robj->IsNull() )
1154 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1155 for ( ; obj != myOrderedObjects.end(); ++obj )
1156 if ( ! obj->IsNull() )
1159 myLastCommand->SetOrderNb( ++myNbCommands );
1160 myCommands.push_back( myLastCommand );
1163 //================================================================================
1165 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1166 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1168 //================================================================================
1170 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1172 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1173 // for ( ; id_obj != myObjects.end(); ++id_obj )
1175 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1176 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1178 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1179 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1181 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1182 // list< _pyID >::iterator id = idList.begin();
1183 // for ( ; id != idList.end(); ++id )
1184 // if ( id_obj->first == *id )
1185 // // _pySubMesh::Process() does what we need
1186 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1191 //================================================================================
1193 * \brief Clean commmands of removed objects depending on myIsPublished flag
1195 //================================================================================
1197 void _pyGen::ClearCommands()
1199 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1200 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1201 id_mesh->second->ClearCommands();
1203 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1204 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1205 if ( !id_hyp->second.IsNull() )
1206 id_hyp->second->ClearCommands();
1208 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1209 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1210 for ( ; robj != myOrderedObjects.rend(); ++robj )
1211 if ( ! robj->IsNull() )
1212 (*robj)->ClearCommands();
1213 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1214 for ( ; obj != myOrderedObjects.end(); ++obj )
1215 if ( ! obj->IsNull() )
1216 (*obj)->ClearCommands();
1219 //================================================================================
1221 * \brief Release mutual handles of objects
1223 //================================================================================
1227 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1228 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1229 id_mesh->second->Free();
1232 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1233 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1234 id_ed->second->Free();
1235 myMeshEditors.clear();
1237 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1238 for ( ; id_obj != myObjects.end(); ++id_obj )
1239 id_obj->second->Free();
1242 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1243 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1244 if ( !id_hyp->second.IsNull() )
1245 id_hyp->second->Free();
1248 myFile2ExportedMesh.clear();
1250 //myKeepAgrCmdsIDs.Print();
1253 //================================================================================
1255 * \brief Add access method to mesh that is an argument
1256 * \param theCmd - command to add access method
1257 * \retval bool - true if added
1259 //================================================================================
1261 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1264 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1265 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1266 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1272 //================================================================================
1274 * \brief Add access method to algo that is an object or an argument
1275 * \param theCmd - command to add access method
1276 * \retval bool - true if added
1278 //================================================================================
1280 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1283 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1284 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1285 if ( !id_hyp->second.IsNull() &&
1286 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1287 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1288 id_hyp->second->AccessorMethod() ))
1294 //================================================================================
1296 * \brief Find hypothesis by ID (entry)
1297 * \param theHypID - The hypothesis ID
1298 * \retval Handle(_pyHypothesis) - The found hypothesis
1300 //================================================================================
1302 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1304 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1305 if ( id_hyp != myHypos.end() &&
1306 !id_hyp->second.IsNull() &&
1307 theHypID == id_hyp->second->GetID() )
1308 return id_hyp->second;
1309 return Handle(_pyHypothesis)();
1312 //================================================================================
1314 * \brief Find algorithm able to create a hypothesis
1315 * \param theGeom - The shape ID the algorithm was created on
1316 * \param theMesh - The mesh ID that created the algorithm
1317 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1318 * \retval Handle(_pyHypothesis) - The found algo
1320 //================================================================================
1322 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1323 const Handle(_pyHypothesis)& theHypothesis )
1325 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1326 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1327 if ( !id_hyp->second.IsNull() &&
1328 id_hyp->second->IsAlgo() &&
1329 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1330 id_hyp->second->GetGeom() == theGeom &&
1331 id_hyp->second->GetMesh() == theMesh )
1332 return id_hyp->second;
1333 return Handle(_pyHypothesis)();
1336 //================================================================================
1338 * \brief Find subMesh by ID (entry)
1339 * \param theSubMeshID - The subMesh ID
1340 * \retval Handle(_pySubMesh) - The found subMesh
1342 //================================================================================
1344 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1346 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1347 if ( id_subMesh != myObjects.end() )
1348 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1349 return Handle(_pySubMesh)();
1353 //================================================================================
1355 * \brief Change order of commands in the script
1356 * \param theCmd1 - One command
1357 * \param theCmd2 - Another command
1359 //================================================================================
1361 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1363 list< Handle(_pyCommand) >::iterator pos1, pos2;
1364 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1365 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1366 myCommands.insert( pos1, theCmd2 );
1367 myCommands.insert( pos2, theCmd1 );
1368 myCommands.erase( pos1 );
1369 myCommands.erase( pos2 );
1371 int nb1 = theCmd1->GetOrderNb();
1372 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1373 theCmd2->SetOrderNb( nb1 );
1374 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1375 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1378 //================================================================================
1380 * \brief Set one command after the other
1381 * \param theCmd - Command to move
1382 * \param theAfterCmd - Command ater which to insert the first one
1384 //================================================================================
1386 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1388 setNeighbourCommand( theCmd, theAfterCmd, true );
1391 //================================================================================
1393 * \brief Set one command before the other
1394 * \param theCmd - Command to move
1395 * \param theBeforeCmd - Command before which to insert the first one
1397 //================================================================================
1399 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1401 setNeighbourCommand( theCmd, theBeforeCmd, false );
1404 //================================================================================
1406 * \brief Set one command before or after the other
1407 * \param theCmd - Command to move
1408 * \param theOtherCmd - Command ater or before which to insert the first one
1410 //================================================================================
1412 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1413 Handle(_pyCommand)& theOtherCmd,
1414 const bool theIsAfter )
1416 list< Handle(_pyCommand) >::iterator pos;
1417 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1418 myCommands.erase( pos );
1419 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1420 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1423 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1424 (*pos)->SetOrderNb( i++ );
1427 //================================================================================
1429 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1431 //================================================================================
1433 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1435 // No more needed after adding _pyObject::myArgCommands
1437 // const char filterPrefix[] = "aFilter0x";
1438 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1441 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1443 // const _AString & arg = theCommand->GetArg( i );
1444 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1445 // if ( arg.Search( filterPrefix ) != 1 )
1448 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1449 // if ( !filter.IsNull() )
1451 // filter->AddUser( user );
1452 // if ( !filter->GetNewID().IsEmpty() )
1453 // theCommand->SetArg( i, filter->GetNewID() );
1458 //================================================================================
1460 * \brief Set command be last in list of commands
1461 * \param theCmd - Command to be last
1463 //================================================================================
1465 Handle(_pyCommand)& _pyGen::GetLastCommand()
1467 return myLastCommand;
1470 //================================================================================
1472 * \brief Set method to access to object wrapped with python class
1473 * \param theID - The wrapped object entry
1474 * \param theMethod - The accessor method
1476 //================================================================================
1478 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1480 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1483 //================================================================================
1485 * \brief Generated new ID for object and assign with existing name
1486 * \param theID - ID of existing object
1488 //================================================================================
1490 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1495 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1497 while ( myObjectNames.IsBound( aNewID ) );
1499 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1500 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1501 : _pyID( "A" ) + aNewID );
1505 //================================================================================
1507 * \brief Stores theObj in myObjects
1509 //================================================================================
1511 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1513 if ( theObj.IsNull() ) return false;
1515 CheckObjectIsReCreated( theObj );
1519 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1520 add = myMeshes.insert( make_pair( theObj->GetID(),
1521 Handle(_pyMesh)::DownCast( theObj ))).second;
1523 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1524 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1525 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1528 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1529 if ( add ) myOrderedObjects.push_back( theObj );
1534 //================================================================================
1536 * \brief Erases an existing object with the same ID. This method should be called
1537 * before storing theObj in _pyGen
1539 //================================================================================
1541 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1543 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1546 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1547 Handle(_pyObject) existing =
1548 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1549 if ( !existing.IsNull() && existing != theObj )
1551 existing->SetRemovedFromStudy( true );
1552 existing->ClearCommands();
1555 if ( myHypos.count( theObj->GetID() ))
1556 myHypos.erase( theObj->GetID() );
1558 else if ( myMeshes.count( theObj->GetID() ))
1560 myMeshes.erase( theObj->GetID() );
1562 else if ( myObjects.count( theObj->GetID() ))
1564 myObjects.erase( theObj->GetID() );
1569 //================================================================================
1571 * \brief Re-register an object with other ID to make it Process() commands of
1572 * other object having this ID
1574 //================================================================================
1576 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1578 if ( theObj.IsNull() ) return;
1580 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1581 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1583 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1584 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1587 myObjects.insert( make_pair( theID, theObj ));
1590 //================================================================================
1592 * \brief Finds a _pyObject by ID
1594 //================================================================================
1596 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1599 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1600 if ( id_obj != myObjects.end() )
1601 return id_obj->second;
1604 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1605 if ( id_obj != myMeshes.end() )
1606 return id_obj->second;
1609 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1610 // if ( id_obj != myMeshEditors.end() )
1611 // return id_obj->second;
1613 return Handle(_pyObject)();
1616 //================================================================================
1618 * \brief Check if a study entry is under GEOM component
1620 //================================================================================
1622 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1626 return ( myGeomIDIndex <= theObjID.Length() &&
1627 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1628 _pyCommand::IsStudyEntry( theObjID ));
1633 //================================================================================
1635 * \brief Returns true if an object is not present in a study
1637 //================================================================================
1639 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1641 if ( theObjID.IsEmpty() ) return false;
1643 if ( myObjectNames.IsBound( theObjID ))
1644 return false; // SMESH object is in study
1646 // either the SMESH object is not in study or it is a GEOM object
1647 if ( IsGeomObject( theObjID ))
1649 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1650 if ( so->_is_nil() ) return true;
1651 CORBA::Object_var obj = so->GetObject();
1652 return CORBA::is_nil( obj );
1654 return true; // SMESH object not in study
1657 //================================================================================
1659 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1660 * this object is not dumped
1661 * \param [in] theObjID - entry of the object whose creation command was eliminated
1663 //================================================================================
1665 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1667 myRemovedObjIDs.insert( theObjID );
1670 //================================================================================
1672 * \brief Return reader of hypotheses of plugins
1674 //================================================================================
1676 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1678 if (myHypReader.IsNull() )
1679 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1685 //================================================================================
1687 * \brief Mesh created by SMESH_Gen
1689 //================================================================================
1691 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1692 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1694 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1695 myGeomNotInStudy = true;
1697 // convert my creation command --> smeshpy.Mesh(...)
1698 Handle(_pyCommand) creationCmd = GetCreationCmd();
1699 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1700 creationCmd->SetMethod( "Mesh" );
1701 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1704 //================================================================================
1706 * \brief Mesh created by SMESH_MeshEditor
1708 //================================================================================
1710 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1711 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1713 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1715 // this mesh depends on the exported mesh
1716 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1717 if ( !file.IsEmpty() )
1719 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1720 addFatherMesh( exportData.myMesh );
1721 if ( !exportData.myLastComputeCmd.IsNull() )
1723 // restore cleared Compute() by which the exported mesh was generated
1724 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1725 // protect that Compute() cmd from clearing
1726 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1727 exportData.myMesh->myLastComputeCmd.Nullify();
1731 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1733 // this mesh depends on concatenated meshes
1734 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1735 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1736 list< _pyID >::iterator meshID = idList.begin();
1737 for ( ; meshID != idList.end(); ++meshID )
1738 addFatherMesh( *meshID );
1740 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1742 // this mesh depends on a copied IdSource
1743 const _pyID& objID = theCreationCmd->GetArg( 1 );
1744 addFatherMesh( objID );
1746 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1747 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1748 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1750 // this mesh depends on a source mesh
1751 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1752 const _pyID& meshID = theCreationCmd->GetObject();
1753 addFatherMesh( meshID );
1756 // convert my creation command
1757 Handle(_pyCommand) creationCmd = GetCreationCmd();
1758 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1759 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1762 //================================================================================
1764 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1765 * \param theCommand - Engine method called for this mesh
1767 //================================================================================
1769 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1771 // some methods of SMESH_Mesh interface needs special conversion
1772 // to methods of Mesh python class
1774 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1775 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1776 // 2. AddHypothesis(geom, hyp)
1777 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1778 // 3. CreateGroupFromGEOM(type, name, grp)
1779 // --> in Mesh.Group(grp, name="")
1780 // 4. ExportToMED(f, auto_groups, version)
1781 // --> in Mesh.ExportMED( f, auto_groups, version )
1784 const TCollection_AsciiString& method = theCommand->GetMethod();
1785 // ----------------------------------------------------------------------
1786 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1788 if ( !theGen->IsToKeepAllCommands() ) // !historical
1790 list< Handle(_pyHypothesis) >::iterator hyp;
1791 if ( !myLastComputeCmd.IsNull() )
1793 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1794 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1796 myLastComputeCmd->Clear();
1798 myLastComputeCmd = theCommand;
1800 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1801 (*hyp)->MeshComputed( myLastComputeCmd );
1805 // ----------------------------------------------------------------------
1806 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1808 if ( !theGen->IsToKeepAllCommands() ) // !historical
1811 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1812 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1813 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1815 if ( !myLastComputeCmd.IsNull() )
1817 list< Handle(_pyHypothesis) >::iterator hyp;
1818 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1819 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1821 myLastComputeCmd->Clear();
1824 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1825 for ( ; e != myEditors.end(); ++e )
1827 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1828 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1829 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1830 if ( !(*cmd)->IsEmpty() )
1832 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1836 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1839 // ----------------------------------------------------------------------
1840 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1841 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1842 if ( !subMesh.IsNull() ) {
1843 subMesh->SetCreator( this );
1844 mySubmeshes.push_back( subMesh );
1847 // ----------------------------------------------------------------------
1848 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1849 myAddHypCmds.push_back( theCommand );
1851 const _pyID& hypID = theCommand->GetArg( 2 );
1852 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1853 if ( !hyp.IsNull() ) {
1854 myHypos.push_back( hyp );
1855 if ( hyp->GetMesh().IsEmpty() )
1856 hyp->SetMesh( this->GetID() );
1859 // ----------------------------------------------------------------------
1860 else if ( method == "CreateGroup" ||
1861 method == "CreateGroupFromGEOM" ||
1862 method == "CreateGroupFromFilter" )
1864 Handle(_pyGroup) group = new _pyGroup( theCommand );
1865 myGroups.push_back( group );
1866 theGen->AddObject( group );
1868 // ----------------------------------------------------------------------
1869 // update list of groups
1870 else if ( method == "GetGroups" )
1872 bool allGroupsRemoved = true;
1873 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1874 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1875 list< _pyID >::iterator grID = idList.begin();
1876 const int nbGroupsBefore = myGroups.size();
1877 Handle(_pyObject) obj;
1878 for ( ; grID != idList.end(); ++grID )
1880 obj = theGen->FindObject( *grID );
1883 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1884 theGen->AddObject( group );
1885 myGroups.push_back( group );
1888 if ( !obj->CanClear() )
1889 allGroupsRemoved = false;
1891 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1892 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1894 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1896 // check if the preceding command is Compute();
1897 // if GetGroups() is just after Compute(), this can mean that the groups
1898 // were created by some algorithm and hence Compute() should not be discarded
1899 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1900 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1901 while ( (*cmd)->GetMethod() == "GetGroups" )
1903 if ( myLastComputeCmd == (*cmd))
1904 // protect last Compute() from clearing by the next Compute()
1905 myLastComputeCmd.Nullify();
1908 // ----------------------------------------------------------------------
1909 // notify a group about full removal
1910 else if ( method == "RemoveGroupWithContents" ||
1911 method == "RemoveGroup")
1913 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1914 const _pyID groupID = theCommand->GetArg( 1 );
1915 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1916 if ( !grp.IsNull() )
1918 if ( method == "RemoveGroupWithContents" )
1919 grp->RemovedWithContents();
1920 // to clear RemoveGroup() if the group creation is cleared
1921 grp->AddProcessedCmd( theCommand );
1925 // ----------------------------------------------------------------------
1926 else if ( theCommand->MethodStartsFrom( "Export" ))
1928 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1929 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1931 theCommand->SetMethod( "ExportMED" );
1932 if ( theCommand->GetNbArgs() == 5 )
1934 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1935 _AString autoDimension = theCommand->GetArg( 5 );
1936 theCommand->SetArg( 5, "None" );
1937 theCommand->SetArg( 6, autoDimension );
1940 else if ( method == "ExportCGNS" )
1941 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1942 _pyID partID = theCommand->GetArg( 1 );
1943 int nbArgs = theCommand->GetNbArgs();
1944 for ( int i = 2; i <= nbArgs; ++i )
1945 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1946 theCommand->SetArg( nbArgs, partID );
1948 else if ( method == "ExportGMF" )
1949 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1950 _pyID partID = theCommand->GetArg( 1 );
1951 _AString file = theCommand->GetArg( 2 );
1952 theCommand->RemoveArgs();
1953 theCommand->SetArg( 1, file );
1954 theCommand->SetArg( 2, partID );
1956 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1957 { // ExportPartTo*(part, ...) -> Export*(..., part)
1959 // remove "PartTo" from the method
1960 TCollection_AsciiString newMethod = method;
1961 newMethod.Remove( 7, 6 );
1962 theCommand->SetMethod( newMethod );
1963 // make the 1st arg be the last one (or last but one for ExportMED())
1964 _pyID partID = theCommand->GetArg( 1 );
1965 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1966 for ( int i = 2; i <= nbArgs; ++i )
1967 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1968 theCommand->SetArg( nbArgs, partID );
1970 // remember file name
1971 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1972 ExportedMeshData( this, myLastComputeCmd ));
1974 // ----------------------------------------------------------------------
1975 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1977 _pyID hypID = theCommand->GetArg( 2 );
1978 _pyID geomID = theCommand->GetArg( 1 );
1979 bool isLocal = ( geomID != GetGeom() );
1981 // check if this mesh still has corresponding addition command
1982 Handle(_pyCommand) addCmd;
1983 list< Handle(_pyCommand) >::iterator cmd;
1984 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1985 for ( int i = 0; i < 2; ++i )
1987 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1988 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1990 bool sameHyp = true;
1991 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1992 sameHyp = false; // other hyp
1993 if ( (*cmd)->GetNbArgs() == 2 &&
1994 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1995 sameHyp = false; // other geom
1996 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1997 sameHyp = false; // other geom
2001 cmd = addHypCmds.erase( cmd );
2002 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2004 theCommand->Clear();
2013 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2014 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2015 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2016 _pyID geom = theCommand->GetArg( 1 );
2017 theCommand->RemoveArgs();
2018 theCommand->SetArg( 1, hypID );
2019 if ( geom != GetGeom() )
2020 theCommand->SetArg( 2, geom );
2022 // remove hyp from myHypos
2023 myHypos.remove( hyp );
2025 // check for SubMesh order commands
2026 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2028 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2029 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2030 // commands are moved at the end of the script
2031 TCollection_AsciiString subIDs =
2032 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2033 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2034 list< _pyID >::iterator subID = idList.begin();
2035 for ( ; subID != idList.end(); ++subID )
2037 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2038 if ( !subMesh.IsNull() )
2039 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2042 // add accessor method if necessary
2045 if ( NeedMeshAccess( theCommand ))
2046 // apply theCommand to the mesh wrapped by smeshpy mesh
2047 AddMeshAccess( theCommand );
2051 //================================================================================
2053 * \brief Return True if addition of accesor method is needed
2055 //================================================================================
2057 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2059 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2060 // so no conversion is needed for them at all:
2061 static TStringSet sameMethods;
2062 if ( sameMethods.empty() ) {
2063 const char * names[] =
2064 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2065 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2066 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2067 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2068 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2069 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2070 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2071 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2072 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2073 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2074 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2075 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2076 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2077 ,"" }; // <- mark of end
2078 sameMethods.Insert( names );
2081 return !sameMethods.Contains( theCommand->GetMethod() );
2084 //================================================================================
2086 * \brief Convert creation and addition of all algos and hypos
2088 //================================================================================
2090 void _pyMesh::Flush()
2093 // get the meshes this mesh depends on via hypotheses
2094 list< Handle(_pyMesh) > fatherMeshes;
2095 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2096 for ( ; hyp != myHypos.end(); ++hyp )
2097 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2098 myGeomNotInStudy = true;
2100 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2101 for ( ; m != fatherMeshes.end(); ++m )
2102 addFatherMesh( *m );
2103 // if ( removedGeom )
2104 // SetRemovedFromStudy(); // as reffered geometry not in study
2106 if ( myGeomNotInStudy )
2109 list < Handle(_pyCommand) >::iterator cmd;
2111 // try to convert algo addition like this:
2112 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2113 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2115 Handle(_pyCommand) addCmd = *cmd;
2117 _pyID algoID = addCmd->GetArg( 2 );
2118 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2119 if ( algo.IsNull() || !algo->IsAlgo() )
2122 // check and create new algorithm instance if it is already wrapped
2123 if ( algo->IsWrapped() ) {
2124 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2125 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2126 TCollection_AsciiString( " = " ) + theGen->GetID() +
2127 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2128 TCollection_AsciiString( "\" )" );
2130 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2131 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2132 if ( !newAlgo.IsNull() ) {
2133 newAlgo->Assign( algo, this->GetID() );
2134 newAlgo->SetCreationCmd( newCmd );
2136 // set algorithm creation
2137 theGen->SetCommandBefore( newCmd, addCmd );
2138 myHypos.push_back( newAlgo );
2139 if ( !myLastComputeCmd.IsNull() &&
2140 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2141 newAlgo->MeshComputed( myLastComputeCmd );
2146 _pyID geom = addCmd->GetArg( 1 );
2147 bool isLocalAlgo = ( geom != GetGeom() );
2150 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2152 // wrapped algo is created after mesh creation
2153 GetCreationCmd()->AddDependantCmd( addCmd );
2155 if ( isLocalAlgo ) {
2156 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2157 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2158 TCollection_AsciiString( "geom=" ) + geom );
2159 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2160 list < Handle(_pySubMesh) >::iterator smIt;
2161 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2162 Handle(_pySubMesh) subMesh = *smIt;
2163 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2164 if ( geom == subCmd->GetArg( 1 )) {
2165 subCmd->SetObject( algo->GetID() );
2166 subCmd->RemoveArgs();
2167 subMesh->SetCreator( algo );
2172 else // KO - ALGO was already created
2174 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2175 addCmd->RemoveArgs();
2176 addCmd->SetArg( 1, algoID );
2178 addCmd->SetArg( 2, geom );
2179 myNotConvertedAddHypCmds.push_back( addCmd );
2183 // try to convert hypo addition like this:
2184 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2185 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2187 Handle(_pyCommand) addCmd = *cmd;
2188 _pyID hypID = addCmd->GetArg( 2 );
2189 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2190 if ( hyp.IsNull() || hyp->IsAlgo() )
2192 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2194 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2195 _pyID geom = addCmd->GetArg( 1 );
2196 addCmd->RemoveArgs();
2197 addCmd->SetArg( 1, hypID );
2198 if ( geom != GetGeom() )
2199 addCmd->SetArg( 2, geom );
2200 myNotConvertedAddHypCmds.push_back( addCmd );
2204 myAddHypCmds.clear();
2205 mySubmeshes.clear();
2208 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2209 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2213 //================================================================================
2215 * \brief Sets myIsPublished of me and of all objects depending on me.
2217 //================================================================================
2219 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2221 _pyObject::SetRemovedFromStudy(isRemoved);
2223 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2224 for ( ; sm != mySubmeshes.end(); ++sm )
2225 (*sm)->SetRemovedFromStudy(isRemoved);
2227 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2228 for ( ; gr != myGroups.end(); ++gr )
2229 (*gr)->SetRemovedFromStudy(isRemoved);
2231 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2232 for ( ; m != myChildMeshes.end(); ++m )
2233 (*m)->SetRemovedFromStudy(isRemoved);
2235 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2236 for ( ; e != myEditors.end(); ++e )
2237 (*e)->SetRemovedFromStudy(isRemoved);
2240 //================================================================================
2242 * \brief Return true if none of myChildMeshes is in study
2244 //================================================================================
2246 bool _pyMesh::CanClear()
2251 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2252 for ( ; m != myChildMeshes.end(); ++m )
2253 if ( !(*m)->CanClear() )
2259 //================================================================================
2261 * \brief Clear my commands and commands of mesh editor
2263 //================================================================================
2265 void _pyMesh::ClearCommands()
2271 // mark all sub-objects as not removed, except child meshes
2272 list< Handle(_pyMesh) > children;
2273 children.swap( myChildMeshes );
2274 SetRemovedFromStudy( false );
2275 children.swap( myChildMeshes );
2279 _pyObject::ClearCommands();
2281 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2282 for ( ; sm != mySubmeshes.end(); ++sm )
2283 (*sm)->ClearCommands();
2285 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2286 for ( ; gr != myGroups.end(); ++gr )
2287 (*gr)->ClearCommands();
2289 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2290 for ( ; e != myEditors.end(); ++e )
2291 (*e)->ClearCommands();
2294 //================================================================================
2296 * \brief Add a father mesh by ID
2298 //================================================================================
2300 void _pyMesh::addFatherMesh( const _pyID& meshID )
2302 if ( !meshID.IsEmpty() && meshID != GetID() )
2303 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2306 //================================================================================
2308 * \brief Add a father mesh
2310 //================================================================================
2312 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2314 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2316 //myFatherMeshes.push_back( mesh );
2317 mesh->myChildMeshes.push_back( this );
2319 // protect last Compute() from clearing by the next Compute()
2320 mesh->myLastComputeCmd.Nullify();
2324 //================================================================================
2326 * \brief MeshEditor convert its commands to ones of mesh
2328 //================================================================================
2330 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2331 _pyObject( theCreationCmd )
2333 myMesh = theCreationCmd->GetObject();
2334 myCreationCmdStr = theCreationCmd->GetString();
2335 theCreationCmd->Clear();
2337 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2338 if ( !mesh.IsNull() )
2339 mesh->AddEditor( this );
2342 //================================================================================
2344 * \brief convert its commands to ones of mesh
2346 //================================================================================
2348 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2350 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2351 // commands calling these methods are converted to calls of Mesh methods without
2352 // additional modifs, only object is changed from MeshEditor to Mesh.
2353 static TStringSet sameMethods;
2354 if ( sameMethods.empty() ) {
2355 const char * names[] = {
2356 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2357 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2358 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2359 "MoveNode", "MoveClosestNodeToPoint",
2360 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2361 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2362 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2363 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2364 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2365 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2366 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2367 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2368 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2369 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2370 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2371 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2372 "GetLastCreatedElems",
2373 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2374 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2375 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2376 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2377 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2378 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2379 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2380 ,"" }; // <- mark of the end
2381 sameMethods.Insert( names );
2384 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2385 TStringMap diffMethods;
2386 if ( diffMethods.empty() ) {
2387 const char * orig2newName[] = {
2388 // original name --------------> new name
2389 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2390 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2391 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2392 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2393 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2394 ""};// <- mark of the end
2395 diffMethods.Insert( orig2newName );
2398 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2399 // only by last two arguments
2400 static TStringSet diffLastTwoArgsMethods;
2401 if (diffLastTwoArgsMethods.empty() ) {
2402 const char * names[] = {
2403 "MirrorMakeGroups","MirrorObjectMakeGroups",
2404 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2405 "RotateMakeGroups","RotateObjectMakeGroups",
2406 ""};// <- mark of the end
2407 diffLastTwoArgsMethods.Insert( names );
2410 // only a method name is to change?
2411 const TCollection_AsciiString & method = theCommand->GetMethod();
2412 bool isPyMeshMethod = sameMethods.Contains( method );
2413 if ( !isPyMeshMethod )
2415 TCollection_AsciiString newMethod = diffMethods.Value( method );
2416 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2417 theCommand->SetMethod( newMethod );
2419 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2420 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2422 isPyMeshMethod = true;
2423 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2424 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2427 if ( !isPyMeshMethod )
2429 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2430 // functions with the flag "theMakeGroups = True" like:
2431 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2432 int pos = method.Search("MakeGroups");
2435 isPyMeshMethod = true;
2436 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2437 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2439 // 1. Remove "MakeGroups" from the Command
2440 TCollection_AsciiString aMethod = theCommand->GetMethod();
2441 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2444 pos = pos-2; //Remove "0D" from the Command too
2445 aMethod.Trunc(pos-1);
2446 theCommand->SetMethod(aMethod);
2448 // 2. And add last "True" argument(s)
2449 while(nbArgsToAdd--)
2450 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2451 if( is0DmethId || is0DmethObj )
2452 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2456 // ExtrusionSweep0D() -> ExtrusionSweep()
2457 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2458 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2459 method == "ExtrusionSweepObject0D" ))
2461 isPyMeshMethod = true;
2462 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2463 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2464 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2467 // DoubleNode...New(...) -> DoubleNode...(...,True)
2468 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2469 method == "DoubleNodeElemGroupsNew" ||
2470 method == "DoubleNodeGroupNew" ||
2471 method == "DoubleNodeGroupsNew" ||
2472 method == "DoubleNodeElemGroup2New" ||
2473 method == "DoubleNodeElemGroups2New"))
2475 isPyMeshMethod = true;
2476 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2477 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2478 if ( excessLen == 3 )
2480 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2482 else if ( theCommand->GetArg(4) == "0" ||
2483 theCommand->GetArg(5) == "0" )
2485 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2486 // Group = DoubleNodeGroup2New(,,,False, True)
2487 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2488 theCommand->SetResultValue( groupID );
2491 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2492 // FindElementsByPoint(x, y, z, elementType, meshPart)
2493 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2495 isPyMeshMethod = true;
2496 theCommand->SetMethod( "FindElementsByPoint" );
2497 // make the 1st arg be the last one
2498 _pyID partID = theCommand->GetArg( 1 );
2499 int nbArgs = theCommand->GetNbArgs();
2500 for ( int i = 2; i <= nbArgs; ++i )
2501 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2502 theCommand->SetArg( nbArgs, partID );
2504 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2505 if ( !isPyMeshMethod && method == "Reorient2D" )
2507 isPyMeshMethod = true;
2508 _AString mesh = theCommand->GetArg( 1 );
2509 _AString dir = theCommand->GetArg( 2 );
2510 _AString face = theCommand->GetArg( 3 );
2511 _AString point = theCommand->GetArg( 4 );
2512 theCommand->RemoveArgs();
2513 theCommand->SetArg( 1, mesh );
2514 theCommand->SetArg( 2, dir );
2515 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2516 theCommand->SetArg( 3, point );
2518 theCommand->SetArg( 3, face );
2521 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2523 isPyMeshMethod = true;
2524 int crit_arg = theCommand->GetNbArgs();
2525 const _AString& crit = theCommand->GetArg(crit_arg);
2526 if (crit.Search("MaxElementLength2D") != -1)
2527 theCommand->SetArg(crit_arg, "");
2530 if ( isPyMeshMethod )
2532 theCommand->SetObject( myMesh );
2536 // editor creation command is needed only if any editor function is called
2537 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2538 if ( !myCreationCmdStr.IsEmpty() ) {
2539 GetCreationCmd()->GetString() = myCreationCmdStr;
2540 myCreationCmdStr.Clear();
2545 //================================================================================
2547 * \brief Return true if my mesh can be removed
2549 //================================================================================
2551 bool _pyMeshEditor::CanClear()
2553 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2554 return mesh.IsNull() ? true : mesh->CanClear();
2557 //================================================================================
2559 * \brief _pyHypothesis constructor
2560 * \param theCreationCmd -
2562 //================================================================================
2564 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2565 _pyObject( theCreationCmd ), myCurCrMethod(0)
2567 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2570 //================================================================================
2572 * \brief Creates algorithm or hypothesis
2573 * \param theCreationCmd - The engine command creating a hypothesis
2574 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2576 //================================================================================
2578 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2580 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2581 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2583 Handle(_pyHypothesis) hyp, algo;
2586 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2587 if ( hypTypeQuoted.IsEmpty() )
2590 TCollection_AsciiString hypType =
2591 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2593 algo = new _pyAlgorithm( theCreationCmd );
2594 hyp = new _pyHypothesis( theCreationCmd );
2596 if ( hypType == "NumberOfSegments" ) {
2597 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2598 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2599 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2600 hyp->AddArgMethod( "SetNumberOfSegments" );
2601 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2602 hyp->AddArgMethod( "SetScaleFactor" );
2603 hyp->AddArgMethod( "SetReversedEdges" );
2604 // same for ""CompositeSegment_1D:
2605 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2606 hyp->AddArgMethod( "SetNumberOfSegments" );
2607 hyp->AddArgMethod( "SetScaleFactor" );
2608 hyp->AddArgMethod( "SetReversedEdges" );
2610 else if ( hypType == "SegmentLengthAroundVertex" ) {
2611 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2612 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2613 hyp->AddArgMethod( "SetLength" );
2614 // same for ""CompositeSegment_1D:
2615 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2616 hyp->AddArgMethod( "SetLength" );
2618 else if ( hypType == "LayerDistribution2D" ) {
2619 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2620 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2622 else if ( hypType == "LayerDistribution" ) {
2623 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2624 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2626 else if ( hypType == "CartesianParameters3D" ) {
2627 hyp = new _pyComplexParamHypo( theCreationCmd );
2628 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2629 for ( int iArg = 0; iArg < 4; ++iArg )
2630 hyp->setCreationArg( iArg+1, "[]");
2634 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2637 return algo->IsValid() ? algo : hyp;
2640 //================================================================================
2642 * \brief Returns true if addition of this hypothesis to a given mesh can be
2643 * wrapped into hypothesis creation
2645 //================================================================================
2647 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2649 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2651 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2652 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2658 //================================================================================
2660 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2661 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2662 * \param theAlgo - The algo that can create this hypo
2663 * \retval bool - false if the command cant be converted
2665 //================================================================================
2667 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2668 const _pyID& theMesh)
2670 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2672 if ( !IsWrappable( theMesh ))
2675 myGeom = theCmd->GetArg( 1 );
2677 Handle(_pyHypothesis) algo;
2679 // find algo created on myGeom in theMesh
2680 algo = theGen->FindAlgo( myGeom, theMesh, this );
2681 if ( algo.IsNull() )
2683 // attach hypothesis creation command to be after algo creation command
2684 // because it can be new created instance of algorithm
2685 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2689 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2690 theCmd->SetResultValue( GetID() );
2691 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2692 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2693 // set args (geom will be set by _pyMesh calling this method)
2694 theCmd->RemoveArgs();
2695 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2696 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2697 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2699 theCmd->SetArg( i+1, "[]");
2701 // set a new creation command
2702 GetCreationCmd()->Clear();
2703 // replace creation command by wrapped instance
2704 // please note, that hypothesis attaches to algo creation command (see upper)
2705 SetCreationCmd( theCmd );
2708 // clear commands setting arg values
2709 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2710 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2713 // set unknown arg commands after hypo creation
2714 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2715 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2716 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2717 afterCmd->AddDependantCmd( *cmd );
2723 //================================================================================
2725 * \brief Remember hypothesis parameter values
2726 * \param theCommand - The called hypothesis method
2728 //================================================================================
2730 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2732 ASSERT( !myIsAlgo );
2733 if ( !theGen->IsToKeepAllCommands() )
2734 rememberCmdOfParameter( theCommand );
2736 bool usedCommand = false;
2737 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2738 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2740 CreationMethod& crMethod = type2meth->second;
2741 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2742 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2744 myArgCommands.push_back( theCommand );
2746 while ( crMethod.myArgs.size() < i+1 )
2747 crMethod.myArgs.push_back( "[]" );
2748 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2753 myUnusedCommands.push_back( theCommand );
2756 //================================================================================
2758 * \brief Finish conversion
2760 //================================================================================
2762 void _pyHypothesis::Flush()
2766 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2767 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2768 // Add access to a wrapped mesh
2769 theGen->AddMeshAccessorMethod( *cmd );
2770 // Add access to a wrapped algorithm
2771 theGen->AddAlgoAccessorMethod( *cmd );
2773 cmd = myUnusedCommands.begin();
2774 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2775 // Add access to a wrapped mesh
2776 theGen->AddMeshAccessorMethod( *cmd );
2777 // Add access to a wrapped algorithm
2778 theGen->AddAlgoAccessorMethod( *cmd );
2781 // forget previous hypothesis modifications
2782 myArgCommands.clear();
2783 myUnusedCommands.clear();
2786 //================================================================================
2788 * \brief clear creation, arg and unkown commands
2790 //================================================================================
2792 void _pyHypothesis::ClearAllCommands()
2794 GetCreationCmd()->Clear();
2795 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2796 for ( ; cmd != myArgCommands.end(); ++cmd )
2798 cmd = myUnusedCommands.begin();
2799 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2804 //================================================================================
2806 * \brief Assign fields of theOther to me except myIsWrapped
2808 //================================================================================
2810 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2811 const _pyID& theMesh )
2813 // myCreationCmd = theOther->myCreationCmd;
2814 myIsAlgo = theOther->myIsAlgo;
2815 myIsWrapped = false;
2816 myGeom = theOther->myGeom;
2818 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2819 myAccumulativeMethods = theOther->myAccumulativeMethods;
2820 //myUnusedCommands = theOther->myUnusedCommands;
2821 // init myCurCrMethod
2822 GetCreationMethod( theOther->GetAlgoType() );
2825 //================================================================================
2827 * \brief Analyze my erasability depending on myReferredObjs
2829 //================================================================================
2831 bool _pyHypothesis::CanClear()
2835 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2836 for ( ; obj != myReferredObjs.end(); ++obj )
2837 if ( (*obj)->CanClear() )
2844 //================================================================================
2846 * \brief Clear my commands depending on usage by meshes
2848 //================================================================================
2850 void _pyHypothesis::ClearCommands()
2852 // if ( !theGen->IsToKeepAllCommands() )
2854 // bool isUsed = false;
2855 // int lastComputeOrder = 0;
2856 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2857 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2858 // if ( ! (*cmd)->IsEmpty() )
2861 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2862 // lastComputeOrder = (*cmd)->GetOrderNb();
2866 // SetRemovedFromStudy( true );
2870 // // clear my commands invoked after lastComputeOrder
2871 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2872 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2874 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2875 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2876 // // cmds.back()->Clear();
2880 _pyObject::ClearCommands();
2883 //================================================================================
2885 * \brief Find arguments that are objects like mesh, group, geometry
2886 * \param meshes - referred meshes (directly or indirrectly)
2887 * \retval bool - false if a referred geometry is not in the study
2889 //================================================================================
2891 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2893 if ( IsAlgo() ) return true;
2895 bool geomPublished = true;
2896 vector< _AString > args;
2897 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2898 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2900 CreationMethod& crMethod = type2meth->second;
2901 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2903 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2904 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2905 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2906 args.push_back( (*cmd)->GetArg( nb ));
2909 for ( size_t i = 0; i < args.size(); ++i )
2911 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2912 if ( idList.empty() && !args[ i ].IsEmpty() )
2913 idList.push_back( args[ i ]);
2914 list< _pyID >::iterator id = idList.begin();
2915 for ( ; id != idList.end(); ++id )
2917 Handle(_pyObject) obj = theGen->FindObject( *id );
2918 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2921 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2922 geomPublished = false;
2926 myReferredObjs.push_back( obj );
2927 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2928 if ( !mesh.IsNull() )
2929 meshes.push_back( mesh );
2930 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2931 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2932 obj->SetRemovedFromStudy( false );
2936 return geomPublished;
2939 //================================================================================
2941 * \brief Remember theCommand setting a parameter
2943 //================================================================================
2945 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2947 // parameters are discriminated by method name
2948 _AString method = theCommand->GetMethod();
2949 if ( myAccumulativeMethods.count( method ))
2950 return; // this method adds values and not override the previus value
2952 // discriminate commands setting different parameters via one method
2953 // by passing parameter names like e.g. SetOption("size", "0.2")
2954 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2955 theCommand->GetNbArgs() > 1 )
2957 // mangle method by appending a 1st textual arg
2958 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2960 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2961 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2962 if ( !isalpha( arg.Value(2))) continue;
2967 // parameters are discriminated by method name
2968 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2969 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2971 cmds.back()->Clear(); // previous parameter value has not been used
2972 cmds.back() = theCommand;
2976 cmds.push_back( theCommand );
2980 //================================================================================
2982 * \brief Return true if a setting parameter command ha been used to compute mesh
2984 //================================================================================
2986 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2987 _pyCommand::TAddr avoidComputeAddr ) const
2989 bool isUsed = false;
2990 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2991 myComputeAddr2Cmds.begin();
2992 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2994 if ( addr2cmds->first == avoidComputeAddr ) continue;
2995 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2996 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3001 //================================================================================
3003 * \brief Save commands setting parameters as they are used for a mesh computation
3005 //================================================================================
3007 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3009 myComputeCmds.push_back( theComputeCmd );
3010 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3012 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3013 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3014 savedCmds.push_back( m2c->second.back() );
3017 //================================================================================
3019 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3021 //================================================================================
3023 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3025 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3027 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3028 for ( ; cmd != savedCmds.end(); ++cmd )
3030 // check if a cmd has been used to compute another mesh
3031 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3033 // check if a cmd is a sole command setting its parameter;
3034 // don't use method name for search as it can change
3035 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3036 m2cmds = myMeth2Commands.begin();
3037 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3039 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3040 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3041 if ( cmdIt != cmds.end() )
3043 if ( cmds.back() != *cmd )
3045 cmds.erase( cmdIt );
3052 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3055 //================================================================================
3057 * \brief Sets an argNb-th argument of current creation command
3058 * \param argNb - argument index countered from 1
3060 //================================================================================
3062 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3064 if ( myCurCrMethod )
3066 while ( myCurCrMethod->myArgs.size() < argNb )
3067 myCurCrMethod->myArgs.push_back( "None" );
3068 if ( arg.IsEmpty() )
3069 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3071 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3076 //================================================================================
3078 * \brief Remember hypothesis parameter values
3079 * \param theCommand - The called hypothesis method
3081 //================================================================================
3083 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3085 if ( GetAlgoType() == "Cartesian_3D" )
3087 // CartesianParameters3D hyp
3089 if ( theCommand->GetMethod() == "SetSizeThreshold" )
3091 setCreationArg( 4, theCommand->GetArg( 1 ));
3092 myArgCommands.push_back( theCommand );
3095 if ( theCommand->GetMethod() == "SetGrid" ||
3096 theCommand->GetMethod() == "SetGridSpacing" )
3098 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3099 int iArg = axis.Value(1) - '0';
3100 if ( theCommand->GetMethod() == "SetGrid" )
3102 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3106 myCurCrMethod->myArgs[ iArg ] = "[ ";
3107 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3108 myCurCrMethod->myArgs[ iArg ] += ", ";
3109 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3110 myCurCrMethod->myArgs[ iArg ] += "]";
3112 myArgCommands.push_back( theCommand );
3113 rememberCmdOfParameter( theCommand );
3118 if( theCommand->GetMethod() == "SetLength" )
3120 // NOW it is OBSOLETE
3121 // ex: hyp.SetLength(start, 1)
3122 // hyp.SetLength(end, 0)
3123 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3124 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3125 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3126 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3128 CreationMethod& crMethod = type2meth->second;
3129 while ( crMethod.myArgs.size() < i+1 )
3130 crMethod.myArgs.push_back( "[]" );
3131 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3133 myArgCommands.push_back( theCommand );
3137 _pyHypothesis::Process( theCommand );
3140 //================================================================================
3142 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3144 //================================================================================
3146 void _pyComplexParamHypo::Flush()
3150 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3151 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3152 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3157 //================================================================================
3159 * \brief Convert methods of 1D hypotheses to my own methods
3160 * \param theCommand - The called hypothesis method
3162 //================================================================================
3164 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3166 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3169 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3170 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3171 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3173 // TCollection_AsciiString cmd =
3174 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3175 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3176 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3179 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3181 // // 1D hypo is already set, so distribution changes and the old
3182 // // 1D hypo is thrown away
3183 // my1dHyp->ClearAllCommands();
3186 // //my1dHyp->SetRemovedFromStudy( false );
3188 // if ( !myArgCommands.empty() )
3189 // myArgCommands.back()->Clear();
3190 myCurCrMethod->myArgs.push_back( hyp1dID );
3191 myArgCommands.push_back( theCommand );
3194 //================================================================================
3197 * \param theAdditionCmd - command to be converted
3198 * \param theMesh - mesh instance
3199 * \retval bool - status
3201 //================================================================================
3203 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3204 const _pyID& theMesh)
3206 myIsWrapped = false;
3208 if ( my1dHyp.IsNull() )
3211 // set "SetLayerDistribution()" after addition cmd
3212 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3214 _pyID geom = theAdditionCmd->GetArg( 1 );
3216 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3217 if ( !algo.IsNull() )
3219 my1dHyp->SetMesh( theMesh );
3220 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3221 algo->GetAlgoType().ToCString());
3222 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3225 // clear "SetLayerDistribution()" cmd
3226 myArgCommands.back()->Clear();
3228 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3230 // find RadialPrism algo created on <geom> for theMesh
3231 GetCreationCmd()->SetObject( algo->GetID() );
3232 GetCreationCmd()->SetMethod( myAlgoMethod );
3233 GetCreationCmd()->RemoveArgs();
3234 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3240 //================================================================================
3244 //================================================================================
3246 void _pyLayerDistributionHypo::Flush()
3248 // as creation of 1D hyp was written later then it's edition,
3249 // we need to find all it's edition calls and process them
3250 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3252 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3254 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3255 if ( hyp1dID.IsEmpty() ) continue;
3257 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3259 // make a new name for 1D hyp = "HypType" + "_Distribution"
3261 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3263 if ( prevNewName.IsEmpty() ) continue;
3264 newName = prevNewName;
3268 if ( hyp1d->IsWrapped() ) {
3269 newName = hyp1d->GetCreationCmd()->GetMethod();
3272 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3273 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3275 newName += "_Distribution";
3276 prevNewName = newName;
3278 hyp1d->GetCreationCmd()->SetResultValue( newName );
3280 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3281 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3282 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3283 const _pyID& objID = (*cmdIt)->GetObject();
3284 if ( objID == hyp1dID ) {
3285 if ( !hyp1d.IsNull() )
3287 hyp1d->Process( *cmdIt );
3288 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3290 ( *cmdIt )->SetObject( newName );
3293 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3294 (*cmd)->SetArg( 1, newName );
3298 //================================================================================
3300 * \brief additionally to Addition2Creation, clears SetDistrType() command
3301 * \param theCmd - AddHypothesis() command
3302 * \param theMesh - mesh to which a hypothesis is added
3303 * \retval bool - convertion result
3305 //================================================================================
3307 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3308 const _pyID& theMesh)
3310 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3311 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3312 bool scaleDistrType = false;
3313 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3314 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3315 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3316 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3317 scaleDistrType = true;
3320 else if ( !scaleDistrType ) {
3321 // distribution type changed: remove scale factor from args
3322 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3323 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3325 CreationMethod& crMethod = type2meth->second;
3326 if ( crMethod.myArgs.size() == 2 )
3327 crMethod.myArgs.pop_back();
3334 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3337 //================================================================================
3339 * \brief remove repeated commands defining distribution
3341 //================================================================================
3343 void _pyNumberOfSegmentsHyp::Flush()
3345 // find number of the last SetDistrType() command
3346 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3347 int distrTypeNb = 0;
3348 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3349 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3350 if ( cmd != myUnusedCommands.rbegin() )
3351 distrTypeNb = (*cmd)->GetOrderNb();
3353 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3356 // clear commands before the last SetDistrType()
3357 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3358 set< int > treatedCmdNbs; // avoid treating same cmd twice
3359 for ( int i = 0; i < 2; ++i ) {
3360 set<TCollection_AsciiString> uniqueMethods;
3361 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3362 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3364 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3365 continue;// avoid treating same cmd twice
3366 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3367 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3368 if ( !clear || method == "SetNumberOfSegments" ) {
3369 bool isNewInSet = uniqueMethods.insert( method ).second;
3370 clear = !isNewInSet;
3379 //================================================================================
3381 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3382 * into regular1D.LengthNearVertex( length, vertex )
3383 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3384 * \param theMesh - The mesh needing this hypo
3385 * \retval bool - false if the command cant be converted
3387 //================================================================================
3389 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3390 const _pyID& theMeshID)
3392 if ( IsWrappable( theMeshID )) {
3394 _pyID vertex = theCmd->GetArg( 1 );
3396 // the problem here is that segment algo will not be found
3397 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3398 // geometry where segment algorithm is assigned
3399 Handle(_pyHypothesis) algo;
3400 _pyID geom = vertex;
3401 while ( algo.IsNull() && !geom.IsEmpty()) {
3402 // try to find geom as a father of <vertex>
3403 geom = FatherID( geom );
3404 algo = theGen->FindAlgo( geom, theMeshID, this );
3406 if ( algo.IsNull() )
3407 return false; // also possible to find geom as brother of veretex...
3408 // set geom instead of vertex
3409 theCmd->SetArg( 1, geom );
3411 // set vertex as a second arg
3412 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3413 setCreationArg( 2, vertex );
3415 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3416 // theMeshID.LengthNearVertex( length, vertex )
3417 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3422 //================================================================================
3424 * \brief _pyAlgorithm constructor
3425 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3427 //================================================================================
3429 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3430 : _pyHypothesis( theCreationCmd )
3435 //================================================================================
3437 * \brief Convert the command adding an algorithm to mesh
3438 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3439 * \param theMesh - The mesh needing this algo
3440 * \retval bool - false if the command cant be converted
3442 //================================================================================
3444 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3445 const _pyID& theMeshID)
3447 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3448 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3449 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3455 //================================================================================
3457 * \brief Return starting position of a part of python command
3458 * \param thePartIndex - The index of command part
3459 * \retval int - Part position
3461 //================================================================================
3463 int _pyCommand::GetBegPos( int thePartIndex ) const
3467 if ( myBegPos.Length() < thePartIndex )
3469 ASSERT( thePartIndex > 0 );
3470 return myBegPos( thePartIndex );
3473 //================================================================================
3475 * \brief Store starting position of a part of python command
3476 * \param thePartIndex - The index of command part
3477 * \param thePosition - Part position
3479 //================================================================================
3481 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3483 while ( myBegPos.Length() < thePartIndex )
3484 myBegPos.Append( UNKNOWN );
3485 ASSERT( thePartIndex > 0 );
3486 myBegPos( thePartIndex ) = thePosition;
3489 //================================================================================
3491 * \brief Returns whitespace symbols at the line beginning
3492 * \retval TCollection_AsciiString - result
3494 //================================================================================
3496 TCollection_AsciiString _pyCommand::GetIndentation()
3499 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3500 GetWord( myString, end, true );
3502 end = GetBegPos( RESULT_IND );
3503 return myString.SubString( 1, Max( end - 1, 1 ));
3506 //================================================================================
3508 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3509 * \retval const TCollection_AsciiString & - ResultValue substring
3511 //================================================================================
3513 const TCollection_AsciiString & _pyCommand::GetResultValue()
3515 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3517 SetBegPos( RESULT_IND, EMPTY );
3518 int begPos, endPos = myString.Location( "=", 1, Length() );
3522 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3523 if ( begPos < endPos )
3525 SetBegPos( RESULT_IND, begPos );
3527 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3528 myRes = myString.SubString( begPos, endPos );
3535 //================================================================================
3537 * \brief Return number of python command result value ResultValue = Obj.Meth()
3539 //================================================================================
3541 int _pyCommand::GetNbResultValues()
3544 return myResults.Length();
3548 //================================================================================
3550 * \brief Return substring of python command looking like
3551 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3552 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3554 //================================================================================
3555 const _AString& _pyCommand::GetResultValue(int res)
3557 if ( GetResultValue().IsEmpty() )
3558 return theEmptyString;
3560 if ( myResults.IsEmpty() )
3563 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3564 ++begPos; // skip [, else the whole list is returned
3565 while ( begPos < myRes.Length() ) {
3566 _AString result = GetWord( myRes, begPos, true );
3567 begPos += result.Length();
3569 // result.RemoveAll('[');
3570 // result.RemoveAll(']');
3575 myResults.Append( result );
3578 if ( res > 0 && res <= myResults.Length() )
3579 return myResults( res );
3580 return theEmptyString;
3583 //================================================================================
3585 * \brief Return substring of python command looking like ResVal = Object.Meth()
3586 * \retval const TCollection_AsciiString & - Object substring
3588 //================================================================================
3590 const TCollection_AsciiString & _pyCommand::GetObject()
3592 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3595 int begPos = GetBegPos( RESULT_IND );
3597 begPos = myString.Location( "=", 1, Length() ) + 1;
3598 // is '=' in the string argument (for example, name) or not
3599 int nb1 = 0; // number of ' character at the left of =
3600 int nb2 = 0; // number of " character at the left of =
3601 for ( int i = 1; i < begPos-1; i++ ) {
3602 if ( myString.Value( i )=='\'' )
3604 else if ( myString.Value( i )=='"' )
3607 // if number of ' or " is not divisible by 2,
3608 // then get an object at the start of the command
3609 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3613 begPos += myRes.Length();
3615 myObj = GetWord( myString, begPos, true );
3616 if ( begPos != EMPTY )
3618 // check if object is complex,
3619 // so far consider case like "smesh.Method()"
3620 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3621 //if ( bracketPos==0 ) bracketPos = Length();
3622 int dotPos = begPos+myObj.Length();
3623 while ( dotPos+1 < bracketPos ) {
3624 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3629 if ( dotPos > begPos+myObj.Length() )
3630 myObj = myString.SubString( begPos, dotPos-1 );
3633 // 1st word after '=' is an object
3634 // else // no method -> no object
3640 SetBegPos( OBJECT_IND, begPos );
3646 //================================================================================
3648 * \brief Return substring of python command looking like ResVal = Obj.Method()
3649 * \retval const TCollection_AsciiString & - Method substring
3651 //================================================================================
3653 const TCollection_AsciiString & _pyCommand::GetMethod()
3655 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3658 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3659 bool forward = true;
3661 begPos = myString.Location( "(", 1, Length() ) - 1;
3665 myMeth = GetWord( myString, begPos, forward );
3666 SetBegPos( METHOD_IND, begPos );
3672 //================================================================================
3674 * \brief Returns true if there are brackets after the method
3676 //================================================================================
3678 bool _pyCommand::IsMethodCall()
3680 if ( GetMethod().IsEmpty() )
3682 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3683 return ( s[0] == '(' || s[1] == '(' );
3686 //================================================================================
3688 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3689 * \retval const TCollection_AsciiString & - Arg<index> substring
3691 //================================================================================
3693 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3695 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3699 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3701 pos = myString.Location( "(", 1, Length() );
3705 // we are at or before '(', skip it if present
3707 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3708 if ( pos > Length() )
3712 SetBegPos( ARG1_IND, 0 ); // even no '('
3713 return theEmptyString;
3717 list< TCollection_AsciiString > separatorStack( 1, ",)");
3718 bool ignoreNesting = false;
3720 while ( pos <= Length() )
3722 const char chr = myString.Value( pos );
3724 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3726 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3728 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3730 TCollection_AsciiString arg;
3731 if ( pos-1 >= prevPos ) {
3732 arg = myString.SubString( prevPos, pos-1 );
3733 arg.RightAdjust(); // remove spaces
3736 if ( !arg.IsEmpty() || chr == ',' )
3738 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3739 myArgs.Append( arg );
3745 else // end of nesting args found
3747 separatorStack.pop_back();
3748 ignoreNesting = false;
3751 else if ( !ignoreNesting )
3754 case '(' : separatorStack.push_back(")"); break;
3755 case '[' : separatorStack.push_back("]"); break;
3756 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3757 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3764 if ( myArgs.Length() < index )
3765 return theEmptyString;
3766 return myArgs( index );
3769 //================================================================================
3771 * \brief Return position where arguments begin
3773 //================================================================================
3775 int _pyCommand::GetArgBeginning() const
3777 int pos = GetBegPos( ARG1_IND );
3778 if ( pos == UNKNOWN )
3780 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3782 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3787 //================================================================================
3789 * \brief Check if char is a word part
3790 * \param c - The character to check
3791 * \retval bool - The check result
3793 //================================================================================
3795 static inline bool isWord(const char c, const bool dotIsWord)
3798 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3801 //================================================================================
3803 * \brief Looks for a word in the string and returns word's beginning
3804 * \param theString - The input string
3805 * \param theStartPos - The position to start the search, returning word's beginning
3806 * \param theForward - The search direction
3807 * \retval TCollection_AsciiString - The found word
3809 //================================================================================
3811 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3813 const bool theForward,
3814 const bool dotIsWord )
3816 int beg = theStartPos, end = theStartPos;
3817 theStartPos = EMPTY;
3818 if ( beg < 1 || beg > theString.Length() )
3819 return theEmptyString;
3821 if ( theForward ) { // search forward
3823 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3825 if ( beg > theString.Length() )
3826 return theEmptyString; // no word found
3829 char begChar = theString.Value( beg );
3830 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3831 char endChar = ( begChar == '[' ) ? ']' : begChar;
3832 // end is at the corresponding quoting mark or bracket
3833 while ( end < theString.Length() &&
3834 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3838 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3843 else { // search backward
3845 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3848 return theEmptyString; // no word found
3850 char endChar = theString.Value( end );
3851 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3852 char begChar = ( endChar == ']' ) ? '[' : endChar;
3853 // beg is at the corresponding quoting mark
3855 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3859 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3865 //cout << theString << " ---- " << beg << " - " << end << endl;
3866 return theString.SubString( beg, end );
3869 //================================================================================
3871 * \brief Returns true if the string looks like a study entry
3873 //================================================================================
3875 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3877 if ( str.Length() < 5 ) return false;
3879 int nbColons = 0, isColon;
3880 for ( int i = 1; i <= str.Length(); ++i )
3882 char c = str.Value(i);
3883 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3885 nbColons += isColon;
3887 return nbColons > 2 && str.Length()-nbColons > 2;
3890 //================================================================================
3892 * \brief Returns true if the string looks like an object ID but not like a list,
3893 * string, command etc.
3895 //================================================================================
3897 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3899 if ( str.Length() < 1 ) return false;
3901 const char* s = str.ToCString();
3903 for ( int i = 0; i < str.Length(); ++i )
3904 if ( !IsIDChar( s[i] ))
3910 //================================================================================
3912 * \brief Finds entries in a sting
3914 //================================================================================
3916 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3918 std::list< _pyID > resList;
3920 while ( ++pos <= str.Length() )
3922 if ( !isdigit( str.Value( pos ))) continue;
3923 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3926 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3927 _pyID entry = str.SubString( pos, end-1 );
3929 if ( IsStudyEntry( entry ))
3930 resList.push_back( entry );
3935 //================================================================================
3937 * \brief Look for position where not space char is
3938 * \param theString - The string
3939 * \param thePos - The position to search from and which returns result
3940 * \retval bool - false if there are only space after thePos in theString
3942 //================================================================================
3944 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3946 if ( thePos < 1 || thePos > theString.Length() )
3949 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3952 return thePos <= theString.Length();
3955 //================================================================================
3957 * \brief Modify a part of the command
3958 * \param thePartIndex - The index of the part
3959 * \param thePart - The new part string
3960 * \param theOldPart - The old part
3962 //================================================================================
3964 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3965 TCollection_AsciiString& theOldPart)
3967 int pos = GetBegPos( thePartIndex );
3968 if ( pos <= Length() && theOldPart != thePart)
3970 TCollection_AsciiString seperator;
3972 pos = GetBegPos( thePartIndex + 1 );
3973 if ( pos < 1 ) return;
3974 switch ( thePartIndex ) {
3975 case RESULT_IND: seperator = " = "; break;
3976 case OBJECT_IND: seperator = "."; break;
3977 case METHOD_IND: seperator = "()"; break;
3981 myString.Remove( pos, theOldPart.Length() );
3982 if ( !seperator.IsEmpty() )
3983 myString.Insert( pos , seperator );
3984 myString.Insert( pos, thePart );
3985 // update starting positions of the following parts
3986 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3987 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3988 if ( myBegPos( i ) > 0 )
3989 myBegPos( i ) += posDelta;
3991 theOldPart = thePart;
3995 //================================================================================
3997 * \brief Set agrument
3998 * \param index - The argument index, it counts from 1
3999 * \param theArg - The argument string
4001 //================================================================================
4003 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4006 int argInd = ARG1_IND + index - 1;
4007 int pos = GetBegPos( argInd );
4008 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4010 // find a closing parenthesis
4011 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4012 int lastArgInd = GetNbArgs();
4013 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4014 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4019 while ( pos > 0 && myString.Value( pos ) != ')' )
4022 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4026 while ( myArgs.Length() < index ) {
4027 if ( myArgs.Length() )
4028 myString.Insert( pos++, "," );
4029 myArgs.Append("None");
4030 myString.Insert( pos, myArgs.Last() );
4031 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4032 pos += myArgs.Last().Length();
4035 SetPart( argInd, theArg, myArgs( index ));
4038 //================================================================================
4040 * \brief Empty arg list
4042 //================================================================================
4044 void _pyCommand::RemoveArgs()
4046 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4047 myString.Trunc( pos );
4050 if ( myBegPos.Length() >= ARG1_IND )
4051 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4054 //================================================================================
4056 * \brief Comment a python command
4058 //================================================================================
4060 void _pyCommand::Comment()
4062 if ( IsEmpty() ) return;
4065 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4066 if ( i <= Length() )
4068 myString.Insert( i, "#" );
4069 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4071 int begPos = GetBegPos( iPart );
4072 if ( begPos != UNKNOWN && begPos != EMPTY )
4073 SetBegPos( iPart, begPos + 1 );
4078 //================================================================================
4080 * \brief Set dependent commands after this one
4082 //================================================================================
4084 bool _pyCommand::SetDependentCmdsAfter() const
4086 bool orderChanged = false;
4087 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4088 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4089 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4090 orderChanged = true;
4091 theGen->SetCommandAfter( *cmd, this );
4092 (*cmd)->SetDependentCmdsAfter();
4095 return orderChanged;
4097 //================================================================================
4099 * \brief Insert accessor method after theObjectID
4100 * \param theObjectID - id of the accessed object
4101 * \param theAcsMethod - name of the method giving access to the object
4102 * \retval bool - false if theObjectID is not found in the command string
4104 //================================================================================
4106 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4108 if ( !theAcsMethod )
4110 // start object search from the object, i.e. ignore result
4112 int beg = GetBegPos( OBJECT_IND );
4113 if ( beg < 1 || beg > Length() )
4116 while (( beg = myString.Location( theObjectID, beg, Length() )))
4118 // check that theObjectID is not just a part of a longer ID
4119 int afterEnd = beg + theObjectID.Length();
4120 Standard_Character c = myString.Value( afterEnd );
4121 if ( !IsIDChar( c ))
4123 // check if accessor method already present
4125 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4127 int oldLen = Length();
4128 myString.Insert( afterEnd, (char*) theAcsMethod );
4129 myString.Insert( afterEnd, "." );
4130 // update starting positions of the parts following the modified one
4131 int posDelta = Length() - oldLen;
4132 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4133 if ( myBegPos( i ) > afterEnd )
4134 myBegPos( i ) += posDelta;
4139 beg = afterEnd; // is a part -> next search
4144 //================================================================================
4146 * \brief Creates pyObject
4148 //================================================================================
4150 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4151 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4156 //================================================================================
4158 * \brief Set up myID and myIsPublished
4160 //================================================================================
4162 void _pyObject::setID(const _pyID& theID)
4165 myIsPublished = !theGen->IsNotPublished( GetID() );
4168 //================================================================================
4170 * \brief Clear myCreationCmd and myProcessedCmds
4172 //================================================================================
4174 void _pyObject::ClearCommands()
4179 if ( !myCreationCmd.IsNull() )
4180 myCreationCmd->Clear();
4182 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4183 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4187 //================================================================================
4189 * \brief Return method name giving access to an interaface object wrapped by python class
4190 * \retval const char* - method name
4192 //================================================================================
4194 const char* _pyObject::AccessorMethod() const
4198 //================================================================================
4200 * \brief Return ID of a father
4202 //================================================================================
4204 _pyID _pyObject::FatherID(const _pyID & childID)
4206 int colPos = childID.SearchFromEnd(':');
4208 return childID.SubString( 1, colPos-1 );
4212 //================================================================================
4214 * \brief SelfEraser erases creation command if none of it's commands invoked
4215 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4217 //================================================================================
4219 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4220 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4222 myIsPublished = true; // prevent clearing as a not published
4223 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4226 //================================================================================
4228 * \brief SelfEraser erases creation command if none of it's commands invoked
4229 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4231 //================================================================================
4233 bool _pySelfEraser::CanClear()
4235 bool toErase = false;
4236 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4239 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4240 for ( ; cmd != myArgCmds.end(); ++cmd )
4241 nbArgUses += IsAliveCmd( *cmd );
4243 toErase = ( nbArgUses < 1 );
4248 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4249 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4250 for ( ; cmd != cmds.end(); ++cmd )
4251 // check of cmd emptiness is not enough as object can change
4252 nbCalls += ( ( *cmd )->GetString().Search( GetID() ) > 0 );
4254 toErase = ( nbCalls < 1 );
4259 //================================================================================
4261 * \brief Check if a command is or can be cleared
4263 //================================================================================
4265 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4267 if ( theCmd->IsEmpty() )
4270 if ( !theGen->IsToKeepAllCommands() )
4272 const _pyID& objID = theCmd->GetObject();
4273 Handle( _pyObject ) obj = theGen->FindObject( objID );
4274 if ( !obj.IsNull() )
4275 return !obj->CanClear();
4280 //================================================================================
4282 * \brief SelfEraser erases creation command if none of it's commands invoked
4283 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4285 //================================================================================
4287 void _pySelfEraser::Flush()
4291 myIsPublished = false;
4292 _pyObject::ClearCommands();
4296 //================================================================================
4298 * \brief _pySubMesh constructor
4300 //================================================================================
4302 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4303 _pyObject(theCreationCmd)
4305 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4306 if ( toKeepAgrCmds )
4307 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4310 //================================================================================
4312 * \brief Return true if a sub-mesh can be used as argument of the given method
4314 //================================================================================
4316 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4319 // // names of all methods where a sub-mesh can be used as argument
4320 // static TStringSet methods;
4321 // if ( methods.empty() ) {
4322 // const char * names[] = {
4323 // // methods of SMESH_Gen
4325 // // methods of SMESH_Group
4327 // // methods of SMESH_Measurements
4329 // // methods of SMESH_Mesh
4330 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4332 // // methods of SMESH_MeshEditor
4333 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4334 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4335 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4336 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4337 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4338 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4339 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4340 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4341 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4342 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4343 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4344 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4345 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4346 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4347 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4348 // "" }; // <- mark of end
4349 // methods.Insert( names );
4351 // return methods.Contains( theMethodName );
4354 //================================================================================
4356 * \brief count invoked commands
4358 //================================================================================
4360 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4362 _pyObject::Process(theCommand); // count calls of Process()
4365 //================================================================================
4367 * \brief Move creation command depending on invoked commands
4369 //================================================================================
4371 void _pySubMesh::Flush()
4373 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4374 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4375 else if ( !myCreator.IsNull() )
4376 // move to be just after creator
4377 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4379 // move sub-mesh usage after creation cmd
4380 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4381 for ( ; cmd != myArgCmds.end(); ++cmd )
4382 if ( !(*cmd)->IsEmpty() )
4383 GetCreationCmd()->AddDependantCmd( *cmd );
4386 //================================================================================
4388 * \brief Creates _pyGroup
4390 //================================================================================
4392 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4393 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4395 if ( !id.IsEmpty() )
4398 myCanClearCreationCmd = true;
4400 const _AString& method = theCreationCmd->GetMethod();
4401 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4403 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4405 // ----------------------------------------------------------------------
4406 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4408 _pyID geom = theCreationCmd->GetArg( 3 );
4409 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4410 // next if(){...} section is commented
4411 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4412 // theCreationCmd->SetMethod( "Group" );
4413 // theCreationCmd->RemoveArgs();
4414 // theCreationCmd->SetArg( 1, geom );
4417 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4418 _pyID type = theCreationCmd->GetArg( 1 );
4419 _pyID name = theCreationCmd->GetArg( 2 );
4420 theCreationCmd->SetMethod( "GroupOnGeom" );
4421 theCreationCmd->RemoveArgs();
4422 theCreationCmd->SetArg( 1, geom );
4423 theCreationCmd->SetArg( 2, name );
4424 theCreationCmd->SetArg( 3, type );
4427 else if ( method == "CreateGroupFromFilter" )
4429 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4430 theCreationCmd->SetMethod( "GroupOnFilter" );
4432 _pyID filterID = theCreationCmd->GetArg(3);
4433 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4434 if ( !filter.IsNull())
4436 if ( !filter->GetNewID().IsEmpty() )
4437 theCreationCmd->SetArg( 3, filter->GetNewID() );
4438 //filter->AddUser( this );
4442 else if ( method == "GetGroups" )
4444 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4448 // theCreationCmd does something else apart from creation of this group
4449 // and thus it can't be cleared if this group is removed
4450 myCanClearCreationCmd = false;
4454 //================================================================================
4456 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4459 //================================================================================
4461 bool _pyGroup::CanClear()
4466 if ( !myCanClearCreationCmd &&
4467 !myCreationCmd.IsNull() &&
4468 myCreationCmd->GetMethod() == "GetGroups" )
4470 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4471 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4472 list< _pyID >::iterator grID = idList.begin();
4473 if ( GetID() == *grID )
4475 myCanClearCreationCmd = true;
4476 list< Handle(_pyGroup ) > groups;
4477 for ( ; grID != idList.end(); ++grID )
4479 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4480 if ( group.IsNull() ) continue;
4481 groups.push_back( group );
4482 if ( group->IsInStudy() )
4483 myCanClearCreationCmd = false;
4485 // set myCanClearCreationCmd == true to all groups
4486 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4487 for ( ; group != groups.end(); ++group )
4488 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4492 return myCanClearCreationCmd;
4495 //================================================================================
4497 * \brief set myCanClearCreationCmd = true if the main action of the creation
4498 * command is discarded
4500 //================================================================================
4502 void _pyGroup::RemovedWithContents()
4504 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4505 // via a created group
4506 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4507 // myCanClearCreationCmd = true;
4510 //================================================================================
4512 * \brief To convert creation of a group by filter
4514 //================================================================================
4516 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4518 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4519 // group = mesh.CreateEmptyGroup( elemType, groupName )
4520 // aFilter.SetMesh(mesh)
4521 // nbAdd = group.AddFrom( aFilter )
4522 Handle(_pyFilter) filter;
4523 if ( theCommand->GetMethod() == "AddFrom" )
4525 _pyID idSource = theCommand->GetArg(1);
4526 // check if idSource is a filter
4527 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4528 if ( !filter.IsNull() )
4530 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4531 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4532 while ( *cmdIt != theCommand ) ++cmdIt;
4533 while ( (*cmdIt)->GetOrderNb() != 1 )
4535 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4536 if ((setMeshCmd->GetObject() == idSource ||
4537 setMeshCmd->GetObject() == filter->GetNewID() )
4539 setMeshCmd->GetMethod() == "SetMesh")
4541 setMeshCmd->Clear();
4545 // replace 3 commands by one
4546 theCommand->Clear();
4547 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4548 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4549 if ( !filter->GetNewID().IsEmpty() )
4550 idSource = filter->GetNewID();
4551 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4552 makeGroupCmd->SetArg( 1, name );
4553 makeGroupCmd->SetArg( 2, idSource );
4554 filter->AddArgCmd( makeGroupCmd );
4557 else if ( theCommand->GetMethod() == "SetFilter" )
4559 // set new name of a filter or clear the command if the same filter is set
4560 _pyID filterID = theCommand->GetArg(1);
4561 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4562 if ( !myFilter.IsNull() && filter == myFilter )
4563 theCommand->Clear();
4564 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4565 theCommand->SetArg( 1, filter->GetNewID() );
4568 else if ( theCommand->GetMethod() == "GetFilter" )
4570 // GetFilter() returns a filter with other ID, make myFilter process
4571 // calls of the returned filter
4572 if ( !myFilter.IsNull() )
4574 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4575 theCommand->Clear();
4579 // if ( !filter.IsNull() )
4580 // filter->AddUser( this );
4582 theGen->AddMeshAccessorMethod( theCommand );
4585 //================================================================================
4587 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4589 //================================================================================
4591 void _pyGroup::Flush()
4593 if ( !theGen->IsToKeepAllCommands() &&
4594 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4596 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4600 //================================================================================
4602 * \brief Constructor of _pyFilter
4604 //================================================================================
4606 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4607 :_pyObject(theCreationCmd), myNewID( newID )
4609 //myIsPublished = true; // prevent clearing as a not published
4610 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4613 //================================================================================
4615 * \brief To convert creation of a filter by criteria and
4616 * to replace an old name by a new one
4618 //================================================================================
4620 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4622 if ( theCommand->GetObject() == GetID() )
4623 _pyObject::Process(theCommand); // count commands
4625 if ( !myNewID.IsEmpty() )
4626 theCommand->SetObject( myNewID );
4628 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4629 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4630 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4631 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4632 theCommand->GetMethod() == "SetCriteria")
4634 // aFilter.SetCriteria(aCriteria) ->
4635 // aFilter = smesh.GetFilterFromCriteria(criteria)
4636 if ( myNewID.IsEmpty() )
4637 theCommand->SetResultValue( GetID() );
4639 theCommand->SetResultValue( myNewID );
4640 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4641 theCommand->SetMethod( "GetFilterFromCriteria" );
4643 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4644 GetCreationCmd()->Clear();
4645 GetCreationCmd()->GetString() = theCommand->GetString();
4646 theCommand->Clear();
4647 theCommand->AddDependantCmd( GetCreationCmd() );
4648 // why swap? -- it's needed
4649 //GetCreationCmd()->Clear();
4651 else if ( theCommand->GetMethod() == "SetMesh" )
4653 if ( myMesh == theCommand->GetArg( 1 ))
4654 theCommand->Clear();
4656 myMesh = theCommand->GetArg( 1 );
4657 theGen->AddMeshAccessorMethod( theCommand );
4661 //================================================================================
4663 * \brief Set new filter name to the creation command and to myArgCmds
4665 //================================================================================
4667 void _pyFilter::Flush()
4669 if ( myNewID.IsEmpty() ) return;
4671 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4672 for ( ; cmd != myArgCmds.end(); ++cmd )
4673 if ( !(*cmd)->IsEmpty() )
4675 _AString cmdStr = (*cmd)->GetString();
4676 _AString id = GetID();
4677 int pos = cmdStr.Search( id );
4680 cmdStr.Remove( pos, id.Length() );
4681 cmdStr.Insert( pos, myNewID );
4684 (*cmd)->GetString() = cmdStr;
4687 if ( !GetCreationCmd()->IsEmpty() )
4688 GetCreationCmd()->SetResultValue( myNewID );
4691 //================================================================================
4693 * \brief Return true if all my users can be cleared
4695 //================================================================================
4697 bool _pyObject::CanClear()
4699 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4700 for ( ; cmd != myArgCmds.end(); ++cmd )
4701 if ( !(*cmd)->IsEmpty() )
4703 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4704 if ( !obj.IsNull() && !obj->CanClear() )
4707 return ( !myIsPublished );
4710 //================================================================================
4712 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4714 //================================================================================
4716 _pyHypothesisReader::_pyHypothesisReader()
4719 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4720 LDOMParser xmlParser;
4721 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4723 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4727 INFOS( xmlParser.GetError(data) );
4730 // <algorithm type="Regular_1D"
4731 // label-id="Wire discretisation"
4734 // <algo>Regular_1D=Segment()</algo>
4735 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4737 LDOM_Document xmlDoc = xmlParser.getDocument();
4738 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4739 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4741 LDOM_Node algoNode = algoNodeList.item( i );
4742 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4743 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4744 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4746 _AString text, algoType, method, arg;
4747 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4749 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4750 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4751 text = textNode.getNodeValue();
4752 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4753 algoType = algoCmd->GetResultValue();
4754 method = algoCmd->GetMethod();
4755 arg = algoCmd->GetArg(1);
4756 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4758 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4759 algo->SetConvMethodAndType( method, algoType );
4760 if ( !arg.IsEmpty() )
4761 algo->setCreationArg( 1, arg );
4763 myType2Hyp[ algoType ] = algo;
4767 if ( algoType.IsEmpty() ) continue;
4769 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4771 Handle( _pyHypothesis ) hyp;
4772 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4774 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4775 LDOM_Node textNode = pyHypoNode.getFirstChild();
4776 text = textNode.getNodeValue();
4777 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4778 hypType = hypoCmd->GetResultValue();
4779 method = hypoCmd->GetMethod();
4780 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4782 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4783 if ( type2hyp == myType2Hyp.end() )
4784 hyp = new _pyHypothesis( hypoCmd );
4786 hyp = type2hyp->second;
4787 hyp->SetConvMethodAndType( method, algoType );
4788 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4790 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4791 _AString argMethod = argCmd.GetMethod();
4792 _AString argNbText = argCmd.GetArg( 1 );
4793 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4794 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4796 hyp->AddArgMethod( argMethod,
4797 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4799 myType2Hyp[ hypType ] = hyp;
4803 // <hypothesis type="BLSURF_Parameters"
4807 // <accumulative-methods>
4808 // SetEnforcedVertex,
4809 // SetEnforcedVertexNamed
4810 // </accumulative-methods>
4814 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4815 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4817 LDOM_Node hypNode = hypNodeList.item( i );
4818 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4819 _AString hypType = hypElem.getAttribute("type");
4820 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4821 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4823 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4824 if ( type2hyp == myType2Hyp.end() ) continue;
4826 LDOM_Node methNode = methNodeList.item( 0 );
4827 LDOM_Node textNode = methNode.getFirstChild();
4828 _AString text = textNode.getNodeValue();
4832 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4833 pos += method.Length();
4834 type2hyp->second->AddAccumulativeMethod( method );
4836 while ( !method.IsEmpty() );
4839 } // loop on xmlPaths
4842 //================================================================================
4844 * \brief Returns a new hypothesis initialized according to the read information
4846 //================================================================================
4848 Handle(_pyHypothesis)
4849 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4850 const Handle(_pyCommand)& creationCmd) const
4852 Handle(_pyHypothesis) resHyp, sampleHyp;
4854 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4855 if ( type2hyp != myType2Hyp.end() )
4856 sampleHyp = type2hyp->second;
4858 if ( sampleHyp.IsNull() )
4860 resHyp = new _pyHypothesis(creationCmd);
4864 if ( sampleHyp->IsAlgo() )
4865 resHyp = new _pyAlgorithm( creationCmd );
4867 resHyp = new _pyHypothesis(creationCmd);
4868 resHyp->Assign( sampleHyp, _pyID() );
4873 //================================================================================
4875 * \brief Adds an object ID to some family of IDs with a common prefix
4876 * \param [in] str - the object ID
4877 * \return bool - \c false if \a str does not have the same prefix as \a this family
4878 * (for internal usage)
4880 //================================================================================
4882 bool _pyStringFamily::Add( const char* str )
4884 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4885 return false; // expected prefix is missing
4887 str += _prefix.Length(); // skip _prefix
4889 // try to add to some of child falimies
4890 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4891 for ( ; itSub != _subFams.end(); ++itSub )
4892 if ( itSub->Add( str ))
4895 // no suitable family found - add str to _strings or create a new child family
4897 // look for a proper place within sorted _strings
4898 std::list< _AString >::iterator itStr = _strings.begin();
4899 while ( itStr != _strings.end() && itStr->IsLess( str ))
4901 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4902 return true; // same ID already kept
4904 const int minPrefixSize = 4;
4906 // count "smaller" strings with the same prefix
4907 std::list< _AString >::iterator itLess = itStr; --itLess;
4909 for ( ; itLess != _strings.end(); --itLess )
4910 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4915 // count "greater" strings with the same prefix
4916 std::list< _AString >::iterator itMore = itStr;
4918 for ( ; itMore != _strings.end(); ++itMore )
4919 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4924 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4926 // look for a maximal prefix length
4927 // int lessPrefSize = 3, morePrefSize = 3;
4928 // if ( nbLess > 0 )
4929 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4931 // if ( nbMore > 0 )
4932 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4934 // int prefixSize = 3;
4935 // if ( nbLess == 0 )
4936 // prefixSize = morePrefSize;
4937 // else if ( nbMore == 0 )
4938 // prefixSize = lessPrefSize;
4940 // prefixSize = Min( lessPrefSize, morePrefSize );
4941 int prefixSize = minPrefixSize;
4942 _AString newPrefix ( str, prefixSize );
4944 // look for a proper place within _subFams sorted by _prefix
4945 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
4946 if ( !itSub->_prefix.IsLess( newPrefix ))
4949 // add the new _pyStringFamily
4950 itSub = _subFams.insert( itSub, _pyStringFamily());
4951 _pyStringFamily& newSubFam = *itSub;
4952 newSubFam._prefix = newPrefix;
4954 // pass this->_strings to newSubFam._strings
4955 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
4956 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4957 newSubFam._strings.push_back( str + prefixSize );
4958 for ( ; nbMore > 0; --nbMore, ++itStr )
4959 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4961 _strings.erase( itLess, ++itMore );
4963 else // to few string to make a family fot them
4965 _strings.insert( itStr, str );
4970 //================================================================================
4972 * \brief Finds an object ID in the command
4973 * \param [in] longStr - the command string
4974 * \param [out] subStr - the found object ID
4975 * \return bool - \c true if the object ID found
4977 //================================================================================
4979 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
4981 const _AString& longStr = cmd->GetString();
4982 const char* s = longStr.ToCString();
4985 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4986 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
4987 if ( argBeg < 4 || argBeg > longStr.Length() )
4989 for ( ; itSub != _subFams.end(); ++itSub )
4992 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
4993 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
4995 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
4996 from = pos + len + itSub->_prefix.Length();
5001 from += itSub->_prefix.Length();
5004 // look among _strings
5005 std::list< _AString >::iterator itStr = _strings.begin();
5006 for ( ; itStr != _strings.end(); ++itStr )
5007 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5008 // check that object ID does not continue after len
5009 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5011 subStr.push_back( *itStr );
5017 //================================================================================
5019 * \brief Return remainder length of the object ID after my _prefix
5020 * \param [in] str - remainder of the command after my _prefix
5021 * \return int - length of the object ID or -1 if not found
5023 //================================================================================
5025 int _pyStringFamily::isIn( const char* str )
5027 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5029 for ( ; itSub != _subFams.end(); ++itSub )
5031 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5034 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5035 return itSub->_prefix.Length() + len;
5040 if ( !_strings.empty() )
5042 std::list< _AString >::iterator itStr = _strings.begin();
5043 bool firstEmpty = itStr->IsEmpty();
5046 for ( ; itStr != _strings.end(); ++itStr )
5048 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5051 len = itStr->Length();
5060 // check that object ID does not continue after len
5061 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5068 //================================================================================
5072 //================================================================================
5074 void _pyStringFamily::Print( int level )
5076 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5077 std::list< _AString >::iterator itStr = _strings.begin();
5078 for ( ; itStr != _strings.end(); ++itStr )
5079 cout << *itStr << " | ";
5081 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5082 for ( ; itSub != _subFams.end(); ++itSub )
5083 itSub->Print( level + 1 );
5085 cout << string( 70, '-' ) << endl;