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 need 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) >::reverse_iterator cmd = cmdList.rbegin();
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<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3162 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3164 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3165 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3166 if ( cmdIt != cmds.end() )
3168 if ( cmds.back() != *cmd )
3170 cmds.erase( cmdIt );
3177 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3180 //================================================================================
3182 * \brief Sets an argNb-th argument of current creation command
3183 * \param argNb - argument index countered from 1
3185 //================================================================================
3187 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3189 if ( myCurCrMethod )
3191 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3192 myCurCrMethod->myArgs.push_back( "None" );
3193 if ( arg.IsEmpty() )
3194 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3196 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3201 //================================================================================
3203 * \brief Remember hypothesis parameter values
3204 * \param theCommand - The called hypothesis method
3206 //================================================================================
3208 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3210 if ( GetAlgoType() == "Cartesian_3D" )
3212 // CartesianParameters3D hyp
3214 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3215 theCommand->GetMethod() == "SetToAddEdges" )
3217 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3218 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3219 myArgCommands.push_back( theCommand );
3222 if ( theCommand->GetMethod() == "SetGrid" ||
3223 theCommand->GetMethod() == "SetGridSpacing" )
3225 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3226 int iArg = axis.Value(1) - '0';
3227 if ( theCommand->GetMethod() == "SetGrid" )
3229 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3233 myCurCrMethod->myArgs[ iArg ] = "[ ";
3234 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3235 myCurCrMethod->myArgs[ iArg ] += ", ";
3236 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3237 myCurCrMethod->myArgs[ iArg ] += "]";
3239 myArgCommands.push_back( theCommand );
3240 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3241 // accumulative, else, if the creation
3242 // is not converted, commands for axes 1 and 2 are lost
3247 if( theCommand->GetMethod() == "SetLength" )
3249 // NOW it is OBSOLETE
3250 // ex: hyp.SetLength(start, 1)
3251 // hyp.SetLength(end, 0)
3252 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3253 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3254 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3255 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3257 CreationMethod& crMethod = type2meth->second;
3258 while ( (int) crMethod.myArgs.size() < i+1 )
3259 crMethod.myArgs.push_back( "[]" );
3260 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3262 myArgCommands.push_back( theCommand );
3266 _pyHypothesis::Process( theCommand );
3269 //================================================================================
3271 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3273 //================================================================================
3275 void _pyComplexParamHypo::Flush()
3277 list < Handle(_pyCommand) >::iterator cmd;
3280 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3281 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3285 // if ( GetAlgoType() == "Cartesian_3D" )
3287 // _pyID algo = myCreationCmd->GetObject();
3288 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3290 // if ( IsWrapped() )
3292 // StructToList( *cmd, /*checkMethod=*/false );
3293 // const _AString & method = (*cmd)->GetMethod();
3294 // if ( method == "SetFixedPoint" )
3295 // (*cmd)->SetObject( algo );
3301 //================================================================================
3303 * \brief Convert methods of 1D hypotheses to my own methods
3304 * \param theCommand - The called hypothesis method
3306 //================================================================================
3308 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3310 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3313 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3314 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3315 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3317 // TCollection_AsciiString cmd =
3318 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3319 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3320 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3323 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3325 // // 1D hypo is already set, so distribution changes and the old
3326 // // 1D hypo is thrown away
3327 // my1dHyp->ClearAllCommands();
3330 // //my1dHyp->SetRemovedFromStudy( false );
3332 // if ( !myArgCommands.empty() )
3333 // myArgCommands.back()->Clear();
3334 myCurCrMethod->myArgs.push_back( hyp1dID );
3335 myArgCommands.push_back( theCommand );
3338 //================================================================================
3341 * \param theAdditionCmd - command to be converted
3342 * \param theMesh - mesh instance
3343 * \retval bool - status
3345 //================================================================================
3347 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3348 const _pyID& theMesh)
3350 myIsWrapped = false;
3352 if ( my1dHyp.IsNull() )
3355 // set "SetLayerDistribution()" after addition cmd
3356 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3358 _pyID geom = theAdditionCmd->GetArg( 1 );
3360 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3361 if ( !algo.IsNull() )
3363 my1dHyp->SetMesh( theMesh );
3364 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3365 algo->GetAlgoType().ToCString());
3366 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3369 // clear "SetLayerDistribution()" cmd
3370 myArgCommands.back()->Clear();
3372 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3374 // find RadialPrism algo created on <geom> for theMesh
3375 GetCreationCmd()->SetObject( algo->GetID() );
3376 GetCreationCmd()->SetMethod( myAlgoMethod );
3377 GetCreationCmd()->RemoveArgs();
3378 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3384 //================================================================================
3388 //================================================================================
3390 void _pyLayerDistributionHypo::Flush()
3392 // as creation of 1D hyp was written later then it's edition,
3393 // we need to find all it's edition calls and process them
3394 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3396 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3398 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3399 if ( hyp1dID.IsEmpty() ) continue;
3401 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3403 // make a new name for 1D hyp = "HypType" + "_Distribution"
3405 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3407 if ( prevNewName.IsEmpty() ) continue;
3408 newName = prevNewName;
3412 if ( hyp1d->IsWrapped() ) {
3413 newName = hyp1d->GetCreationCmd()->GetMethod();
3416 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3417 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3419 newName += "_Distribution";
3420 prevNewName = newName;
3422 hyp1d->GetCreationCmd()->SetResultValue( newName );
3424 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3425 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3426 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3427 const _pyID& objID = (*cmdIt)->GetObject();
3428 if ( objID == hyp1dID ) {
3429 if ( !hyp1d.IsNull() )
3431 hyp1d->Process( *cmdIt );
3432 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3434 ( *cmdIt )->SetObject( newName );
3437 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3438 (*cmd)->SetArg( 1, newName );
3442 //================================================================================
3444 * \brief additionally to Addition2Creation, clears SetDistrType() command
3445 * \param theCmd - AddHypothesis() command
3446 * \param theMesh - mesh to which a hypothesis is added
3447 * \retval bool - conversion result
3449 //================================================================================
3451 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3452 const _pyID& theMesh)
3454 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3455 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3456 bool scaleDistrType = false;
3457 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3458 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3459 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3460 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3461 scaleDistrType = true;
3464 else if ( !scaleDistrType ) {
3465 // distribution type changed: remove scale factor from args
3466 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3467 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3469 CreationMethod& crMethod = type2meth->second;
3470 if ( crMethod.myArgs.size() == 2 )
3471 crMethod.myArgs.pop_back();
3478 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3481 //================================================================================
3483 * \brief remove repeated commands defining distribution
3485 //================================================================================
3487 void _pyNumberOfSegmentsHyp::Flush()
3489 // find number of the last SetDistrType() command
3490 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3491 int distrTypeNb = 0;
3492 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3493 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3494 if ( cmd != myUnusedCommands.rbegin() )
3495 distrTypeNb = (*cmd)->GetOrderNb();
3497 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3500 // clear commands before the last SetDistrType()
3501 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3502 set< int > treatedCmdNbs; // avoid treating same cmd twice
3503 for ( int i = 0; i < 2; ++i ) {
3504 set<TCollection_AsciiString> uniqueMethods;
3505 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3506 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3508 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3509 continue;// avoid treating same cmd twice
3510 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3511 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3512 if ( !clear || method == "SetNumberOfSegments" ) {
3513 bool isNewInSet = uniqueMethods.insert( method ).second;
3514 clear = !isNewInSet;
3523 //================================================================================
3525 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3526 * into regular1D.LengthNearVertex( length, vertex )
3527 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3528 * \param theMesh - The mesh needing this hypo
3529 * \retval bool - false if the command can't be converted
3531 //================================================================================
3533 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3534 const _pyID& theMeshID)
3536 if ( IsWrappable( theMeshID )) {
3538 _pyID vertex = theCmd->GetArg( 1 );
3540 // the problem here is that segment algo can be not found
3541 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3542 // geometry where segment algorithm is assigned
3543 _pyID geom = vertex;
3544 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3545 while ( algo.IsNull() && !geom.IsEmpty()) {
3546 // try to find geom as a father of <vertex>
3547 geom = FatherID( geom );
3548 algo = theGen->FindAlgo( geom, theMeshID, this );
3550 if ( algo.IsNull() || geom.IsEmpty() )
3551 return false; // also possible to find geom as brother of veretex...
3553 // set geom instead of vertex
3554 theCmd->SetArg( 1, geom );
3556 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3557 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3558 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3560 // set vertex as a second arg
3561 theCmd->SetArg( 2, vertex );
3569 //================================================================================
3571 * \brief _pyAlgorithm constructor
3572 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3574 //================================================================================
3576 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3577 : _pyHypothesis( theCreationCmd )
3582 //================================================================================
3584 * \brief Convert the command adding an algorithm to mesh
3585 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3586 * \param theMesh - The mesh needing this algo
3587 * \retval bool - false if the command can't be converted
3589 //================================================================================
3591 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3592 const _pyID& theMeshID)
3594 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3595 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3596 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3602 //================================================================================
3604 * \brief Return starting position of a part of python command
3605 * \param thePartIndex - The index of command part
3606 * \retval int - Part position
3608 //================================================================================
3610 int _pyCommand::GetBegPos( int thePartIndex ) const
3614 if ( myBegPos.Length() < thePartIndex )
3616 ASSERT( thePartIndex > 0 );
3617 return myBegPos( thePartIndex );
3620 //================================================================================
3622 * \brief Store starting position of a part of python command
3623 * \param thePartIndex - The index of command part
3624 * \param thePosition - Part position
3626 //================================================================================
3628 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3630 while ( myBegPos.Length() < thePartIndex )
3631 myBegPos.Append( UNKNOWN );
3632 ASSERT( thePartIndex > 0 );
3633 myBegPos( thePartIndex ) = thePosition;
3636 //================================================================================
3638 * \brief Returns whitespace symbols at the line beginning
3639 * \retval TCollection_AsciiString - result
3641 //================================================================================
3643 TCollection_AsciiString _pyCommand::GetIndentation()
3646 //while ( end <= Length() && isblank( myString.Value( end )))
3647 //ANA: isblank() function isn't provided in VC2010 compiler
3648 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3650 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3653 //================================================================================
3655 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3656 * \retval const TCollection_AsciiString & - ResultValue substring
3658 //================================================================================
3660 const TCollection_AsciiString & _pyCommand::GetResultValue()
3662 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3664 SetBegPos( RESULT_IND, EMPTY );
3665 int begPos, endPos = myString.Location( "=", 1, Length() );
3669 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3670 if ( begPos < endPos )
3672 SetBegPos( RESULT_IND, begPos );
3674 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3675 myRes = myString.SubString( begPos, endPos );
3682 //================================================================================
3684 * \brief Return number of python command result value ResultValue = Obj.Meth()
3686 //================================================================================
3688 int _pyCommand::GetNbResultValues()
3691 return myResults.Length();
3695 //================================================================================
3697 * \brief Return substring of python command looking like
3698 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3699 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3701 //================================================================================
3702 const _AString& _pyCommand::GetResultValue(int res)
3704 if ( GetResultValue().IsEmpty() )
3705 return theEmptyString;
3707 if ( myResults.IsEmpty() )
3710 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3711 ++begPos; // skip [, else the whole list is returned
3712 while ( begPos < myRes.Length() ) {
3713 _AString result = GetWord( myRes, begPos, true );
3714 begPos += result.Length();
3716 // result.RemoveAll('[');
3717 // result.RemoveAll(']');
3722 myResults.Append( result );
3725 if ( res > 0 && res <= myResults.Length() )
3726 return myResults( res );
3727 return theEmptyString;
3730 //================================================================================
3732 * \brief Return substring of python command looking like ResVal = Object.Meth()
3733 * \retval const TCollection_AsciiString & - Object substring
3735 //================================================================================
3737 const TCollection_AsciiString & _pyCommand::GetObject()
3739 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3742 int begPos = GetBegPos( RESULT_IND );
3744 begPos = myString.Location( "=", 1, Length() ) + 1;
3745 // is '=' in the string argument (for example, name) or not
3746 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3747 for ( int i = 1; i < begPos-1; i++ )
3748 switch ( myString.Value( i )) {
3749 case '\'': nb[0]++; break;
3750 case '"' : nb[1]++; break;
3751 case '(' : nb[2]++; break;
3752 case ')' : nb[3]++; break;
3754 // if = is inside a string or a list
3755 // then get an object at the start of the command
3756 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3760 begPos += myRes.Length();
3762 myObj = GetWord( myString, begPos, true );
3763 if ( begPos != EMPTY )
3765 // check if object is complex,
3766 // so far consider case like "smesh.Method()"
3767 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3768 //if ( bracketPos==0 ) bracketPos = Length();
3769 int dotPos = begPos+myObj.Length();
3770 while ( dotPos+1 < bracketPos ) {
3771 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3776 if ( dotPos > begPos+myObj.Length() )
3777 myObj = myString.SubString( begPos, dotPos-1 );
3780 // 1st word after '=' is an object
3781 // else // no method -> no object
3787 SetBegPos( OBJECT_IND, begPos );
3793 //================================================================================
3795 * \brief Return substring of python command looking like ResVal = Obj.Method()
3796 * \retval const TCollection_AsciiString & - Method substring
3798 //================================================================================
3800 const TCollection_AsciiString & _pyCommand::GetMethod()
3802 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3805 int begPos = GetBegPos( OBJECT_IND );
3806 bool forward = true;
3808 begPos = myString.Location( "(", 1, Length() ) - 1;
3812 begPos += myObj.Length();
3815 myMeth = GetWord( myString, begPos, forward );
3816 SetBegPos( METHOD_IND, begPos );
3822 //================================================================================
3824 * \brief Returns true if there are brackets after the method
3826 //================================================================================
3828 bool _pyCommand::IsMethodCall()
3830 if ( GetMethod().IsEmpty() )
3832 if ( myString.StartsWith("#") )
3834 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3835 return ( s[0] == '(' || s[1] == '(' );
3838 //================================================================================
3840 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3841 * \retval const TCollection_AsciiString & - Arg<index> substring
3843 //================================================================================
3845 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3847 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3851 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3853 pos = myString.Location( "(", 1, Length() );
3857 // we are at or before '(', skip it if present
3859 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3860 if ( pos > Length() )
3864 SetBegPos( ARG1_IND, 0 ); // even no '('
3865 return theEmptyString;
3869 list< TCollection_AsciiString > separatorStack( 1, ",)");
3870 bool ignoreNesting = false;
3872 while ( pos <= Length() )
3874 const char chr = myString.Value( pos );
3876 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3878 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3880 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3882 TCollection_AsciiString arg;
3883 if ( pos-1 >= prevPos ) {
3884 arg = myString.SubString( prevPos, pos-1 );
3885 arg.RightAdjust(); // remove spaces
3888 if ( !arg.IsEmpty() || chr == ',' )
3890 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3891 myArgs.Append( arg );
3897 else // end of nesting args found
3899 separatorStack.pop_back();
3900 ignoreNesting = false;
3903 else if ( !ignoreNesting )
3906 case '(' : separatorStack.push_back(")"); break;
3907 case '[' : separatorStack.push_back("]"); break;
3908 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3909 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3916 if ( myArgs.Length() < index )
3917 return theEmptyString;
3918 return myArgs( index );
3921 //================================================================================
3923 * \brief Return position where arguments begin
3925 //================================================================================
3927 int _pyCommand::GetArgBeginning() const
3929 int pos = GetBegPos( ARG1_IND );
3930 if ( pos == UNKNOWN )
3932 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3934 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3939 //================================================================================
3941 * \brief Check if char is a word part
3942 * \param c - The character to check
3943 * \retval bool - The check result
3945 //================================================================================
3947 static inline bool isWord(const char c, const bool dotIsWord)
3950 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3953 //================================================================================
3955 * \brief Looks for a word in the string and returns word's beginning
3956 * \param theString - The input string
3957 * \param theStartPos - The position to start the search, returning word's beginning
3958 * \param theForward - The search direction
3959 * \retval TCollection_AsciiString - The found word
3961 //================================================================================
3963 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3965 const bool theForward,
3966 const bool dotIsWord )
3968 int beg = theStartPos, end = theStartPos;
3969 theStartPos = EMPTY;
3970 if ( beg < 1 || beg > theString.Length() )
3971 return theEmptyString;
3973 if ( theForward ) { // search forward
3975 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3977 if ( beg > theString.Length() )
3978 return theEmptyString; // no word found
3981 char begChar = theString.Value( beg );
3982 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3983 char endChar = ( begChar == '[' ) ? ']' : begChar;
3984 // end is at the corresponding quoting mark or bracket
3985 while ( end < theString.Length() &&
3986 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3990 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3995 else { // search backward
3997 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4000 return theEmptyString; // no word found
4002 char endChar = theString.Value( end );
4003 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4004 char begChar = ( endChar == ']' ) ? '[' : endChar;
4005 // beg is at the corresponding quoting mark
4007 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4011 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4017 //cout << theString << " ---- " << beg << " - " << end << endl;
4018 return theString.SubString( beg, end );
4021 //================================================================================
4023 * \brief Returns true if the string looks like a study entry
4025 //================================================================================
4027 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4029 if ( str.Length() < 5 ) return false;
4031 int nbColons = 0, isColon;
4032 for ( int i = 1; i <= str.Length(); ++i )
4034 char c = str.Value(i);
4035 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4037 nbColons += isColon;
4039 return nbColons > 2 && str.Length()-nbColons > 2;
4042 //================================================================================
4044 * \brief Returns true if the string looks like an object ID but not like a list,
4045 * string, command etc.
4047 //================================================================================
4049 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4051 if ( str.Length() < 1 ) return false;
4053 const char* s = str.ToCString();
4055 for ( int i = 0; i < str.Length(); ++i )
4056 if ( !IsIDChar( s[i] ))
4062 //================================================================================
4064 * \brief Finds entries in a string
4066 //================================================================================
4068 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4070 std::list< _pyID > resList;
4072 while ( ++pos <= str.Length() )
4074 if ( !isdigit( str.Value( pos ))) continue;
4075 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4078 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4079 _pyID entry = str.SubString( pos, end-1 );
4081 if ( IsStudyEntry( entry ))
4082 resList.push_back( entry );
4087 //================================================================================
4089 * \brief Look for position where not space char is
4090 * \param theString - The string
4091 * \param thePos - The position to search from and which returns result
4092 * \retval bool - false if there are only space after thePos in theString
4094 //================================================================================
4096 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4098 if ( thePos < 1 || thePos > theString.Length() )
4101 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4104 return thePos <= theString.Length();
4107 //================================================================================
4109 * \brief Modify a part of the command
4110 * \param thePartIndex - The index of the part
4111 * \param thePart - The new part string
4112 * \param theOldPart - The old part
4114 //================================================================================
4116 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4117 TCollection_AsciiString& theOldPart)
4119 int pos = GetBegPos( thePartIndex );
4120 if ( pos <= Length() && theOldPart != thePart)
4122 TCollection_AsciiString seperator;
4124 pos = GetBegPos( thePartIndex + 1 );
4125 if ( pos < 1 ) return;
4126 switch ( thePartIndex ) {
4127 case RESULT_IND: seperator = " = "; break;
4128 case OBJECT_IND: seperator = "."; break;
4129 case METHOD_IND: seperator = "()"; break;
4133 myString.Remove( pos, theOldPart.Length() );
4134 if ( !seperator.IsEmpty() )
4135 myString.Insert( pos , seperator );
4136 myString.Insert( pos, thePart );
4137 // update starting positions of the following parts
4138 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4139 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4140 if ( myBegPos( i ) > 0 )
4141 myBegPos( i ) += posDelta;
4143 theOldPart = thePart;
4147 //================================================================================
4149 * \brief Set argument
4150 * \param index - The argument index, it counts from 1
4151 * \param theArg - The argument string
4153 //================================================================================
4155 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4158 int argInd = ARG1_IND + index - 1;
4159 int pos = GetBegPos( argInd );
4160 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4162 // find a closing parenthesis
4163 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4164 int lastArgInd = GetNbArgs();
4165 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4166 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4171 while ( pos > 0 && myString.Value( pos ) != ')' )
4174 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4178 while ( myArgs.Length() < index ) {
4179 if ( myArgs.Length() )
4180 myString.Insert( pos++, "," );
4181 myArgs.Append("None");
4182 myString.Insert( pos, myArgs.Last() );
4183 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4184 pos += myArgs.Last().Length();
4187 SetPart( argInd, theArg, myArgs( index ));
4190 //================================================================================
4192 * \brief Empty arg list
4194 //================================================================================
4196 void _pyCommand::RemoveArgs()
4198 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4199 myString.Trunc( pos );
4202 if ( myBegPos.Length() >= ARG1_IND )
4203 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4206 //================================================================================
4208 * \brief Comment a python command
4210 //================================================================================
4212 void _pyCommand::Comment()
4214 if ( IsEmpty() ) return;
4217 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4218 if ( i <= Length() )
4220 myString.Insert( i, "#" );
4221 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4223 int begPos = GetBegPos( iPart );
4224 if ( begPos != UNKNOWN && begPos != EMPTY )
4225 SetBegPos( iPart, begPos + 1 );
4230 //================================================================================
4232 * \brief Set dependent commands after this one
4234 //================================================================================
4236 bool _pyCommand::SetDependentCmdsAfter() const
4238 bool orderChanged = false;
4239 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4240 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4241 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4242 orderChanged = true;
4243 theGen->SetCommandAfter( *cmd, this );
4244 (*cmd)->SetDependentCmdsAfter();
4247 return orderChanged;
4249 //================================================================================
4251 * \brief Insert accessor method after theObjectID
4252 * \param theObjectID - id of the accessed object
4253 * \param theAcsMethod - name of the method giving access to the object
4254 * \retval bool - false if theObjectID is not found in the command string
4256 //================================================================================
4258 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4260 if ( !theAcsMethod )
4262 // start object search from the object, i.e. ignore result
4264 int beg = GetBegPos( OBJECT_IND );
4265 if ( beg < 1 || beg > Length() )
4268 while (( beg = myString.Location( theObjectID, beg, Length() )))
4270 // check that theObjectID is not just a part of a longer ID
4271 int afterEnd = beg + theObjectID.Length();
4272 Standard_Character c = myString.Value( afterEnd );
4273 if ( !IsIDChar( c ))
4275 // check if accessor method already present
4277 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4279 int oldLen = Length();
4280 myString.Insert( afterEnd, (char*) theAcsMethod );
4281 myString.Insert( afterEnd, "." );
4282 // update starting positions of the parts following the modified one
4283 int posDelta = Length() - oldLen;
4284 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4285 if ( myBegPos( i ) > afterEnd )
4286 myBegPos( i ) += posDelta;
4291 beg = afterEnd; // is a part -> next search
4296 //================================================================================
4298 * \brief Creates pyObject
4300 //================================================================================
4302 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4303 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4308 //================================================================================
4310 * \brief Set up myID and myIsPublished
4312 //================================================================================
4314 void _pyObject::setID(const _pyID& theID)
4317 myIsPublished = !theGen->IsNotPublished( GetID() );
4320 //================================================================================
4322 * \brief Clear myCreationCmd and myProcessedCmds
4324 //================================================================================
4326 void _pyObject::ClearCommands()
4331 if ( !myCreationCmd.IsNull() )
4332 myCreationCmd->Clear();
4334 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4335 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4339 //================================================================================
4341 * \brief Return method name giving access to an interaface object wrapped by python class
4342 * \retval const char* - method name
4344 //================================================================================
4346 const char* _pyObject::AccessorMethod() const
4350 //================================================================================
4352 * \brief Return ID of a father
4354 //================================================================================
4356 _pyID _pyObject::FatherID(const _pyID & childID)
4358 int colPos = childID.SearchFromEnd(':');
4360 return childID.SubString( 1, colPos-1 );
4364 //================================================================================
4366 * \brief SelfEraser erases creation command if none of it's commands invoked
4367 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4369 //================================================================================
4371 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4372 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4374 myIsPublished = true; // prevent clearing as a not published
4375 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4378 //================================================================================
4380 * \brief SelfEraser erases creation command if none of it's commands invoked
4381 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4383 //================================================================================
4385 bool _pySelfEraser::CanClear()
4387 bool toErase = false;
4388 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4391 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4392 for ( ; cmd != myArgCmds.end(); ++cmd )
4393 nbArgUses += IsAliveCmd( *cmd );
4395 toErase = ( nbArgUses < 1 );
4400 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4401 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4402 for ( ; cmd != cmds.end(); )
4403 // check of cmd emptiness is not enough as object can change
4404 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4407 cmd = cmds.erase( cmd ); // save the cmd from clearing
4409 toErase = ( nbCalls < 1 );
4414 //================================================================================
4416 * \brief Check if a command is or can be cleared
4418 //================================================================================
4420 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4422 if ( theCmd->IsEmpty() )
4425 if ( !theGen->IsToKeepAllCommands() )
4427 const _pyID& objID = theCmd->GetObject();
4428 Handle( _pyObject ) obj = theGen->FindObject( objID );
4429 if ( !obj.IsNull() )
4430 return !obj->CanClear();
4435 //================================================================================
4437 * \brief SelfEraser erases creation command if none of it's commands invoked
4438 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4440 //================================================================================
4442 void _pySelfEraser::Flush()
4446 myIsPublished = false;
4447 _pyObject::ClearCommands();
4451 //================================================================================
4453 * \brief _pySubMesh constructor
4455 //================================================================================
4457 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4458 _pyObject(theCreationCmd)
4460 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4461 if ( toKeepAgrCmds )
4462 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4465 //================================================================================
4467 * \brief Return true if a sub-mesh can be used as argument of the given method
4469 //================================================================================
4471 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4474 // names of all methods where a sub-mesh can be used as argument
4475 // static TStringSet methods;
4476 // if ( methods.empty() ) {
4477 // const char * names[] = {
4478 // // methods of SMESH_Gen
4480 // // methods of SMESH_Group
4482 // // methods of SMESH_Measurements
4484 // // methods of SMESH_Mesh
4485 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4487 // // methods of SMESH_MeshEditor
4488 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4489 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4490 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4491 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4492 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4493 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4494 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4495 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4496 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4497 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4498 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4499 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4500 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4501 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4502 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4503 // "" }; // <- mark of end
4504 // methods.Insert( names );
4506 // return methods.Contains( theMethodName );
4509 //================================================================================
4511 * \brief count invoked commands
4513 //================================================================================
4515 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4517 _pyObject::Process(theCommand); // count calls of Process()
4520 //================================================================================
4522 * \brief Move creation command depending on invoked commands
4524 //================================================================================
4526 void _pySubMesh::Flush()
4528 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4529 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4530 else if ( !myCreator.IsNull() )
4531 // move to be just after creator
4532 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4534 // move sub-mesh usage after creation cmd
4535 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4536 for ( ; cmd != myArgCmds.end(); ++cmd )
4537 if ( !(*cmd)->IsEmpty() )
4538 GetCreationCmd()->AddDependantCmd( *cmd );
4541 //================================================================================
4543 * \brief Creates _pyGroup
4545 //================================================================================
4547 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4548 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4550 if ( !id.IsEmpty() )
4553 myCanClearCreationCmd = true;
4555 const _AString& method = theCreationCmd->GetMethod();
4556 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4558 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4560 // ----------------------------------------------------------------------
4561 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4563 _pyID geom = theCreationCmd->GetArg( 3 );
4564 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4565 // next if(){...} section is commented
4566 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4567 // theCreationCmd->SetMethod( "Group" );
4568 // theCreationCmd->RemoveArgs();
4569 // theCreationCmd->SetArg( 1, geom );
4572 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4573 _pyID type = theCreationCmd->GetArg( 1 );
4574 _pyID name = theCreationCmd->GetArg( 2 );
4575 theCreationCmd->SetMethod( "GroupOnGeom" );
4576 theCreationCmd->RemoveArgs();
4577 theCreationCmd->SetArg( 1, geom );
4578 theCreationCmd->SetArg( 2, name );
4579 theCreationCmd->SetArg( 3, type );
4582 else if ( method == "CreateGroupFromFilter" )
4584 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4585 theCreationCmd->SetMethod( "GroupOnFilter" );
4587 _pyID filterID = theCreationCmd->GetArg(3);
4588 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4589 if ( !filter.IsNull())
4591 if ( !filter->GetNewID().IsEmpty() )
4592 theCreationCmd->SetArg( 3, filter->GetNewID() );
4593 //filter->AddUser( this );
4597 else if ( method == "GetGroups" )
4599 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4603 // theCreationCmd does something else apart from creation of this group
4604 // and thus it can't be cleared if this group is removed
4605 myCanClearCreationCmd = false;
4609 //================================================================================
4611 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4614 //================================================================================
4616 bool _pyGroup::CanClear()
4621 if ( !myCanClearCreationCmd &&
4622 !myCreationCmd.IsNull() &&
4623 myCreationCmd->GetMethod() == "GetGroups" )
4625 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4626 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4627 list< _pyID >::iterator grID = idList.begin();
4628 if ( GetID() == *grID )
4630 myCanClearCreationCmd = true;
4631 list< Handle(_pyGroup ) > groups;
4632 for ( ; grID != idList.end(); ++grID )
4634 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4635 if ( group.IsNull() ) continue;
4636 groups.push_back( group );
4637 if ( group->IsInStudy() )
4638 myCanClearCreationCmd = false;
4640 // set myCanClearCreationCmd == true to all groups
4641 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4642 for ( ; group != groups.end(); ++group )
4643 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4647 return myCanClearCreationCmd;
4650 //================================================================================
4652 * \brief set myCanClearCreationCmd = true if the main action of the creation
4653 * command is discarded
4655 //================================================================================
4657 void _pyGroup::RemovedWithContents()
4659 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4660 // via a created group
4661 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4662 // myCanClearCreationCmd = true;
4665 //================================================================================
4667 * \brief To convert creation of a group by filter
4669 //================================================================================
4671 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4673 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4674 // group = mesh.CreateEmptyGroup( elemType, groupName )
4675 // aFilter.SetMesh(mesh)
4676 // nbAdd = group.AddFrom( aFilter )
4677 Handle(_pyFilter) filter;
4678 if ( theCommand->GetMethod() == "AddFrom" )
4680 _pyID idSource = theCommand->GetArg(1);
4681 // check if idSource is a filter
4682 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4683 if ( !filter.IsNull() )
4685 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4686 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4687 while ( *cmdIt != theCommand ) ++cmdIt;
4688 while ( (*cmdIt)->GetOrderNb() != 1 )
4690 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4691 if ((setMeshCmd->GetObject() == idSource ||
4692 setMeshCmd->GetObject() == filter->GetNewID() )
4694 setMeshCmd->GetMethod() == "SetMesh")
4696 setMeshCmd->Clear();
4700 // replace 3 commands by one
4701 theCommand->Clear();
4702 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4703 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4704 if ( !filter->GetNewID().IsEmpty() )
4705 idSource = filter->GetNewID();
4706 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4707 makeGroupCmd->SetArg( 1, name );
4708 makeGroupCmd->SetArg( 2, idSource );
4709 filter->AddArgCmd( makeGroupCmd );
4712 else if ( theCommand->GetMethod() == "SetFilter" )
4714 // set new name of a filter or clear the command if the same filter is set
4715 _pyID filterID = theCommand->GetArg(1);
4716 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4717 if ( !myFilter.IsNull() && filter == myFilter )
4718 theCommand->Clear();
4719 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4720 theCommand->SetArg( 1, filter->GetNewID() );
4723 else if ( theCommand->GetMethod() == "GetFilter" )
4725 // GetFilter() returns a filter with other ID, make myFilter process
4726 // calls of the returned filter
4727 if ( !myFilter.IsNull() )
4729 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4730 theCommand->Clear();
4734 // if ( !filter.IsNull() )
4735 // filter->AddUser( this );
4737 theGen->AddMeshAccessorMethod( theCommand );
4740 //================================================================================
4742 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4744 //================================================================================
4746 void _pyGroup::Flush()
4748 if ( !theGen->IsToKeepAllCommands() &&
4749 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4751 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4755 //================================================================================
4757 * \brief Constructor of _pyFilter
4759 //================================================================================
4761 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4762 :_pyObject(theCreationCmd), myNewID( newID )
4764 //myIsPublished = true; // prevent clearing as a not published
4765 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4768 //================================================================================
4770 * \brief To convert creation of a filter by criteria and
4771 * to replace an old name by a new one
4773 //================================================================================
4775 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4777 if ( theCommand->GetObject() == GetID() )
4778 _pyObject::Process(theCommand); // count commands
4780 if ( !myNewID.IsEmpty() )
4781 theCommand->SetObject( myNewID );
4783 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4784 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4785 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4786 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4787 theCommand->GetMethod() == "SetCriteria")
4789 // aFilter.SetCriteria(aCriteria) ->
4790 // aFilter = smesh.GetFilterFromCriteria(criteria)
4791 if ( myNewID.IsEmpty() )
4792 theCommand->SetResultValue( GetID() );
4794 theCommand->SetResultValue( myNewID );
4795 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4796 theCommand->SetMethod( "GetFilterFromCriteria" );
4798 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4799 GetCreationCmd()->Clear();
4800 GetCreationCmd()->GetString() = theCommand->GetString();
4801 theCommand->Clear();
4802 theCommand->AddDependantCmd( GetCreationCmd() );
4803 // why swap? -- it's needed
4804 //GetCreationCmd()->Clear();
4806 else if ( theCommand->GetMethod() == "SetMesh" )
4808 if ( myMesh == theCommand->GetArg( 1 ))
4809 theCommand->Clear();
4811 myMesh = theCommand->GetArg( 1 );
4812 theGen->AddMeshAccessorMethod( theCommand );
4816 //================================================================================
4818 * \brief Set new filter name to the creation command and to myArgCmds
4820 //================================================================================
4822 void _pyFilter::Flush()
4824 if ( myNewID.IsEmpty() ) return;
4826 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4827 for ( ; cmd != myArgCmds.end(); ++cmd )
4828 if ( !(*cmd)->IsEmpty() )
4830 _AString cmdStr = (*cmd)->GetString();
4831 _AString id = GetID();
4832 int pos = cmdStr.Search( id );
4835 cmdStr.Remove( pos, id.Length() );
4836 cmdStr.Insert( pos, myNewID );
4839 (*cmd)->GetString() = cmdStr;
4842 if ( !GetCreationCmd()->IsEmpty() )
4843 GetCreationCmd()->SetResultValue( myNewID );
4846 //================================================================================
4848 * \brief Return true if all my users can be cleared
4850 //================================================================================
4852 bool _pyObject::CanClear()
4854 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4855 for ( ; cmd != myArgCmds.end(); ++cmd )
4856 if ( !(*cmd)->IsEmpty() )
4858 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4859 if ( !obj.IsNull() && !obj->CanClear() )
4862 return ( !myIsPublished );
4865 //================================================================================
4867 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4869 //================================================================================
4871 _pyHypothesisReader::_pyHypothesisReader()
4874 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4875 LDOMParser xmlParser;
4876 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4878 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4882 INFOS( xmlParser.GetError(data) );
4885 // <algorithm type="Regular_1D"
4886 // label-id="Wire discretisation"
4889 // <algo>Regular_1D=Segment()</algo>
4890 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4892 LDOM_Document xmlDoc = xmlParser.getDocument();
4893 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4894 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4896 LDOM_Node algoNode = algoNodeList.item( i );
4897 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4898 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4899 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4901 _AString text, algoType, method, arg;
4902 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4904 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4905 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4906 text = textNode.getNodeValue();
4907 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4908 algoType = algoCmd->GetResultValue();
4909 method = algoCmd->GetMethod();
4910 arg = algoCmd->GetArg(1);
4911 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4913 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4914 algo->SetConvMethodAndType( method, algoType );
4915 if ( !arg.IsEmpty() )
4916 algo->setCreationArg( 1, arg );
4918 myType2Hyp[ algoType ] = algo;
4922 if ( algoType.IsEmpty() ) continue;
4924 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4926 Handle( _pyHypothesis ) hyp;
4927 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4929 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4930 LDOM_Node textNode = pyHypoNode.getFirstChild();
4931 text = textNode.getNodeValue();
4932 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4933 hypType = hypoCmd->GetResultValue();
4934 method = hypoCmd->GetMethod();
4935 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4937 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4938 if ( type2hyp == myType2Hyp.end() )
4939 hyp = new _pyHypothesis( hypoCmd );
4941 hyp = type2hyp->second;
4942 hyp->SetConvMethodAndType( method, algoType );
4943 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4945 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4946 _AString argMethod = argCmd.GetMethod();
4947 _AString argNbText = argCmd.GetArg( 1 );
4948 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4949 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4951 hyp->AddArgMethod( argMethod,
4952 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4954 myType2Hyp[ hypType ] = hyp;
4958 // <hypothesis type="BLSURF_Parameters"
4962 // <accumulative-methods>
4963 // SetEnforcedVertex,
4964 // SetEnforcedVertexNamed
4965 // </accumulative-methods>
4969 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4970 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4972 LDOM_Node hypNode = hypNodeList.item( i );
4973 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4974 _AString hypType = hypElem.getAttribute("type");
4975 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4976 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4978 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4979 if ( type2hyp == myType2Hyp.end() ) continue;
4981 LDOM_Node methNode = methNodeList.item( 0 );
4982 LDOM_Node textNode = methNode.getFirstChild();
4983 _AString text = textNode.getNodeValue();
4987 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4988 pos += method.Length();
4989 type2hyp->second->AddAccumulativeMethod( method );
4991 while ( !method.IsEmpty() );
4994 } // loop on xmlPaths
4997 //================================================================================
4999 * \brief Returns a new hypothesis initialized according to the read information
5001 //================================================================================
5003 Handle(_pyHypothesis)
5004 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5005 const Handle(_pyCommand)& creationCmd) const
5007 Handle(_pyHypothesis) resHyp, sampleHyp;
5009 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5010 if ( type2hyp != myType2Hyp.end() )
5011 sampleHyp = type2hyp->second;
5013 if ( sampleHyp.IsNull() )
5015 resHyp = new _pyHypothesis(creationCmd);
5019 if ( sampleHyp->IsAlgo() )
5020 resHyp = new _pyAlgorithm( creationCmd );
5022 resHyp = new _pyHypothesis(creationCmd);
5023 resHyp->Assign( sampleHyp, _pyID() );
5028 //================================================================================
5030 * \brief Adds an object ID to some family of IDs with a common prefix
5031 * \param [in] str - the object ID
5032 * \return bool - \c false if \a str does not have the same prefix as \a this family
5033 * (for internal usage)
5035 //================================================================================
5037 bool _pyStringFamily::Add( const char* str )
5039 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5040 return false; // expected prefix is missing
5042 str += _prefix.Length(); // skip _prefix
5044 // try to add to some of child falimies
5045 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5046 for ( ; itSub != _subFams.end(); ++itSub )
5047 if ( itSub->Add( str ))
5050 // no suitable family found - add str to _strings or create a new child family
5052 // look for a proper place within sorted _strings
5053 std::list< _AString >::iterator itStr = _strings.begin();
5054 while ( itStr != _strings.end() && itStr->IsLess( str ))
5056 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5057 return true; // same ID already kept
5059 const int minPrefixSize = 4;
5061 // count "smaller" strings with the same prefix
5063 std::list< _AString >::iterator itLess = itStr;
5064 while ( itLess != _strings.begin() )
5067 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5075 // itLess points to the 1st string with same prefix
5077 // count "greater" strings with the same prefix
5079 std::list< _AString >::iterator itMore = itStr;
5080 for ( ; itMore != _strings.end(); ++itMore )
5081 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5085 // itMore points to the 1st string with greater prefix
5087 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5089 int prefixSize = minPrefixSize;
5090 _AString newPrefix ( str, prefixSize );
5092 // look for a proper place within _subFams sorted by _prefix
5093 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5094 if ( !itSub->_prefix.IsLess( newPrefix ))
5097 // add the new _pyStringFamily
5098 itSub = _subFams.insert( itSub, _pyStringFamily());
5099 _pyStringFamily& newSubFam = *itSub;
5100 newSubFam._prefix = newPrefix;
5102 // pass this->_strings to newSubFam._strings
5103 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5104 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5105 newSubFam._strings.push_back( str + prefixSize );
5106 for ( ; nbMore > 0; --nbMore, ++itStr )
5107 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5109 _strings.erase( itLess, itMore );
5111 else // too few string to make a family for them
5113 _strings.insert( itStr, str );
5118 //================================================================================
5120 * \brief Finds an object ID in the command
5121 * \param [in] longStr - the command string
5122 * \param [out] subStr - the found object ID
5123 * \return bool - \c true if the object ID found
5125 //================================================================================
5127 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5129 const _AString& longStr = cmd->GetString();
5130 const char* s = longStr.ToCString();
5133 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5134 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5135 if ( argBeg < 4 || argBeg > longStr.Length() )
5137 for ( ; itSub != _subFams.end(); ++itSub )
5140 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5141 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5143 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5144 from = pos + len + itSub->_prefix.Length();
5149 from += itSub->_prefix.Length();
5152 // look among _strings
5153 std::list< _AString >::iterator itStr = _strings.begin();
5154 for ( ; itStr != _strings.end(); ++itStr )
5155 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5156 // check that object ID does not continue after len
5157 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5159 subStr.push_back( *itStr );
5165 //================================================================================
5167 * \brief Return remainder length of the object ID after my _prefix
5168 * \param [in] str - remainder of the command after my _prefix
5169 * \return int - length of the object ID or -1 if not found
5171 //================================================================================
5173 int _pyStringFamily::isIn( const char* str )
5175 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5177 for ( ; itSub != _subFams.end(); ++itSub )
5179 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5182 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5183 return itSub->_prefix.Length() + len;
5188 if ( !_strings.empty() )
5190 std::list< _AString >::iterator itStr = _strings.begin();
5191 bool firstEmpty = itStr->IsEmpty();
5194 for ( ; itStr != _strings.end(); ++itStr )
5196 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5199 len = itStr->Length();
5208 // check that object ID does not continue after len
5209 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5216 //================================================================================
5220 //================================================================================
5222 void _pyStringFamily::Print( int level )
5224 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5225 std::list< _AString >::iterator itStr = _strings.begin();
5226 for ( ; itStr != _strings.end(); ++itStr )
5227 cout << *itStr << " | ";
5229 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5230 for ( ; itSub != _subFams.end(); ++itSub )
5231 itSub->Print( level + 1 );
5233 cout << string( 70, '-' ) << endl;