1 // Copyright (C) 2007-2019 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>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print(" ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
299 // v 9.3.0: FT_Undefined == 50, new items:
300 // - FT_Length3D = 22
302 // It's necessary to continue recording this history and to fill
303 // undef2newItems (see below) accordingly.
305 typedef map< int, vector< int > > TUndef2newItems;
306 static TUndef2newItems undef2newItems;
307 if ( undef2newItems.empty() )
309 undef2newItems[ 26 ].push_back( 7 );
310 undef2newItems[ 27 ].push_back( 17 );
311 { int items[] = { 10, 11, 23, 24, 25 };
312 undef2newItems[ 32 ].assign( items, items+5 ); }
313 undef2newItems[ 33 ].push_back( 26 );
314 { int items[] = { 8, 9, 25, 26, 27, 28 };
315 undef2newItems[ 39 ].assign( items, items+6 ); }
316 { int items[] = { 14, 15, 16, 17 };
317 undef2newItems[ 43 ].assign( items, items+4 ); }
318 undef2newItems[ 44 ].push_back( 37 );
319 undef2newItems[ 45 ].push_back( 36 );
320 undef2newItems[ 46 ].push_back( 39 );
321 undef2newItems[ 47 ].push_back( 22 );
322 undef2newItems[ 48 ].push_back( 22 );
323 undef2newItems[ 49 ].push_back( 22 );
324 undef2newItems[ 50 ].push_back( 22 );
326 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
329 int iType = Type.IntegerValue();
330 int iCompare = Compare.IntegerValue();
331 int iUnaryOp = UnaryOp.IntegerValue();
332 int iBinaryOp = BinaryOp.IntegerValue();
334 // find out integer value of FT_Undefined at the moment of dump
335 int oldUndefined = iBinaryOp;
336 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
339 // apply history to args
340 TUndef2newItems::const_iterator undef_items =
341 undef2newItems.upper_bound( oldUndefined );
342 if ( undef_items != undef2newItems.end() )
344 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
345 for ( ; undef_items != undef2newItems.end(); ++undef_items )
347 const vector< int > & addedItems = undef_items->second;
348 for ( size_t i = 0; i < addedItems.size(); ++i )
349 for ( int iArg = 0; iArg < 4; ++iArg )
351 int& arg = *pArg[iArg];
352 if ( arg >= addedItems[i] )
356 Type = TCollection_AsciiString( iType );
357 Compare = TCollection_AsciiString( iCompare );
358 UnaryOp = TCollection_AsciiString( iUnaryOp );
359 BinaryOp = TCollection_AsciiString( iBinaryOp );
363 //================================================================================
365 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
366 * arguments of a given command by a list "[x,y,z]" if the list is accessible
369 //================================================================================
371 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
373 static TStringSet methodsAcceptingList;
374 if ( methodsAcceptingList.empty() ) {
375 const char * methodNames[] = {
376 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
377 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
378 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
379 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
380 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
381 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
382 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
383 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
384 "Translate","TranslateMakeGroups","TranslateMakeMesh",
385 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
386 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
387 ,"" }; // <- mark of the end
388 methodsAcceptingList.Insert( methodNames );
390 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
392 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
394 const _AString & arg = theCommand->GetArg( i );
395 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
396 arg.Search( "SMESH.DirStruct" ) == 1 )
398 Handle(_pyCommand) workCmd = new _pyCommand( arg );
399 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
401 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
403 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
405 _AString newArg = "[ ";
406 newArg += ( workCmd->GetArg( 1 ) + ", " +
407 workCmd->GetArg( 2 ) + ", " +
408 workCmd->GetArg( 3 ) + " ]");
409 theCommand->SetArg( i, newArg );
415 //================================================================================
417 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
418 * a list "[id1,id2]" if the list is an accessible type of argument.
420 //================================================================================
422 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
424 static TStringSet methodsAcceptingList;
425 if ( methodsAcceptingList.empty() ) {
426 const char * methodNames[] = {
427 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
428 "ExportCGNS","ExportGMF",
429 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
430 "ScaleMakeGroups","Scale","ScaleMakeMesh",
431 "FindCoincidentNodesOnPartBut","DoubleElements",
432 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
433 ,"" }; // <- mark of the end
434 methodsAcceptingList.Insert( methodNames );
436 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
438 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
440 _pyCommand argCmd( theCommand->GetArg( i ));
441 if ( argCmd.GetMethod() == "GetIDSource" &&
442 argCmd.GetNbArgs() == 2 )
444 theCommand->SetArg( i, argCmd.GetArg( 1 ));
450 bool _FilterArg( const _AString& theArg )
452 static std::list<_AString> filteredArgs;
453 static bool initialized = false;
454 if ( !initialized ) {
456 filteredArgs.push_back( "SMESH.MED_V2_1" );
457 filteredArgs.push_back( "SMESH.MED_V2_2" );
459 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
463 //================================================================================
465 * \brief Convert a python script using commands of smeshBuilder.py
466 * \param theScriptLines - Lines of the input script
467 * \param theEntry2AccessorMethod - returns method names to access to
468 * objects wrapped with python class
469 * \param theObjectNames - names of objects
470 * \param theRemovedObjIDs - entries of objects whose created commands were removed
471 * \param theHistoricalDump - true means to keep all commands, false means
472 * to exclude commands relating to objects removed from study
473 * \retval TCollection_AsciiString - Conversion result
475 //================================================================================
478 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
479 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
480 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
481 std::set< TCollection_AsciiString >& theRemovedObjIDs,
482 const bool theToKeepAllCommands)
484 std::list< TCollection_AsciiString >::iterator lineIt;
485 // process notebook variables
487 SMESH_NoteBook aNoteBook;
489 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
490 aNoteBook.AddCommand( *lineIt );
492 theScriptLines.clear();
494 aNoteBook.ReplaceVariables();
496 aNoteBook.GetResultLines( theScriptLines );
499 // convert to smeshBuilder.py API
501 theGen = new _pyGen( theEntry2AccessorMethod,
504 theToKeepAllCommands );
506 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
507 theGen->AddCommand( *lineIt );
509 theScriptLines.clear();
513 #ifdef DUMP_CONVERSION
514 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
517 // clean commands of removed objects depending on myIsPublished flag
518 theGen->ClearCommands();
520 // reorder commands after conversion
521 list< Handle(_pyCommand) >::iterator cmd;
524 orderChanges = false;
525 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
526 if ( (*cmd)->SetDependentCmdsAfter() )
528 } while ( orderChanges );
530 // concat commands back into a script
531 TCollection_AsciiString aPrevCmd;
532 set<_pyID> createdObjects;
533 createdObjects.insert( "smeshBuilder" );
534 createdObjects.insert( "smesh" );
535 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
537 #ifdef DUMP_CONVERSION
538 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
540 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
541 CheckObjectPresence( *cmd, createdObjects );
542 if ( !(*cmd)->IsEmpty() ) {
543 aPrevCmd = (*cmd)->GetString();
544 theScriptLines.push_back( aPrevCmd );
553 //================================================================================
555 * \brief _pyGen constructor
557 //================================================================================
559 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
560 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
561 std::set< TCollection_AsciiString >& theRemovedObjIDs,
562 const bool theToKeepAllCommands)
563 : _pyObject( new _pyCommand( "", 0 )),
565 myID2AccessorMethod( theEntry2AccessorMethod ),
566 myObjectNames( theObjectNames ),
567 myRemovedObjIDs( theRemovedObjIDs ),
569 myToKeepAllCommands( theToKeepAllCommands ),
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() )
582 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->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 pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
703 _AString excStr = indent + "except:";
704 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
706 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
708 aCommand->GetString() = newCmd;
709 aCommand->SetOrderNb( ++myNbCommands );
710 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
711 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
712 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
714 // check for mesh editor object
715 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
716 _pyID editorID = aCommand->GetResultValue();
717 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
718 myMeshEditors.insert( make_pair( editorID, editor ));
721 // check for SubMesh objects
722 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
723 _pyID subMeshID = aCommand->GetResultValue();
724 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
725 AddObject( subMesh );
728 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
729 GetIDSourceToList( aCommand );
731 //addFilterUser( aCommand, theGen ); // protect filters from clearing
733 id_mesh->second->Process( aCommand );
734 id_mesh->second->AddProcessedCmd( aCommand );
738 // SMESH_MeshEditor method?
739 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
740 if ( id_editor != myMeshEditors.end() )
742 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
743 GetIDSourceToList( aCommand );
745 //addFilterUser( aCommand, theGen ); // protect filters from clearing
747 // some commands of SMESH_MeshEditor create meshes and groups
748 _pyID meshID, groups;
749 if ( method.Search("MakeMesh") != -1 )
750 meshID = aCommand->GetResultValue();
751 else if ( method == "MakeBoundaryMesh")
752 meshID = aCommand->GetResultValue(1);
753 else if ( method == "MakeBoundaryElements")
754 meshID = aCommand->GetResultValue(2);
756 if ( method.Search("MakeGroups") != -1 ||
757 method == "ExtrusionAlongPathX" ||
758 method == "ExtrusionAlongPathObjX" ||
759 method == "DoubleNodeGroupNew" ||
760 method == "DoubleNodeGroupsNew" ||
761 method == "DoubleNodeElemGroupNew" ||
762 method == "DoubleNodeElemGroupsNew" ||
763 method == "DoubleNodeElemGroup2New" ||
764 method == "DoubleNodeElemGroups2New" ||
765 method == "AffectedElemGroupsInRegion"
767 groups = aCommand->GetResultValue();
768 else if ( method == "MakeBoundaryMesh" )
769 groups = aCommand->GetResultValue(2);
770 else if ( method == "MakeBoundaryElements")
771 groups = aCommand->GetResultValue(3);
772 else if ( method == "Create0DElementsOnAllNodes" &&
773 aCommand->GetArg(2).Length() > 2 ) // group name != ''
774 groups = aCommand->GetResultValue();
776 id_editor->second->Process( aCommand );
777 id_editor->second->AddProcessedCmd( aCommand );
780 if ( !meshID.IsEmpty() &&
781 !myMeshes.count( meshID ) &&
782 aCommand->IsStudyEntry( meshID ))
784 _AString processedCommand = aCommand->GetString();
785 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
786 CheckObjectIsReCreated( mesh );
787 myMeshes.insert( make_pair( meshID, mesh ));
789 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
792 if ( !groups.IsEmpty() )
794 if ( !aCommand->IsStudyEntry( meshID ))
795 meshID = id_editor->second->GetMesh();
796 Handle(_pyMesh) mesh = myMeshes[ meshID ];
798 list< _pyID > idList = aCommand->GetStudyEntries( groups );
799 list< _pyID >::iterator grID = idList.begin();
800 for ( ; grID != idList.end(); ++grID )
801 if ( !myObjects.count( *grID ))
803 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
805 if ( !mesh.IsNull() ) mesh->AddGroup( group );
809 } // SMESH_MeshEditor methods
811 // SMESH_Hypothesis method?
812 Handle(_pyHypothesis) hyp = FindHyp( objID );
813 if ( !hyp.IsNull() && !hyp->IsAlgo() )
815 hyp->Process( aCommand );
816 hyp->AddProcessedCmd( aCommand );
820 // aFilterManager.CreateFilter() ?
821 if ( aCommand->GetMethod() == "CreateFilter" )
823 // Set a more human readable name to a filter
824 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
825 _pyID newID, filterID = aCommand->GetResultValue();
826 int pos = filterID.Search( "0x" );
828 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
830 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
833 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
834 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
836 // create _pySelfEraser for functors
837 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
838 functor->IgnoreOwnCalls(); // to erase if not used as an argument
839 AddObject( functor );
842 // other object method?
843 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
844 if ( id_obj != myObjects.end() ) {
845 id_obj->second->Process( aCommand );
846 id_obj->second->AddProcessedCmd( aCommand );
850 // Add access to a wrapped mesh
851 AddMeshAccessorMethod( aCommand );
853 // Add access to a wrapped algorithm
854 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
856 // PAL12227. PythonDump was not updated at proper time; result is
857 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
858 // TypeError: __init__() takes exactly 11 arguments (10 given)
859 const char wrongCommand[] = "SMESH.Filter.Criterion(";
860 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
862 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
863 // there must be 10 arguments, 5-th arg ThresholdID is missing,
864 const int wrongNbArgs = 9, missingArg = 5;
865 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
867 for ( int i = wrongNbArgs; i > missingArg; --i )
868 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
869 tmpCmd.SetArg( missingArg, "''");
870 aCommand->GetString().Trunc( beg - 1 );
871 aCommand->GetString() += tmpCmd.GetString();
874 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
876 // instead of "SMESH.Filter.Criterion(
877 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
878 // 1 2 3 4 5 6 7 8 9 10
879 // in order to avoid the problem of type mismatch of long and FunctorType
880 const TCollection_AsciiString
881 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
882 TCollection_AsciiString
883 Type = aCommand->GetArg(1), // long
884 Compare = aCommand->GetArg(2), // long
885 Threshold = aCommand->GetArg(3), // double
886 ThresholdStr = aCommand->GetArg(4), // string
887 ThresholdID = aCommand->GetArg(5), // string
888 UnaryOp = aCommand->GetArg(6), // long
889 BinaryOp = aCommand->GetArg(7), // long
890 Tolerance = aCommand->GetArg(8), // double
891 TypeOfElement = aCommand->GetArg(9), // ElementType
892 Precision = aCommand->GetArg(10); // long
893 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
894 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
895 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
896 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
897 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
899 if ( Compare == "SMESH.FT_EqualTo" )
902 aCommand->RemoveArgs();
903 aCommand->SetObject( SMESH_2smeshpy::GenName() );
904 aCommand->SetMethod( "GetCriterion" );
906 aCommand->SetArg( 1, TypeOfElement );
907 aCommand->SetArg( 2, Type );
908 aCommand->SetArg( 3, Compare );
910 if ( Threshold.IsIntegerValue() )
912 int iGeom = Threshold.IntegerValue();
913 if ( Type == "SMESH.FT_ElemGeomType" )
915 // set SMESH.GeometryType instead of a numerical Threshold
916 const int nbTypes = SMESH::Geom_LAST;
917 const char* types[] = {
918 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
919 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
920 "Geom_POLYHEDRA", "Geom_BALL" };
921 if ( -1 < iGeom && iGeom < nbTypes )
922 Threshold = SMESH + types[ iGeom ];
924 // is types complete? (compilation failure mains that enum GeometryType changed)
925 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
928 if (Type == "SMESH.FT_EntityType")
930 // set SMESH.EntityType instead of a numerical Threshold
931 const int nbTypes = SMESH::Entity_Last;
932 const char* types[] = {
933 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
934 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
935 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
936 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
937 "Entity_Pyramid", "Entity_Quad_Pyramid",
938 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
939 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
940 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
941 if ( -1 < iGeom && iGeom < nbTypes )
942 Threshold = SMESH + types[ iGeom ];
944 // is 'types' complete? (compilation failure mains that enum EntityType changed)
945 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
949 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
950 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
951 else if ( ThresholdStr.Length() != 2 )
952 aCommand->SetArg( 4, ThresholdStr );
953 else if ( ThresholdID.Length() != 2 )
954 aCommand->SetArg( 4, ThresholdID );
956 aCommand->SetArg( 4, Threshold );
957 // find the last not default arg
959 if ( Tolerance == dfltTol ) {
961 if ( BinaryOp == dfltFunctor ) {
963 if ( UnaryOp == dfltFunctor )
967 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
968 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
969 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
970 if ( Precision != dfltPreci )
972 TCollection_AsciiString crit = aCommand->GetResultValue();
973 aCommand->GetString() += "; ";
974 aCommand->GetString() += crit + ".Precision = " + Precision;
980 //================================================================================
982 * \brief Convert the command or remember it for later conversion
983 * \param theCommand - The python command calling a method of SMESH_Gen
985 //================================================================================
987 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
989 // there are methods to convert:
990 // CreateMesh( shape )
991 // Concatenate( [mesh1, ...], ... )
992 // CreateHypothesis( theHypType, theLibName )
993 // Compute( mesh, geom )
994 // Evaluate( mesh, geom )
996 TCollection_AsciiString method = theCommand->GetMethod();
998 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1000 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1004 if ( method == "CreateMeshesFromUNV" ||
1005 method == "CreateMeshesFromSTL" ||
1006 method == "CopyMesh" ) // command result is a mesh
1008 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1012 if ( method == "CreateMeshesFromMED" ||
1013 method == "CreateMeshesFromSAUV"||
1014 method == "CreateMeshesFromCGNS" ||
1015 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1017 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1018 std::list< _pyID >::iterator meshID = meshIDs.begin();
1019 for ( ; meshID != meshIDs.end(); ++meshID )
1021 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1024 if ( method == "CreateMeshesFromGMF" )
1026 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1027 // CreateMeshesFromGMF( theFileName )
1028 _AString file = theCommand->GetArg(1);
1029 theCommand->RemoveArgs();
1030 theCommand->SetArg( 1, file );
1033 if ( method == "CopyMeshWithGeom" )
1035 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1036 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1040 // CreateHypothesis()
1041 if ( method == "CreateHypothesis" )
1043 // issue 199929, remove standard library name (default parameter)
1044 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1045 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1046 // keep the first argument
1047 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1048 theCommand->RemoveArgs();
1049 theCommand->SetArg( 1, arg );
1052 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1053 CheckObjectIsReCreated( hyp );
1054 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1059 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1060 if ( method == "Compute" )
1062 const _pyID& meshID = theCommand->GetArg( 1 );
1063 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1064 if ( id_mesh != myMeshes.end() ) {
1065 theCommand->SetObject( meshID );
1066 theCommand->RemoveArgs();
1067 id_mesh->second->Process( theCommand );
1068 id_mesh->second->AddProcessedCmd( theCommand );
1073 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1074 if ( method == "Evaluate" )
1076 const _pyID& meshID = theCommand->GetArg( 1 );
1077 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1078 if ( id_mesh != myMeshes.end() ) {
1079 theCommand->SetObject( meshID );
1080 _pyID geom = theCommand->GetArg( 2 );
1081 theCommand->RemoveArgs();
1082 theCommand->SetArg( 1, geom );
1083 id_mesh->second->AddProcessedCmd( theCommand );
1088 // objects erasing creation command if no more its commands invoked:
1089 // SMESH_Pattern, FilterManager
1090 if ( method == "GetPattern" ||
1091 method == "CreateFilterManager" ||
1092 method == "CreateMeasurements" )
1094 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1095 if ( !AddObject( obj ) )
1096 theCommand->Clear(); // already created
1098 // Concatenate( [mesh1, ...], ... )
1099 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1101 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1102 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1103 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1104 _pyID appendMesh = theCommand->GetArg( 5 );
1105 if ( method == "ConcatenateWithGroups" ) {
1106 theCommand->SetMethod( "Concatenate" );
1107 theCommand->SetArg( 5, "True" );
1110 theCommand->SetArg( 5, "False" );
1112 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1114 appendMesh.Insert( 1, "meshToAppendTo=" );
1115 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1117 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1119 AddMeshAccessorMethod( theCommand );
1121 else if ( method == "SetName" ) // SetName(obj,name)
1123 // store theCommand as one of object commands to erase it along with the object
1124 const _pyID& objID = theCommand->GetArg( 1 );
1125 Handle(_pyObject) obj = FindObject( objID );
1126 if ( !obj.IsNull() )
1127 obj->AddProcessedCmd( theCommand );
1130 // Replace name of SMESH_Gen
1132 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1133 static TStringSet smeshpyMethods;
1134 if ( smeshpyMethods.empty() ) {
1135 const char * names[] =
1136 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1137 "GetPattern","GetSubShapesId",
1138 "" }; // <- mark of array end
1139 smeshpyMethods.Insert( names );
1141 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1142 // smeshgen.Method() --> smesh.Method()
1143 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1145 // smeshgen.Method() --> smesh.Method()
1146 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1149 //================================================================================
1151 * \brief Convert the remembered commands
1153 //================================================================================
1155 void _pyGen::Flush()
1157 // create an empty command
1158 myLastCommand = new _pyCommand();
1160 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1161 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1162 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1164 if ( IsToKeepAllCommands() ) // historical dump
1166 // set myIsPublished = true to all objects
1167 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1168 id_mesh->second->SetRemovedFromStudy( false );
1169 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1170 id_hyp->second->SetRemovedFromStudy( false );
1171 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1172 id_obj->second->SetRemovedFromStudy( false );
1176 // let hypotheses find referred objects in order to prevent clearing
1177 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1178 list< Handle(_pyMesh) > fatherMeshes;
1179 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1180 if ( !id_hyp->second.IsNull() )
1181 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1183 // set myIsPublished = false to all objects depending on
1184 // meshes built on a removed geometry
1185 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1186 if ( id_mesh->second->IsNotGeomPublished() )
1187 id_mesh->second->SetRemovedFromStudy( true );
1190 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1191 if ( ! id_mesh->second.IsNull() )
1192 id_mesh->second->Flush();
1195 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1196 if ( !id_hyp->second.IsNull() ) {
1197 id_hyp->second->Flush();
1198 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1199 if ( !id_hyp->second->IsWrapped() )
1200 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1203 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1204 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1205 for ( ; robj != myOrderedObjects.rend(); ++robj )
1206 if ( ! robj->IsNull() )
1208 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1209 for ( ; obj != myOrderedObjects.end(); ++obj )
1210 if ( ! obj->IsNull() )
1213 myLastCommand->SetOrderNb( ++myNbCommands );
1214 myCommands.push_back( myLastCommand );
1217 //================================================================================
1219 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1220 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1222 //================================================================================
1224 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1226 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1227 // for ( ; id_obj != myObjects.end(); ++id_obj )
1229 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1230 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1232 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1233 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1235 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1236 // list< _pyID >::iterator id = idList.begin();
1237 // for ( ; id != idList.end(); ++id )
1238 // if ( id_obj->first == *id )
1239 // // _pySubMesh::Process() does what we need
1240 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1245 //================================================================================
1247 * \brief Clean commands of removed objects depending on myIsPublished flag
1249 //================================================================================
1251 void _pyGen::ClearCommands()
1253 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1254 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1255 id_mesh->second->ClearCommands();
1257 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1258 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1259 if ( !id_hyp->second.IsNull() )
1260 id_hyp->second->ClearCommands();
1262 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1263 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1264 for ( ; robj != myOrderedObjects.rend(); ++robj )
1265 if ( ! robj->IsNull() )
1266 (*robj)->ClearCommands();
1267 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1268 for ( ; obj != myOrderedObjects.end(); ++obj )
1269 if ( ! obj->IsNull() )
1270 (*obj)->ClearCommands();
1273 //================================================================================
1275 * \brief Release mutual handles of objects
1277 //================================================================================
1281 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1282 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1283 id_mesh->second->Free();
1286 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1287 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1288 id_ed->second->Free();
1289 myMeshEditors.clear();
1291 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1292 for ( ; id_obj != myObjects.end(); ++id_obj )
1293 id_obj->second->Free();
1296 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1297 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1298 if ( !id_hyp->second.IsNull() )
1299 id_hyp->second->Free();
1302 myFile2ExportedMesh.clear();
1304 //myKeepAgrCmdsIDs.Print();
1307 //================================================================================
1309 * \brief Add access method to mesh that is an argument
1310 * \param theCmd - command to add access method
1311 * \retval bool - true if added
1313 //================================================================================
1315 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1318 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1319 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1320 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1326 //================================================================================
1328 * \brief Add access method to algo that is an object or an argument
1329 * \param theCmd - command to add access method
1330 * \retval bool - true if added
1332 //================================================================================
1334 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1337 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1338 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1339 if ( !id_hyp->second.IsNull() &&
1340 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1341 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1342 id_hyp->second->AccessorMethod() ))
1348 //================================================================================
1350 * \brief Find hypothesis by ID (entry)
1351 * \param theHypID - The hypothesis ID
1352 * \retval Handle(_pyHypothesis) - The found hypothesis
1354 //================================================================================
1356 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1358 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1359 if ( id_hyp != myHypos.end() &&
1360 !id_hyp->second.IsNull() &&
1361 theHypID == id_hyp->second->GetID() )
1362 return id_hyp->second;
1363 return Handle(_pyHypothesis)();
1366 //================================================================================
1368 * \brief Find algorithm able to create a hypothesis
1369 * \param theGeom - The shape ID the algorithm was created on
1370 * \param theMesh - The mesh ID that created the algorithm
1371 * \param theHypothesis - The hypothesis the algorithm should be able to create
1372 * \retval Handle(_pyHypothesis) - The found algo
1374 //================================================================================
1376 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1377 const Handle(_pyHypothesis)& theHypothesis )
1379 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1380 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1381 if ( !id_hyp->second.IsNull() &&
1382 id_hyp->second->IsAlgo() &&
1383 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1384 id_hyp->second->GetGeom() == theGeom &&
1385 id_hyp->second->GetMesh() == theMesh )
1386 return id_hyp->second;
1387 return Handle(_pyHypothesis)();
1390 //================================================================================
1392 * \brief Find subMesh by ID (entry)
1393 * \param theSubMeshID - The subMesh ID
1394 * \retval Handle(_pySubMesh) - The found subMesh
1396 //================================================================================
1398 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1400 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1401 if ( id_subMesh != myObjects.end() )
1402 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1403 return Handle(_pySubMesh)();
1407 //================================================================================
1409 * \brief Change order of commands in the script
1410 * \param theCmd1 - One command
1411 * \param theCmd2 - Another command
1413 //================================================================================
1415 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1417 list< Handle(_pyCommand) >::iterator pos1, pos2;
1418 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1419 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1420 myCommands.insert( pos1, theCmd2 );
1421 myCommands.insert( pos2, theCmd1 );
1422 myCommands.erase( pos1 );
1423 myCommands.erase( pos2 );
1425 int nb1 = theCmd1->GetOrderNb();
1426 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1427 theCmd2->SetOrderNb( nb1 );
1428 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1429 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1432 //================================================================================
1434 * \brief Set one command after the other
1435 * \param theCmd - Command to move
1436 * \param theAfterCmd - Command ater which to insert the first one
1438 //================================================================================
1440 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1442 setNeighbourCommand( theCmd, theAfterCmd, true );
1445 //================================================================================
1447 * \brief Set one command before the other
1448 * \param theCmd - Command to move
1449 * \param theBeforeCmd - Command before which to insert the first one
1451 //================================================================================
1453 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1455 setNeighbourCommand( theCmd, theBeforeCmd, false );
1458 //================================================================================
1460 * \brief Set one command before or after the other
1461 * \param theCmd - Command to move
1462 * \param theOtherCmd - Command ater or before which to insert the first one
1464 //================================================================================
1466 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1467 Handle(_pyCommand)& theOtherCmd,
1468 const bool theIsAfter )
1470 list< Handle(_pyCommand) >::iterator pos;
1471 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1472 myCommands.erase( pos );
1473 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1474 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1477 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1478 (*pos)->SetOrderNb( i++ );
1481 //================================================================================
1483 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1485 //================================================================================
1487 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1489 // No more needed after adding _pyObject::myArgCommands
1491 // const char filterPrefix[] = "aFilter0x";
1492 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1495 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1497 // const _AString & arg = theCommand->GetArg( i );
1498 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1499 // if ( arg.Search( filterPrefix ) != 1 )
1502 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1503 // if ( !filter.IsNull() )
1505 // filter->AddUser( user );
1506 // if ( !filter->GetNewID().IsEmpty() )
1507 // theCommand->SetArg( i, filter->GetNewID() );
1512 //================================================================================
1514 * \brief Set command be last in list of commands
1515 * \param theCmd - Command to be last
1517 //================================================================================
1519 Handle(_pyCommand)& _pyGen::GetLastCommand()
1521 return myLastCommand;
1524 //================================================================================
1526 * \brief Set method to access to object wrapped with python class
1527 * \param theID - The wrapped object entry
1528 * \param theMethod - The accessor method
1530 //================================================================================
1532 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1534 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1537 //================================================================================
1539 * \brief Generated new ID for object and assign with existing name
1540 * \param theID - ID of existing object
1542 //================================================================================
1544 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1549 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1551 while ( myObjectNames.IsBound( aNewID ) );
1553 if ( myObjectNames.IsBound( theID ) )
1554 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1556 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1560 //================================================================================
1562 * \brief Stores theObj in myObjects
1564 //================================================================================
1566 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1568 if ( theObj.IsNull() ) return false;
1570 CheckObjectIsReCreated( theObj );
1574 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1575 add = myMeshes.insert( make_pair( theObj->GetID(),
1576 Handle(_pyMesh)::DownCast( theObj ))).second;
1578 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1579 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1580 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1583 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1584 if ( add ) myOrderedObjects.push_back( theObj );
1589 //================================================================================
1591 * \brief Erases an existing object with the same ID. This method should be called
1592 * before storing theObj in _pyGen
1594 //================================================================================
1596 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1598 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1601 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1602 Handle(_pyObject) existing;
1604 existing = FindHyp( theObj->GetID() );
1606 existing = FindObject( theObj->GetID() );
1607 if ( !existing.IsNull() && existing != theObj )
1609 existing->SetRemovedFromStudy( true );
1610 existing->ClearCommands();
1613 if ( myHypos.count( theObj->GetID() ))
1614 myHypos.erase( theObj->GetID() );
1616 else if ( myMeshes.count( theObj->GetID() ))
1618 myMeshes.erase( theObj->GetID() );
1620 else if ( myObjects.count( theObj->GetID() ))
1622 myObjects.erase( theObj->GetID() );
1627 //================================================================================
1629 * \brief Re-register an object with other ID to make it Process() commands of
1630 * other object having this ID
1632 //================================================================================
1634 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1636 if ( theObj.IsNull() ) return;
1638 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1639 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1641 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1642 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1645 myObjects.insert( make_pair( theID, theObj ));
1648 //================================================================================
1650 * \brief Finds a _pyObject by ID
1652 //================================================================================
1654 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1657 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1658 if ( id_obj != myObjects.end() )
1659 return id_obj->second;
1662 _pyGen* me = const_cast< _pyGen* >( this );
1663 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1664 if ( id_obj != myMeshes.end() )
1665 return id_obj->second;
1668 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1669 // if ( id_obj != myMeshEditors.end() )
1670 // return id_obj->second;
1672 return Handle(_pyObject)();
1675 //================================================================================
1677 * \brief Check if a study entry is under GEOM component
1679 //================================================================================
1681 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1685 return ( myGeomIDIndex <= theObjID.Length() &&
1686 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1687 _pyCommand::IsStudyEntry( theObjID ));
1692 //================================================================================
1694 * \brief Returns true if an object is not present in a study
1696 //================================================================================
1698 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1700 if ( theObjID.IsEmpty() ) return false;
1702 if ( myObjectNames.IsBound( theObjID ))
1703 return false; // SMESH object is in study
1705 // either the SMESH object is not in study or it is a GEOM object
1706 if ( IsGeomObject( theObjID ))
1708 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1709 if ( so->_is_nil() ) return true;
1710 CORBA::Object_var obj = so->GetObject();
1711 return CORBA::is_nil( obj );
1713 return true; // SMESH object not in study
1716 //================================================================================
1718 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1719 * this object is not dumped
1720 * \param [in] theObjID - entry of the object whose creation command was eliminated
1722 //================================================================================
1724 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1726 myRemovedObjIDs.insert( theObjID );
1729 //================================================================================
1731 * \brief Return reader of hypotheses of plugins
1733 //================================================================================
1735 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1737 if (myHypReader.IsNull() )
1738 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1744 //================================================================================
1746 * \brief Mesh created by SMESH_Gen
1748 //================================================================================
1750 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1751 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1753 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1754 myGeomNotInStudy = true;
1756 // convert my creation command --> smeshpy.Mesh(...)
1757 Handle(_pyCommand) creationCmd = GetCreationCmd();
1758 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1759 creationCmd->SetMethod( "Mesh" );
1760 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1763 //================================================================================
1765 * \brief Mesh created by SMESH_MeshEditor
1767 //================================================================================
1769 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1770 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1772 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1774 // this mesh depends on the exported mesh
1775 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1776 if ( !file.IsEmpty() )
1778 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1779 addFatherMesh( exportData.myMesh );
1780 if ( !exportData.myLastComputeCmd.IsNull() )
1782 // restore cleared Compute() by which the exported mesh was generated
1783 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1784 // protect that Compute() cmd from clearing
1785 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1786 exportData.myMesh->myLastComputeCmd.Nullify();
1790 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1792 // this mesh depends on concatenated meshes
1793 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1794 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1795 list< _pyID >::iterator meshID = idList.begin();
1796 for ( ; meshID != idList.end(); ++meshID )
1797 addFatherMesh( *meshID );
1799 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1801 // this mesh depends on a copied IdSource
1802 const _pyID& objID = theCreationCmd->GetArg( 1 );
1803 addFatherMesh( objID );
1805 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1806 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1807 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1809 // this mesh depends on a source mesh
1810 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1811 const _pyID& meshID = theCreationCmd->GetObject();
1812 addFatherMesh( meshID );
1815 // convert my creation command
1816 Handle(_pyCommand) creationCmd = GetCreationCmd();
1817 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1818 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1821 //================================================================================
1823 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1824 * \param theCommand - Engine method called for this mesh
1826 //================================================================================
1828 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1830 // some methods of SMESH_Mesh interface needs special conversion
1831 // to methods of Mesh python class
1833 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1834 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1835 // 2. AddHypothesis(geom, hyp)
1836 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1837 // 3. CreateGroupFromGEOM(type, name, grp)
1838 // --> in Mesh.Group(grp, name="")
1839 // 4. ExportToMED(f, auto_groups, version)
1840 // --> in Mesh.ExportMED( f, auto_groups, version )
1843 const TCollection_AsciiString& method = theCommand->GetMethod();
1844 // ----------------------------------------------------------------------
1845 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1847 if ( !theGen->IsToKeepAllCommands() ) // !historical
1849 list< Handle(_pyHypothesis) >::iterator hyp;
1850 if ( !myLastComputeCmd.IsNull() )
1852 // check if the previously computed mesh has been edited,
1853 // if so then we do not clear the previous Compute()
1854 bool toClear = true;
1855 if ( myLastComputeCmd->GetMethod() == "Compute" )
1857 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1858 for ( ; e != myEditors.end() && toClear; ++e )
1860 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1861 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1862 if ( cmd != cmds.rend() &&
1863 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1869 // clear hyp commands called before myLastComputeCmd
1870 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1871 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1873 myLastComputeCmd->Clear();
1876 myLastComputeCmd = theCommand;
1878 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1879 (*hyp)->MeshComputed( myLastComputeCmd );
1883 // ----------------------------------------------------------------------
1884 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1886 if ( !theGen->IsToKeepAllCommands() ) // !historical
1889 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1890 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1891 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1893 if ( !myLastComputeCmd.IsNull() )
1895 list< Handle(_pyHypothesis) >::iterator hyp;
1896 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1897 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1899 myLastComputeCmd->Clear();
1902 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1903 for ( ; e != myEditors.end(); ++e )
1905 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1906 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1907 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1908 if ( !(*cmd)->IsEmpty() )
1910 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1914 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1917 // ----------------------------------------------------------------------
1918 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1919 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1920 if ( !subMesh.IsNull() ) {
1921 subMesh->SetCreator( this );
1922 mySubmeshes.push_back( subMesh );
1925 // ----------------------------------------------------------------------
1926 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1927 theCommand->Clear();
1929 // ----------------------------------------------------------------------
1930 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1931 myAddHypCmds.push_back( theCommand );
1933 const _pyID& hypID = theCommand->GetArg( 2 );
1934 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1935 if ( !hyp.IsNull() ) {
1936 myHypos.push_back( hyp );
1937 if ( hyp->GetMesh().IsEmpty() )
1938 hyp->SetMesh( this->GetID() );
1941 // ----------------------------------------------------------------------
1942 else if ( method == "CreateGroup" ||
1943 method == "CreateGroupFromGEOM" ||
1944 method == "CreateGroupFromFilter" ||
1945 method == "CreateDimGroup" )
1947 Handle(_pyGroup) group = new _pyGroup( theCommand );
1948 myGroups.push_back( group );
1949 theGen->AddObject( group );
1951 // ----------------------------------------------------------------------
1952 // update list of groups
1953 else if ( method == "GetGroups" )
1955 bool allGroupsRemoved = true;
1956 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1957 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1958 list< _pyID >::iterator grID = idList.begin();
1959 const size_t nbGroupsBefore = myGroups.size();
1960 Handle(_pyObject) obj;
1961 for ( ; grID != idList.end(); ++grID )
1963 obj = theGen->FindObject( *grID );
1966 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1967 theGen->AddObject( group );
1968 myGroups.push_back( group );
1971 if ( !obj->CanClear() )
1972 allGroupsRemoved = false;
1974 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
1975 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1977 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1979 // check if the preceding command is Compute();
1980 // if GetGroups() is just after Compute(), this can mean that the groups
1981 // were created by some algorithm and hence Compute() should not be discarded
1982 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1983 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1984 while ( (*cmd)->GetMethod() == "GetGroups" )
1986 if ( myLastComputeCmd == (*cmd))
1987 // protect last Compute() from clearing by the next Compute()
1988 myLastComputeCmd.Nullify();
1991 // ----------------------------------------------------------------------
1992 // notify a group about full removal
1993 else if ( method == "RemoveGroupWithContents" ||
1994 method == "RemoveGroup")
1996 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1997 const _pyID groupID = theCommand->GetArg( 1 );
1998 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1999 if ( !grp.IsNull() )
2001 if ( method == "RemoveGroupWithContents" )
2002 grp->RemovedWithContents();
2003 // to clear RemoveGroup() if the group creation is cleared
2004 grp->AddProcessedCmd( theCommand );
2008 // ----------------------------------------------------------------------
2009 else if ( theCommand->MethodStartsFrom( "Export" ))
2011 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2012 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2013 method == "ExportMED" )
2015 theCommand->SetMethod( "ExportMED" );
2016 // filter out deprecated version parameter
2017 vector< _AString > args;
2018 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2019 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2020 args.push_back( theCommand->GetArg( i ) );
2022 theCommand->RemoveArgs();
2023 for ( unsigned int i = 0; i < args.size(); i++ )
2024 theCommand->SetArg( i+1, args[i] );
2025 if ( theCommand->GetNbArgs() == 4 )
2027 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2028 _AString autoDimension = theCommand->GetArg( 4 );
2029 theCommand->SetArg( 4, "None" );
2030 theCommand->SetArg( 5, autoDimension );
2033 else if ( method == "ExportCGNS" )
2034 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2035 _pyID partID = theCommand->GetArg( 1 );
2036 int nbArgs = theCommand->GetNbArgs();
2037 for ( int i = 2; i <= nbArgs; ++i )
2038 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2039 theCommand->SetArg( nbArgs, partID );
2041 else if ( method == "ExportGMF" )
2042 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2043 _pyID partID = theCommand->GetArg( 1 );
2044 _AString file = theCommand->GetArg( 2 );
2045 theCommand->RemoveArgs();
2046 theCommand->SetArg( 1, file );
2047 theCommand->SetArg( 2, partID );
2049 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2050 { // ExportPartTo*(part, ...) -> Export*(..., part)
2052 // remove "PartTo" from the method
2053 TCollection_AsciiString newMethod = method;
2054 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2055 theCommand->SetMethod( newMethod );
2056 // replace version parameter by minor
2057 std::list< _AString > args;
2058 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2059 if ( _FilterArg( theCommand->GetArg( i )))
2060 args.push_back( "minor=0");
2062 args.push_back( theCommand->GetArg( i ));
2064 // check the 1st arg meshPart, it must be SMESH_IDSource
2065 _AString meshPart = args.front();
2066 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2067 meshPart.Search( "Filter" ) > 0 ||
2068 meshPart.Search( "GetIDSource" ) > 0 ||
2069 meshPart.Search( "meshPart" ) > 0 )
2071 // set the 1st arg meshPart
2072 // - to 5th place for ExportMED command
2073 // - to last place for the rest commands
2074 std::list< _AString >::iterator newPos = args.end();
2075 if ( newMethod == "ExportMED" )
2076 std::advance( newPos = args.begin(), 5 );
2077 args.splice( newPos, args, args.begin() );
2079 std::list< _AString >::iterator a = args.begin();
2080 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2081 theCommand->SetArg( i, *a );
2083 // remember file name
2084 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2085 ExportedMeshData( this, myLastComputeCmd ));
2087 // ----------------------------------------------------------------------
2088 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2090 _pyID hypID = theCommand->GetArg( 2 );
2091 _pyID geomID = theCommand->GetArg( 1 );
2092 bool isLocal = ( geomID != GetGeom() );
2094 // check if this mesh still has corresponding addition command
2095 Handle(_pyCommand) addCmd;
2096 list< Handle(_pyCommand) >::iterator cmd;
2097 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2098 for ( int i = 0; i < 2; ++i )
2100 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2101 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2103 bool sameHyp = true;
2104 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2105 sameHyp = false; // other hyp
2106 if ( (*cmd)->GetNbArgs() == 2 &&
2107 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2108 sameHyp = false; // other geom
2109 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2110 sameHyp = false; // other geom
2114 cmd = addHypCmds.erase( cmd );
2115 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2117 theCommand->Clear();
2121 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2122 addCmd->RemoveArgs();
2123 addCmd->SetArg( 1, hypID );
2125 addCmd->SetArg( 2, geomID );
2134 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2135 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2136 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2137 _pyID geom = theCommand->GetArg( 1 );
2138 theCommand->RemoveArgs();
2139 theCommand->SetArg( 1, hypID );
2140 if ( geom != GetGeom() )
2141 theCommand->SetArg( 2, geom );
2143 // remove hyp from myHypos
2144 myHypos.remove( hyp );
2146 // check for SubMesh order commands
2147 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2149 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2150 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2151 // commands are moved at the end of the script
2152 TCollection_AsciiString subIDs =
2153 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2154 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2155 list< _pyID >::iterator subID = idList.begin();
2156 for ( ; subID != idList.end(); ++subID )
2158 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2159 if ( !subMesh.IsNull() )
2160 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2163 // add accessor method if necessary
2166 if ( NeedMeshAccess( theCommand ))
2167 // apply theCommand to the mesh wrapped by smeshpy mesh
2168 AddMeshAccess( theCommand );
2172 //================================================================================
2174 * \brief Return True if addition of accesor method is needed
2176 //================================================================================
2178 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2180 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2181 // so no conversion is needed for them at all:
2182 static TStringSet sameMethods;
2183 if ( sameMethods.empty() ) {
2184 const char * names[] =
2185 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2186 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2187 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2188 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2189 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2190 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2191 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2192 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2193 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2194 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2195 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2196 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2197 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2198 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2199 ,"" }; // <- mark of end
2200 sameMethods.Insert( names );
2203 return !sameMethods.Contains( theCommand->GetMethod() );
2206 //================================================================================
2208 * \brief Convert creation and addition of all algos and hypos
2210 //================================================================================
2212 void _pyMesh::Flush()
2215 // get the meshes this mesh depends on via hypotheses
2216 list< Handle(_pyMesh) > fatherMeshes;
2217 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2218 for ( ; hyp != myHypos.end(); ++hyp )
2219 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2220 myGeomNotInStudy = true;
2222 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2223 for ( ; m != fatherMeshes.end(); ++m )
2224 addFatherMesh( *m );
2225 // if ( removedGeom )
2226 // SetRemovedFromStudy(); // as referred geometry not in study
2228 if ( myGeomNotInStudy )
2231 list < Handle(_pyCommand) >::iterator cmd;
2233 // try to convert algo addition like this:
2234 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2235 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2237 Handle(_pyCommand) addCmd = *cmd;
2239 _pyID algoID = addCmd->GetArg( 2 );
2240 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2241 if ( algo.IsNull() || !algo->IsAlgo() )
2244 // check and create new algorithm instance if it is already wrapped
2245 if ( algo->IsWrapped() ) {
2246 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2247 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2248 TCollection_AsciiString( " = " ) + theGen->GetID() +
2249 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2250 TCollection_AsciiString( "\" )" );
2252 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2253 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2254 if ( !newAlgo.IsNull() ) {
2255 newAlgo->Assign( algo, this->GetID() );
2256 newAlgo->SetCreationCmd( newCmd );
2258 // set algorithm creation
2259 theGen->SetCommandBefore( newCmd, addCmd );
2260 myHypos.push_back( newAlgo );
2261 if ( !myLastComputeCmd.IsNull() &&
2262 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2263 newAlgo->MeshComputed( myLastComputeCmd );
2268 _pyID geom = addCmd->GetArg( 1 );
2269 bool isLocalAlgo = ( geom != GetGeom() );
2272 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2274 // wrapped algo is created after mesh creation
2275 GetCreationCmd()->AddDependantCmd( addCmd );
2277 if ( isLocalAlgo ) {
2278 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2279 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2280 TCollection_AsciiString( "geom=" ) + geom );
2281 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2282 list < Handle(_pySubMesh) >::iterator smIt;
2283 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2284 Handle(_pySubMesh) subMesh = *smIt;
2285 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2286 if ( geom == subCmd->GetArg( 1 )) {
2287 subCmd->SetObject( algo->GetID() );
2288 subCmd->RemoveArgs();
2289 subMesh->SetCreator( algo );
2294 else // KO - ALGO was already created
2296 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2297 addCmd->RemoveArgs();
2298 addCmd->SetArg( 1, algoID );
2300 addCmd->SetArg( 2, geom );
2301 myNotConvertedAddHypCmds.push_back( addCmd );
2305 // try to convert hypo addition like this:
2306 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2307 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2309 Handle(_pyCommand) addCmd = *cmd;
2310 _pyID hypID = addCmd->GetArg( 2 );
2311 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2312 if ( hyp.IsNull() || hyp->IsAlgo() )
2314 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2316 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2317 _pyID geom = addCmd->GetArg( 1 );
2318 addCmd->RemoveArgs();
2319 addCmd->SetArg( 1, hypID );
2320 if ( geom != GetGeom() )
2321 addCmd->SetArg( 2, geom );
2322 myNotConvertedAddHypCmds.push_back( addCmd );
2326 myAddHypCmds.clear();
2327 mySubmeshes.clear();
2330 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2331 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2335 //================================================================================
2337 * \brief Sets myIsPublished of me and of all objects depending on me.
2339 //================================================================================
2341 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2343 _pyObject::SetRemovedFromStudy(isRemoved);
2345 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2346 for ( ; sm != mySubmeshes.end(); ++sm )
2347 (*sm)->SetRemovedFromStudy(isRemoved);
2349 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2350 for ( ; gr != myGroups.end(); ++gr )
2351 (*gr)->SetRemovedFromStudy(isRemoved);
2353 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2354 for ( ; m != myChildMeshes.end(); ++m )
2355 (*m)->SetRemovedFromStudy(isRemoved);
2357 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2358 for ( ; e != myEditors.end(); ++e )
2359 (*e)->SetRemovedFromStudy(isRemoved);
2362 //================================================================================
2364 * \brief Return true if none of myChildMeshes is in study
2366 //================================================================================
2368 bool _pyMesh::CanClear()
2373 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2374 for ( ; m != myChildMeshes.end(); ++m )
2375 if ( !(*m)->CanClear() )
2381 //================================================================================
2383 * \brief Clear my commands and commands of mesh editor
2385 //================================================================================
2387 void _pyMesh::ClearCommands()
2393 // mark all sub-objects as not removed, except child meshes
2394 list< Handle(_pyMesh) > children;
2395 children.swap( myChildMeshes );
2396 SetRemovedFromStudy( false );
2397 children.swap( myChildMeshes );
2401 _pyObject::ClearCommands();
2403 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2404 for ( ; sm != mySubmeshes.end(); ++sm )
2405 (*sm)->ClearCommands();
2407 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2408 for ( ; gr != myGroups.end(); ++gr )
2409 (*gr)->ClearCommands();
2411 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2412 for ( ; e != myEditors.end(); ++e )
2413 (*e)->ClearCommands();
2416 //================================================================================
2418 * \brief Add a father mesh by ID
2420 //================================================================================
2422 void _pyMesh::addFatherMesh( const _pyID& meshID )
2424 if ( !meshID.IsEmpty() && meshID != GetID() )
2425 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2428 //================================================================================
2430 * \brief Add a father mesh
2432 //================================================================================
2434 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2436 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2438 //myFatherMeshes.push_back( mesh );
2439 mesh->myChildMeshes.push_back( this );
2441 // protect last Compute() from clearing by the next Compute()
2442 mesh->myLastComputeCmd.Nullify();
2446 //================================================================================
2448 * \brief MeshEditor convert its commands to ones of mesh
2450 //================================================================================
2452 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2453 _pyObject( theCreationCmd )
2455 myMesh = theCreationCmd->GetObject();
2456 myCreationCmdStr = theCreationCmd->GetString();
2457 theCreationCmd->Clear();
2459 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2460 if ( !mesh.IsNull() )
2461 mesh->AddEditor( this );
2464 //================================================================================
2466 * \brief convert its commands to ones of mesh
2468 //================================================================================
2470 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2472 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2473 // commands calling these methods are converted to calls of Mesh methods without
2474 // additional modifs, only object is changed from MeshEditor to Mesh.
2475 static TStringSet sameMethods;
2476 if ( sameMethods.empty() ) {
2477 const char * names[] = {
2478 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2479 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2480 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2481 "MoveNode", "MoveClosestNodeToPoint",
2482 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2483 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2484 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2485 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2486 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2487 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2488 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2489 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2490 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2491 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2492 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2493 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2494 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2495 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2496 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2497 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2498 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2499 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2500 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2501 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2502 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2503 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2504 ,"" }; // <- mark of the end
2505 sameMethods.Insert( names );
2508 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2509 TStringMap diffMethods;
2510 if ( diffMethods.empty() ) {
2511 const char * orig2newName[] = {
2512 // original name --------------> new name
2513 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2514 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2515 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2516 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2517 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2518 ""};// <- mark of the end
2519 diffMethods.Insert( orig2newName );
2522 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2523 // only by last two arguments
2524 static TStringSet diffLastTwoArgsMethods;
2525 if (diffLastTwoArgsMethods.empty() ) {
2526 const char * names[] = {
2527 "MirrorMakeGroups","MirrorObjectMakeGroups",
2528 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2529 "RotateMakeGroups","RotateObjectMakeGroups",
2530 ""};// <- mark of the end
2531 diffLastTwoArgsMethods.Insert( names );
2534 // only a method name is to change?
2535 const TCollection_AsciiString & method = theCommand->GetMethod();
2536 bool isPyMeshMethod = sameMethods.Contains( method );
2537 if ( !isPyMeshMethod )
2539 TCollection_AsciiString newMethod = diffMethods.Value( method );
2540 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2541 theCommand->SetMethod( newMethod );
2543 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2544 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2546 isPyMeshMethod = true;
2547 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2548 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2551 if ( !isPyMeshMethod )
2553 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2554 // functions with the flag "theMakeGroups = True" like:
2555 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2556 int pos = method.Search("MakeGroups");
2559 isPyMeshMethod = true;
2560 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2561 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2563 // 1. Remove "MakeGroups" from the Command
2564 TCollection_AsciiString aMethod = theCommand->GetMethod();
2565 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2568 pos = pos-2; //Remove "0D" from the Command too
2569 aMethod.Trunc(pos-1);
2570 theCommand->SetMethod(aMethod);
2572 // 2. And add last "True" argument(s)
2573 while(nbArgsToAdd--)
2574 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2575 if( is0DmethId || is0DmethObj )
2576 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2580 // ExtrusionSweep0D() -> ExtrusionSweep()
2581 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2582 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2583 method == "ExtrusionSweepObject0D" ))
2585 isPyMeshMethod = true;
2586 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2587 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2588 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2591 // DoubleNode...New(...) -> DoubleNode...(...,True)
2592 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2593 method == "DoubleNodeElemGroupsNew" ||
2594 method == "DoubleNodeGroupNew" ||
2595 method == "DoubleNodeGroupsNew" ||
2596 method == "DoubleNodeElemGroup2New" ||
2597 method == "DoubleNodeElemGroups2New"))
2599 isPyMeshMethod = true;
2600 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2601 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2602 if ( excessLen == 3 )
2604 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2606 else if ( theCommand->GetArg(4) == "0" ||
2607 theCommand->GetArg(5) == "0" )
2609 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2610 // Group = DoubleNodeGroup2New(,,,False, True)
2611 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2612 theCommand->SetResultValue( groupID );
2615 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2616 // FindElementsByPoint(x, y, z, elementType, meshPart)
2617 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2619 isPyMeshMethod = true;
2620 theCommand->SetMethod( "FindElementsByPoint" );
2621 // make the 1st arg be the last one
2622 _pyID partID = theCommand->GetArg( 1 );
2623 int nbArgs = theCommand->GetNbArgs();
2624 for ( int i = 2; i <= nbArgs; ++i )
2625 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2626 theCommand->SetArg( nbArgs, partID );
2628 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2629 if ( !isPyMeshMethod && method == "Reorient2D" )
2631 isPyMeshMethod = true;
2632 _AString mesh = theCommand->GetArg( 1 );
2633 _AString dir = theCommand->GetArg( 2 );
2634 _AString face = theCommand->GetArg( 3 );
2635 _AString point = theCommand->GetArg( 4 );
2636 theCommand->RemoveArgs();
2637 theCommand->SetArg( 1, mesh );
2638 theCommand->SetArg( 2, dir );
2639 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2640 theCommand->SetArg( 3, point );
2642 theCommand->SetArg( 3, face );
2645 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2647 isPyMeshMethod = true;
2648 int crit_arg = theCommand->GetNbArgs();
2649 const _AString& crit = theCommand->GetArg(crit_arg);
2650 if (crit.Search("MaxElementLength2D") != -1)
2651 theCommand->SetArg(crit_arg, "");
2654 if ( isPyMeshMethod )
2656 theCommand->SetObject( myMesh );
2660 // editor creation command is needed only if any editor function is called
2661 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2662 if ( !myCreationCmdStr.IsEmpty() ) {
2663 GetCreationCmd()->GetString() = myCreationCmdStr;
2664 myCreationCmdStr.Clear();
2669 //================================================================================
2671 * \brief Return true if my mesh can be removed
2673 //================================================================================
2675 bool _pyMeshEditor::CanClear()
2677 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2678 return mesh.IsNull() ? true : mesh->CanClear();
2681 //================================================================================
2683 * \brief _pyHypothesis constructor
2684 * \param theCreationCmd -
2686 //================================================================================
2688 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2689 _pyObject( theCreationCmd ), myCurCrMethod(0)
2691 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2694 //================================================================================
2696 * \brief Creates algorithm or hypothesis
2697 * \param theCreationCmd - The engine command creating a hypothesis
2698 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2700 //================================================================================
2702 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2704 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2705 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2707 Handle(_pyHypothesis) hyp, algo;
2710 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2711 if ( hypTypeQuoted.IsEmpty() )
2714 TCollection_AsciiString hypType =
2715 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2717 algo = new _pyAlgorithm( theCreationCmd );
2718 hyp = new _pyHypothesis( theCreationCmd );
2720 if ( hypType == "NumberOfSegments" ) {
2721 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2722 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2723 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2724 hyp->AddArgMethod( "SetNumberOfSegments" );
2725 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2726 hyp->AddArgMethod( "SetScaleFactor" );
2727 hyp->AddArgMethod( "SetReversedEdges" );
2728 // same for ""CompositeSegment_1D:
2729 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2730 hyp->AddArgMethod( "SetNumberOfSegments" );
2731 hyp->AddArgMethod( "SetScaleFactor" );
2732 hyp->AddArgMethod( "SetReversedEdges" );
2734 else if ( hypType == "SegmentLengthAroundVertex" ) {
2735 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2736 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2737 hyp->AddArgMethod( "SetLength" );
2738 // same for ""CompositeSegment_1D:
2739 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2740 hyp->AddArgMethod( "SetLength" );
2742 else if ( hypType == "LayerDistribution2D" ) {
2743 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2744 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2746 else if ( hypType == "LayerDistribution" ) {
2747 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2748 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2750 else if ( hypType == "CartesianParameters3D" ) {
2751 hyp = new _pyComplexParamHypo( theCreationCmd );
2752 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2753 for ( int iArg = 0; iArg < 4; ++iArg )
2754 hyp->setCreationArg( iArg+1, "[]");
2755 hyp->AddAccumulativeMethod( "SetGrid" );
2756 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2760 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2763 return algo->IsValid() ? algo : hyp;
2766 //================================================================================
2768 * \brief Returns true if addition of this hypothesis to a given mesh can be
2769 * wrapped into hypothesis creation
2771 //================================================================================
2773 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2775 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2777 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2778 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2784 //================================================================================
2786 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2787 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2788 * \param theAlgo - The algo that can create this hypo
2789 * \retval bool - false if the command can't be converted
2791 //================================================================================
2793 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2794 const _pyID& theMesh)
2796 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2798 if ( !IsWrappable( theMesh ))
2801 myGeom = theCmd->GetArg( 1 );
2803 Handle(_pyHypothesis) algo;
2805 // find algo created on myGeom in theMesh
2806 algo = theGen->FindAlgo( myGeom, theMesh, this );
2807 if ( algo.IsNull() )
2809 // attach hypothesis creation command to be after algo creation command
2810 // because it can be new created instance of algorithm
2811 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2815 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2816 theCmd->SetResultValue( GetID() );
2817 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2818 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2819 // set args (geom will be set by _pyMesh calling this method)
2820 theCmd->RemoveArgs();
2821 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2822 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2823 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2825 theCmd->SetArg( i+1, "[]");
2827 // set a new creation command
2828 GetCreationCmd()->Clear();
2829 // replace creation command by wrapped instance
2830 // please note, that hypothesis attaches to algo creation command (see upper)
2831 SetCreationCmd( theCmd );
2834 // clear commands setting arg values
2835 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2836 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2839 // set unknown arg commands after hypo creation
2840 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2841 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2842 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2843 afterCmd->AddDependantCmd( *cmd );
2849 //================================================================================
2851 * \brief Remember hypothesis parameter values
2852 * \param theCommand - The called hypothesis method
2854 //================================================================================
2856 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2858 ASSERT( !myIsAlgo );
2859 if ( !theGen->IsToKeepAllCommands() )
2860 rememberCmdOfParameter( theCommand );
2862 bool usedCommand = false;
2863 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2864 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2866 CreationMethod& crMethod = type2meth->second;
2867 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2868 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2870 myArgCommands.push_back( theCommand );
2872 while ( crMethod.myArgs.size() < i+1 )
2873 crMethod.myArgs.push_back( "None" );
2874 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2879 myUnusedCommands.push_back( theCommand );
2882 //================================================================================
2884 * \brief Finish conversion
2886 //================================================================================
2888 void _pyHypothesis::Flush()
2892 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2893 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2894 // Add access to a wrapped mesh
2895 theGen->AddMeshAccessorMethod( *cmd );
2896 // Add access to a wrapped algorithm
2897 theGen->AddAlgoAccessorMethod( *cmd );
2899 cmd = myUnusedCommands.begin();
2900 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2901 // Add access to a wrapped mesh
2902 theGen->AddMeshAccessorMethod( *cmd );
2903 // Add access to a wrapped algorithm
2904 theGen->AddAlgoAccessorMethod( *cmd );
2907 // forget previous hypothesis modifications
2908 myArgCommands.clear();
2909 myUnusedCommands.clear();
2912 //================================================================================
2914 * \brief clear creation, arg and unknown commands
2916 //================================================================================
2918 void _pyHypothesis::ClearAllCommands()
2920 GetCreationCmd()->Clear();
2921 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2922 for ( ; cmd != myArgCommands.end(); ++cmd )
2924 cmd = myUnusedCommands.begin();
2925 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2930 //================================================================================
2932 * \brief Assign fields of theOther to me except myIsWrapped
2934 //================================================================================
2936 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2937 const _pyID& theMesh )
2939 // myCreationCmd = theOther->myCreationCmd;
2940 myIsAlgo = theOther->myIsAlgo;
2941 myIsWrapped = false;
2942 myGeom = theOther->myGeom;
2944 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2945 myAccumulativeMethods = theOther->myAccumulativeMethods;
2946 //myUnusedCommands = theOther->myUnusedCommands;
2947 // init myCurCrMethod
2948 GetCreationMethod( theOther->GetAlgoType() );
2951 //================================================================================
2953 * \brief Analyze my erasability depending on myReferredObjs
2955 //================================================================================
2957 bool _pyHypothesis::CanClear()
2961 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2962 for ( ; obj != myReferredObjs.end(); ++obj )
2963 if ( (*obj)->CanClear() )
2970 //================================================================================
2972 * \brief Clear my commands depending on usage by meshes
2974 //================================================================================
2976 void _pyHypothesis::ClearCommands()
2978 // if ( !theGen->IsToKeepAllCommands() )
2980 // bool isUsed = false;
2981 // int lastComputeOrder = 0;
2982 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2983 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2984 // if ( ! (*cmd)->IsEmpty() )
2987 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2988 // lastComputeOrder = (*cmd)->GetOrderNb();
2992 // SetRemovedFromStudy( true );
2996 // // clear my commands invoked after lastComputeOrder
2997 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2998 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3000 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3001 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3002 // // cmds.back()->Clear();
3006 _pyObject::ClearCommands();
3009 //================================================================================
3011 * \brief Find arguments that are objects like mesh, group, geometry
3012 * \param meshes - referred meshes (directly or indirrectly)
3013 * \retval bool - false if a referred geometry is not in the study
3015 //================================================================================
3017 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3019 if ( IsAlgo() ) return true;
3021 bool geomPublished = true;
3022 vector< _AString > args;
3023 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3024 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3026 CreationMethod& crMethod = type2meth->second;
3027 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3029 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3030 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3031 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3032 args.push_back( (*cmd)->GetArg( nb ));
3035 for ( size_t i = 0; i < args.size(); ++i )
3037 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3038 if ( idList.empty() && !args[ i ].IsEmpty() )
3039 idList.push_back( args[ i ]);
3040 list< _pyID >::iterator id = idList.begin();
3041 for ( ; id != idList.end(); ++id )
3043 Handle(_pyObject) obj = theGen->FindObject( *id );
3044 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3047 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3048 geomPublished = false;
3052 myReferredObjs.push_back( obj );
3053 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3054 if ( !mesh.IsNull() )
3055 meshes.push_back( mesh );
3056 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3057 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3058 obj->SetRemovedFromStudy( false );
3062 return geomPublished;
3065 //================================================================================
3067 * \brief Remember theCommand setting a parameter
3069 //================================================================================
3071 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3073 // parameters are discriminated by method name
3074 _AString method = theCommand->GetMethod();
3075 if ( myAccumulativeMethods.count( method ))
3076 return; // this method adds values and not override the previous value
3078 // discriminate commands setting different parameters via one method
3079 // by passing parameter names like e.g. SetOption("size", "0.2")
3080 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3081 theCommand->GetNbArgs() > 1 )
3083 // mangle method by appending a 1st textual arg
3084 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3086 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3087 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3088 if ( !isalpha( arg.Value(2))) continue;
3093 // parameters are discriminated by method name
3094 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3095 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3097 cmds.back()->Clear(); // previous parameter value has not been used
3098 cmds.back() = theCommand;
3102 cmds.push_back( theCommand );
3106 //================================================================================
3108 * \brief Return true if a setting parameter command ha been used to compute mesh
3110 //================================================================================
3112 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3113 _pyCommand::TAddr avoidComputeAddr ) const
3115 bool isUsed = false;
3116 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3117 myComputeAddr2Cmds.begin();
3118 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3120 if ( addr2cmds->first == avoidComputeAddr ) continue;
3121 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3122 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3127 //================================================================================
3129 * \brief Save commands setting parameters as they are used for a mesh computation
3131 //================================================================================
3133 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3135 myComputeCmds.push_back( theComputeCmd );
3136 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3138 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3139 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3140 savedCmds.push_back( m2c->second.back() );
3143 //================================================================================
3145 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3147 //================================================================================
3149 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3151 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3153 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3154 for ( ; cmd != savedCmds.end(); ++cmd )
3156 // check if a cmd has been used to compute another mesh
3157 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3159 // check if a cmd is a sole command setting its parameter;
3160 // don't use method name for search as it can change
3161 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3162 m2cmds = myMeth2Commands.begin();
3163 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3165 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3166 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3167 if ( cmdIt != cmds.end() )
3169 if ( cmds.back() != *cmd )
3171 cmds.erase( cmdIt );
3178 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3181 //================================================================================
3183 * \brief Sets an argNb-th argument of current creation command
3184 * \param argNb - argument index countered from 1
3186 //================================================================================
3188 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3190 if ( myCurCrMethod )
3192 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3193 myCurCrMethod->myArgs.push_back( "None" );
3194 if ( arg.IsEmpty() )
3195 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3197 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3202 //================================================================================
3204 * \brief Remember hypothesis parameter values
3205 * \param theCommand - The called hypothesis method
3207 //================================================================================
3209 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3211 if ( GetAlgoType() == "Cartesian_3D" )
3213 // CartesianParameters3D hyp
3215 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3216 theCommand->GetMethod() == "SetToAddEdges" )
3218 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3219 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3220 myArgCommands.push_back( theCommand );
3223 if ( theCommand->GetMethod() == "SetGrid" ||
3224 theCommand->GetMethod() == "SetGridSpacing" )
3226 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3227 int iArg = axis.Value(1) - '0';
3228 if ( theCommand->GetMethod() == "SetGrid" )
3230 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3234 myCurCrMethod->myArgs[ iArg ] = "[ ";
3235 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3236 myCurCrMethod->myArgs[ iArg ] += ", ";
3237 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3238 myCurCrMethod->myArgs[ iArg ] += "]";
3240 myArgCommands.push_back( theCommand );
3241 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3242 // accumulative, else, if the creation
3243 // is not converted, commands for axes 1 and 2 are lost
3248 if( theCommand->GetMethod() == "SetLength" )
3250 // NOW it is OBSOLETE
3251 // ex: hyp.SetLength(start, 1)
3252 // hyp.SetLength(end, 0)
3253 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3254 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3255 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3256 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3258 CreationMethod& crMethod = type2meth->second;
3259 while ( (int) crMethod.myArgs.size() < i+1 )
3260 crMethod.myArgs.push_back( "[]" );
3261 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3263 myArgCommands.push_back( theCommand );
3267 _pyHypothesis::Process( theCommand );
3270 //================================================================================
3272 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3274 //================================================================================
3276 void _pyComplexParamHypo::Flush()
3278 list < Handle(_pyCommand) >::iterator cmd;
3281 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3282 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3286 // if ( GetAlgoType() == "Cartesian_3D" )
3288 // _pyID algo = myCreationCmd->GetObject();
3289 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3291 // if ( IsWrapped() )
3293 // StructToList( *cmd, /*checkMethod=*/false );
3294 // const _AString & method = (*cmd)->GetMethod();
3295 // if ( method == "SetFixedPoint" )
3296 // (*cmd)->SetObject( algo );
3302 //================================================================================
3304 * \brief Convert methods of 1D hypotheses to my own methods
3305 * \param theCommand - The called hypothesis method
3307 //================================================================================
3309 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3311 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3314 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3315 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3316 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3318 // TCollection_AsciiString cmd =
3319 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3320 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3321 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3324 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3326 // // 1D hypo is already set, so distribution changes and the old
3327 // // 1D hypo is thrown away
3328 // my1dHyp->ClearAllCommands();
3331 // //my1dHyp->SetRemovedFromStudy( false );
3333 // if ( !myArgCommands.empty() )
3334 // myArgCommands.back()->Clear();
3335 myCurCrMethod->myArgs.push_back( hyp1dID );
3336 myArgCommands.push_back( theCommand );
3339 //================================================================================
3342 * \param theAdditionCmd - command to be converted
3343 * \param theMesh - mesh instance
3344 * \retval bool - status
3346 //================================================================================
3348 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3349 const _pyID& theMesh)
3351 myIsWrapped = false;
3353 if ( my1dHyp.IsNull() )
3356 // set "SetLayerDistribution()" after addition cmd
3357 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3359 _pyID geom = theAdditionCmd->GetArg( 1 );
3361 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3362 if ( !algo.IsNull() )
3364 my1dHyp->SetMesh( theMesh );
3365 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3366 algo->GetAlgoType().ToCString());
3367 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3370 // clear "SetLayerDistribution()" cmd
3371 myArgCommands.back()->Clear();
3373 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3375 // find RadialPrism algo created on <geom> for theMesh
3376 GetCreationCmd()->SetObject( algo->GetID() );
3377 GetCreationCmd()->SetMethod( myAlgoMethod );
3378 GetCreationCmd()->RemoveArgs();
3379 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3385 //================================================================================
3389 //================================================================================
3391 void _pyLayerDistributionHypo::Flush()
3393 // as creation of 1D hyp was written later then it's edition,
3394 // we need to find all it's edition calls and process them
3395 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3397 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3399 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3400 if ( hyp1dID.IsEmpty() ) continue;
3402 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3404 // make a new name for 1D hyp = "HypType" + "_Distribution"
3406 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3408 if ( prevNewName.IsEmpty() ) continue;
3409 newName = prevNewName;
3413 if ( hyp1d->IsWrapped() ) {
3414 newName = hyp1d->GetCreationCmd()->GetMethod();
3417 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3418 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3420 newName += "_Distribution";
3421 prevNewName = newName;
3423 hyp1d->GetCreationCmd()->SetResultValue( newName );
3425 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3426 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3427 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3428 const _pyID& objID = (*cmdIt)->GetObject();
3429 if ( objID == hyp1dID ) {
3430 if ( !hyp1d.IsNull() )
3432 hyp1d->Process( *cmdIt );
3433 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3435 ( *cmdIt )->SetObject( newName );
3438 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3439 (*cmd)->SetArg( 1, newName );
3443 //================================================================================
3445 * \brief additionally to Addition2Creation, clears SetDistrType() command
3446 * \param theCmd - AddHypothesis() command
3447 * \param theMesh - mesh to which a hypothesis is added
3448 * \retval bool - conversion result
3450 //================================================================================
3452 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3453 const _pyID& theMesh)
3455 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3456 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3457 bool scaleDistrType = false;
3458 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3459 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3460 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3461 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3462 scaleDistrType = true;
3465 else if ( !scaleDistrType ) {
3466 // distribution type changed: remove scale factor from args
3467 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3468 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3470 CreationMethod& crMethod = type2meth->second;
3471 if ( crMethod.myArgs.size() == 2 )
3472 crMethod.myArgs.pop_back();
3479 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3482 //================================================================================
3484 * \brief remove repeated commands defining distribution
3486 //================================================================================
3488 void _pyNumberOfSegmentsHyp::Flush()
3490 // find number of the last SetDistrType() command
3491 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3492 int distrTypeNb = 0;
3493 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3494 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3495 if ( cmd != myUnusedCommands.rbegin() )
3496 distrTypeNb = (*cmd)->GetOrderNb();
3498 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3501 // clear commands before the last SetDistrType()
3502 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3503 set< int > treatedCmdNbs; // avoid treating same cmd twice
3504 for ( int i = 0; i < 2; ++i ) {
3505 set<TCollection_AsciiString> uniqueMethods;
3506 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3507 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3509 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3510 continue;// avoid treating same cmd twice
3511 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3512 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3513 if ( !clear || method == "SetNumberOfSegments" ) {
3514 bool isNewInSet = uniqueMethods.insert( method ).second;
3515 clear = !isNewInSet;
3524 //================================================================================
3526 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3527 * into regular1D.LengthNearVertex( length, vertex )
3528 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3529 * \param theMesh - The mesh needing this hypo
3530 * \retval bool - false if the command can't be converted
3532 //================================================================================
3534 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3535 const _pyID& theMeshID)
3537 if ( IsWrappable( theMeshID )) {
3539 _pyID vertex = theCmd->GetArg( 1 );
3541 // the problem here is that segment algo can be not found
3542 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3543 // geometry where segment algorithm is assigned
3544 _pyID geom = vertex;
3545 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3546 while ( algo.IsNull() && !geom.IsEmpty()) {
3547 // try to find geom as a father of <vertex>
3548 geom = FatherID( geom );
3549 algo = theGen->FindAlgo( geom, theMeshID, this );
3551 if ( algo.IsNull() || geom.IsEmpty() )
3552 return false; // also possible to find geom as brother of veretex...
3554 // set geom instead of vertex
3555 theCmd->SetArg( 1, geom );
3557 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3558 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3559 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3561 // set vertex as a second arg
3562 theCmd->SetArg( 2, vertex );
3570 //================================================================================
3572 * \brief _pyAlgorithm constructor
3573 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3575 //================================================================================
3577 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3578 : _pyHypothesis( theCreationCmd )
3583 //================================================================================
3585 * \brief Convert the command adding an algorithm to mesh
3586 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3587 * \param theMesh - The mesh needing this algo
3588 * \retval bool - false if the command can't be converted
3590 //================================================================================
3592 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3593 const _pyID& theMeshID)
3595 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3596 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3597 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3603 //================================================================================
3605 * \brief Return starting position of a part of python command
3606 * \param thePartIndex - The index of command part
3607 * \retval int - Part position
3609 //================================================================================
3611 int _pyCommand::GetBegPos( int thePartIndex ) const
3615 if ( myBegPos.Length() < thePartIndex )
3617 ASSERT( thePartIndex > 0 );
3618 return myBegPos( thePartIndex );
3621 //================================================================================
3623 * \brief Store starting position of a part of python command
3624 * \param thePartIndex - The index of command part
3625 * \param thePosition - Part position
3627 //================================================================================
3629 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3631 while ( myBegPos.Length() < thePartIndex )
3632 myBegPos.Append( UNKNOWN );
3633 ASSERT( thePartIndex > 0 );
3634 myBegPos( thePartIndex ) = thePosition;
3637 //================================================================================
3639 * \brief Returns whitespace symbols at the line beginning
3640 * \retval TCollection_AsciiString - result
3642 //================================================================================
3644 TCollection_AsciiString _pyCommand::GetIndentation()
3647 //while ( end <= Length() && isblank( myString.Value( end )))
3648 //ANA: isblank() function isn't provided in VC2010 compiler
3649 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3651 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3654 //================================================================================
3656 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3657 * \retval const TCollection_AsciiString & - ResultValue substring
3659 //================================================================================
3661 const TCollection_AsciiString & _pyCommand::GetResultValue()
3663 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3665 SetBegPos( RESULT_IND, EMPTY );
3666 int begPos, endPos = myString.Location( "=", 1, Length() );
3670 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3671 if ( begPos < endPos )
3673 SetBegPos( RESULT_IND, begPos );
3675 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3676 myRes = myString.SubString( begPos, endPos );
3683 //================================================================================
3685 * \brief Return number of python command result value ResultValue = Obj.Meth()
3687 //================================================================================
3689 int _pyCommand::GetNbResultValues()
3692 return myResults.Length();
3696 //================================================================================
3698 * \brief Return substring of python command looking like
3699 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3700 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3702 //================================================================================
3703 const _AString& _pyCommand::GetResultValue(int res)
3705 if ( GetResultValue().IsEmpty() )
3706 return theEmptyString;
3708 if ( myResults.IsEmpty() )
3711 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3712 ++begPos; // skip [, else the whole list is returned
3713 while ( begPos < myRes.Length() ) {
3714 _AString result = GetWord( myRes, begPos, true );
3715 begPos += result.Length();
3717 // result.RemoveAll('[');
3718 // result.RemoveAll(']');
3723 myResults.Append( result );
3726 if ( res > 0 && res <= myResults.Length() )
3727 return myResults( res );
3728 return theEmptyString;
3731 //================================================================================
3733 * \brief Return substring of python command looking like ResVal = Object.Meth()
3734 * \retval const TCollection_AsciiString & - Object substring
3736 //================================================================================
3738 const TCollection_AsciiString & _pyCommand::GetObject()
3740 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3743 int begPos = GetBegPos( RESULT_IND );
3745 begPos = myString.Location( "=", 1, Length() ) + 1;
3746 // is '=' in the string argument (for example, name) or not
3747 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3748 for ( int i = 1; i < begPos-1; i++ )
3749 switch ( myString.Value( i )) {
3750 case '\'': nb[0]++; break;
3751 case '"' : nb[1]++; break;
3752 case '(' : nb[2]++; break;
3753 case ')' : nb[3]++; break;
3755 // if = is inside a string or a list
3756 // then get an object at the start of the command
3757 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3761 begPos += myRes.Length();
3763 myObj = GetWord( myString, begPos, true );
3764 if ( begPos != EMPTY )
3766 // check if object is complex,
3767 // so far consider case like "smesh.Method()"
3768 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3769 //if ( bracketPos==0 ) bracketPos = Length();
3770 int dotPos = begPos+myObj.Length();
3771 while ( dotPos+1 < bracketPos ) {
3772 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3777 if ( dotPos > begPos+myObj.Length() )
3778 myObj = myString.SubString( begPos, dotPos-1 );
3781 // 1st word after '=' is an object
3782 // else // no method -> no object
3788 SetBegPos( OBJECT_IND, begPos );
3794 //================================================================================
3796 * \brief Return substring of python command looking like ResVal = Obj.Method()
3797 * \retval const TCollection_AsciiString & - Method substring
3799 //================================================================================
3801 const TCollection_AsciiString & _pyCommand::GetMethod()
3803 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3806 int begPos = GetBegPos( OBJECT_IND );
3807 bool forward = true;
3809 begPos = myString.Location( "(", 1, Length() ) - 1;
3813 begPos += myObj.Length();
3816 myMeth = GetWord( myString, begPos, forward );
3817 SetBegPos( METHOD_IND, begPos );
3823 //================================================================================
3825 * \brief Returns true if there are brackets after the method
3827 //================================================================================
3829 bool _pyCommand::IsMethodCall()
3831 if ( GetMethod().IsEmpty() )
3833 if ( myString.StartsWith("#") )
3835 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3836 return ( s[0] == '(' || s[1] == '(' );
3839 //================================================================================
3841 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3842 * \retval const TCollection_AsciiString & - Arg<index> substring
3844 //================================================================================
3846 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3848 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3852 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3854 pos = myString.Location( "(", 1, Length() );
3858 // we are at or before '(', skip it if present
3860 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3861 if ( pos > Length() )
3865 SetBegPos( ARG1_IND, 0 ); // even no '('
3866 return theEmptyString;
3870 list< TCollection_AsciiString > separatorStack( 1, ",)");
3871 bool ignoreNesting = false;
3873 while ( pos <= Length() )
3875 const char chr = myString.Value( pos );
3877 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3879 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3881 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3883 TCollection_AsciiString arg;
3884 if ( pos-1 >= prevPos ) {
3885 arg = myString.SubString( prevPos, pos-1 );
3886 arg.RightAdjust(); // remove spaces
3889 if ( !arg.IsEmpty() || chr == ',' )
3891 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3892 myArgs.Append( arg );
3898 else // end of nesting args found
3900 separatorStack.pop_back();
3901 ignoreNesting = false;
3904 else if ( !ignoreNesting )
3907 case '(' : separatorStack.push_back(")"); break;
3908 case '[' : separatorStack.push_back("]"); break;
3909 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3910 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3917 if ( myArgs.Length() < index )
3918 return theEmptyString;
3919 return myArgs( index );
3922 //================================================================================
3924 * \brief Return position where arguments begin
3926 //================================================================================
3928 int _pyCommand::GetArgBeginning() const
3930 int pos = GetBegPos( ARG1_IND );
3931 if ( pos == UNKNOWN )
3933 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3935 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3940 //================================================================================
3942 * \brief Check if char is a word part
3943 * \param c - The character to check
3944 * \retval bool - The check result
3946 //================================================================================
3948 static inline bool isWord(const char c, const bool dotIsWord)
3951 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3954 //================================================================================
3956 * \brief Looks for a word in the string and returns word's beginning
3957 * \param theString - The input string
3958 * \param theStartPos - The position to start the search, returning word's beginning
3959 * \param theForward - The search direction
3960 * \retval TCollection_AsciiString - The found word
3962 //================================================================================
3964 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3966 const bool theForward,
3967 const bool dotIsWord )
3969 int beg = theStartPos, end = theStartPos;
3970 theStartPos = EMPTY;
3971 if ( beg < 1 || beg > theString.Length() )
3972 return theEmptyString;
3974 if ( theForward ) { // search forward
3976 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3978 if ( beg > theString.Length() )
3979 return theEmptyString; // no word found
3982 char begChar = theString.Value( beg );
3983 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3984 char endChar = ( begChar == '[' ) ? ']' : begChar;
3985 // end is at the corresponding quoting mark or bracket
3986 while ( end < theString.Length() &&
3987 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3991 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3996 else { // search backward
3998 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4001 return theEmptyString; // no word found
4003 char endChar = theString.Value( end );
4004 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4005 char begChar = ( endChar == ']' ) ? '[' : endChar;
4006 // beg is at the corresponding quoting mark
4008 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4012 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4018 //cout << theString << " ---- " << beg << " - " << end << endl;
4019 return theString.SubString( beg, end );
4022 //================================================================================
4024 * \brief Returns true if the string looks like a study entry
4026 //================================================================================
4028 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4030 if ( str.Length() < 5 ) return false;
4032 int nbColons = 0, isColon;
4033 for ( int i = 1; i <= str.Length(); ++i )
4035 char c = str.Value(i);
4036 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4038 nbColons += isColon;
4040 return nbColons > 2 && str.Length()-nbColons > 2;
4043 //================================================================================
4045 * \brief Returns true if the string looks like an object ID but not like a list,
4046 * string, command etc.
4048 //================================================================================
4050 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4052 if ( str.Length() < 1 ) return false;
4054 const char* s = str.ToCString();
4056 for ( int i = 0; i < str.Length(); ++i )
4057 if ( !IsIDChar( s[i] ))
4063 //================================================================================
4065 * \brief Finds entries in a string
4067 //================================================================================
4069 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4071 std::list< _pyID > resList;
4073 while ( ++pos <= str.Length() )
4075 if ( !isdigit( str.Value( pos ))) continue;
4076 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4079 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4080 _pyID entry = str.SubString( pos, end-1 );
4082 if ( IsStudyEntry( entry ))
4083 resList.push_back( entry );
4088 //================================================================================
4090 * \brief Look for position where not space char is
4091 * \param theString - The string
4092 * \param thePos - The position to search from and which returns result
4093 * \retval bool - false if there are only space after thePos in theString
4095 //================================================================================
4097 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4099 if ( thePos < 1 || thePos > theString.Length() )
4102 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4105 return thePos <= theString.Length();
4108 //================================================================================
4110 * \brief Modify a part of the command
4111 * \param thePartIndex - The index of the part
4112 * \param thePart - The new part string
4113 * \param theOldPart - The old part
4115 //================================================================================
4117 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4118 TCollection_AsciiString& theOldPart)
4120 int pos = GetBegPos( thePartIndex );
4121 if ( pos <= Length() && theOldPart != thePart)
4123 TCollection_AsciiString seperator;
4125 pos = GetBegPos( thePartIndex + 1 );
4126 if ( pos < 1 ) return;
4127 switch ( thePartIndex ) {
4128 case RESULT_IND: seperator = " = "; break;
4129 case OBJECT_IND: seperator = "."; break;
4130 case METHOD_IND: seperator = "()"; break;
4134 myString.Remove( pos, theOldPart.Length() );
4135 if ( !seperator.IsEmpty() )
4136 myString.Insert( pos , seperator );
4137 myString.Insert( pos, thePart );
4138 // update starting positions of the following parts
4139 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4140 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4141 if ( myBegPos( i ) > 0 )
4142 myBegPos( i ) += posDelta;
4144 theOldPart = thePart;
4148 //================================================================================
4150 * \brief Set argument
4151 * \param index - The argument index, it counts from 1
4152 * \param theArg - The argument string
4154 //================================================================================
4156 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4159 int argInd = ARG1_IND + index - 1;
4160 int pos = GetBegPos( argInd );
4161 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4163 // find a closing parenthesis
4164 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4165 int lastArgInd = GetNbArgs();
4166 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4167 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4172 while ( pos > 0 && myString.Value( pos ) != ')' )
4175 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4179 while ( myArgs.Length() < index ) {
4180 if ( myArgs.Length() )
4181 myString.Insert( pos++, "," );
4182 myArgs.Append("None");
4183 myString.Insert( pos, myArgs.Last() );
4184 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4185 pos += myArgs.Last().Length();
4188 SetPart( argInd, theArg, myArgs( index ));
4191 //================================================================================
4193 * \brief Empty arg list
4195 //================================================================================
4197 void _pyCommand::RemoveArgs()
4199 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4200 myString.Trunc( pos );
4203 if ( myBegPos.Length() >= ARG1_IND )
4204 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4207 //================================================================================
4209 * \brief Comment a python command
4211 //================================================================================
4213 void _pyCommand::Comment()
4215 if ( IsEmpty() ) return;
4218 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4219 if ( i <= Length() )
4221 myString.Insert( i, "#" );
4222 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4224 int begPos = GetBegPos( iPart );
4225 if ( begPos != UNKNOWN && begPos != EMPTY )
4226 SetBegPos( iPart, begPos + 1 );
4231 //================================================================================
4233 * \brief Set dependent commands after this one
4235 //================================================================================
4237 bool _pyCommand::SetDependentCmdsAfter() const
4239 bool orderChanged = false;
4240 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4241 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4242 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4243 orderChanged = true;
4244 theGen->SetCommandAfter( *cmd, this );
4245 (*cmd)->SetDependentCmdsAfter();
4248 return orderChanged;
4250 //================================================================================
4252 * \brief Insert accessor method after theObjectID
4253 * \param theObjectID - id of the accessed object
4254 * \param theAcsMethod - name of the method giving access to the object
4255 * \retval bool - false if theObjectID is not found in the command string
4257 //================================================================================
4259 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4261 if ( !theAcsMethod )
4263 // start object search from the object, i.e. ignore result
4265 int beg = GetBegPos( OBJECT_IND );
4266 if ( beg < 1 || beg > Length() )
4269 while (( beg = myString.Location( theObjectID, beg, Length() )))
4271 // check that theObjectID is not just a part of a longer ID
4272 int afterEnd = beg + theObjectID.Length();
4273 Standard_Character c = myString.Value( afterEnd );
4274 if ( !IsIDChar( c ))
4276 // check if accessor method already present
4278 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4280 int oldLen = Length();
4281 myString.Insert( afterEnd, (char*) theAcsMethod );
4282 myString.Insert( afterEnd, "." );
4283 // update starting positions of the parts following the modified one
4284 int posDelta = Length() - oldLen;
4285 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4286 if ( myBegPos( i ) > afterEnd )
4287 myBegPos( i ) += posDelta;
4292 beg = afterEnd; // is a part -> next search
4297 //================================================================================
4299 * \brief Creates pyObject
4301 //================================================================================
4303 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4304 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4309 //================================================================================
4311 * \brief Set up myID and myIsPublished
4313 //================================================================================
4315 void _pyObject::setID(const _pyID& theID)
4318 myIsPublished = !theGen->IsNotPublished( GetID() );
4321 //================================================================================
4323 * \brief Clear myCreationCmd and myProcessedCmds
4325 //================================================================================
4327 void _pyObject::ClearCommands()
4332 if ( !myCreationCmd.IsNull() )
4333 myCreationCmd->Clear();
4335 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4336 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4340 //================================================================================
4342 * \brief Return method name giving access to an interaface object wrapped by python class
4343 * \retval const char* - method name
4345 //================================================================================
4347 const char* _pyObject::AccessorMethod() const
4351 //================================================================================
4353 * \brief Return ID of a father
4355 //================================================================================
4357 _pyID _pyObject::FatherID(const _pyID & childID)
4359 int colPos = childID.SearchFromEnd(':');
4361 return childID.SubString( 1, colPos-1 );
4365 //================================================================================
4367 * \brief SelfEraser erases creation command if none of it's commands invoked
4368 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4370 //================================================================================
4372 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4373 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4375 myIsPublished = true; // prevent clearing as a not published
4376 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4379 //================================================================================
4381 * \brief SelfEraser erases creation command if none of it's commands invoked
4382 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4384 //================================================================================
4386 bool _pySelfEraser::CanClear()
4388 bool toErase = false;
4389 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4392 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4393 for ( ; cmd != myArgCmds.end(); ++cmd )
4394 nbArgUses += IsAliveCmd( *cmd );
4396 toErase = ( nbArgUses < 1 );
4401 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4402 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4403 for ( ; cmd != cmds.end(); )
4404 // check of cmd emptiness is not enough as object can change
4405 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4408 cmd = cmds.erase( cmd ); // save the cmd from clearing
4410 toErase = ( nbCalls < 1 );
4415 //================================================================================
4417 * \brief Check if a command is or can be cleared
4419 //================================================================================
4421 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4423 if ( theCmd->IsEmpty() )
4426 if ( !theGen->IsToKeepAllCommands() )
4428 const _pyID& objID = theCmd->GetObject();
4429 Handle( _pyObject ) obj = theGen->FindObject( objID );
4430 if ( !obj.IsNull() )
4431 return !obj->CanClear();
4436 //================================================================================
4438 * \brief SelfEraser erases creation command if none of it's commands invoked
4439 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4441 //================================================================================
4443 void _pySelfEraser::Flush()
4447 myIsPublished = false;
4448 _pyObject::ClearCommands();
4452 //================================================================================
4454 * \brief _pySubMesh constructor
4456 //================================================================================
4458 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4459 _pyObject(theCreationCmd)
4461 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4462 if ( toKeepAgrCmds )
4463 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4466 //================================================================================
4468 * \brief Return true if a sub-mesh can be used as argument of the given method
4470 //================================================================================
4472 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4475 // names of all methods where a sub-mesh can be used as argument
4476 // static TStringSet methods;
4477 // if ( methods.empty() ) {
4478 // const char * names[] = {
4479 // // methods of SMESH_Gen
4481 // // methods of SMESH_Group
4483 // // methods of SMESH_Measurements
4485 // // methods of SMESH_Mesh
4486 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4488 // // methods of SMESH_MeshEditor
4489 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4490 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4491 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4492 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4493 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4494 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4495 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4496 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4497 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4498 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4499 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4500 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4501 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4502 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4503 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4504 // "" }; // <- mark of end
4505 // methods.Insert( names );
4507 // return methods.Contains( theMethodName );
4510 //================================================================================
4512 * \brief count invoked commands
4514 //================================================================================
4516 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4518 _pyObject::Process(theCommand); // count calls of Process()
4521 //================================================================================
4523 * \brief Move creation command depending on invoked commands
4525 //================================================================================
4527 void _pySubMesh::Flush()
4529 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4530 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4531 else if ( !myCreator.IsNull() )
4532 // move to be just after creator
4533 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4535 // move sub-mesh usage after creation cmd
4536 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4537 for ( ; cmd != myArgCmds.end(); ++cmd )
4538 if ( !(*cmd)->IsEmpty() )
4539 GetCreationCmd()->AddDependantCmd( *cmd );
4542 //================================================================================
4544 * \brief Creates _pyGroup
4546 //================================================================================
4548 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4549 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4551 if ( !id.IsEmpty() )
4554 myCanClearCreationCmd = true;
4556 const _AString& method = theCreationCmd->GetMethod();
4557 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4559 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4561 // ----------------------------------------------------------------------
4562 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4564 _pyID geom = theCreationCmd->GetArg( 3 );
4565 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4566 // next if(){...} section is commented
4567 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4568 // theCreationCmd->SetMethod( "Group" );
4569 // theCreationCmd->RemoveArgs();
4570 // theCreationCmd->SetArg( 1, geom );
4573 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4574 _pyID type = theCreationCmd->GetArg( 1 );
4575 _pyID name = theCreationCmd->GetArg( 2 );
4576 theCreationCmd->SetMethod( "GroupOnGeom" );
4577 theCreationCmd->RemoveArgs();
4578 theCreationCmd->SetArg( 1, geom );
4579 theCreationCmd->SetArg( 2, name );
4580 theCreationCmd->SetArg( 3, type );
4583 else if ( method == "CreateGroupFromFilter" )
4585 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4586 theCreationCmd->SetMethod( "GroupOnFilter" );
4588 _pyID filterID = theCreationCmd->GetArg(3);
4589 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4590 if ( !filter.IsNull())
4592 if ( !filter->GetNewID().IsEmpty() )
4593 theCreationCmd->SetArg( 3, filter->GetNewID() );
4594 //filter->AddUser( this );
4598 else if ( method == "GetGroups" )
4600 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4604 // theCreationCmd does something else apart from creation of this group
4605 // and thus it can't be cleared if this group is removed
4606 myCanClearCreationCmd = false;
4610 //================================================================================
4612 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4615 //================================================================================
4617 bool _pyGroup::CanClear()
4622 if ( !myCanClearCreationCmd &&
4623 !myCreationCmd.IsNull() &&
4624 myCreationCmd->GetMethod() == "GetGroups" )
4626 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4627 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4628 list< _pyID >::iterator grID = idList.begin();
4629 if ( GetID() == *grID )
4631 myCanClearCreationCmd = true;
4632 list< Handle(_pyGroup ) > groups;
4633 for ( ; grID != idList.end(); ++grID )
4635 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4636 if ( group.IsNull() ) continue;
4637 groups.push_back( group );
4638 if ( group->IsInStudy() )
4639 myCanClearCreationCmd = false;
4641 // set myCanClearCreationCmd == true to all groups
4642 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4643 for ( ; group != groups.end(); ++group )
4644 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4648 return myCanClearCreationCmd;
4651 //================================================================================
4653 * \brief set myCanClearCreationCmd = true if the main action of the creation
4654 * command is discarded
4656 //================================================================================
4658 void _pyGroup::RemovedWithContents()
4660 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4661 // via a created group
4662 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4663 // myCanClearCreationCmd = true;
4666 //================================================================================
4668 * \brief To convert creation of a group by filter
4670 //================================================================================
4672 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4674 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4675 // group = mesh.CreateEmptyGroup( elemType, groupName )
4676 // aFilter.SetMesh(mesh)
4677 // nbAdd = group.AddFrom( aFilter )
4678 Handle(_pyFilter) filter;
4679 if ( theCommand->GetMethod() == "AddFrom" )
4681 _pyID idSource = theCommand->GetArg(1);
4682 // check if idSource is a filter
4683 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4684 if ( !filter.IsNull() )
4686 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4687 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4688 while ( *cmdIt != theCommand ) ++cmdIt;
4689 while ( (*cmdIt)->GetOrderNb() != 1 )
4691 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4692 if ((setMeshCmd->GetObject() == idSource ||
4693 setMeshCmd->GetObject() == filter->GetNewID() )
4695 setMeshCmd->GetMethod() == "SetMesh")
4697 setMeshCmd->Clear();
4701 // replace 3 commands by one
4702 theCommand->Clear();
4703 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4704 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4705 if ( !filter->GetNewID().IsEmpty() )
4706 idSource = filter->GetNewID();
4707 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4708 makeGroupCmd->SetArg( 1, name );
4709 makeGroupCmd->SetArg( 2, idSource );
4710 filter->AddArgCmd( makeGroupCmd );
4713 else if ( theCommand->GetMethod() == "SetFilter" )
4715 // set new name of a filter or clear the command if the same filter is set
4716 _pyID filterID = theCommand->GetArg(1);
4717 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4718 if ( !myFilter.IsNull() && filter == myFilter )
4719 theCommand->Clear();
4720 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4721 theCommand->SetArg( 1, filter->GetNewID() );
4724 else if ( theCommand->GetMethod() == "GetFilter" )
4726 // GetFilter() returns a filter with other ID, make myFilter process
4727 // calls of the returned filter
4728 if ( !myFilter.IsNull() )
4730 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4731 theCommand->Clear();
4735 // if ( !filter.IsNull() )
4736 // filter->AddUser( this );
4738 theGen->AddMeshAccessorMethod( theCommand );
4741 //================================================================================
4743 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4745 //================================================================================
4747 void _pyGroup::Flush()
4749 if ( !theGen->IsToKeepAllCommands() &&
4750 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4752 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4756 //================================================================================
4758 * \brief Constructor of _pyFilter
4760 //================================================================================
4762 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4763 :_pyObject(theCreationCmd), myNewID( newID )
4765 //myIsPublished = true; // prevent clearing as a not published
4766 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4769 //================================================================================
4771 * \brief To convert creation of a filter by criteria and
4772 * to replace an old name by a new one
4774 //================================================================================
4776 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4778 if ( theCommand->GetObject() == GetID() )
4779 _pyObject::Process(theCommand); // count commands
4781 if ( !myNewID.IsEmpty() )
4782 theCommand->SetObject( myNewID );
4784 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4785 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4786 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4787 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4788 theCommand->GetMethod() == "SetCriteria")
4790 // aFilter.SetCriteria(aCriteria) ->
4791 // aFilter = smesh.GetFilterFromCriteria(criteria)
4792 if ( myNewID.IsEmpty() )
4793 theCommand->SetResultValue( GetID() );
4795 theCommand->SetResultValue( myNewID );
4796 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4797 theCommand->SetMethod( "GetFilterFromCriteria" );
4799 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4800 GetCreationCmd()->Clear();
4801 GetCreationCmd()->GetString() = theCommand->GetString();
4802 theCommand->Clear();
4803 theCommand->AddDependantCmd( GetCreationCmd() );
4804 // why swap? -- it's needed
4805 //GetCreationCmd()->Clear();
4807 else if ( theCommand->GetMethod() == "SetMesh" )
4809 if ( myMesh == theCommand->GetArg( 1 ))
4810 theCommand->Clear();
4812 myMesh = theCommand->GetArg( 1 );
4813 theGen->AddMeshAccessorMethod( theCommand );
4817 //================================================================================
4819 * \brief Set new filter name to the creation command and to myArgCmds
4821 //================================================================================
4823 void _pyFilter::Flush()
4825 if ( myNewID.IsEmpty() ) return;
4827 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4828 for ( ; cmd != myArgCmds.end(); ++cmd )
4829 if ( !(*cmd)->IsEmpty() )
4831 _AString cmdStr = (*cmd)->GetString();
4832 _AString id = GetID();
4833 int pos = cmdStr.Search( id );
4836 cmdStr.Remove( pos, id.Length() );
4837 cmdStr.Insert( pos, myNewID );
4840 (*cmd)->GetString() = cmdStr;
4843 if ( !GetCreationCmd()->IsEmpty() )
4844 GetCreationCmd()->SetResultValue( myNewID );
4847 //================================================================================
4849 * \brief Return true if all my users can be cleared
4851 //================================================================================
4853 bool _pyObject::CanClear()
4855 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4856 for ( ; cmd != myArgCmds.end(); ++cmd )
4857 if ( !(*cmd)->IsEmpty() )
4859 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4860 if ( !obj.IsNull() && !obj->CanClear() )
4863 return ( !myIsPublished );
4866 //================================================================================
4868 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4870 //================================================================================
4872 _pyHypothesisReader::_pyHypothesisReader()
4875 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4876 LDOMParser xmlParser;
4877 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4879 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4883 INFOS( xmlParser.GetError(data) );
4886 // <algorithm type="Regular_1D"
4887 // label-id="Wire discretisation"
4890 // <algo>Regular_1D=Segment()</algo>
4891 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4893 LDOM_Document xmlDoc = xmlParser.getDocument();
4894 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4895 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4897 LDOM_Node algoNode = algoNodeList.item( i );
4898 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4899 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4900 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4902 _AString text, algoType, method, arg;
4903 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4905 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4906 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4907 text = textNode.getNodeValue();
4908 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4909 algoType = algoCmd->GetResultValue();
4910 method = algoCmd->GetMethod();
4911 arg = algoCmd->GetArg(1);
4912 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4914 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4915 algo->SetConvMethodAndType( method, algoType );
4916 if ( !arg.IsEmpty() )
4917 algo->setCreationArg( 1, arg );
4919 myType2Hyp[ algoType ] = algo;
4923 if ( algoType.IsEmpty() ) continue;
4925 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4927 Handle( _pyHypothesis ) hyp;
4928 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4930 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4931 LDOM_Node textNode = pyHypoNode.getFirstChild();
4932 text = textNode.getNodeValue();
4933 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4934 hypType = hypoCmd->GetResultValue();
4935 method = hypoCmd->GetMethod();
4936 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4938 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4939 if ( type2hyp == myType2Hyp.end() )
4940 hyp = new _pyHypothesis( hypoCmd );
4942 hyp = type2hyp->second;
4943 hyp->SetConvMethodAndType( method, algoType );
4944 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4946 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4947 _AString argMethod = argCmd.GetMethod();
4948 _AString argNbText = argCmd.GetArg( 1 );
4949 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4950 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4952 hyp->AddArgMethod( argMethod,
4953 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4955 myType2Hyp[ hypType ] = hyp;
4959 // <hypothesis type="BLSURF_Parameters"
4963 // <accumulative-methods>
4964 // SetEnforcedVertex,
4965 // SetEnforcedVertexNamed
4966 // </accumulative-methods>
4970 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4971 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4973 LDOM_Node hypNode = hypNodeList.item( i );
4974 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4975 _AString hypType = hypElem.getAttribute("type");
4976 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4977 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4979 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4980 if ( type2hyp == myType2Hyp.end() ) continue;
4982 LDOM_Node methNode = methNodeList.item( 0 );
4983 LDOM_Node textNode = methNode.getFirstChild();
4984 _AString text = textNode.getNodeValue();
4988 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4989 pos += method.Length();
4990 type2hyp->second->AddAccumulativeMethod( method );
4992 while ( !method.IsEmpty() );
4995 } // loop on xmlPaths
4998 //================================================================================
5000 * \brief Returns a new hypothesis initialized according to the read information
5002 //================================================================================
5004 Handle(_pyHypothesis)
5005 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5006 const Handle(_pyCommand)& creationCmd) const
5008 Handle(_pyHypothesis) resHyp, sampleHyp;
5010 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5011 if ( type2hyp != myType2Hyp.end() )
5012 sampleHyp = type2hyp->second;
5014 if ( sampleHyp.IsNull() )
5016 resHyp = new _pyHypothesis(creationCmd);
5020 if ( sampleHyp->IsAlgo() )
5021 resHyp = new _pyAlgorithm( creationCmd );
5023 resHyp = new _pyHypothesis(creationCmd);
5024 resHyp->Assign( sampleHyp, _pyID() );
5029 //================================================================================
5031 * \brief Adds an object ID to some family of IDs with a common prefix
5032 * \param [in] str - the object ID
5033 * \return bool - \c false if \a str does not have the same prefix as \a this family
5034 * (for internal usage)
5036 //================================================================================
5038 bool _pyStringFamily::Add( const char* str )
5040 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5041 return false; // expected prefix is missing
5043 str += _prefix.Length(); // skip _prefix
5045 // try to add to some of child falimies
5046 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5047 for ( ; itSub != _subFams.end(); ++itSub )
5048 if ( itSub->Add( str ))
5051 // no suitable family found - add str to _strings or create a new child family
5053 // look for a proper place within sorted _strings
5054 std::list< _AString >::iterator itStr = _strings.begin();
5055 while ( itStr != _strings.end() && itStr->IsLess( str ))
5057 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5058 return true; // same ID already kept
5060 const int minPrefixSize = 4;
5062 // count "smaller" strings with the same prefix
5064 std::list< _AString >::iterator itLess = itStr;
5065 while ( itLess != _strings.begin() )
5068 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5076 // itLess points to the 1st string with same prefix
5078 // count "greater" strings with the same prefix
5080 std::list< _AString >::iterator itMore = itStr;
5081 for ( ; itMore != _strings.end(); ++itMore )
5082 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5086 // itMore points to the 1st string with greater prefix
5088 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5090 int prefixSize = minPrefixSize;
5091 _AString newPrefix ( str, prefixSize );
5093 // look for a proper place within _subFams sorted by _prefix
5094 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5095 if ( !itSub->_prefix.IsLess( newPrefix ))
5098 // add the new _pyStringFamily
5099 itSub = _subFams.insert( itSub, _pyStringFamily());
5100 _pyStringFamily& newSubFam = *itSub;
5101 newSubFam._prefix = newPrefix;
5103 // pass this->_strings to newSubFam._strings
5104 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5105 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5106 newSubFam._strings.push_back( str + prefixSize );
5107 for ( ; nbMore > 0; --nbMore, ++itStr )
5108 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5110 _strings.erase( itLess, itMore );
5112 else // too few string to make a family for them
5114 _strings.insert( itStr, str );
5119 //================================================================================
5121 * \brief Finds an object ID in the command
5122 * \param [in] longStr - the command string
5123 * \param [out] subStr - the found object ID
5124 * \return bool - \c true if the object ID found
5126 //================================================================================
5128 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5130 const _AString& longStr = cmd->GetString();
5131 const char* s = longStr.ToCString();
5134 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5135 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5136 if ( argBeg < 4 || argBeg > longStr.Length() )
5138 for ( ; itSub != _subFams.end(); ++itSub )
5141 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5142 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5144 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5145 from = pos + len + itSub->_prefix.Length();
5150 from += itSub->_prefix.Length();
5153 // look among _strings
5154 std::list< _AString >::iterator itStr = _strings.begin();
5155 for ( ; itStr != _strings.end(); ++itStr )
5156 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5157 // check that object ID does not continue after len
5158 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5160 subStr.push_back( *itStr );
5166 //================================================================================
5168 * \brief Return remainder length of the object ID after my _prefix
5169 * \param [in] str - remainder of the command after my _prefix
5170 * \return int - length of the object ID or -1 if not found
5172 //================================================================================
5174 int _pyStringFamily::isIn( const char* str )
5176 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5178 for ( ; itSub != _subFams.end(); ++itSub )
5180 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5183 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5184 return itSub->_prefix.Length() + len;
5189 if ( !_strings.empty() )
5191 std::list< _AString >::iterator itStr = _strings.begin();
5192 bool firstEmpty = itStr->IsEmpty();
5195 for ( ; itStr != _strings.end(); ++itStr )
5197 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5200 len = itStr->Length();
5209 // check that object ID does not continue after len
5210 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5217 //================================================================================
5221 //================================================================================
5223 void _pyStringFamily::Print( int level )
5225 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5226 std::list< _AString >::iterator itStr = _strings.begin();
5227 for ( ; itStr != _strings.end(); ++itStr )
5228 cout << *itStr << " | ";
5230 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5231 for ( ; itSub != _subFams.end(); ++itSub )
5232 itSub->Print( level + 1 );
5234 cout << string( 70, '-' ) << endl;