1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
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.Search( "print " ) == 1 )
205 return; // print statement
207 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
208 // remove an accessor method
209 obj = _pyCommand( obj ).GetObject();
211 const bool isMethodCall = cmd->IsMethodCall();
212 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
214 comment = "not created Object";
215 theGen->ObjectCreationRemoved( obj );
217 // check if a command has not created args
218 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
220 const _pyID& arg = cmd->GetArg( iArg );
221 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
223 list< _pyID > idList = cmd->GetStudyEntries( arg );
224 list< _pyID >::iterator id = idList.begin();
225 for ( ; id != idList.end(); ++id )
226 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
228 comment += *id + " has not been yet created";
231 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
232 // comment += arg + " has not been yet created";
234 // treat result objects
235 const _pyID& result = cmd->GetResultValue();
236 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
238 list< _pyID > idList = cmd->GetStudyEntries( result );
239 list< _pyID >::iterator id = idList.begin();
240 for ( ; id != idList.end(); ++id )
242 if ( comment.IsEmpty() )
243 presentObjects.insert( *id );
245 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
247 if ( idList.empty() && cmd->IsID( result ))
248 presentObjects.insert( result );
250 // comment the command
251 if ( !comment.IsEmpty() )
254 cmd->GetString() += " ### ";
255 cmd->GetString() += comment;
259 //================================================================================
261 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
263 //================================================================================
265 void fixFunctorType( TCollection_AsciiString& Type,
266 TCollection_AsciiString& Compare,
267 TCollection_AsciiString& UnaryOp,
268 TCollection_AsciiString& BinaryOp )
270 // The problem is that dumps of old studies created using filters becomes invalid
271 // when new items are inserted in the enum SMESH::FunctorType since values
272 // of this enum are dumped as integer values.
273 // This function corrects enum values of old studies given as args (Type,Compare,...)
274 // We can find out how to correct them by value of BinaryOp which can have only two
275 // values: FT_Undefined or FT_LogicalNOT.
276 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
277 // where PythonDump appeared
278 // v 3.0.0: FT_Undefined == 25
279 // v 3.1.0: FT_Undefined == 26, new items:
281 // v 4.1.2: FT_Undefined == 27, new items:
282 // - FT_BelongToGenSurface = 17
283 // v 5.1.1: FT_Undefined == 32, new items:
284 // - FT_FreeNodes = 10
285 // - FT_FreeFaces = 11
286 // - FT_LinearOrQuadratic = 23
287 // - FT_GroupColor = 24
288 // - FT_ElemGeomType = 25
289 // v 5.1.5: FT_Undefined == 33, new items:
290 // - FT_CoplanarFaces = 26
291 // v 6.2.0: FT_Undefined == 39, new items:
292 // - FT_MaxElementLength2D = 8
293 // - FT_MaxElementLength3D = 9
294 // - FT_BareBorderVolume = 25
295 // - FT_BareBorderFace = 26
296 // - FT_OverConstrainedVolume = 27
297 // - FT_OverConstrainedFace = 28
298 // v 6.5.0: FT_Undefined == 43, new items:
299 // - FT_EqualNodes = 14
300 // - FT_EqualEdges = 15
301 // - FT_EqualFaces = 16
302 // - FT_EqualVolumes = 17
303 // v 6.6.0: FT_Undefined == 44, new items:
304 // - FT_BallDiameter = 37
305 // v 6.7.1: FT_Undefined == 45, new items:
306 // - FT_EntityType = 36
307 // v 7.3.0: FT_Undefined == 46, new items:
308 // - FT_ConnectedElements = 39
309 // v 7.6.0: FT_Undefined == 47, new items:
310 // - FT_BelongToMeshGroup = 22
312 // It's necessary to continue recording this history and to fill
313 // undef2newItems (see below) accordingly.
315 typedef map< int, vector< int > > TUndef2newItems;
316 static TUndef2newItems undef2newItems;
317 if ( undef2newItems.empty() )
319 undef2newItems[ 26 ].push_back( 7 );
320 undef2newItems[ 27 ].push_back( 17 );
321 { int items[] = { 10, 11, 23, 24, 25 };
322 undef2newItems[ 32 ].assign( items, items+5 ); }
323 undef2newItems[ 33 ].push_back( 26 );
324 { int items[] = { 8, 9, 25, 26, 27, 28 };
325 undef2newItems[ 39 ].assign( items, items+6 ); }
326 { int items[] = { 14, 15, 16, 17 };
327 undef2newItems[ 43 ].assign( items, items+4 ); }
328 undef2newItems[ 44 ].push_back( 37 );
329 undef2newItems[ 45 ].push_back( 36 );
330 undef2newItems[ 46 ].push_back( 39 );
331 undef2newItems[ 47 ].push_back( 22 );
333 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
336 int iType = Type.IntegerValue();
337 int iCompare = Compare.IntegerValue();
338 int iUnaryOp = UnaryOp.IntegerValue();
339 int iBinaryOp = BinaryOp.IntegerValue();
341 // find out integer value of FT_Undefined at the moment of dump
342 int oldUndefined = iBinaryOp;
343 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
346 // apply history to args
347 TUndef2newItems::const_iterator undef_items =
348 undef2newItems.upper_bound( oldUndefined );
349 if ( undef_items != undef2newItems.end() )
351 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
352 for ( ; undef_items != undef2newItems.end(); ++undef_items )
354 const vector< int > & addedItems = undef_items->second;
355 for ( size_t i = 0; i < addedItems.size(); ++i )
356 for ( int iArg = 0; iArg < 4; ++iArg )
358 int& arg = *pArg[iArg];
359 if ( arg >= addedItems[i] )
363 Type = TCollection_AsciiString( iType );
364 Compare = TCollection_AsciiString( iCompare );
365 UnaryOp = TCollection_AsciiString( iUnaryOp );
366 BinaryOp = TCollection_AsciiString( iBinaryOp );
370 //================================================================================
372 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
373 * arguments of a given command by a list "[x,y,z]" if the list is accesible
376 //================================================================================
378 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
380 static TStringSet methodsAcceptingList;
381 if ( methodsAcceptingList.empty() ) {
382 const char * methodNames[] = {
383 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
384 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
385 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
386 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
387 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
388 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
389 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
390 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
391 "Translate","TranslateMakeGroups","TranslateMakeMesh",
392 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
393 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
394 ,"" }; // <- mark of the end
395 methodsAcceptingList.Insert( methodNames );
397 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
399 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
401 const _AString & arg = theCommand->GetArg( i );
402 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
403 arg.Search( "SMESH.DirStruct" ) == 1 )
405 Handle(_pyCommand) workCmd = new _pyCommand( arg );
406 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
408 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
410 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
412 _AString newArg = "[ ";
413 newArg += ( workCmd->GetArg( 1 ) + ", " +
414 workCmd->GetArg( 2 ) + ", " +
415 workCmd->GetArg( 3 ) + " ]");
416 theCommand->SetArg( i, newArg );
422 //================================================================================
424 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
425 * a list "[id1,id2]" if the list is an accesible type of argument.
427 //================================================================================
429 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
431 static TStringSet methodsAcceptingList;
432 if ( methodsAcceptingList.empty() ) {
433 const char * methodNames[] = {
434 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
435 "ExportCGNS","ExportGMF",
436 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
437 "ScaleMakeGroups","Scale","ScaleMakeMesh",
438 "FindCoincidentNodesOnPartBut","DoubleElements",
439 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
440 ,"" }; // <- mark of the end
441 methodsAcceptingList.Insert( methodNames );
443 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
445 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
447 _pyCommand argCmd( theCommand->GetArg( i ));
448 if ( argCmd.GetMethod() == "GetIDSource" &&
449 argCmd.GetNbArgs() == 2 )
451 theCommand->SetArg( i, argCmd.GetArg( 1 ));
458 //================================================================================
460 * \brief Convert a python script using commands of smeshBuilder.py
461 * \param theScriptLines - Lines of the input script
462 * \param theEntry2AccessorMethod - returns method names to access to
463 * objects wrapped with python class
464 * \param theObjectNames - names of objects
465 * \param theRemovedObjIDs - entries of objects whose created commands were removed
466 * \param theHistoricalDump - true means to keep all commands, false means
467 * to exclude commands relating to objects removed from study
468 * \retval TCollection_AsciiString - Convertion result
470 //================================================================================
473 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
474 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
475 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
476 std::set< TCollection_AsciiString >& theRemovedObjIDs,
477 SALOMEDS::Study_ptr& theStudy,
478 const bool theToKeepAllCommands)
480 std::list< TCollection_AsciiString >::iterator lineIt;
481 // process notebook variables
483 SMESH_NoteBook aNoteBook;
485 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
486 aNoteBook.AddCommand( *lineIt );
488 theScriptLines.clear();
490 aNoteBook.ReplaceVariables();
492 aNoteBook.GetResultLines( theScriptLines );
495 // convert to smeshBuilder.py API
497 theGen = new _pyGen( theEntry2AccessorMethod,
501 theToKeepAllCommands );
503 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504 theGen->AddCommand( *lineIt );
506 theScriptLines.clear();
510 #ifdef DUMP_CONVERSION
511 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
514 // clean commmands of removed objects depending on myIsPublished flag
515 theGen->ClearCommands();
517 // reorder commands after conversion
518 list< Handle(_pyCommand) >::iterator cmd;
521 orderChanges = false;
522 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523 if ( (*cmd)->SetDependentCmdsAfter() )
525 } while ( orderChanges );
527 // concat commands back into a script
528 TCollection_AsciiString aPrevCmd;
529 set<_pyID> createdObjects;
530 createdObjects.insert( "smeshBuilder" );
531 createdObjects.insert( "smesh" );
532 createdObjects.insert( "theStudy" );
533 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
535 #ifdef DUMP_CONVERSION
536 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
538 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
539 CheckObjectPresence( *cmd, createdObjects );
540 if ( !(*cmd)->IsEmpty() ) {
541 aPrevCmd = (*cmd)->GetString();
542 theScriptLines.push_back( aPrevCmd );
551 //================================================================================
553 * \brief _pyGen constructor
555 //================================================================================
557 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
558 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
559 std::set< TCollection_AsciiString >& theRemovedObjIDs,
560 SALOMEDS::Study_ptr& theStudy,
561 const bool theToKeepAllCommands)
562 : _pyObject( new _pyCommand( "", 0 )),
564 myID2AccessorMethod( theEntry2AccessorMethod ),
565 myObjectNames( theObjectNames ),
566 myRemovedObjIDs( theRemovedObjIDs ),
568 myToKeepAllCommands( theToKeepAllCommands ),
569 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
570 myGeomIDNb(0), myGeomIDIndex(-1)
572 // make that GetID() to return TPythonDump::SMESHGenName()
573 GetCreationCmd()->Clear();
574 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
575 GetCreationCmd()->GetString() += "=";
577 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
578 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
582 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
583 if ( geomComp->_is_nil() ) return;
584 CORBA::String_var entry = geomComp->GetID();
587 // find a SMESH entry
589 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
590 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
591 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
594 // find 1st difference between smeshID and geomID
595 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
596 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
597 if ( geomID.Value( i ) != smeshID.Value( i ))
599 myGeomIDNb = geomID.Value( i );
605 //================================================================================
607 * \brief name of SMESH_Gen in smeshBuilder.py
609 //================================================================================
611 const char* _pyGen::AccessorMethod() const
613 return SMESH_2smeshpy::GenName();
616 //================================================================================
618 * \brief Convert a command using a specific converter
619 * \param theCommand - the command to convert
621 //================================================================================
623 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
625 // store theCommand in the sequence
626 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
628 Handle(_pyCommand) aCommand = myCommands.back();
629 #ifdef DUMP_CONVERSION
630 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
633 const _pyID& objID = aCommand->GetObject();
635 if ( objID.IsEmpty() )
638 // Prevent moving a command creating a sub-mesh to the end of the script
639 // if the sub-mesh is used in theCommand as argument
640 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
642 // PlaceSubmeshAfterItsCreation( aCommand );
645 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
646 StructToList( aCommand );
648 const TCollection_AsciiString& method = aCommand->GetMethod();
650 // not to erase _pySelfEraser's etc. used as args in some commands
652 #ifdef USE_STRING_FAMILY
653 std::list<_pyID> objIDs;
654 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
656 std::list<_pyID>::iterator objID = objIDs.begin();
657 for ( ; objID != objIDs.end(); ++objID )
659 Handle(_pyObject) obj = FindObject( *objID );
662 obj->AddArgCmd( aCommand );
663 //cout << objID << " found in " << theCommand << endl;
668 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
669 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
670 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
672 Handle(_pyObject) obj = FindObject( *id );
674 obj->AddArgCmd( aCommand );
679 // Find an object to process theCommand
682 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
684 this->Process( aCommand );
685 //addFilterUser( aCommand, theGen ); // protect filters from clearing
689 // SMESH_Mesh method?
690 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
691 if ( id_mesh != myMeshes.end() )
693 //id_mesh->second->AddProcessedCmd( aCommand );
695 // Wrap Export*() into try-except
696 if ( aCommand->MethodStartsFrom("Export"))
699 _AString indent = aCommand->GetIndentation();
700 _AString tryStr = indent + "try:";
701 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
702 _AString excStr = indent + "except:";
703 _AString msgStr = indent + "\tprint '"; msgStr += method + "() failed. Invalid file name?'";
705 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
707 aCommand->GetString() = newCmd;
708 aCommand->SetOrderNb( ++myNbCommands );
709 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
710 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
712 // check for mesh editor object
713 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
714 _pyID editorID = aCommand->GetResultValue();
715 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
716 myMeshEditors.insert( make_pair( editorID, editor ));
719 // check for SubMesh objects
720 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
721 _pyID subMeshID = aCommand->GetResultValue();
722 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
723 AddObject( subMesh );
726 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
727 GetIDSourceToList( aCommand );
729 //addFilterUser( aCommand, theGen ); // protect filters from clearing
731 id_mesh->second->Process( aCommand );
732 id_mesh->second->AddProcessedCmd( aCommand );
736 // SMESH_MeshEditor method?
737 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
738 if ( id_editor != myMeshEditors.end() )
740 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
741 GetIDSourceToList( aCommand );
743 //addFilterUser( aCommand, theGen ); // protect filters from clearing
745 // some commands of SMESH_MeshEditor create meshes and groups
746 _pyID meshID, groups;
747 if ( method.Search("MakeMesh") != -1 )
748 meshID = aCommand->GetResultValue();
749 else if ( method == "MakeBoundaryMesh")
750 meshID = aCommand->GetResultValue(1);
751 else if ( method == "MakeBoundaryElements")
752 meshID = aCommand->GetResultValue(2);
754 if ( method.Search("MakeGroups") != -1 ||
755 method == "ExtrusionAlongPathX" ||
756 method == "ExtrusionAlongPathObjX" ||
757 method == "DoubleNodeGroupNew" ||
758 method == "DoubleNodeGroupsNew" ||
759 method == "DoubleNodeElemGroupNew" ||
760 method == "DoubleNodeElemGroupsNew"||
761 method == "DoubleNodeElemGroup2New"||
762 method == "DoubleNodeElemGroups2New"
764 groups = aCommand->GetResultValue();
765 else if ( method == "MakeBoundaryMesh" )
766 groups = aCommand->GetResultValue(2);
767 else if ( method == "MakeBoundaryElements")
768 groups = aCommand->GetResultValue(3);
769 else if ( method == "Create0DElementsOnAllNodes" &&
770 aCommand->GetArg(2).Length() > 2 ) // group name != ''
771 groups = aCommand->GetResultValue();
773 id_editor->second->Process( aCommand );
774 id_editor->second->AddProcessedCmd( aCommand );
777 if ( !meshID.IsEmpty() &&
778 !myMeshes.count( meshID ) &&
779 aCommand->IsStudyEntry( meshID ))
781 _AString processedCommand = aCommand->GetString();
782 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
783 CheckObjectIsReCreated( mesh );
784 myMeshes.insert( make_pair( meshID, mesh ));
786 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
789 if ( !groups.IsEmpty() )
791 if ( !aCommand->IsStudyEntry( meshID ))
792 meshID = id_editor->second->GetMesh();
793 Handle(_pyMesh) mesh = myMeshes[ meshID ];
795 list< _pyID > idList = aCommand->GetStudyEntries( groups );
796 list< _pyID >::iterator grID = idList.begin();
797 for ( ; grID != idList.end(); ++grID )
798 if ( !myObjects.count( *grID ))
800 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
802 if ( !mesh.IsNull() ) mesh->AddGroup( group );
806 } // SMESH_MeshEditor methods
808 // SMESH_Hypothesis method?
809 Handle(_pyHypothesis) hyp = FindHyp( objID );
810 if ( !hyp.IsNull() && !hyp->IsAlgo() )
812 hyp->Process( aCommand );
813 hyp->AddProcessedCmd( aCommand );
817 // aFilterManager.CreateFilter() ?
818 if ( aCommand->GetMethod() == "CreateFilter" )
820 // Set a more human readable name to a filter
821 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
822 _pyID newID, filterID = aCommand->GetResultValue();
823 int pos = filterID.Search( "0x" );
825 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
827 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
830 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
831 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
833 // create _pySelfEraser for functors
834 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
835 functor->IgnoreOwnCalls(); // to erase if not used as an argument
836 AddObject( functor );
839 // other object method?
840 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
841 if ( id_obj != myObjects.end() ) {
842 id_obj->second->Process( aCommand );
843 id_obj->second->AddProcessedCmd( aCommand );
847 // Add access to a wrapped mesh
848 AddMeshAccessorMethod( aCommand );
850 // Add access to a wrapped algorithm
851 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
853 // PAL12227. PythonDump was not updated at proper time; result is
854 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
855 // TypeError: __init__() takes exactly 11 arguments (10 given)
856 const char wrongCommand[] = "SMESH.Filter.Criterion(";
857 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
859 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
860 // there must be 10 arguments, 5-th arg ThresholdID is missing,
861 const int wrongNbArgs = 9, missingArg = 5;
862 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
864 for ( int i = wrongNbArgs; i > missingArg; --i )
865 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
866 tmpCmd.SetArg( missingArg, "''");
867 aCommand->GetString().Trunc( beg - 1 );
868 aCommand->GetString() += tmpCmd.GetString();
871 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
873 // instead of "SMESH.Filter.Criterion(
874 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
875 // 1 2 3 4 5 6 7 8 9 10
876 // in order to avoid the problem of type mismatch of long and FunctorType
877 const TCollection_AsciiString
878 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
879 TCollection_AsciiString
880 Type = aCommand->GetArg(1), // long
881 Compare = aCommand->GetArg(2), // long
882 Threshold = aCommand->GetArg(3), // double
883 ThresholdStr = aCommand->GetArg(4), // string
884 ThresholdID = aCommand->GetArg(5), // string
885 UnaryOp = aCommand->GetArg(6), // long
886 BinaryOp = aCommand->GetArg(7), // long
887 Tolerance = aCommand->GetArg(8), // double
888 TypeOfElement = aCommand->GetArg(9), // ElementType
889 Precision = aCommand->GetArg(10); // long
890 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
891 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
892 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
893 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
894 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
896 if ( Compare == "SMESH.FT_EqualTo" )
899 aCommand->RemoveArgs();
900 aCommand->SetObject( SMESH_2smeshpy::GenName() );
901 aCommand->SetMethod( "GetCriterion" );
903 aCommand->SetArg( 1, TypeOfElement );
904 aCommand->SetArg( 2, Type );
905 aCommand->SetArg( 3, Compare );
907 if ( Threshold.IsIntegerValue() )
909 int iGeom = Threshold.IntegerValue();
910 if ( Type == "SMESH.FT_ElemGeomType" )
912 // set SMESH.GeometryType instead of a numerical Threshold
913 const int nbTypes = SMESH::Geom_LAST;
914 const char* types[nbTypes] = {
915 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
916 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
917 "Geom_POLYHEDRA", "Geom_BALL" };
918 if ( -1 < iGeom && iGeom < nbTypes )
919 Threshold = SMESH + types[ iGeom ];
921 // is types complete? (compilation failure mains that enum GeometryType changed)
922 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ]; _assert[0]=1;
925 if (Type == "SMESH.FT_EntityType")
927 // set SMESH.EntityType instead of a numerical Threshold
928 const int nbTypes = SMESH::Entity_Last;
929 const char* types[nbTypes] = {
930 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
931 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
932 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
933 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
934 "Entity_Pyramid", "Entity_Quad_Pyramid",
935 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
936 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
937 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
938 if ( -1 < iGeom && iGeom < nbTypes )
939 Threshold = SMESH + types[ iGeom ];
941 // is types complete? (compilation failure mains that enum EntityType changed)
942 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ]; _assert[0]=1;
946 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
947 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
948 else if ( ThresholdStr.Length() != 2 )
949 aCommand->SetArg( 4, ThresholdStr );
950 else if ( ThresholdID.Length() != 2 )
951 aCommand->SetArg( 4, ThresholdID );
953 aCommand->SetArg( 4, Threshold );
954 // find the last not default arg
956 if ( Tolerance == dfltTol ) {
958 if ( BinaryOp == dfltFunctor ) {
960 if ( UnaryOp == dfltFunctor )
964 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
965 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
966 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
967 if ( Precision != dfltPreci )
969 TCollection_AsciiString crit = aCommand->GetResultValue();
970 aCommand->GetString() += "; ";
971 aCommand->GetString() += crit + ".Precision = " + Precision;
977 //================================================================================
979 * \brief Convert the command or remember it for later conversion
980 * \param theCommand - The python command calling a method of SMESH_Gen
982 //================================================================================
984 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
986 // there are methods to convert:
987 // CreateMesh( shape )
988 // Concatenate( [mesh1, ...], ... )
989 // CreateHypothesis( theHypType, theLibName )
990 // Compute( mesh, geom )
991 // Evaluate( mesh, geom )
993 TCollection_AsciiString method = theCommand->GetMethod();
995 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
997 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1001 if ( method == "CreateMeshesFromUNV" ||
1002 method == "CreateMeshesFromSTL" ||
1003 method == "CopyMesh" ) // command result is a mesh
1005 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1009 if( method == "CreateMeshesFromMED" ||
1010 method == "CreateMeshesFromSAUV"||
1011 method == "CreateMeshesFromCGNS" ||
1012 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1014 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1015 std::list< _pyID >::iterator meshID = meshIDs.begin();
1016 for ( ; meshID != meshIDs.end(); ++meshID )
1018 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1021 if ( method == "CreateMeshesFromGMF" )
1023 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1024 // CreateMeshesFromGMF( theFileName )
1025 _AString file = theCommand->GetArg(1);
1026 theCommand->RemoveArgs();
1027 theCommand->SetArg( 1, file );
1031 // CreateHypothesis()
1032 if ( method == "CreateHypothesis" )
1034 // issue 199929, remove standard library name (default parameter)
1035 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1036 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1037 // keep the first argument
1038 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1039 theCommand->RemoveArgs();
1040 theCommand->SetArg( 1, arg );
1043 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1044 CheckObjectIsReCreated( hyp );
1045 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1050 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1051 if ( method == "Compute" )
1053 const _pyID& meshID = theCommand->GetArg( 1 );
1054 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1055 if ( id_mesh != myMeshes.end() ) {
1056 theCommand->SetObject( meshID );
1057 theCommand->RemoveArgs();
1058 id_mesh->second->Process( theCommand );
1059 id_mesh->second->AddProcessedCmd( theCommand );
1064 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1065 if ( method == "Evaluate" )
1067 const _pyID& meshID = theCommand->GetArg( 1 );
1068 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1069 if ( id_mesh != myMeshes.end() ) {
1070 theCommand->SetObject( meshID );
1071 _pyID geom = theCommand->GetArg( 2 );
1072 theCommand->RemoveArgs();
1073 theCommand->SetArg( 1, geom );
1074 id_mesh->second->AddProcessedCmd( theCommand );
1079 // objects erasing creation command if no more its commands invoked:
1080 // SMESH_Pattern, FilterManager
1081 if ( method == "GetPattern" ||
1082 method == "CreateFilterManager" ||
1083 method == "CreateMeasurements" )
1085 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1086 if ( !AddObject( obj ) )
1087 theCommand->Clear(); // already created
1089 // Concatenate( [mesh1, ...], ... )
1090 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1092 if ( method == "ConcatenateWithGroups" ) {
1093 theCommand->SetMethod( "Concatenate" );
1094 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1096 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1098 AddMeshAccessorMethod( theCommand );
1100 else if ( method == "SetName" ) // SetName(obj,name)
1102 // store theCommand as one of object commands to erase it along with the object
1103 const _pyID& objID = theCommand->GetArg( 1 );
1104 Handle(_pyObject) obj = FindObject( objID );
1105 if ( !obj.IsNull() )
1106 obj->AddProcessedCmd( theCommand );
1109 // Replace name of SMESH_Gen
1111 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1112 static TStringSet smeshpyMethods;
1113 if ( smeshpyMethods.empty() ) {
1114 const char * names[] =
1115 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1116 "GetPattern","GetSubShapesId",
1117 "" }; // <- mark of array end
1118 smeshpyMethods.Insert( names );
1120 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1121 // smeshgen.Method() --> smesh.Method()
1122 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1124 // smeshgen.Method() --> smesh.Method()
1125 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1128 //================================================================================
1130 * \brief Convert the remembered commands
1132 //================================================================================
1134 void _pyGen::Flush()
1136 // create an empty command
1137 myLastCommand = new _pyCommand();
1139 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1140 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1141 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1143 if ( IsToKeepAllCommands() ) // historical dump
1145 // set myIsPublished = true to all objects
1146 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1147 id_mesh->second->SetRemovedFromStudy( false );
1148 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1149 id_hyp->second->SetRemovedFromStudy( false );
1150 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1151 id_obj->second->SetRemovedFromStudy( false );
1155 // let hypotheses find referred objects in order to prevent clearing
1156 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1157 list< Handle(_pyMesh) > fatherMeshes;
1158 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1159 if ( !id_hyp->second.IsNull() )
1160 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1162 // set myIsPublished = false to all objects depending on
1163 // meshes built on a removed geometry
1164 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1165 if ( id_mesh->second->IsNotGeomPublished() )
1166 id_mesh->second->SetRemovedFromStudy( true );
1169 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1170 if ( ! id_mesh->second.IsNull() )
1171 id_mesh->second->Flush();
1174 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1175 if ( !id_hyp->second.IsNull() ) {
1176 id_hyp->second->Flush();
1177 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1178 if ( !id_hyp->second->IsWrapped() )
1179 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1182 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1183 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1184 for ( ; robj != myOrderedObjects.rend(); ++robj )
1185 if ( ! robj->IsNull() )
1187 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1188 for ( ; obj != myOrderedObjects.end(); ++obj )
1189 if ( ! obj->IsNull() )
1192 myLastCommand->SetOrderNb( ++myNbCommands );
1193 myCommands.push_back( myLastCommand );
1196 //================================================================================
1198 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1199 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1201 //================================================================================
1203 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1205 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1206 // for ( ; id_obj != myObjects.end(); ++id_obj )
1208 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1209 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1211 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1212 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1214 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1215 // list< _pyID >::iterator id = idList.begin();
1216 // for ( ; id != idList.end(); ++id )
1217 // if ( id_obj->first == *id )
1218 // // _pySubMesh::Process() does what we need
1219 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1224 //================================================================================
1226 * \brief Clean commmands of removed objects depending on myIsPublished flag
1228 //================================================================================
1230 void _pyGen::ClearCommands()
1232 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1233 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1234 id_mesh->second->ClearCommands();
1236 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1237 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1238 if ( !id_hyp->second.IsNull() )
1239 id_hyp->second->ClearCommands();
1241 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1242 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1243 for ( ; robj != myOrderedObjects.rend(); ++robj )
1244 if ( ! robj->IsNull() )
1245 (*robj)->ClearCommands();
1246 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1247 for ( ; obj != myOrderedObjects.end(); ++obj )
1248 if ( ! obj->IsNull() )
1249 (*obj)->ClearCommands();
1252 //================================================================================
1254 * \brief Release mutual handles of objects
1256 //================================================================================
1260 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1261 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1262 id_mesh->second->Free();
1265 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1266 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1267 id_ed->second->Free();
1268 myMeshEditors.clear();
1270 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1271 for ( ; id_obj != myObjects.end(); ++id_obj )
1272 id_obj->second->Free();
1275 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1276 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1277 if ( !id_hyp->second.IsNull() )
1278 id_hyp->second->Free();
1281 myFile2ExportedMesh.clear();
1283 //myKeepAgrCmdsIDs.Print();
1286 //================================================================================
1288 * \brief Add access method to mesh that is an argument
1289 * \param theCmd - command to add access method
1290 * \retval bool - true if added
1292 //================================================================================
1294 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1297 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1298 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1299 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1305 //================================================================================
1307 * \brief Add access method to algo that is an object or an argument
1308 * \param theCmd - command to add access method
1309 * \retval bool - true if added
1311 //================================================================================
1313 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1316 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1317 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1318 if ( !id_hyp->second.IsNull() &&
1319 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1320 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1321 id_hyp->second->AccessorMethod() ))
1327 //================================================================================
1329 * \brief Find hypothesis by ID (entry)
1330 * \param theHypID - The hypothesis ID
1331 * \retval Handle(_pyHypothesis) - The found hypothesis
1333 //================================================================================
1335 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1337 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1338 if ( id_hyp != myHypos.end() &&
1339 !id_hyp->second.IsNull() &&
1340 theHypID == id_hyp->second->GetID() )
1341 return id_hyp->second;
1342 return Handle(_pyHypothesis)();
1345 //================================================================================
1347 * \brief Find algorithm able to create a hypothesis
1348 * \param theGeom - The shape ID the algorithm was created on
1349 * \param theMesh - The mesh ID that created the algorithm
1350 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1351 * \retval Handle(_pyHypothesis) - The found algo
1353 //================================================================================
1355 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1356 const Handle(_pyHypothesis)& theHypothesis )
1358 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1359 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1360 if ( !id_hyp->second.IsNull() &&
1361 id_hyp->second->IsAlgo() &&
1362 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1363 id_hyp->second->GetGeom() == theGeom &&
1364 id_hyp->second->GetMesh() == theMesh )
1365 return id_hyp->second;
1366 return Handle(_pyHypothesis)();
1369 //================================================================================
1371 * \brief Find subMesh by ID (entry)
1372 * \param theSubMeshID - The subMesh ID
1373 * \retval Handle(_pySubMesh) - The found subMesh
1375 //================================================================================
1377 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1379 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1380 if ( id_subMesh != myObjects.end() )
1381 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1382 return Handle(_pySubMesh)();
1386 //================================================================================
1388 * \brief Change order of commands in the script
1389 * \param theCmd1 - One command
1390 * \param theCmd2 - Another command
1392 //================================================================================
1394 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1396 list< Handle(_pyCommand) >::iterator pos1, pos2;
1397 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1398 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1399 myCommands.insert( pos1, theCmd2 );
1400 myCommands.insert( pos2, theCmd1 );
1401 myCommands.erase( pos1 );
1402 myCommands.erase( pos2 );
1404 int nb1 = theCmd1->GetOrderNb();
1405 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1406 theCmd2->SetOrderNb( nb1 );
1407 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1408 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1411 //================================================================================
1413 * \brief Set one command after the other
1414 * \param theCmd - Command to move
1415 * \param theAfterCmd - Command ater which to insert the first one
1417 //================================================================================
1419 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1421 setNeighbourCommand( theCmd, theAfterCmd, true );
1424 //================================================================================
1426 * \brief Set one command before the other
1427 * \param theCmd - Command to move
1428 * \param theBeforeCmd - Command before which to insert the first one
1430 //================================================================================
1432 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1434 setNeighbourCommand( theCmd, theBeforeCmd, false );
1437 //================================================================================
1439 * \brief Set one command before or after the other
1440 * \param theCmd - Command to move
1441 * \param theOtherCmd - Command ater or before which to insert the first one
1443 //================================================================================
1445 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1446 Handle(_pyCommand)& theOtherCmd,
1447 const bool theIsAfter )
1449 list< Handle(_pyCommand) >::iterator pos;
1450 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1451 myCommands.erase( pos );
1452 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1453 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1456 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1457 (*pos)->SetOrderNb( i++ );
1460 //================================================================================
1462 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1464 //================================================================================
1466 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1468 // No more needed after adding _pyObject::myArgCommands
1470 // const char filterPrefix[] = "aFilter0x";
1471 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1474 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1476 // const _AString & arg = theCommand->GetArg( i );
1477 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1478 // if ( arg.Search( filterPrefix ) != 1 )
1481 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1482 // if ( !filter.IsNull() )
1484 // filter->AddUser( user );
1485 // if ( !filter->GetNewID().IsEmpty() )
1486 // theCommand->SetArg( i, filter->GetNewID() );
1491 //================================================================================
1493 * \brief Set command be last in list of commands
1494 * \param theCmd - Command to be last
1496 //================================================================================
1498 Handle(_pyCommand)& _pyGen::GetLastCommand()
1500 return myLastCommand;
1503 //================================================================================
1505 * \brief Set method to access to object wrapped with python class
1506 * \param theID - The wrapped object entry
1507 * \param theMethod - The accessor method
1509 //================================================================================
1511 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1513 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1516 //================================================================================
1518 * \brief Generated new ID for object and assign with existing name
1519 * \param theID - ID of existing object
1521 //================================================================================
1523 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1528 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1530 while ( myObjectNames.IsBound( aNewID ) );
1532 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1533 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1534 : _pyID( "A" ) + aNewID );
1538 //================================================================================
1540 * \brief Stores theObj in myObjects
1542 //================================================================================
1544 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1546 if ( theObj.IsNull() ) return false;
1548 CheckObjectIsReCreated( theObj );
1552 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1553 add = myMeshes.insert( make_pair( theObj->GetID(),
1554 Handle(_pyMesh)::DownCast( theObj ))).second;
1556 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1557 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1558 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1561 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1562 if ( add ) myOrderedObjects.push_back( theObj );
1567 //================================================================================
1569 * \brief Erases an existing object with the same ID. This method should be called
1570 * before storing theObj in _pyGen
1572 //================================================================================
1574 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1576 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1579 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1580 Handle(_pyObject) existing =
1581 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1582 if ( !existing.IsNull() && existing != theObj )
1584 existing->SetRemovedFromStudy( true );
1585 existing->ClearCommands();
1588 if ( myHypos.count( theObj->GetID() ))
1589 myHypos.erase( theObj->GetID() );
1591 else if ( myMeshes.count( theObj->GetID() ))
1593 myMeshes.erase( theObj->GetID() );
1595 else if ( myObjects.count( theObj->GetID() ))
1597 myObjects.erase( theObj->GetID() );
1602 //================================================================================
1604 * \brief Re-register an object with other ID to make it Process() commands of
1605 * other object having this ID
1607 //================================================================================
1609 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1611 if ( theObj.IsNull() ) return;
1613 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1614 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1616 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1617 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1620 myObjects.insert( make_pair( theID, theObj ));
1623 //================================================================================
1625 * \brief Finds a _pyObject by ID
1627 //================================================================================
1629 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1632 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1633 if ( id_obj != myObjects.end() )
1634 return id_obj->second;
1637 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1638 if ( id_obj != myMeshes.end() )
1639 return id_obj->second;
1642 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1643 // if ( id_obj != myMeshEditors.end() )
1644 // return id_obj->second;
1646 return Handle(_pyObject)();
1649 //================================================================================
1651 * \brief Check if a study entry is under GEOM component
1653 //================================================================================
1655 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1659 return ( myGeomIDIndex <= theObjID.Length() &&
1660 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1661 _pyCommand::IsStudyEntry( theObjID ));
1666 //================================================================================
1668 * \brief Returns true if an object is not present in a study
1670 //================================================================================
1672 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1674 if ( theObjID.IsEmpty() ) return false;
1676 if ( myObjectNames.IsBound( theObjID ))
1677 return false; // SMESH object is in study
1679 // either the SMESH object is not in study or it is a GEOM object
1680 if ( IsGeomObject( theObjID ))
1682 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1683 if ( so->_is_nil() ) return true;
1684 CORBA::Object_var obj = so->GetObject();
1685 return CORBA::is_nil( obj );
1687 return true; // SMESH object not in study
1690 //================================================================================
1692 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1693 * this object is not dumped
1694 * \param [in] theObjID - entry of the object whose creation command was eliminated
1696 //================================================================================
1698 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1700 myRemovedObjIDs.insert( theObjID );
1703 //================================================================================
1705 * \brief Return reader of hypotheses of plugins
1707 //================================================================================
1709 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1711 if (myHypReader.IsNull() )
1712 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1718 //================================================================================
1720 * \brief Mesh created by SMESH_Gen
1722 //================================================================================
1724 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1725 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1727 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1728 myGeomNotInStudy = true;
1730 // convert my creation command --> smeshpy.Mesh(...)
1731 Handle(_pyCommand) creationCmd = GetCreationCmd();
1732 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1733 creationCmd->SetMethod( "Mesh" );
1734 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1737 //================================================================================
1739 * \brief Mesh created by SMESH_MeshEditor
1741 //================================================================================
1743 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1744 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1746 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1748 // this mesh depends on the exported mesh
1749 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1750 if ( !file.IsEmpty() )
1752 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1753 addFatherMesh( exportData.myMesh );
1754 if ( !exportData.myLastComputeCmd.IsNull() )
1756 // restore cleared Compute() by which the exported mesh was generated
1757 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1758 // protect that Compute() cmd from clearing
1759 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1760 exportData.myMesh->myLastComputeCmd.Nullify();
1764 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1766 // this mesh depends on concatenated meshes
1767 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1768 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1769 list< _pyID >::iterator meshID = idList.begin();
1770 for ( ; meshID != idList.end(); ++meshID )
1771 addFatherMesh( *meshID );
1773 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1775 // this mesh depends on a copied IdSource
1776 const _pyID& objID = theCreationCmd->GetArg( 1 );
1777 addFatherMesh( objID );
1779 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1780 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1781 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1783 // this mesh depends on a source mesh
1784 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1785 const _pyID& meshID = theCreationCmd->GetObject();
1786 addFatherMesh( meshID );
1789 // convert my creation command
1790 Handle(_pyCommand) creationCmd = GetCreationCmd();
1791 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1792 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1795 //================================================================================
1797 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1798 * \param theCommand - Engine method called for this mesh
1800 //================================================================================
1802 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1804 // some methods of SMESH_Mesh interface needs special conversion
1805 // to methods of Mesh python class
1807 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1808 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1809 // 2. AddHypothesis(geom, hyp)
1810 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1811 // 3. CreateGroupFromGEOM(type, name, grp)
1812 // --> in Mesh.Group(grp, name="")
1813 // 4. ExportToMED(f, auto_groups, version)
1814 // --> in Mesh.ExportMED( f, auto_groups, version )
1817 const TCollection_AsciiString& method = theCommand->GetMethod();
1818 // ----------------------------------------------------------------------
1819 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1821 if ( !theGen->IsToKeepAllCommands() ) // !historical
1823 list< Handle(_pyHypothesis) >::iterator hyp;
1824 if ( !myLastComputeCmd.IsNull() )
1826 // check if the previously computed mesh has been edited,
1827 // if so then we do not clear the previous Compute()
1828 bool toClear = true;
1829 if ( myLastComputeCmd->GetMethod() == "Compute" )
1831 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1832 for ( ; e != myEditors.end() && toClear; ++e )
1834 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1835 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1836 if ( cmd != cmds.rend() &&
1837 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1843 // clear hyp commands called before myLastComputeCmd
1844 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1845 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1847 myLastComputeCmd->Clear();
1850 myLastComputeCmd = theCommand;
1852 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1853 (*hyp)->MeshComputed( myLastComputeCmd );
1857 // ----------------------------------------------------------------------
1858 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1860 if ( !theGen->IsToKeepAllCommands() ) // !historical
1863 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1864 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1865 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1867 if ( !myLastComputeCmd.IsNull() )
1869 list< Handle(_pyHypothesis) >::iterator hyp;
1870 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1871 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1873 myLastComputeCmd->Clear();
1876 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1877 for ( ; e != myEditors.end(); ++e )
1879 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1880 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1881 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1882 if ( !(*cmd)->IsEmpty() )
1884 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1888 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1891 // ----------------------------------------------------------------------
1892 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1893 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1894 if ( !subMesh.IsNull() ) {
1895 subMesh->SetCreator( this );
1896 mySubmeshes.push_back( subMesh );
1899 // ----------------------------------------------------------------------
1900 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1901 theCommand->Clear();
1903 // ----------------------------------------------------------------------
1904 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1905 myAddHypCmds.push_back( theCommand );
1907 const _pyID& hypID = theCommand->GetArg( 2 );
1908 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1909 if ( !hyp.IsNull() ) {
1910 myHypos.push_back( hyp );
1911 if ( hyp->GetMesh().IsEmpty() )
1912 hyp->SetMesh( this->GetID() );
1915 // ----------------------------------------------------------------------
1916 else if ( method == "CreateGroup" ||
1917 method == "CreateGroupFromGEOM" ||
1918 method == "CreateGroupFromFilter" ||
1919 method == "CreateDimGroup" )
1921 Handle(_pyGroup) group = new _pyGroup( theCommand );
1922 myGroups.push_back( group );
1923 theGen->AddObject( group );
1925 // ----------------------------------------------------------------------
1926 // update list of groups
1927 else if ( method == "GetGroups" )
1929 bool allGroupsRemoved = true;
1930 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1931 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1932 list< _pyID >::iterator grID = idList.begin();
1933 const size_t nbGroupsBefore = myGroups.size();
1934 Handle(_pyObject) obj;
1935 for ( ; grID != idList.end(); ++grID )
1937 obj = theGen->FindObject( *grID );
1940 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1941 theGen->AddObject( group );
1942 myGroups.push_back( group );
1945 if ( !obj->CanClear() )
1946 allGroupsRemoved = false;
1948 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1949 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1951 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1953 // check if the preceding command is Compute();
1954 // if GetGroups() is just after Compute(), this can mean that the groups
1955 // were created by some algorithm and hence Compute() should not be discarded
1956 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1957 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1958 while ( (*cmd)->GetMethod() == "GetGroups" )
1960 if ( myLastComputeCmd == (*cmd))
1961 // protect last Compute() from clearing by the next Compute()
1962 myLastComputeCmd.Nullify();
1965 // ----------------------------------------------------------------------
1966 // notify a group about full removal
1967 else if ( method == "RemoveGroupWithContents" ||
1968 method == "RemoveGroup")
1970 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1971 const _pyID groupID = theCommand->GetArg( 1 );
1972 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1973 if ( !grp.IsNull() )
1975 if ( method == "RemoveGroupWithContents" )
1976 grp->RemovedWithContents();
1977 // to clear RemoveGroup() if the group creation is cleared
1978 grp->AddProcessedCmd( theCommand );
1982 // ----------------------------------------------------------------------
1983 else if ( theCommand->MethodStartsFrom( "Export" ))
1985 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1986 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1988 theCommand->SetMethod( "ExportMED" );
1989 if ( theCommand->GetNbArgs() == 5 )
1991 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1992 _AString autoDimension = theCommand->GetArg( 5 );
1993 theCommand->SetArg( 5, "None" );
1994 theCommand->SetArg( 6, autoDimension );
1997 else if ( method == "ExportCGNS" )
1998 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1999 _pyID partID = theCommand->GetArg( 1 );
2000 int nbArgs = theCommand->GetNbArgs();
2001 for ( int i = 2; i <= nbArgs; ++i )
2002 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2003 theCommand->SetArg( nbArgs, partID );
2005 else if ( method == "ExportGMF" )
2006 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2007 _pyID partID = theCommand->GetArg( 1 );
2008 _AString file = theCommand->GetArg( 2 );
2009 theCommand->RemoveArgs();
2010 theCommand->SetArg( 1, file );
2011 theCommand->SetArg( 2, partID );
2013 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2014 { // ExportPartTo*(part, ...) -> Export*(..., part)
2016 // remove "PartTo" from the method
2017 TCollection_AsciiString newMethod = method;
2018 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2019 theCommand->SetMethod( newMethod );
2020 // make the 1st arg be the last one (or last but three for ExportMED())
2021 _pyID partID = theCommand->GetArg( 1 );
2022 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2023 for ( int i = 2; i <= nbArgs; ++i )
2024 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2025 theCommand->SetArg( nbArgs, partID );
2027 // remember file name
2028 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2029 ExportedMeshData( this, myLastComputeCmd ));
2031 // ----------------------------------------------------------------------
2032 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2034 _pyID hypID = theCommand->GetArg( 2 );
2035 _pyID geomID = theCommand->GetArg( 1 );
2036 bool isLocal = ( geomID != GetGeom() );
2038 // check if this mesh still has corresponding addition command
2039 Handle(_pyCommand) addCmd;
2040 list< Handle(_pyCommand) >::iterator cmd;
2041 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2042 for ( int i = 0; i < 2; ++i )
2044 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2045 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2047 bool sameHyp = true;
2048 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2049 sameHyp = false; // other hyp
2050 if ( (*cmd)->GetNbArgs() == 2 &&
2051 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2052 sameHyp = false; // other geom
2053 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2054 sameHyp = false; // other geom
2058 cmd = addHypCmds.erase( cmd );
2059 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2061 theCommand->Clear();
2065 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2066 addCmd->RemoveArgs();
2067 addCmd->SetArg( 1, hypID );
2069 addCmd->SetArg( 2, geomID );
2078 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2079 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2080 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2081 _pyID geom = theCommand->GetArg( 1 );
2082 theCommand->RemoveArgs();
2083 theCommand->SetArg( 1, hypID );
2084 if ( geom != GetGeom() )
2085 theCommand->SetArg( 2, geom );
2087 // remove hyp from myHypos
2088 myHypos.remove( hyp );
2090 // check for SubMesh order commands
2091 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2093 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2094 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2095 // commands are moved at the end of the script
2096 TCollection_AsciiString subIDs =
2097 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2098 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2099 list< _pyID >::iterator subID = idList.begin();
2100 for ( ; subID != idList.end(); ++subID )
2102 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2103 if ( !subMesh.IsNull() )
2104 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2107 // add accessor method if necessary
2110 if ( NeedMeshAccess( theCommand ))
2111 // apply theCommand to the mesh wrapped by smeshpy mesh
2112 AddMeshAccess( theCommand );
2116 //================================================================================
2118 * \brief Return True if addition of accesor method is needed
2120 //================================================================================
2122 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2124 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2125 // so no conversion is needed for them at all:
2126 static TStringSet sameMethods;
2127 if ( sameMethods.empty() ) {
2128 const char * names[] =
2129 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2130 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2131 "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2132 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2133 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2134 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2135 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2136 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2137 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2138 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2139 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2140 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2141 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2142 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2143 ,"" }; // <- mark of end
2144 sameMethods.Insert( names );
2147 return !sameMethods.Contains( theCommand->GetMethod() );
2150 //================================================================================
2152 * \brief Convert creation and addition of all algos and hypos
2154 //================================================================================
2156 void _pyMesh::Flush()
2159 // get the meshes this mesh depends on via hypotheses
2160 list< Handle(_pyMesh) > fatherMeshes;
2161 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2162 for ( ; hyp != myHypos.end(); ++hyp )
2163 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2164 myGeomNotInStudy = true;
2166 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2167 for ( ; m != fatherMeshes.end(); ++m )
2168 addFatherMesh( *m );
2169 // if ( removedGeom )
2170 // SetRemovedFromStudy(); // as reffered geometry not in study
2172 if ( myGeomNotInStudy )
2175 list < Handle(_pyCommand) >::iterator cmd;
2177 // try to convert algo addition like this:
2178 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2179 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2181 Handle(_pyCommand) addCmd = *cmd;
2183 _pyID algoID = addCmd->GetArg( 2 );
2184 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2185 if ( algo.IsNull() || !algo->IsAlgo() )
2188 // check and create new algorithm instance if it is already wrapped
2189 if ( algo->IsWrapped() ) {
2190 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2191 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2192 TCollection_AsciiString( " = " ) + theGen->GetID() +
2193 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2194 TCollection_AsciiString( "\" )" );
2196 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2197 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2198 if ( !newAlgo.IsNull() ) {
2199 newAlgo->Assign( algo, this->GetID() );
2200 newAlgo->SetCreationCmd( newCmd );
2202 // set algorithm creation
2203 theGen->SetCommandBefore( newCmd, addCmd );
2204 myHypos.push_back( newAlgo );
2205 if ( !myLastComputeCmd.IsNull() &&
2206 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2207 newAlgo->MeshComputed( myLastComputeCmd );
2212 _pyID geom = addCmd->GetArg( 1 );
2213 bool isLocalAlgo = ( geom != GetGeom() );
2216 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2218 // wrapped algo is created after mesh creation
2219 GetCreationCmd()->AddDependantCmd( addCmd );
2221 if ( isLocalAlgo ) {
2222 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2223 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2224 TCollection_AsciiString( "geom=" ) + geom );
2225 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2226 list < Handle(_pySubMesh) >::iterator smIt;
2227 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2228 Handle(_pySubMesh) subMesh = *smIt;
2229 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2230 if ( geom == subCmd->GetArg( 1 )) {
2231 subCmd->SetObject( algo->GetID() );
2232 subCmd->RemoveArgs();
2233 subMesh->SetCreator( algo );
2238 else // KO - ALGO was already created
2240 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2241 addCmd->RemoveArgs();
2242 addCmd->SetArg( 1, algoID );
2244 addCmd->SetArg( 2, geom );
2245 myNotConvertedAddHypCmds.push_back( addCmd );
2249 // try to convert hypo addition like this:
2250 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2251 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2253 Handle(_pyCommand) addCmd = *cmd;
2254 _pyID hypID = addCmd->GetArg( 2 );
2255 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2256 if ( hyp.IsNull() || hyp->IsAlgo() )
2258 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2260 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2261 _pyID geom = addCmd->GetArg( 1 );
2262 addCmd->RemoveArgs();
2263 addCmd->SetArg( 1, hypID );
2264 if ( geom != GetGeom() )
2265 addCmd->SetArg( 2, geom );
2266 myNotConvertedAddHypCmds.push_back( addCmd );
2270 myAddHypCmds.clear();
2271 mySubmeshes.clear();
2274 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2275 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2279 //================================================================================
2281 * \brief Sets myIsPublished of me and of all objects depending on me.
2283 //================================================================================
2285 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2287 _pyObject::SetRemovedFromStudy(isRemoved);
2289 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2290 for ( ; sm != mySubmeshes.end(); ++sm )
2291 (*sm)->SetRemovedFromStudy(isRemoved);
2293 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2294 for ( ; gr != myGroups.end(); ++gr )
2295 (*gr)->SetRemovedFromStudy(isRemoved);
2297 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2298 for ( ; m != myChildMeshes.end(); ++m )
2299 (*m)->SetRemovedFromStudy(isRemoved);
2301 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2302 for ( ; e != myEditors.end(); ++e )
2303 (*e)->SetRemovedFromStudy(isRemoved);
2306 //================================================================================
2308 * \brief Return true if none of myChildMeshes is in study
2310 //================================================================================
2312 bool _pyMesh::CanClear()
2317 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2318 for ( ; m != myChildMeshes.end(); ++m )
2319 if ( !(*m)->CanClear() )
2325 //================================================================================
2327 * \brief Clear my commands and commands of mesh editor
2329 //================================================================================
2331 void _pyMesh::ClearCommands()
2337 // mark all sub-objects as not removed, except child meshes
2338 list< Handle(_pyMesh) > children;
2339 children.swap( myChildMeshes );
2340 SetRemovedFromStudy( false );
2341 children.swap( myChildMeshes );
2345 _pyObject::ClearCommands();
2347 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2348 for ( ; sm != mySubmeshes.end(); ++sm )
2349 (*sm)->ClearCommands();
2351 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2352 for ( ; gr != myGroups.end(); ++gr )
2353 (*gr)->ClearCommands();
2355 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2356 for ( ; e != myEditors.end(); ++e )
2357 (*e)->ClearCommands();
2360 //================================================================================
2362 * \brief Add a father mesh by ID
2364 //================================================================================
2366 void _pyMesh::addFatherMesh( const _pyID& meshID )
2368 if ( !meshID.IsEmpty() && meshID != GetID() )
2369 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2372 //================================================================================
2374 * \brief Add a father mesh
2376 //================================================================================
2378 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2380 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2382 //myFatherMeshes.push_back( mesh );
2383 mesh->myChildMeshes.push_back( this );
2385 // protect last Compute() from clearing by the next Compute()
2386 mesh->myLastComputeCmd.Nullify();
2390 //================================================================================
2392 * \brief MeshEditor convert its commands to ones of mesh
2394 //================================================================================
2396 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2397 _pyObject( theCreationCmd )
2399 myMesh = theCreationCmd->GetObject();
2400 myCreationCmdStr = theCreationCmd->GetString();
2401 theCreationCmd->Clear();
2403 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2404 if ( !mesh.IsNull() )
2405 mesh->AddEditor( this );
2408 //================================================================================
2410 * \brief convert its commands to ones of mesh
2412 //================================================================================
2414 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2416 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2417 // commands calling these methods are converted to calls of Mesh methods without
2418 // additional modifs, only object is changed from MeshEditor to Mesh.
2419 static TStringSet sameMethods;
2420 if ( sameMethods.empty() ) {
2421 const char * names[] = {
2422 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2423 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2424 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2425 "MoveNode", "MoveClosestNodeToPoint",
2426 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2427 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2428 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2429 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2430 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2431 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2432 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2433 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2434 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2435 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2436 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2437 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2438 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2439 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2440 "GetLastCreatedElems",
2441 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2442 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2443 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2444 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2445 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2446 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2447 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2448 ,"" }; // <- mark of the end
2449 sameMethods.Insert( names );
2452 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2453 TStringMap diffMethods;
2454 if ( diffMethods.empty() ) {
2455 const char * orig2newName[] = {
2456 // original name --------------> new name
2457 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2458 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2459 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2460 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2461 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2462 ""};// <- mark of the end
2463 diffMethods.Insert( orig2newName );
2466 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2467 // only by last two arguments
2468 static TStringSet diffLastTwoArgsMethods;
2469 if (diffLastTwoArgsMethods.empty() ) {
2470 const char * names[] = {
2471 "MirrorMakeGroups","MirrorObjectMakeGroups",
2472 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2473 "RotateMakeGroups","RotateObjectMakeGroups",
2474 ""};// <- mark of the end
2475 diffLastTwoArgsMethods.Insert( names );
2478 // only a method name is to change?
2479 const TCollection_AsciiString & method = theCommand->GetMethod();
2480 bool isPyMeshMethod = sameMethods.Contains( method );
2481 if ( !isPyMeshMethod )
2483 TCollection_AsciiString newMethod = diffMethods.Value( method );
2484 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2485 theCommand->SetMethod( newMethod );
2487 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2488 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2490 isPyMeshMethod = true;
2491 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2492 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2495 if ( !isPyMeshMethod )
2497 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2498 // functions with the flag "theMakeGroups = True" like:
2499 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2500 int pos = method.Search("MakeGroups");
2503 isPyMeshMethod = true;
2504 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2505 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2507 // 1. Remove "MakeGroups" from the Command
2508 TCollection_AsciiString aMethod = theCommand->GetMethod();
2509 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2512 pos = pos-2; //Remove "0D" from the Command too
2513 aMethod.Trunc(pos-1);
2514 theCommand->SetMethod(aMethod);
2516 // 2. And add last "True" argument(s)
2517 while(nbArgsToAdd--)
2518 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2519 if( is0DmethId || is0DmethObj )
2520 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2524 // ExtrusionSweep0D() -> ExtrusionSweep()
2525 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2526 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2527 method == "ExtrusionSweepObject0D" ))
2529 isPyMeshMethod = true;
2530 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2531 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2532 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2535 // DoubleNode...New(...) -> DoubleNode...(...,True)
2536 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2537 method == "DoubleNodeElemGroupsNew" ||
2538 method == "DoubleNodeGroupNew" ||
2539 method == "DoubleNodeGroupsNew" ||
2540 method == "DoubleNodeElemGroup2New" ||
2541 method == "DoubleNodeElemGroups2New"))
2543 isPyMeshMethod = true;
2544 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2545 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2546 if ( excessLen == 3 )
2548 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2550 else if ( theCommand->GetArg(4) == "0" ||
2551 theCommand->GetArg(5) == "0" )
2553 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2554 // Group = DoubleNodeGroup2New(,,,False, True)
2555 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2556 theCommand->SetResultValue( groupID );
2559 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2560 // FindElementsByPoint(x, y, z, elementType, meshPart)
2561 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2563 isPyMeshMethod = true;
2564 theCommand->SetMethod( "FindElementsByPoint" );
2565 // make the 1st arg be the last one
2566 _pyID partID = theCommand->GetArg( 1 );
2567 int nbArgs = theCommand->GetNbArgs();
2568 for ( int i = 2; i <= nbArgs; ++i )
2569 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2570 theCommand->SetArg( nbArgs, partID );
2572 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2573 if ( !isPyMeshMethod && method == "Reorient2D" )
2575 isPyMeshMethod = true;
2576 _AString mesh = theCommand->GetArg( 1 );
2577 _AString dir = theCommand->GetArg( 2 );
2578 _AString face = theCommand->GetArg( 3 );
2579 _AString point = theCommand->GetArg( 4 );
2580 theCommand->RemoveArgs();
2581 theCommand->SetArg( 1, mesh );
2582 theCommand->SetArg( 2, dir );
2583 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2584 theCommand->SetArg( 3, point );
2586 theCommand->SetArg( 3, face );
2589 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2591 isPyMeshMethod = true;
2592 int crit_arg = theCommand->GetNbArgs();
2593 const _AString& crit = theCommand->GetArg(crit_arg);
2594 if (crit.Search("MaxElementLength2D") != -1)
2595 theCommand->SetArg(crit_arg, "");
2598 if ( isPyMeshMethod )
2600 theCommand->SetObject( myMesh );
2604 // editor creation command is needed only if any editor function is called
2605 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2606 if ( !myCreationCmdStr.IsEmpty() ) {
2607 GetCreationCmd()->GetString() = myCreationCmdStr;
2608 myCreationCmdStr.Clear();
2613 //================================================================================
2615 * \brief Return true if my mesh can be removed
2617 //================================================================================
2619 bool _pyMeshEditor::CanClear()
2621 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2622 return mesh.IsNull() ? true : mesh->CanClear();
2625 //================================================================================
2627 * \brief _pyHypothesis constructor
2628 * \param theCreationCmd -
2630 //================================================================================
2632 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2633 _pyObject( theCreationCmd ), myCurCrMethod(0)
2635 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2638 //================================================================================
2640 * \brief Creates algorithm or hypothesis
2641 * \param theCreationCmd - The engine command creating a hypothesis
2642 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2644 //================================================================================
2646 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2648 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2649 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2651 Handle(_pyHypothesis) hyp, algo;
2654 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2655 if ( hypTypeQuoted.IsEmpty() )
2658 TCollection_AsciiString hypType =
2659 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2661 algo = new _pyAlgorithm( theCreationCmd );
2662 hyp = new _pyHypothesis( theCreationCmd );
2664 if ( hypType == "NumberOfSegments" ) {
2665 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2666 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2667 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2668 hyp->AddArgMethod( "SetNumberOfSegments" );
2669 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2670 hyp->AddArgMethod( "SetScaleFactor" );
2671 hyp->AddArgMethod( "SetReversedEdges" );
2672 // same for ""CompositeSegment_1D:
2673 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2674 hyp->AddArgMethod( "SetNumberOfSegments" );
2675 hyp->AddArgMethod( "SetScaleFactor" );
2676 hyp->AddArgMethod( "SetReversedEdges" );
2678 else if ( hypType == "SegmentLengthAroundVertex" ) {
2679 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2680 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2681 hyp->AddArgMethod( "SetLength" );
2682 // same for ""CompositeSegment_1D:
2683 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2684 hyp->AddArgMethod( "SetLength" );
2686 else if ( hypType == "LayerDistribution2D" ) {
2687 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2688 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2690 else if ( hypType == "LayerDistribution" ) {
2691 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2692 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2694 else if ( hypType == "CartesianParameters3D" ) {
2695 hyp = new _pyComplexParamHypo( theCreationCmd );
2696 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2697 for ( int iArg = 0; iArg < 4; ++iArg )
2698 hyp->setCreationArg( iArg+1, "[]");
2699 hyp->AddAccumulativeMethod( "SetGrid" );
2700 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2704 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2707 return algo->IsValid() ? algo : hyp;
2710 //================================================================================
2712 * \brief Returns true if addition of this hypothesis to a given mesh can be
2713 * wrapped into hypothesis creation
2715 //================================================================================
2717 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2719 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2721 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2722 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2728 //================================================================================
2730 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2731 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2732 * \param theAlgo - The algo that can create this hypo
2733 * \retval bool - false if the command cant be converted
2735 //================================================================================
2737 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2738 const _pyID& theMesh)
2740 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2742 if ( !IsWrappable( theMesh ))
2745 myGeom = theCmd->GetArg( 1 );
2747 Handle(_pyHypothesis) algo;
2749 // find algo created on myGeom in theMesh
2750 algo = theGen->FindAlgo( myGeom, theMesh, this );
2751 if ( algo.IsNull() )
2753 // attach hypothesis creation command to be after algo creation command
2754 // because it can be new created instance of algorithm
2755 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2759 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2760 theCmd->SetResultValue( GetID() );
2761 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2762 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2763 // set args (geom will be set by _pyMesh calling this method)
2764 theCmd->RemoveArgs();
2765 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2766 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2767 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2769 theCmd->SetArg( i+1, "[]");
2771 // set a new creation command
2772 GetCreationCmd()->Clear();
2773 // replace creation command by wrapped instance
2774 // please note, that hypothesis attaches to algo creation command (see upper)
2775 SetCreationCmd( theCmd );
2778 // clear commands setting arg values
2779 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2780 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2783 // set unknown arg commands after hypo creation
2784 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2785 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2786 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2787 afterCmd->AddDependantCmd( *cmd );
2793 //================================================================================
2795 * \brief Remember hypothesis parameter values
2796 * \param theCommand - The called hypothesis method
2798 //================================================================================
2800 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2802 ASSERT( !myIsAlgo );
2803 if ( !theGen->IsToKeepAllCommands() )
2804 rememberCmdOfParameter( theCommand );
2806 bool usedCommand = false;
2807 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2808 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2810 CreationMethod& crMethod = type2meth->second;
2811 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2812 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2814 myArgCommands.push_back( theCommand );
2816 while ( crMethod.myArgs.size() < i+1 )
2817 crMethod.myArgs.push_back( "None" );
2818 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2823 myUnusedCommands.push_back( theCommand );
2826 //================================================================================
2828 * \brief Finish conversion
2830 //================================================================================
2832 void _pyHypothesis::Flush()
2836 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2837 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2838 // Add access to a wrapped mesh
2839 theGen->AddMeshAccessorMethod( *cmd );
2840 // Add access to a wrapped algorithm
2841 theGen->AddAlgoAccessorMethod( *cmd );
2843 cmd = myUnusedCommands.begin();
2844 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2845 // Add access to a wrapped mesh
2846 theGen->AddMeshAccessorMethod( *cmd );
2847 // Add access to a wrapped algorithm
2848 theGen->AddAlgoAccessorMethod( *cmd );
2851 // forget previous hypothesis modifications
2852 myArgCommands.clear();
2853 myUnusedCommands.clear();
2856 //================================================================================
2858 * \brief clear creation, arg and unkown commands
2860 //================================================================================
2862 void _pyHypothesis::ClearAllCommands()
2864 GetCreationCmd()->Clear();
2865 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2866 for ( ; cmd != myArgCommands.end(); ++cmd )
2868 cmd = myUnusedCommands.begin();
2869 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2874 //================================================================================
2876 * \brief Assign fields of theOther to me except myIsWrapped
2878 //================================================================================
2880 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2881 const _pyID& theMesh )
2883 // myCreationCmd = theOther->myCreationCmd;
2884 myIsAlgo = theOther->myIsAlgo;
2885 myIsWrapped = false;
2886 myGeom = theOther->myGeom;
2888 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2889 myAccumulativeMethods = theOther->myAccumulativeMethods;
2890 //myUnusedCommands = theOther->myUnusedCommands;
2891 // init myCurCrMethod
2892 GetCreationMethod( theOther->GetAlgoType() );
2895 //================================================================================
2897 * \brief Analyze my erasability depending on myReferredObjs
2899 //================================================================================
2901 bool _pyHypothesis::CanClear()
2905 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2906 for ( ; obj != myReferredObjs.end(); ++obj )
2907 if ( (*obj)->CanClear() )
2914 //================================================================================
2916 * \brief Clear my commands depending on usage by meshes
2918 //================================================================================
2920 void _pyHypothesis::ClearCommands()
2922 // if ( !theGen->IsToKeepAllCommands() )
2924 // bool isUsed = false;
2925 // int lastComputeOrder = 0;
2926 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2927 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2928 // if ( ! (*cmd)->IsEmpty() )
2931 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2932 // lastComputeOrder = (*cmd)->GetOrderNb();
2936 // SetRemovedFromStudy( true );
2940 // // clear my commands invoked after lastComputeOrder
2941 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2942 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2944 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2945 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2946 // // cmds.back()->Clear();
2950 _pyObject::ClearCommands();
2953 //================================================================================
2955 * \brief Find arguments that are objects like mesh, group, geometry
2956 * \param meshes - referred meshes (directly or indirrectly)
2957 * \retval bool - false if a referred geometry is not in the study
2959 //================================================================================
2961 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2963 if ( IsAlgo() ) return true;
2965 bool geomPublished = true;
2966 vector< _AString > args;
2967 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2968 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2970 CreationMethod& crMethod = type2meth->second;
2971 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2973 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2974 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2975 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2976 args.push_back( (*cmd)->GetArg( nb ));
2979 for ( size_t i = 0; i < args.size(); ++i )
2981 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2982 if ( idList.empty() && !args[ i ].IsEmpty() )
2983 idList.push_back( args[ i ]);
2984 list< _pyID >::iterator id = idList.begin();
2985 for ( ; id != idList.end(); ++id )
2987 Handle(_pyObject) obj = theGen->FindObject( *id );
2988 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2991 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2992 geomPublished = false;
2996 myReferredObjs.push_back( obj );
2997 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2998 if ( !mesh.IsNull() )
2999 meshes.push_back( mesh );
3000 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3001 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3002 obj->SetRemovedFromStudy( false );
3006 return geomPublished;
3009 //================================================================================
3011 * \brief Remember theCommand setting a parameter
3013 //================================================================================
3015 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3017 // parameters are discriminated by method name
3018 _AString method = theCommand->GetMethod();
3019 if ( myAccumulativeMethods.count( method ))
3020 return; // this method adds values and not override the previus value
3022 // discriminate commands setting different parameters via one method
3023 // by passing parameter names like e.g. SetOption("size", "0.2")
3024 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3025 theCommand->GetNbArgs() > 1 )
3027 // mangle method by appending a 1st textual arg
3028 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3030 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3031 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3032 if ( !isalpha( arg.Value(2))) continue;
3037 // parameters are discriminated by method name
3038 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3039 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3041 cmds.back()->Clear(); // previous parameter value has not been used
3042 cmds.back() = theCommand;
3046 cmds.push_back( theCommand );
3050 //================================================================================
3052 * \brief Return true if a setting parameter command ha been used to compute mesh
3054 //================================================================================
3056 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3057 _pyCommand::TAddr avoidComputeAddr ) const
3059 bool isUsed = false;
3060 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3061 myComputeAddr2Cmds.begin();
3062 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3064 if ( addr2cmds->first == avoidComputeAddr ) continue;
3065 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3066 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3071 //================================================================================
3073 * \brief Save commands setting parameters as they are used for a mesh computation
3075 //================================================================================
3077 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3079 myComputeCmds.push_back( theComputeCmd );
3080 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3082 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3083 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3084 savedCmds.push_back( m2c->second.back() );
3087 //================================================================================
3089 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3091 //================================================================================
3093 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3095 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3097 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3098 for ( ; cmd != savedCmds.end(); ++cmd )
3100 // check if a cmd has been used to compute another mesh
3101 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3103 // check if a cmd is a sole command setting its parameter;
3104 // don't use method name for search as it can change
3105 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3106 m2cmds = myMeth2Commands.begin();
3107 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3109 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3110 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3111 if ( cmdIt != cmds.end() )
3113 if ( cmds.back() != *cmd )
3115 cmds.erase( cmdIt );
3122 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3125 //================================================================================
3127 * \brief Sets an argNb-th argument of current creation command
3128 * \param argNb - argument index countered from 1
3130 //================================================================================
3132 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3134 if ( myCurCrMethod )
3136 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3137 myCurCrMethod->myArgs.push_back( "None" );
3138 if ( arg.IsEmpty() )
3139 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3141 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3146 //================================================================================
3148 * \brief Remember hypothesis parameter values
3149 * \param theCommand - The called hypothesis method
3151 //================================================================================
3153 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3155 if ( GetAlgoType() == "Cartesian_3D" )
3157 // CartesianParameters3D hyp
3159 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3160 theCommand->GetMethod() == "SetToAddEdges" )
3162 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3163 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3164 myArgCommands.push_back( theCommand );
3167 if ( theCommand->GetMethod() == "SetGrid" ||
3168 theCommand->GetMethod() == "SetGridSpacing" )
3170 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3171 int iArg = axis.Value(1) - '0';
3172 if ( theCommand->GetMethod() == "SetGrid" )
3174 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3178 myCurCrMethod->myArgs[ iArg ] = "[ ";
3179 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3180 myCurCrMethod->myArgs[ iArg ] += ", ";
3181 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3182 myCurCrMethod->myArgs[ iArg ] += "]";
3184 myArgCommands.push_back( theCommand );
3185 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3186 // accumulative, else, if the creation
3187 // is not converted, commands for axes 1 and 2 are lost
3192 if( theCommand->GetMethod() == "SetLength" )
3194 // NOW it is OBSOLETE
3195 // ex: hyp.SetLength(start, 1)
3196 // hyp.SetLength(end, 0)
3197 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3198 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3199 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3200 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3202 CreationMethod& crMethod = type2meth->second;
3203 while ( (int) crMethod.myArgs.size() < i+1 )
3204 crMethod.myArgs.push_back( "[]" );
3205 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3207 myArgCommands.push_back( theCommand );
3211 _pyHypothesis::Process( theCommand );
3214 //================================================================================
3216 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3218 //================================================================================
3220 void _pyComplexParamHypo::Flush()
3222 list < Handle(_pyCommand) >::iterator cmd;
3225 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3226 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3230 // if ( GetAlgoType() == "Cartesian_3D" )
3232 // _pyID algo = myCreationCmd->GetObject();
3233 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3235 // if ( IsWrapped() )
3237 // StructToList( *cmd, /*checkMethod=*/false );
3238 // const _AString & method = (*cmd)->GetMethod();
3239 // if ( method == "SetFixedPoint" )
3240 // (*cmd)->SetObject( algo );
3246 //================================================================================
3248 * \brief Convert methods of 1D hypotheses to my own methods
3249 * \param theCommand - The called hypothesis method
3251 //================================================================================
3253 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3255 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3258 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3259 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3260 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3262 // TCollection_AsciiString cmd =
3263 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3264 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3265 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3268 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3270 // // 1D hypo is already set, so distribution changes and the old
3271 // // 1D hypo is thrown away
3272 // my1dHyp->ClearAllCommands();
3275 // //my1dHyp->SetRemovedFromStudy( false );
3277 // if ( !myArgCommands.empty() )
3278 // myArgCommands.back()->Clear();
3279 myCurCrMethod->myArgs.push_back( hyp1dID );
3280 myArgCommands.push_back( theCommand );
3283 //================================================================================
3286 * \param theAdditionCmd - command to be converted
3287 * \param theMesh - mesh instance
3288 * \retval bool - status
3290 //================================================================================
3292 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3293 const _pyID& theMesh)
3295 myIsWrapped = false;
3297 if ( my1dHyp.IsNull() )
3300 // set "SetLayerDistribution()" after addition cmd
3301 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3303 _pyID geom = theAdditionCmd->GetArg( 1 );
3305 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3306 if ( !algo.IsNull() )
3308 my1dHyp->SetMesh( theMesh );
3309 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3310 algo->GetAlgoType().ToCString());
3311 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3314 // clear "SetLayerDistribution()" cmd
3315 myArgCommands.back()->Clear();
3317 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3319 // find RadialPrism algo created on <geom> for theMesh
3320 GetCreationCmd()->SetObject( algo->GetID() );
3321 GetCreationCmd()->SetMethod( myAlgoMethod );
3322 GetCreationCmd()->RemoveArgs();
3323 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3329 //================================================================================
3333 //================================================================================
3335 void _pyLayerDistributionHypo::Flush()
3337 // as creation of 1D hyp was written later then it's edition,
3338 // we need to find all it's edition calls and process them
3339 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3341 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3343 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3344 if ( hyp1dID.IsEmpty() ) continue;
3346 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3348 // make a new name for 1D hyp = "HypType" + "_Distribution"
3350 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3352 if ( prevNewName.IsEmpty() ) continue;
3353 newName = prevNewName;
3357 if ( hyp1d->IsWrapped() ) {
3358 newName = hyp1d->GetCreationCmd()->GetMethod();
3361 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3362 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3364 newName += "_Distribution";
3365 prevNewName = newName;
3367 hyp1d->GetCreationCmd()->SetResultValue( newName );
3369 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3370 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3371 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3372 const _pyID& objID = (*cmdIt)->GetObject();
3373 if ( objID == hyp1dID ) {
3374 if ( !hyp1d.IsNull() )
3376 hyp1d->Process( *cmdIt );
3377 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3379 ( *cmdIt )->SetObject( newName );
3382 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3383 (*cmd)->SetArg( 1, newName );
3387 //================================================================================
3389 * \brief additionally to Addition2Creation, clears SetDistrType() command
3390 * \param theCmd - AddHypothesis() command
3391 * \param theMesh - mesh to which a hypothesis is added
3392 * \retval bool - convertion result
3394 //================================================================================
3396 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3397 const _pyID& theMesh)
3399 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3400 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3401 bool scaleDistrType = false;
3402 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3403 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3404 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3405 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3406 scaleDistrType = true;
3409 else if ( !scaleDistrType ) {
3410 // distribution type changed: remove scale factor from args
3411 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3412 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3414 CreationMethod& crMethod = type2meth->second;
3415 if ( crMethod.myArgs.size() == 2 )
3416 crMethod.myArgs.pop_back();
3423 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3426 //================================================================================
3428 * \brief remove repeated commands defining distribution
3430 //================================================================================
3432 void _pyNumberOfSegmentsHyp::Flush()
3434 // find number of the last SetDistrType() command
3435 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3436 int distrTypeNb = 0;
3437 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3438 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3439 if ( cmd != myUnusedCommands.rbegin() )
3440 distrTypeNb = (*cmd)->GetOrderNb();
3442 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3445 // clear commands before the last SetDistrType()
3446 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3447 set< int > treatedCmdNbs; // avoid treating same cmd twice
3448 for ( int i = 0; i < 2; ++i ) {
3449 set<TCollection_AsciiString> uniqueMethods;
3450 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3451 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3453 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3454 continue;// avoid treating same cmd twice
3455 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3456 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3457 if ( !clear || method == "SetNumberOfSegments" ) {
3458 bool isNewInSet = uniqueMethods.insert( method ).second;
3459 clear = !isNewInSet;
3468 //================================================================================
3470 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3471 * into regular1D.LengthNearVertex( length, vertex )
3472 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3473 * \param theMesh - The mesh needing this hypo
3474 * \retval bool - false if the command cant be converted
3476 //================================================================================
3478 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3479 const _pyID& theMeshID)
3481 if ( IsWrappable( theMeshID )) {
3483 _pyID vertex = theCmd->GetArg( 1 );
3485 // the problem here is that segment algo will not be found
3486 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3487 // geometry where segment algorithm is assigned
3488 Handle(_pyHypothesis) algo;
3489 _pyID geom = vertex;
3490 while ( algo.IsNull() && !geom.IsEmpty()) {
3491 // try to find geom as a father of <vertex>
3492 geom = FatherID( geom );
3493 algo = theGen->FindAlgo( geom, theMeshID, this );
3495 if ( algo.IsNull() )
3496 return false; // also possible to find geom as brother of veretex...
3497 // set geom instead of vertex
3498 theCmd->SetArg( 1, geom );
3500 // set vertex as a second arg
3501 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3502 setCreationArg( 2, vertex );
3504 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3505 // theMeshID.LengthNearVertex( length, vertex )
3506 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3511 //================================================================================
3513 * \brief _pyAlgorithm constructor
3514 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3516 //================================================================================
3518 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3519 : _pyHypothesis( theCreationCmd )
3524 //================================================================================
3526 * \brief Convert the command adding an algorithm to mesh
3527 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3528 * \param theMesh - The mesh needing this algo
3529 * \retval bool - false if the command cant be converted
3531 //================================================================================
3533 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3534 const _pyID& theMeshID)
3536 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3537 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3538 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3544 //================================================================================
3546 * \brief Return starting position of a part of python command
3547 * \param thePartIndex - The index of command part
3548 * \retval int - Part position
3550 //================================================================================
3552 int _pyCommand::GetBegPos( int thePartIndex ) const
3556 if ( myBegPos.Length() < thePartIndex )
3558 ASSERT( thePartIndex > 0 );
3559 return myBegPos( thePartIndex );
3562 //================================================================================
3564 * \brief Store starting position of a part of python command
3565 * \param thePartIndex - The index of command part
3566 * \param thePosition - Part position
3568 //================================================================================
3570 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3572 while ( myBegPos.Length() < thePartIndex )
3573 myBegPos.Append( UNKNOWN );
3574 ASSERT( thePartIndex > 0 );
3575 myBegPos( thePartIndex ) = thePosition;
3578 //================================================================================
3580 * \brief Returns whitespace symbols at the line beginning
3581 * \retval TCollection_AsciiString - result
3583 //================================================================================
3585 TCollection_AsciiString _pyCommand::GetIndentation()
3588 //while ( end <= Length() && isblank( myString.Value( end )))
3589 //ANA: isblank() function isn't provided in VC2010 compiler
3590 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3592 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3595 //================================================================================
3597 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3598 * \retval const TCollection_AsciiString & - ResultValue substring
3600 //================================================================================
3602 const TCollection_AsciiString & _pyCommand::GetResultValue()
3604 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3606 SetBegPos( RESULT_IND, EMPTY );
3607 int begPos, endPos = myString.Location( "=", 1, Length() );
3611 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3612 if ( begPos < endPos )
3614 SetBegPos( RESULT_IND, begPos );
3616 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3617 myRes = myString.SubString( begPos, endPos );
3624 //================================================================================
3626 * \brief Return number of python command result value ResultValue = Obj.Meth()
3628 //================================================================================
3630 int _pyCommand::GetNbResultValues()
3633 return myResults.Length();
3637 //================================================================================
3639 * \brief Return substring of python command looking like
3640 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3641 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3643 //================================================================================
3644 const _AString& _pyCommand::GetResultValue(int res)
3646 if ( GetResultValue().IsEmpty() )
3647 return theEmptyString;
3649 if ( myResults.IsEmpty() )
3652 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3653 ++begPos; // skip [, else the whole list is returned
3654 while ( begPos < myRes.Length() ) {
3655 _AString result = GetWord( myRes, begPos, true );
3656 begPos += result.Length();
3658 // result.RemoveAll('[');
3659 // result.RemoveAll(']');
3664 myResults.Append( result );
3667 if ( res > 0 && res <= myResults.Length() )
3668 return myResults( res );
3669 return theEmptyString;
3672 //================================================================================
3674 * \brief Return substring of python command looking like ResVal = Object.Meth()
3675 * \retval const TCollection_AsciiString & - Object substring
3677 //================================================================================
3679 const TCollection_AsciiString & _pyCommand::GetObject()
3681 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3684 int begPos = GetBegPos( RESULT_IND );
3686 begPos = myString.Location( "=", 1, Length() ) + 1;
3687 // is '=' in the string argument (for example, name) or not
3688 int nb1 = 0; // number of ' character at the left of =
3689 int nb2 = 0; // number of " character at the left of =
3690 for ( int i = 1; i < begPos-1; i++ ) {
3691 if ( myString.Value( i )=='\'' )
3693 else if ( myString.Value( i )=='"' )
3696 // if number of ' or " is not divisible by 2,
3697 // then get an object at the start of the command
3698 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3702 begPos += myRes.Length();
3704 myObj = GetWord( myString, begPos, true );
3705 if ( begPos != EMPTY )
3707 // check if object is complex,
3708 // so far consider case like "smesh.Method()"
3709 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3710 //if ( bracketPos==0 ) bracketPos = Length();
3711 int dotPos = begPos+myObj.Length();
3712 while ( dotPos+1 < bracketPos ) {
3713 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3718 if ( dotPos > begPos+myObj.Length() )
3719 myObj = myString.SubString( begPos, dotPos-1 );
3722 // 1st word after '=' is an object
3723 // else // no method -> no object
3729 SetBegPos( OBJECT_IND, begPos );
3735 //================================================================================
3737 * \brief Return substring of python command looking like ResVal = Obj.Method()
3738 * \retval const TCollection_AsciiString & - Method substring
3740 //================================================================================
3742 const TCollection_AsciiString & _pyCommand::GetMethod()
3744 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3747 int begPos = GetBegPos( OBJECT_IND );
3748 bool forward = true;
3750 begPos = myString.Location( "(", 1, Length() ) - 1;
3754 begPos += myObj.Length();
3757 myMeth = GetWord( myString, begPos, forward );
3758 SetBegPos( METHOD_IND, begPos );
3764 //================================================================================
3766 * \brief Returns true if there are brackets after the method
3768 //================================================================================
3770 bool _pyCommand::IsMethodCall()
3772 if ( GetMethod().IsEmpty() )
3774 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3775 return ( s[0] == '(' || s[1] == '(' );
3778 //================================================================================
3780 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3781 * \retval const TCollection_AsciiString & - Arg<index> substring
3783 //================================================================================
3785 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3787 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3791 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3793 pos = myString.Location( "(", 1, Length() );
3797 // we are at or before '(', skip it if present
3799 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3800 if ( pos > Length() )
3804 SetBegPos( ARG1_IND, 0 ); // even no '('
3805 return theEmptyString;
3809 list< TCollection_AsciiString > separatorStack( 1, ",)");
3810 bool ignoreNesting = false;
3812 while ( pos <= Length() )
3814 const char chr = myString.Value( pos );
3816 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3818 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3820 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3822 TCollection_AsciiString arg;
3823 if ( pos-1 >= prevPos ) {
3824 arg = myString.SubString( prevPos, pos-1 );
3825 arg.RightAdjust(); // remove spaces
3828 if ( !arg.IsEmpty() || chr == ',' )
3830 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3831 myArgs.Append( arg );
3837 else // end of nesting args found
3839 separatorStack.pop_back();
3840 ignoreNesting = false;
3843 else if ( !ignoreNesting )
3846 case '(' : separatorStack.push_back(")"); break;
3847 case '[' : separatorStack.push_back("]"); break;
3848 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3849 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3856 if ( myArgs.Length() < index )
3857 return theEmptyString;
3858 return myArgs( index );
3861 //================================================================================
3863 * \brief Return position where arguments begin
3865 //================================================================================
3867 int _pyCommand::GetArgBeginning() const
3869 int pos = GetBegPos( ARG1_IND );
3870 if ( pos == UNKNOWN )
3872 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3874 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3879 //================================================================================
3881 * \brief Check if char is a word part
3882 * \param c - The character to check
3883 * \retval bool - The check result
3885 //================================================================================
3887 static inline bool isWord(const char c, const bool dotIsWord)
3890 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3893 //================================================================================
3895 * \brief Looks for a word in the string and returns word's beginning
3896 * \param theString - The input string
3897 * \param theStartPos - The position to start the search, returning word's beginning
3898 * \param theForward - The search direction
3899 * \retval TCollection_AsciiString - The found word
3901 //================================================================================
3903 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3905 const bool theForward,
3906 const bool dotIsWord )
3908 int beg = theStartPos, end = theStartPos;
3909 theStartPos = EMPTY;
3910 if ( beg < 1 || beg > theString.Length() )
3911 return theEmptyString;
3913 if ( theForward ) { // search forward
3915 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3917 if ( beg > theString.Length() )
3918 return theEmptyString; // no word found
3921 char begChar = theString.Value( beg );
3922 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3923 char endChar = ( begChar == '[' ) ? ']' : begChar;
3924 // end is at the corresponding quoting mark or bracket
3925 while ( end < theString.Length() &&
3926 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3930 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3935 else { // search backward
3937 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3940 return theEmptyString; // no word found
3942 char endChar = theString.Value( end );
3943 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3944 char begChar = ( endChar == ']' ) ? '[' : endChar;
3945 // beg is at the corresponding quoting mark
3947 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3951 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3957 //cout << theString << " ---- " << beg << " - " << end << endl;
3958 return theString.SubString( beg, end );
3961 //================================================================================
3963 * \brief Returns true if the string looks like a study entry
3965 //================================================================================
3967 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3969 if ( str.Length() < 5 ) return false;
3971 int nbColons = 0, isColon;
3972 for ( int i = 1; i <= str.Length(); ++i )
3974 char c = str.Value(i);
3975 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3977 nbColons += isColon;
3979 return nbColons > 2 && str.Length()-nbColons > 2;
3982 //================================================================================
3984 * \brief Returns true if the string looks like an object ID but not like a list,
3985 * string, command etc.
3987 //================================================================================
3989 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3991 if ( str.Length() < 1 ) return false;
3993 const char* s = str.ToCString();
3995 for ( int i = 0; i < str.Length(); ++i )
3996 if ( !IsIDChar( s[i] ))
4002 //================================================================================
4004 * \brief Finds entries in a sting
4006 //================================================================================
4008 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4010 std::list< _pyID > resList;
4012 while ( ++pos <= str.Length() )
4014 if ( !isdigit( str.Value( pos ))) continue;
4015 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4018 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4019 _pyID entry = str.SubString( pos, end-1 );
4021 if ( IsStudyEntry( entry ))
4022 resList.push_back( entry );
4027 //================================================================================
4029 * \brief Look for position where not space char is
4030 * \param theString - The string
4031 * \param thePos - The position to search from and which returns result
4032 * \retval bool - false if there are only space after thePos in theString
4034 //================================================================================
4036 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4038 if ( thePos < 1 || thePos > theString.Length() )
4041 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4044 return thePos <= theString.Length();
4047 //================================================================================
4049 * \brief Modify a part of the command
4050 * \param thePartIndex - The index of the part
4051 * \param thePart - The new part string
4052 * \param theOldPart - The old part
4054 //================================================================================
4056 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4057 TCollection_AsciiString& theOldPart)
4059 int pos = GetBegPos( thePartIndex );
4060 if ( pos <= Length() && theOldPart != thePart)
4062 TCollection_AsciiString seperator;
4064 pos = GetBegPos( thePartIndex + 1 );
4065 if ( pos < 1 ) return;
4066 switch ( thePartIndex ) {
4067 case RESULT_IND: seperator = " = "; break;
4068 case OBJECT_IND: seperator = "."; break;
4069 case METHOD_IND: seperator = "()"; break;
4073 myString.Remove( pos, theOldPart.Length() );
4074 if ( !seperator.IsEmpty() )
4075 myString.Insert( pos , seperator );
4076 myString.Insert( pos, thePart );
4077 // update starting positions of the following parts
4078 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4079 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4080 if ( myBegPos( i ) > 0 )
4081 myBegPos( i ) += posDelta;
4083 theOldPart = thePart;
4087 //================================================================================
4089 * \brief Set agrument
4090 * \param index - The argument index, it counts from 1
4091 * \param theArg - The argument string
4093 //================================================================================
4095 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4098 int argInd = ARG1_IND + index - 1;
4099 int pos = GetBegPos( argInd );
4100 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4102 // find a closing parenthesis
4103 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4104 int lastArgInd = GetNbArgs();
4105 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4106 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4111 while ( pos > 0 && myString.Value( pos ) != ')' )
4114 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4118 while ( myArgs.Length() < index ) {
4119 if ( myArgs.Length() )
4120 myString.Insert( pos++, "," );
4121 myArgs.Append("None");
4122 myString.Insert( pos, myArgs.Last() );
4123 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4124 pos += myArgs.Last().Length();
4127 SetPart( argInd, theArg, myArgs( index ));
4130 //================================================================================
4132 * \brief Empty arg list
4134 //================================================================================
4136 void _pyCommand::RemoveArgs()
4138 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4139 myString.Trunc( pos );
4142 if ( myBegPos.Length() >= ARG1_IND )
4143 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4146 //================================================================================
4148 * \brief Comment a python command
4150 //================================================================================
4152 void _pyCommand::Comment()
4154 if ( IsEmpty() ) return;
4157 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4158 if ( i <= Length() )
4160 myString.Insert( i, "#" );
4161 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4163 int begPos = GetBegPos( iPart );
4164 if ( begPos != UNKNOWN && begPos != EMPTY )
4165 SetBegPos( iPart, begPos + 1 );
4170 //================================================================================
4172 * \brief Set dependent commands after this one
4174 //================================================================================
4176 bool _pyCommand::SetDependentCmdsAfter() const
4178 bool orderChanged = false;
4179 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4180 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4181 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4182 orderChanged = true;
4183 theGen->SetCommandAfter( *cmd, this );
4184 (*cmd)->SetDependentCmdsAfter();
4187 return orderChanged;
4189 //================================================================================
4191 * \brief Insert accessor method after theObjectID
4192 * \param theObjectID - id of the accessed object
4193 * \param theAcsMethod - name of the method giving access to the object
4194 * \retval bool - false if theObjectID is not found in the command string
4196 //================================================================================
4198 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4200 if ( !theAcsMethod )
4202 // start object search from the object, i.e. ignore result
4204 int beg = GetBegPos( OBJECT_IND );
4205 if ( beg < 1 || beg > Length() )
4208 while (( beg = myString.Location( theObjectID, beg, Length() )))
4210 // check that theObjectID is not just a part of a longer ID
4211 int afterEnd = beg + theObjectID.Length();
4212 Standard_Character c = myString.Value( afterEnd );
4213 if ( !IsIDChar( c ))
4215 // check if accessor method already present
4217 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4219 int oldLen = Length();
4220 myString.Insert( afterEnd, (char*) theAcsMethod );
4221 myString.Insert( afterEnd, "." );
4222 // update starting positions of the parts following the modified one
4223 int posDelta = Length() - oldLen;
4224 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4225 if ( myBegPos( i ) > afterEnd )
4226 myBegPos( i ) += posDelta;
4231 beg = afterEnd; // is a part -> next search
4236 //================================================================================
4238 * \brief Creates pyObject
4240 //================================================================================
4242 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4243 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4248 //================================================================================
4250 * \brief Set up myID and myIsPublished
4252 //================================================================================
4254 void _pyObject::setID(const _pyID& theID)
4257 myIsPublished = !theGen->IsNotPublished( GetID() );
4260 //================================================================================
4262 * \brief Clear myCreationCmd and myProcessedCmds
4264 //================================================================================
4266 void _pyObject::ClearCommands()
4271 if ( !myCreationCmd.IsNull() )
4272 myCreationCmd->Clear();
4274 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4275 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4279 //================================================================================
4281 * \brief Return method name giving access to an interaface object wrapped by python class
4282 * \retval const char* - method name
4284 //================================================================================
4286 const char* _pyObject::AccessorMethod() const
4290 //================================================================================
4292 * \brief Return ID of a father
4294 //================================================================================
4296 _pyID _pyObject::FatherID(const _pyID & childID)
4298 int colPos = childID.SearchFromEnd(':');
4300 return childID.SubString( 1, colPos-1 );
4304 //================================================================================
4306 * \brief SelfEraser erases creation command if none of it's commands invoked
4307 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4309 //================================================================================
4311 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4312 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4314 myIsPublished = true; // prevent clearing as a not published
4315 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4318 //================================================================================
4320 * \brief SelfEraser erases creation command if none of it's commands invoked
4321 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4323 //================================================================================
4325 bool _pySelfEraser::CanClear()
4327 bool toErase = false;
4328 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4331 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4332 for ( ; cmd != myArgCmds.end(); ++cmd )
4333 nbArgUses += IsAliveCmd( *cmd );
4335 toErase = ( nbArgUses < 1 );
4340 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4341 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4342 for ( ; cmd != cmds.end(); )
4343 // check of cmd emptiness is not enough as object can change
4344 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4347 cmd = cmds.erase( cmd ); // save the cmd from clearing
4349 toErase = ( nbCalls < 1 );
4354 //================================================================================
4356 * \brief Check if a command is or can be cleared
4358 //================================================================================
4360 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4362 if ( theCmd->IsEmpty() )
4365 if ( !theGen->IsToKeepAllCommands() )
4367 const _pyID& objID = theCmd->GetObject();
4368 Handle( _pyObject ) obj = theGen->FindObject( objID );
4369 if ( !obj.IsNull() )
4370 return !obj->CanClear();
4375 //================================================================================
4377 * \brief SelfEraser erases creation command if none of it's commands invoked
4378 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4380 //================================================================================
4382 void _pySelfEraser::Flush()
4386 myIsPublished = false;
4387 _pyObject::ClearCommands();
4391 //================================================================================
4393 * \brief _pySubMesh constructor
4395 //================================================================================
4397 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4398 _pyObject(theCreationCmd)
4400 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4401 if ( toKeepAgrCmds )
4402 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4405 //================================================================================
4407 * \brief Return true if a sub-mesh can be used as argument of the given method
4409 //================================================================================
4411 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4414 // // names of all methods where a sub-mesh can be used as argument
4415 // static TStringSet methods;
4416 // if ( methods.empty() ) {
4417 // const char * names[] = {
4418 // // methods of SMESH_Gen
4420 // // methods of SMESH_Group
4422 // // methods of SMESH_Measurements
4424 // // methods of SMESH_Mesh
4425 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4427 // // methods of SMESH_MeshEditor
4428 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4429 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4430 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4431 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4432 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4433 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4434 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4435 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4436 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4437 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4438 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4439 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4440 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4441 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4442 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4443 // "" }; // <- mark of end
4444 // methods.Insert( names );
4446 // return methods.Contains( theMethodName );
4449 //================================================================================
4451 * \brief count invoked commands
4453 //================================================================================
4455 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4457 _pyObject::Process(theCommand); // count calls of Process()
4460 //================================================================================
4462 * \brief Move creation command depending on invoked commands
4464 //================================================================================
4466 void _pySubMesh::Flush()
4468 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4469 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4470 else if ( !myCreator.IsNull() )
4471 // move to be just after creator
4472 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4474 // move sub-mesh usage after creation cmd
4475 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4476 for ( ; cmd != myArgCmds.end(); ++cmd )
4477 if ( !(*cmd)->IsEmpty() )
4478 GetCreationCmd()->AddDependantCmd( *cmd );
4481 //================================================================================
4483 * \brief Creates _pyGroup
4485 //================================================================================
4487 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4488 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4490 if ( !id.IsEmpty() )
4493 myCanClearCreationCmd = true;
4495 const _AString& method = theCreationCmd->GetMethod();
4496 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4498 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4500 // ----------------------------------------------------------------------
4501 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4503 _pyID geom = theCreationCmd->GetArg( 3 );
4504 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4505 // next if(){...} section is commented
4506 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4507 // theCreationCmd->SetMethod( "Group" );
4508 // theCreationCmd->RemoveArgs();
4509 // theCreationCmd->SetArg( 1, geom );
4512 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4513 _pyID type = theCreationCmd->GetArg( 1 );
4514 _pyID name = theCreationCmd->GetArg( 2 );
4515 theCreationCmd->SetMethod( "GroupOnGeom" );
4516 theCreationCmd->RemoveArgs();
4517 theCreationCmd->SetArg( 1, geom );
4518 theCreationCmd->SetArg( 2, name );
4519 theCreationCmd->SetArg( 3, type );
4522 else if ( method == "CreateGroupFromFilter" )
4524 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4525 theCreationCmd->SetMethod( "GroupOnFilter" );
4527 _pyID filterID = theCreationCmd->GetArg(3);
4528 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4529 if ( !filter.IsNull())
4531 if ( !filter->GetNewID().IsEmpty() )
4532 theCreationCmd->SetArg( 3, filter->GetNewID() );
4533 //filter->AddUser( this );
4537 else if ( method == "GetGroups" )
4539 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4543 // theCreationCmd does something else apart from creation of this group
4544 // and thus it can't be cleared if this group is removed
4545 myCanClearCreationCmd = false;
4549 //================================================================================
4551 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4554 //================================================================================
4556 bool _pyGroup::CanClear()
4561 if ( !myCanClearCreationCmd &&
4562 !myCreationCmd.IsNull() &&
4563 myCreationCmd->GetMethod() == "GetGroups" )
4565 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4566 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4567 list< _pyID >::iterator grID = idList.begin();
4568 if ( GetID() == *grID )
4570 myCanClearCreationCmd = true;
4571 list< Handle(_pyGroup ) > groups;
4572 for ( ; grID != idList.end(); ++grID )
4574 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4575 if ( group.IsNull() ) continue;
4576 groups.push_back( group );
4577 if ( group->IsInStudy() )
4578 myCanClearCreationCmd = false;
4580 // set myCanClearCreationCmd == true to all groups
4581 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4582 for ( ; group != groups.end(); ++group )
4583 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4587 return myCanClearCreationCmd;
4590 //================================================================================
4592 * \brief set myCanClearCreationCmd = true if the main action of the creation
4593 * command is discarded
4595 //================================================================================
4597 void _pyGroup::RemovedWithContents()
4599 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4600 // via a created group
4601 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4602 // myCanClearCreationCmd = true;
4605 //================================================================================
4607 * \brief To convert creation of a group by filter
4609 //================================================================================
4611 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4613 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4614 // group = mesh.CreateEmptyGroup( elemType, groupName )
4615 // aFilter.SetMesh(mesh)
4616 // nbAdd = group.AddFrom( aFilter )
4617 Handle(_pyFilter) filter;
4618 if ( theCommand->GetMethod() == "AddFrom" )
4620 _pyID idSource = theCommand->GetArg(1);
4621 // check if idSource is a filter
4622 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4623 if ( !filter.IsNull() )
4625 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4626 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4627 while ( *cmdIt != theCommand ) ++cmdIt;
4628 while ( (*cmdIt)->GetOrderNb() != 1 )
4630 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4631 if ((setMeshCmd->GetObject() == idSource ||
4632 setMeshCmd->GetObject() == filter->GetNewID() )
4634 setMeshCmd->GetMethod() == "SetMesh")
4636 setMeshCmd->Clear();
4640 // replace 3 commands by one
4641 theCommand->Clear();
4642 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4643 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4644 if ( !filter->GetNewID().IsEmpty() )
4645 idSource = filter->GetNewID();
4646 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4647 makeGroupCmd->SetArg( 1, name );
4648 makeGroupCmd->SetArg( 2, idSource );
4649 filter->AddArgCmd( makeGroupCmd );
4652 else if ( theCommand->GetMethod() == "SetFilter" )
4654 // set new name of a filter or clear the command if the same filter is set
4655 _pyID filterID = theCommand->GetArg(1);
4656 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4657 if ( !myFilter.IsNull() && filter == myFilter )
4658 theCommand->Clear();
4659 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4660 theCommand->SetArg( 1, filter->GetNewID() );
4663 else if ( theCommand->GetMethod() == "GetFilter" )
4665 // GetFilter() returns a filter with other ID, make myFilter process
4666 // calls of the returned filter
4667 if ( !myFilter.IsNull() )
4669 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4670 theCommand->Clear();
4674 // if ( !filter.IsNull() )
4675 // filter->AddUser( this );
4677 theGen->AddMeshAccessorMethod( theCommand );
4680 //================================================================================
4682 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4684 //================================================================================
4686 void _pyGroup::Flush()
4688 if ( !theGen->IsToKeepAllCommands() &&
4689 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4691 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4695 //================================================================================
4697 * \brief Constructor of _pyFilter
4699 //================================================================================
4701 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4702 :_pyObject(theCreationCmd), myNewID( newID )
4704 //myIsPublished = true; // prevent clearing as a not published
4705 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4708 //================================================================================
4710 * \brief To convert creation of a filter by criteria and
4711 * to replace an old name by a new one
4713 //================================================================================
4715 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4717 if ( theCommand->GetObject() == GetID() )
4718 _pyObject::Process(theCommand); // count commands
4720 if ( !myNewID.IsEmpty() )
4721 theCommand->SetObject( myNewID );
4723 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4724 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4725 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4726 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4727 theCommand->GetMethod() == "SetCriteria")
4729 // aFilter.SetCriteria(aCriteria) ->
4730 // aFilter = smesh.GetFilterFromCriteria(criteria)
4731 if ( myNewID.IsEmpty() )
4732 theCommand->SetResultValue( GetID() );
4734 theCommand->SetResultValue( myNewID );
4735 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4736 theCommand->SetMethod( "GetFilterFromCriteria" );
4738 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4739 GetCreationCmd()->Clear();
4740 GetCreationCmd()->GetString() = theCommand->GetString();
4741 theCommand->Clear();
4742 theCommand->AddDependantCmd( GetCreationCmd() );
4743 // why swap? -- it's needed
4744 //GetCreationCmd()->Clear();
4746 else if ( theCommand->GetMethod() == "SetMesh" )
4748 if ( myMesh == theCommand->GetArg( 1 ))
4749 theCommand->Clear();
4751 myMesh = theCommand->GetArg( 1 );
4752 theGen->AddMeshAccessorMethod( theCommand );
4756 //================================================================================
4758 * \brief Set new filter name to the creation command and to myArgCmds
4760 //================================================================================
4762 void _pyFilter::Flush()
4764 if ( myNewID.IsEmpty() ) return;
4766 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4767 for ( ; cmd != myArgCmds.end(); ++cmd )
4768 if ( !(*cmd)->IsEmpty() )
4770 _AString cmdStr = (*cmd)->GetString();
4771 _AString id = GetID();
4772 int pos = cmdStr.Search( id );
4775 cmdStr.Remove( pos, id.Length() );
4776 cmdStr.Insert( pos, myNewID );
4779 (*cmd)->GetString() = cmdStr;
4782 if ( !GetCreationCmd()->IsEmpty() )
4783 GetCreationCmd()->SetResultValue( myNewID );
4786 //================================================================================
4788 * \brief Return true if all my users can be cleared
4790 //================================================================================
4792 bool _pyObject::CanClear()
4794 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4795 for ( ; cmd != myArgCmds.end(); ++cmd )
4796 if ( !(*cmd)->IsEmpty() )
4798 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4799 if ( !obj.IsNull() && !obj->CanClear() )
4802 return ( !myIsPublished );
4805 //================================================================================
4807 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4809 //================================================================================
4811 _pyHypothesisReader::_pyHypothesisReader()
4814 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4815 LDOMParser xmlParser;
4816 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4818 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4822 INFOS( xmlParser.GetError(data) );
4825 // <algorithm type="Regular_1D"
4826 // label-id="Wire discretisation"
4829 // <algo>Regular_1D=Segment()</algo>
4830 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4832 LDOM_Document xmlDoc = xmlParser.getDocument();
4833 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4834 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4836 LDOM_Node algoNode = algoNodeList.item( i );
4837 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4838 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4839 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4841 _AString text, algoType, method, arg;
4842 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4844 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4845 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4846 text = textNode.getNodeValue();
4847 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4848 algoType = algoCmd->GetResultValue();
4849 method = algoCmd->GetMethod();
4850 arg = algoCmd->GetArg(1);
4851 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4853 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4854 algo->SetConvMethodAndType( method, algoType );
4855 if ( !arg.IsEmpty() )
4856 algo->setCreationArg( 1, arg );
4858 myType2Hyp[ algoType ] = algo;
4862 if ( algoType.IsEmpty() ) continue;
4864 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4866 Handle( _pyHypothesis ) hyp;
4867 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4869 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4870 LDOM_Node textNode = pyHypoNode.getFirstChild();
4871 text = textNode.getNodeValue();
4872 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4873 hypType = hypoCmd->GetResultValue();
4874 method = hypoCmd->GetMethod();
4875 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4877 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4878 if ( type2hyp == myType2Hyp.end() )
4879 hyp = new _pyHypothesis( hypoCmd );
4881 hyp = type2hyp->second;
4882 hyp->SetConvMethodAndType( method, algoType );
4883 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4885 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4886 _AString argMethod = argCmd.GetMethod();
4887 _AString argNbText = argCmd.GetArg( 1 );
4888 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4889 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4891 hyp->AddArgMethod( argMethod,
4892 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4894 myType2Hyp[ hypType ] = hyp;
4898 // <hypothesis type="BLSURF_Parameters"
4902 // <accumulative-methods>
4903 // SetEnforcedVertex,
4904 // SetEnforcedVertexNamed
4905 // </accumulative-methods>
4909 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4910 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4912 LDOM_Node hypNode = hypNodeList.item( i );
4913 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4914 _AString hypType = hypElem.getAttribute("type");
4915 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4916 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4918 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4919 if ( type2hyp == myType2Hyp.end() ) continue;
4921 LDOM_Node methNode = methNodeList.item( 0 );
4922 LDOM_Node textNode = methNode.getFirstChild();
4923 _AString text = textNode.getNodeValue();
4927 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4928 pos += method.Length();
4929 type2hyp->second->AddAccumulativeMethod( method );
4931 while ( !method.IsEmpty() );
4934 } // loop on xmlPaths
4937 //================================================================================
4939 * \brief Returns a new hypothesis initialized according to the read information
4941 //================================================================================
4943 Handle(_pyHypothesis)
4944 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4945 const Handle(_pyCommand)& creationCmd) const
4947 Handle(_pyHypothesis) resHyp, sampleHyp;
4949 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4950 if ( type2hyp != myType2Hyp.end() )
4951 sampleHyp = type2hyp->second;
4953 if ( sampleHyp.IsNull() )
4955 resHyp = new _pyHypothesis(creationCmd);
4959 if ( sampleHyp->IsAlgo() )
4960 resHyp = new _pyAlgorithm( creationCmd );
4962 resHyp = new _pyHypothesis(creationCmd);
4963 resHyp->Assign( sampleHyp, _pyID() );
4968 //================================================================================
4970 * \brief Adds an object ID to some family of IDs with a common prefix
4971 * \param [in] str - the object ID
4972 * \return bool - \c false if \a str does not have the same prefix as \a this family
4973 * (for internal usage)
4975 //================================================================================
4977 bool _pyStringFamily::Add( const char* str )
4979 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4980 return false; // expected prefix is missing
4982 str += _prefix.Length(); // skip _prefix
4984 // try to add to some of child falimies
4985 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4986 for ( ; itSub != _subFams.end(); ++itSub )
4987 if ( itSub->Add( str ))
4990 // no suitable family found - add str to _strings or create a new child family
4992 // look for a proper place within sorted _strings
4993 std::list< _AString >::iterator itStr = _strings.begin();
4994 while ( itStr != _strings.end() && itStr->IsLess( str ))
4996 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4997 return true; // same ID already kept
4999 const int minPrefixSize = 4;
5001 // count "smaller" strings with the same prefix
5002 std::list< _AString >::iterator itLess = itStr; --itLess;
5004 for ( ; itLess != _strings.end(); --itLess )
5005 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5010 // count "greater" strings with the same prefix
5011 std::list< _AString >::iterator itMore = itStr;
5013 for ( ; itMore != _strings.end(); ++itMore )
5014 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5019 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5021 // look for a maximal prefix length
5022 // int lessPrefSize = 3, morePrefSize = 3;
5023 // if ( nbLess > 0 )
5024 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5026 // if ( nbMore > 0 )
5027 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5029 // int prefixSize = 3;
5030 // if ( nbLess == 0 )
5031 // prefixSize = morePrefSize;
5032 // else if ( nbMore == 0 )
5033 // prefixSize = lessPrefSize;
5035 // prefixSize = Min( lessPrefSize, morePrefSize );
5036 int prefixSize = minPrefixSize;
5037 _AString newPrefix ( str, prefixSize );
5039 // look for a proper place within _subFams sorted by _prefix
5040 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5041 if ( !itSub->_prefix.IsLess( newPrefix ))
5044 // add the new _pyStringFamily
5045 itSub = _subFams.insert( itSub, _pyStringFamily());
5046 _pyStringFamily& newSubFam = *itSub;
5047 newSubFam._prefix = newPrefix;
5049 // pass this->_strings to newSubFam._strings
5050 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5051 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5052 newSubFam._strings.push_back( str + prefixSize );
5053 for ( ; nbMore > 0; --nbMore, ++itStr )
5054 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5056 _strings.erase( itLess, ++itMore );
5058 else // to few string to make a family fot them
5060 _strings.insert( itStr, str );
5065 //================================================================================
5067 * \brief Finds an object ID in the command
5068 * \param [in] longStr - the command string
5069 * \param [out] subStr - the found object ID
5070 * \return bool - \c true if the object ID found
5072 //================================================================================
5074 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5076 const _AString& longStr = cmd->GetString();
5077 const char* s = longStr.ToCString();
5080 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5081 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5082 if ( argBeg < 4 || argBeg > longStr.Length() )
5084 for ( ; itSub != _subFams.end(); ++itSub )
5087 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5088 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5090 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5091 from = pos + len + itSub->_prefix.Length();
5096 from += itSub->_prefix.Length();
5099 // look among _strings
5100 std::list< _AString >::iterator itStr = _strings.begin();
5101 for ( ; itStr != _strings.end(); ++itStr )
5102 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5103 // check that object ID does not continue after len
5104 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5106 subStr.push_back( *itStr );
5112 //================================================================================
5114 * \brief Return remainder length of the object ID after my _prefix
5115 * \param [in] str - remainder of the command after my _prefix
5116 * \return int - length of the object ID or -1 if not found
5118 //================================================================================
5120 int _pyStringFamily::isIn( const char* str )
5122 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5124 for ( ; itSub != _subFams.end(); ++itSub )
5126 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5129 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5130 return itSub->_prefix.Length() + len;
5135 if ( !_strings.empty() )
5137 std::list< _AString >::iterator itStr = _strings.begin();
5138 bool firstEmpty = itStr->IsEmpty();
5141 for ( ; itStr != _strings.end(); ++itStr )
5143 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5146 len = itStr->Length();
5155 // check that object ID does not continue after len
5156 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5163 //================================================================================
5167 //================================================================================
5169 void _pyStringFamily::Print( int level )
5171 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5172 std::list< _AString >::iterator itStr = _strings.begin();
5173 for ( ; itStr != _strings.end(); ++itStr )
5174 cout << *itStr << " | ";
5176 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5177 for ( ; itSub != _subFams.end(); ++itSub )
5178 itSub->Print( level + 1 );
5180 cout << string( 70, '-' ) << endl;