1 // Copyright (C) 2007-2023 CEA, EDF, 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 <Basics_OCCTVersion.hxx>
37 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
38 #if OCC_VERSION_LARGE < 0x07050000
39 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
42 #include "SMESH_Gen_i.hxx"
43 /* SALOME headers that include CORBA headers that include windows.h
44 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
45 * that declare methods named GetObject - to apply the same rules of GetObject renaming
46 * and thus to avoid mess with GetObject symbol on Windows */
48 #include <LDOMParser.hxx>
56 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient)
57 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient)
58 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient)
59 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject)
60 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject)
61 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject)
62 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject)
63 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject)
64 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject)
65 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject)
66 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject)
67 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis)
68 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis)
69 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis)
70 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis)
71 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis)
74 using SMESH::TPythonDump;
77 * \brief Container of commands into which the initial script is split.
78 * It also contains data corresponding to SMESH_Gen contents
80 static Handle(_pyGen) theGen;
82 static TCollection_AsciiString theEmptyString;
84 //#define DUMP_CONVERSION
86 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
87 #undef DUMP_CONVERSION
93 //================================================================================
95 * \brief Set of TCollection_AsciiString initialized by C array of C strings
97 //================================================================================
99 struct TStringSet: public set<TCollection_AsciiString>
102 * \brief Filling. The last string must be ""
104 void Insert(const char* names[]) {
105 for ( int i = 0; names[i][0] ; ++i )
106 insert( (char*) names[i] );
109 * \brief Check if a string is in
111 bool Contains(const TCollection_AsciiString& name ) {
112 return find( name ) != end();
116 //================================================================================
118 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
119 * Odd items of the C array are map keys, and even items are values
121 //================================================================================
123 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
126 * \brief Filling. The last string must be ""
128 void Insert(const char* names_values[]) {
129 for ( int i = 0; names_values[i][0] ; i += 2 )
130 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
133 * \brief Check if a string is in
135 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
136 map< _AString, _AString >::iterator it = find( name );
137 return it == end() ? "" : it->second;
141 //================================================================================
143 * \brief Returns a mesh by object
145 //================================================================================
147 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
151 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
152 return Handle(_pyMesh)::DownCast( obj );
153 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
154 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
155 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
156 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
158 return Handle(_pyMesh)();
161 //================================================================================
163 * \brief Check if objects used as args have been created by previous commands
165 //================================================================================
167 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
169 // either comment or erase a command including NotPublishedObjectName()
170 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
172 bool isResultPublished = false;
173 const int nbRes = cmd->GetNbResultValues();
174 for ( int i = 0; i < nbRes; i++ )
176 _pyID objID = cmd->GetResultValue( i+1 );
177 if ( cmd->IsStudyEntry( objID ))
178 isResultPublished = (! theGen->IsNotPublished( objID ));
179 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
181 if ( isResultPublished )
187 // check if an Object was created in the script
190 _pyID obj = cmd->GetObject();
191 if ( obj.Search( "print(" ) == 1 )
192 return; // print statement
194 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
195 // remove an accessor method
196 obj = _pyCommand( obj ).GetObject();
198 const bool isMethodCall = cmd->IsMethodCall();
199 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
201 comment = "not created Object";
202 theGen->ObjectCreationRemoved( obj );
204 // check if a command has not created args
205 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
207 const _pyID& arg = cmd->GetArg( iArg );
208 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
210 list< _pyID > idList = cmd->GetStudyEntries( arg );
211 list< _pyID >::iterator id = idList.begin();
212 for ( ; id != idList.end(); ++id )
213 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
215 comment += *id + " has not been yet created";
218 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
219 // comment += arg + " has not been yet created";
221 // treat result objects
222 const _pyID& result = cmd->GetResultValue();
223 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
225 list< _pyID > idList = cmd->GetStudyEntries( result );
226 list< _pyID >::iterator id = idList.begin();
227 for ( ; id != idList.end(); ++id )
229 if ( comment.IsEmpty() )
230 presentObjects.insert( *id );
232 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
234 if ( idList.empty() && cmd->IsID( result ))
235 presentObjects.insert( result );
237 // comment the command
238 if ( !comment.IsEmpty() )
241 cmd->GetString() += " ### ";
242 cmd->GetString() += comment;
246 //================================================================================
248 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
250 //================================================================================
252 void fixFunctorType( TCollection_AsciiString& Type,
253 TCollection_AsciiString& Compare,
254 TCollection_AsciiString& UnaryOp,
255 TCollection_AsciiString& BinaryOp )
257 // The problem is that dumps of old studies created using filters becomes invalid
258 // when new items are inserted in the enum SMESH::FunctorType since values
259 // of this enum are dumped as integer values.
260 // This function corrects enum values of old studies given as args (Type,Compare,...)
261 // We can find out how to correct them by value of BinaryOp which can have only two
262 // values: FT_Undefined or FT_LogicalNOT.
263 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
264 // where PythonDump appeared
265 // v 3.0.0: FT_Undefined == 25
266 // v 3.1.0: FT_Undefined == 26, new items:
268 // v 4.1.2: FT_Undefined == 27, new items:
269 // - FT_BelongToGenSurface = 17
270 // v 5.1.1: FT_Undefined == 32, new items:
271 // - FT_FreeNodes = 10
272 // - FT_FreeFaces = 11
273 // - FT_LinearOrQuadratic = 23
274 // - FT_GroupColor = 24
275 // - FT_ElemGeomType = 25
276 // v 5.1.5: FT_Undefined == 33, new items:
277 // - FT_CoplanarFaces = 26
278 // v 6.2.0: FT_Undefined == 39, new items:
279 // - FT_MaxElementLength2D = 8
280 // - FT_MaxElementLength3D = 9
281 // - FT_BareBorderVolume = 25
282 // - FT_BareBorderFace = 26
283 // - FT_OverConstrainedVolume = 27
284 // - FT_OverConstrainedFace = 28
285 // v 6.5.0: FT_Undefined == 43, new items:
286 // - FT_EqualNodes = 14
287 // - FT_EqualEdges = 15
288 // - FT_EqualFaces = 16
289 // - FT_EqualVolumes = 17
290 // v 6.6.0: FT_Undefined == 44, new items:
291 // - FT_BallDiameter = 37
292 // v 6.7.1: FT_Undefined == 45, new items:
293 // - FT_EntityType = 36
294 // v 7.3.0: FT_Undefined == 46, new items:
295 // - FT_ConnectedElements = 39
296 // v 7.6.0: FT_Undefined == 47, new items:
297 // - FT_BelongToMeshGroup = 22
298 // v 8.1.0: FT_Undefined == 48, new items:
299 // - FT_NodeConnectivityNumber= 22
300 // v 8.5.0: FT_Undefined == 49, new items:
301 // - FT_Deflection2D = 22
302 // v 9.3.0: FT_Undefined == 50, new items:
303 // - FT_Length3D = 22
304 // v 9.12.0: FT_Undefined == 51, new items:
305 // - FT_ScaledJacobian = 8
307 // It's necessary to continue recording this history and to fill
308 // undef2newItems (see below) accordingly.
310 typedef map< int, vector< int > > TUndef2newItems;
311 static TUndef2newItems undef2newItems;
312 if ( undef2newItems.empty() )
314 undef2newItems[ 26 ].push_back( 7 );
315 undef2newItems[ 27 ].push_back( 17 );
316 { int items[] = { 10, 11, 23, 24, 25 };
317 undef2newItems[ 32 ].assign( items, items+5 ); }
318 undef2newItems[ 33 ].push_back( 26 );
319 { int items[] = { 8, 9, 25, 26, 27, 28 };
320 undef2newItems[ 39 ].assign( items, items+6 ); }
321 { int items[] = { 14, 15, 16, 17 };
322 undef2newItems[ 43 ].assign( items, items+4 ); }
323 undef2newItems[ 44 ].push_back( 37 );
324 undef2newItems[ 45 ].push_back( 36 );
325 undef2newItems[ 46 ].push_back( 39 );
326 undef2newItems[ 47 ].push_back( 22 );
327 undef2newItems[ 48 ].push_back( 22 );
328 undef2newItems[ 49 ].push_back( 22 );
329 undef2newItems[ 50 ].push_back( 22 );
330 undef2newItems[ 51 ].push_back( 8 );
332 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
335 int iType = Type.IntegerValue();
336 int iCompare = Compare.IntegerValue();
337 int iUnaryOp = UnaryOp.IntegerValue();
338 int iBinaryOp = BinaryOp.IntegerValue();
340 // find out integer value of FT_Undefined at the moment of dump
341 int oldUndefined = iBinaryOp;
342 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
345 // apply history to args
346 TUndef2newItems::const_iterator undef_items =
347 undef2newItems.upper_bound( oldUndefined );
348 if ( undef_items != undef2newItems.end() )
350 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
351 for ( ; undef_items != undef2newItems.end(); ++undef_items )
353 const vector< int > & addedItems = undef_items->second;
354 for ( size_t i = 0; i < addedItems.size(); ++i )
355 for ( int iArg = 0; iArg < 4; ++iArg )
357 int& arg = *pArg[iArg];
358 if ( arg >= addedItems[i] )
362 Type = TCollection_AsciiString( iType );
363 Compare = TCollection_AsciiString( iCompare );
364 UnaryOp = TCollection_AsciiString( iUnaryOp );
365 BinaryOp = TCollection_AsciiString( iBinaryOp );
369 //================================================================================
371 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
372 * arguments of a given command by a list "[x,y,z]" if the list is accessible
375 //================================================================================
377 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
379 static TStringSet methodsAcceptingList;
380 if ( methodsAcceptingList.empty() ) {
381 const char * methodNames[] = {
382 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
383 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
384 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
385 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
386 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
387 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
388 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
389 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
390 "Translate","TranslateMakeGroups","TranslateMakeMesh",
391 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
392 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
393 ,"" }; // <- mark of the end
394 methodsAcceptingList.Insert( methodNames );
396 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
398 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
400 const _AString & arg = theCommand->GetArg( i );
401 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
402 arg.Search( "SMESH.DirStruct" ) == 1 )
404 Handle(_pyCommand) workCmd = new _pyCommand( arg );
405 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
407 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
409 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
411 _AString newArg = "[ ";
412 newArg += ( workCmd->GetArg( 1 ) + ", " +
413 workCmd->GetArg( 2 ) + ", " +
414 workCmd->GetArg( 3 ) + " ]");
415 theCommand->SetArg( i, newArg );
421 //================================================================================
423 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
424 * a list "[id1,id2]" if the list is an accessible type of argument.
426 //================================================================================
428 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
430 static TStringSet methodsAcceptingList;
431 if ( methodsAcceptingList.empty() ) {
432 const char * methodNames[] = {
433 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
434 "ExportCGNS","ExportGMF",
435 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
436 "ScaleMakeGroups","Scale","ScaleMakeMesh",
437 "FindCoincidentNodesOnPartBut","DoubleElements",
438 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
439 ,"" }; // <- mark of the end
440 methodsAcceptingList.Insert( methodNames );
442 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
444 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
446 _pyCommand argCmd( theCommand->GetArg( i ));
447 if ( argCmd.GetMethod() == "GetIDSource" &&
448 argCmd.GetNbArgs() == 2 )
450 theCommand->SetArg( i, argCmd.GetArg( 1 ));
456 bool _FilterArg( const _AString& theArg )
458 static std::list<_AString> filteredArgs;
459 static bool initialized = false;
460 if ( !initialized ) {
462 filteredArgs.push_back( "SMESH.MED_V2_1" );
463 filteredArgs.push_back( "SMESH.MED_V2_2" );
465 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
469 //================================================================================
471 * \brief Convert a python script using commands of smeshBuilder.py
472 * \param theScriptLines - Lines of the input script
473 * \param theEntry2AccessorMethod - returns method names to access to
474 * objects wrapped with python class
475 * \param theObjectNames - names of objects
476 * \param theRemovedObjIDs - entries of objects whose created commands were removed
477 * \param theHistoricalDump - true means to keep all commands, false means
478 * to exclude commands relating to objects removed from study
479 * \retval TCollection_AsciiString - Conversion result
481 //================================================================================
484 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
485 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
486 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
487 std::set< TCollection_AsciiString >& theRemovedObjIDs,
488 const bool theToKeepAllCommands)
490 std::list< TCollection_AsciiString >::iterator lineIt;
491 // process notebook variables
493 SMESH_NoteBook aNoteBook;
495 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
496 aNoteBook.AddCommand( *lineIt );
498 theScriptLines.clear();
500 aNoteBook.ReplaceVariables();
502 aNoteBook.GetResultLines( theScriptLines );
505 // convert to smeshBuilder.py API
507 theGen = new _pyGen( theEntry2AccessorMethod,
510 theToKeepAllCommands );
512 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
513 theGen->AddCommand( *lineIt );
515 theScriptLines.clear();
519 #ifdef DUMP_CONVERSION
520 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
523 // clean commands of removed objects depending on myIsPublished flag
524 theGen->ClearCommands();
526 // reorder commands after conversion
527 list< Handle(_pyCommand) >::iterator cmd;
530 orderChanges = false;
531 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
532 if ( (*cmd)->SetDependentCmdsAfter() )
534 } while ( orderChanges );
536 // concat commands back into a script
537 TCollection_AsciiString aPrevCmd;
538 set<_pyID> createdObjects;
539 createdObjects.insert( "smeshBuilder" );
540 createdObjects.insert( "smesh" );
541 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
543 #ifdef DUMP_CONVERSION
544 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
546 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
547 CheckObjectPresence( *cmd, createdObjects );
548 if ( !(*cmd)->IsEmpty() ) {
549 aPrevCmd = (*cmd)->GetString();
550 theScriptLines.push_back( aPrevCmd );
559 //================================================================================
561 * \brief _pyGen constructor
563 //================================================================================
565 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
566 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
567 std::set< TCollection_AsciiString >& theRemovedObjIDs,
568 const bool theToKeepAllCommands)
569 : _pyObject( new _pyCommand( "", 0 )),
571 myID2AccessorMethod( theEntry2AccessorMethod ),
572 myObjectNames( theObjectNames ),
573 myRemovedObjIDs( theRemovedObjIDs ),
575 myToKeepAllCommands( theToKeepAllCommands ),
576 myGeomIDNb(0), myGeomIDIndex(-1),
577 myShaperIDNb(0), myShaperIDIndex(-1)
579 // make that GetID() to return TPythonDump::SMESHGenName()
580 GetCreationCmd()->Clear();
581 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
582 GetCreationCmd()->GetString() += "=";
584 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
585 if (!theObjectNames.IsEmpty())
587 // find a GEOM (aPass == 0) and SHAPERSTUDY (aPass == 1) entries
588 for(int aPass = 0; aPass < 2; aPass++) {
590 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->
591 FindComponent(aPass == 0 ? "GEOM" : "SHAPERSTUDY");
592 if (geomComp->_is_nil()) continue;
593 CORBA::String_var entry = geomComp->GetID();
596 // find a SMESH entry
598 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n(theObjectNames);
599 for (; e2n.More() && smeshID.IsEmpty(); e2n.Next())
600 if (_pyCommand::IsStudyEntry(e2n.Key()))
603 // find 1st difference between smeshID and geomID
604 if (!geomID.IsEmpty() && !smeshID.IsEmpty())
605 for (int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i)
606 if (geomID.Value(i) != smeshID.Value(i))
609 myGeomIDNb = geomID.Value(i);
612 myShaperIDNb = geomID.Value(i);
620 //================================================================================
622 * \brief name of SMESH_Gen in smeshBuilder.py
624 //================================================================================
626 const char* _pyGen::AccessorMethod() const
628 return SMESH_2smeshpy::GenName();
631 //================================================================================
633 * \brief Convert a command using a specific converter
634 * \param theCommand - the command to convert
636 //================================================================================
638 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
640 // store theCommand in the sequence
641 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
643 Handle(_pyCommand) aCommand = myCommands.back();
644 #ifdef DUMP_CONVERSION
645 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
648 const _pyID& objID = aCommand->GetObject();
650 if ( objID.IsEmpty() )
653 // Prevent moving a command creating a sub-mesh to the end of the script
654 // if the sub-mesh is used in theCommand as argument
655 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
657 // PlaceSubmeshAfterItsCreation( aCommand );
660 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
661 StructToList( aCommand );
663 const TCollection_AsciiString& method = aCommand->GetMethod();
665 // not to erase _pySelfEraser's etc. used as args in some commands
667 #ifdef USE_STRING_FAMILY
668 std::list<_pyID> objIDs;
669 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
671 std::list<_pyID>::iterator objID = objIDs.begin();
672 for ( ; objID != objIDs.end(); ++objID )
674 Handle(_pyObject) obj = FindObject( *objID );
677 obj->AddArgCmd( aCommand );
678 //cout << objID << " found in " << theCommand << endl;
683 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
684 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
685 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
687 Handle(_pyObject) obj = FindObject( *id );
689 obj->AddArgCmd( aCommand );
694 // Find an object to process theCommand
697 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
699 this->Process( aCommand );
700 //addFilterUser( aCommand, theGen ); // protect filters from clearing
704 // SMESH_Mesh method?
705 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
706 if ( id_mesh != myMeshes.end() )
708 //id_mesh->second->AddProcessedCmd( aCommand );
710 // Wrap Export*() into try-except
711 if ( aCommand->MethodStartsFrom("Export"))
714 _AString indent = aCommand->GetIndentation();
715 _AString tryStr = indent + "try:";
716 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
717 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
718 _AString excStr = indent + "except:";
719 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
721 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
723 aCommand->GetString() = newCmd;
724 aCommand->SetOrderNb( ++myNbCommands );
725 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
726 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
727 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
729 // check for mesh editor object
730 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
731 _pyID editorID = aCommand->GetResultValue();
732 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
733 myMeshEditors.insert( make_pair( editorID, editor ));
736 // check for SubMesh objects
737 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
738 _pyID subMeshID = aCommand->GetResultValue();
739 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
740 AddObject( subMesh );
743 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
744 GetIDSourceToList( aCommand );
746 //addFilterUser( aCommand, theGen ); // protect filters from clearing
748 id_mesh->second->Process( aCommand );
749 id_mesh->second->AddProcessedCmd( aCommand );
753 // SMESH_MeshEditor method?
754 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
755 if ( id_editor != myMeshEditors.end() )
757 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
758 GetIDSourceToList( aCommand );
760 //addFilterUser( aCommand, theGen ); // protect filters from clearing
762 // some commands of SMESH_MeshEditor create meshes and groups
763 _pyID meshID, groups;
764 if ( method.Search("MakeMesh") != -1 )
765 meshID = aCommand->GetResultValue();
766 else if ( method == "MakeBoundaryMesh")
767 meshID = aCommand->GetResultValue(1);
768 else if ( method == "MakeBoundaryElements")
769 meshID = aCommand->GetResultValue(2);
771 if ( method.Search("MakeGroups") != -1 ||
772 method == "ExtrusionAlongPathX" ||
773 method == "ExtrusionAlongPathObjX" ||
774 method == "DoubleNodeGroupNew" ||
775 method == "DoubleNodeGroupsNew" ||
776 method == "DoubleNodeElemGroupNew" ||
777 method == "DoubleNodeElemGroupsNew" ||
778 method == "DoubleNodeElemGroup2New" ||
779 method == "DoubleNodeElemGroups2New" ||
780 method == "AffectedElemGroupsInRegion"
782 groups = aCommand->GetResultValue();
783 else if ( method == "MakeBoundaryMesh" )
784 groups = aCommand->GetResultValue(2);
785 else if ( method == "MakeBoundaryElements")
786 groups = aCommand->GetResultValue(3);
787 else if ( method == "Create0DElementsOnAllNodes" &&
788 aCommand->GetArg(2).Length() > 2 ) // group name != ''
789 groups = aCommand->GetResultValue();
791 id_editor->second->Process( aCommand );
792 id_editor->second->AddProcessedCmd( aCommand );
795 if ( !meshID.IsEmpty() &&
796 !myMeshes.count( meshID ) &&
797 aCommand->IsStudyEntry( meshID ))
799 _AString processedCommand = aCommand->GetString();
800 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
801 CheckObjectIsReCreated( mesh );
802 myMeshes.insert( make_pair( meshID, mesh ));
804 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
807 if ( !groups.IsEmpty() )
809 if ( !aCommand->IsStudyEntry( meshID ))
810 meshID = id_editor->second->GetMesh();
811 Handle(_pyMesh) mesh = myMeshes[ meshID ];
813 list< _pyID > idList = aCommand->GetStudyEntries( groups );
814 list< _pyID >::iterator grID = idList.begin();
815 for ( ; grID != idList.end(); ++grID )
816 if ( !myObjects.count( *grID ))
818 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
820 if ( !mesh.IsNull() ) mesh->AddGroup( group );
824 } // SMESH_MeshEditor methods
826 // SMESH_Hypothesis method?
827 Handle(_pyHypothesis) hyp = FindHyp( objID );
828 if ( !hyp.IsNull() && !hyp->IsAlgo() )
830 hyp->Process( aCommand );
831 hyp->AddProcessedCmd( aCommand );
835 // aFilterManager.CreateFilter() ?
836 if ( aCommand->GetMethod() == "CreateFilter" )
838 // Set a more human readable name to a filter
839 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
840 _pyID newID, filterID = aCommand->GetResultValue();
841 int pos = filterID.Search( "0x" );
843 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
845 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
848 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
849 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
851 // create _pySelfEraser for functors
852 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
853 functor->IgnoreOwnCalls(); // to erase if not used as an argument
854 AddObject( functor );
857 // other object method?
858 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
859 if ( id_obj != myObjects.end() ) {
860 id_obj->second->Process( aCommand );
861 id_obj->second->AddProcessedCmd( aCommand );
865 // Add access to a wrapped mesh
866 AddMeshAccessorMethod( aCommand );
868 // Add access to a wrapped algorithm
869 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
871 // PAL12227. PythonDump was not updated at proper time; result is
872 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
873 // TypeError: __init__() takes exactly 11 arguments (10 given)
874 const char wrongCommand[] = "SMESH.Filter.Criterion(";
875 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
877 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
878 // there must be 10 arguments, 5-th arg ThresholdID is missing,
879 const int wrongNbArgs = 9, missingArg = 5;
880 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
882 for ( int i = wrongNbArgs; i > missingArg; --i )
883 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
884 tmpCmd.SetArg( missingArg, "''");
885 aCommand->GetString().Trunc( beg - 1 );
886 aCommand->GetString() += tmpCmd.GetString();
889 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
891 // instead of "SMESH.Filter.Criterion(
892 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
893 // 1 2 3 4 5 6 7 8 9 10
894 // in order to avoid the problem of type mismatch of long and FunctorType
895 const TCollection_AsciiString
896 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
897 TCollection_AsciiString
898 Type = aCommand->GetArg(1), // long
899 Compare = aCommand->GetArg(2), // long
900 Threshold = aCommand->GetArg(3), // double
901 ThresholdStr = aCommand->GetArg(4), // string
902 ThresholdID = aCommand->GetArg(5), // string
903 UnaryOp = aCommand->GetArg(6), // long
904 BinaryOp = aCommand->GetArg(7), // long
905 Tolerance = aCommand->GetArg(8), // double
906 TypeOfElement = aCommand->GetArg(9), // ElementType
907 Precision = aCommand->GetArg(10); // long
908 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
909 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
910 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
911 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
912 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
914 if ( Compare == "SMESH.FT_EqualTo" )
917 aCommand->RemoveArgs();
918 aCommand->SetObject( SMESH_2smeshpy::GenName() );
919 aCommand->SetMethod( "GetCriterion" );
921 aCommand->SetArg( 1, TypeOfElement );
922 aCommand->SetArg( 2, Type );
923 aCommand->SetArg( 3, Compare );
925 if ( Threshold.IsIntegerValue() )
927 int iGeom = Threshold.IntegerValue();
928 if ( Type == "SMESH.FT_ElemGeomType" )
930 // set SMESH.GeometryType instead of a numerical Threshold
931 const int nbTypes = SMESH::Geom_LAST;
932 const char* types[] = {
933 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
934 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
935 "Geom_POLYHEDRA", "Geom_BALL" };
936 if ( -1 < iGeom && iGeom < nbTypes )
937 Threshold = SMESH + types[ iGeom ];
939 if (SALOME::VerbosityActivated())
941 // is types complete? (compilation failure means that enum GeometryType changed)
942 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
943 "Update names of GeometryType's!!!" );
946 if (Type == "SMESH.FT_EntityType")
948 // set SMESH.EntityType instead of a numerical Threshold
949 const int nbTypes = SMESH::Entity_Last;
950 const char* types[] = {
951 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
952 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
953 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
954 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
955 "Entity_Pyramid", "Entity_Quad_Pyramid",
956 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
957 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
958 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
959 if ( -1 < iGeom && iGeom < nbTypes )
960 Threshold = SMESH + types[ iGeom ];
962 if (SALOME::VerbosityActivated())
964 // is 'types' complete? (compilation failure means that enum EntityType changed)
965 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
966 "Update names of EntityType's!!!" );
970 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
971 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
972 else if ( ThresholdStr.Length() != 2 )
973 aCommand->SetArg( 4, ThresholdStr );
974 else if ( ThresholdID.Length() != 2 )
975 aCommand->SetArg( 4, ThresholdID );
977 aCommand->SetArg( 4, Threshold );
978 // find the last not default arg
980 if ( Tolerance == dfltTol ) {
982 if ( BinaryOp == dfltFunctor ) {
984 if ( UnaryOp == dfltFunctor )
988 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
989 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
990 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
991 if ( Precision != dfltPreci )
993 TCollection_AsciiString crit = aCommand->GetResultValue();
994 aCommand->GetString() += "; ";
995 aCommand->GetString() += crit + ".Precision = " + Precision;
1001 //================================================================================
1003 * \brief Convert the command or remember it for later conversion
1004 * \param theCommand - The python command calling a method of SMESH_Gen
1006 //================================================================================
1008 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
1010 // there are methods to convert:
1011 // CreateMesh( shape )
1012 // Concatenate( [mesh1, ...], ... )
1013 // CreateHypothesis( theHypType, theLibName )
1014 // Compute( mesh, geom )
1015 // Evaluate( mesh, geom )
1017 TCollection_AsciiString method = theCommand->GetMethod();
1019 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1021 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1024 _pyID id = mesh->GetID(), comma("'");
1025 if ( myObjectNames.IsBound( id ))
1026 theCommand->SetArg( theCommand->GetNbArgs() + 1,
1027 comma + myObjectNames( id ) + comma);
1030 if ( method == "CreateMeshesFromUNV" ||
1031 method == "CreateMeshesFromSTL" ||
1032 method == "CreateDualMesh" ||
1033 method == "CopyMesh" ) // command result is a mesh
1035 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1039 if ( method == "CreateMeshesFromMED" ||
1040 method == "CreateMeshesFromCGNS" ||
1041 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1043 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1044 std::list< _pyID >::iterator meshID = meshIDs.begin();
1045 for ( ; meshID != meshIDs.end(); ++meshID )
1047 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1050 if ( method == "CreateMeshesFromGMF" )
1052 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1053 // CreateMeshesFromGMF( theFileName )
1054 _AString file = theCommand->GetArg(1);
1055 theCommand->RemoveArgs();
1056 theCommand->SetArg( 1, file );
1059 if ( method == "CopyMeshWithGeom" )
1061 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1062 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1066 // CreateHypothesis()
1067 if ( method == "CreateHypothesis" )
1069 // issue 199929, remove standard library name (default parameter)
1070 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1071 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1072 // keep the first argument
1073 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1074 theCommand->RemoveArgs();
1075 theCommand->SetArg( 1, arg );
1078 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1079 CheckObjectIsReCreated( hyp );
1080 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1085 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1086 if ( method == "Compute" )
1088 const _pyID& meshID = theCommand->GetArg( 1 );
1089 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1090 if ( id_mesh != myMeshes.end() ) {
1091 theCommand->SetObject( meshID );
1092 theCommand->RemoveArgs();
1093 id_mesh->second->Process( theCommand );
1094 id_mesh->second->AddProcessedCmd( theCommand );
1099 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1100 if ( method == "Evaluate" )
1102 const _pyID& meshID = theCommand->GetArg( 1 );
1103 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1104 if ( id_mesh != myMeshes.end() ) {
1105 theCommand->SetObject( meshID );
1106 _pyID geom = theCommand->GetArg( 2 );
1107 theCommand->RemoveArgs();
1108 theCommand->SetArg( 1, geom );
1109 id_mesh->second->AddProcessedCmd( theCommand );
1114 // objects erasing creation command if no more its commands invoked:
1115 // SMESH_Pattern, FilterManager
1116 if ( method == "GetPattern" ||
1117 method == "CreateFilterManager" ||
1118 method == "CreateMeasurements" )
1120 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1121 if ( !AddObject( obj ) )
1122 theCommand->Clear(); // already created
1124 // Concatenate( [mesh1, ...], ... )
1125 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1127 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1128 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1129 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1130 _pyID appendMesh = theCommand->GetArg( 5 );
1131 if ( method == "ConcatenateWithGroups" ) {
1132 theCommand->SetMethod( "Concatenate" );
1133 theCommand->SetArg( 5, "True" );
1136 theCommand->SetArg( 5, "False" );
1138 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1140 appendMesh.Insert( 1, "meshToAppendTo=" );
1141 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1143 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1145 AddMeshAccessorMethod( theCommand );
1147 else if ( method == "SetName" ) // SetName(obj,name)
1149 // store theCommand as one of object commands to erase it along with the object
1150 const _pyID& objID = theCommand->GetArg( 1 );
1151 Handle(_pyObject) obj = FindObject( objID );
1152 if ( !obj.IsNull() )
1153 obj->AddProcessedCmd( theCommand );
1156 // Replace name of SMESH_Gen
1158 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1159 static TStringSet smeshpyMethods;
1160 if ( smeshpyMethods.empty() ) {
1161 const char * names[] =
1162 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1163 "GetPattern","GetSubShapesId",
1164 "" }; // <- mark of array end
1165 smeshpyMethods.Insert( names );
1167 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1168 // smeshgen.Method() --> smesh.Method()
1169 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1171 // smeshgen.Method() --> smesh.Method()
1172 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1175 //================================================================================
1177 * \brief Convert the remembered commands
1179 //================================================================================
1181 void _pyGen::Flush()
1183 // create an empty command
1184 myLastCommand = new _pyCommand();
1186 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1187 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1188 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1190 if ( IsToKeepAllCommands() ) // historical dump
1192 // set myIsPublished = true to all objects
1193 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1194 id_mesh->second->SetRemovedFromStudy( false );
1195 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1196 id_hyp->second->SetRemovedFromStudy( false );
1197 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1198 id_obj->second->SetRemovedFromStudy( false );
1202 // let hypotheses find referred objects in order to prevent clearing
1203 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1204 list< Handle(_pyMesh) > fatherMeshes;
1205 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1206 if ( !id_hyp->second.IsNull() )
1207 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1209 // set myIsPublished = false to all objects depending on
1210 // meshes built on a removed geometry
1211 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1212 if ( id_mesh->second->IsNotGeomPublished() )
1213 id_mesh->second->SetRemovedFromStudy( true );
1216 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1217 if ( ! id_mesh->second.IsNull() )
1218 id_mesh->second->Flush();
1221 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1222 if ( !id_hyp->second.IsNull() ) {
1223 id_hyp->second->Flush();
1224 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1225 if ( !id_hyp->second->IsWrapped() )
1226 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1229 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1230 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1231 for ( ; robj != myOrderedObjects.rend(); ++robj )
1232 if ( ! robj->IsNull() )
1234 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1235 for ( ; obj != myOrderedObjects.end(); ++obj )
1236 if ( ! obj->IsNull() )
1239 myLastCommand->SetOrderNb( ++myNbCommands );
1240 myCommands.push_back( myLastCommand );
1243 //================================================================================
1245 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1246 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1248 //================================================================================
1250 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) /*theCmdUsingSubmesh*/ ) const
1252 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1253 // for ( ; id_obj != myObjects.end(); ++id_obj )
1255 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1256 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1258 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1259 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1261 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1262 // list< _pyID >::iterator id = idList.begin();
1263 // for ( ; id != idList.end(); ++id )
1264 // if ( id_obj->first == *id )
1265 // // _pySubMesh::Process() does what we need
1266 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1271 //================================================================================
1273 * \brief Clean commands of removed objects depending on myIsPublished flag
1275 //================================================================================
1277 void _pyGen::ClearCommands()
1279 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1280 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1281 id_mesh->second->ClearCommands();
1283 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1284 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1285 if ( !id_hyp->second.IsNull() )
1286 id_hyp->second->ClearCommands();
1288 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1289 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1290 for ( ; robj != myOrderedObjects.rend(); ++robj )
1291 if ( ! robj->IsNull() )
1292 (*robj)->ClearCommands();
1293 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1294 for ( ; obj != myOrderedObjects.end(); ++obj )
1295 if ( ! obj->IsNull() )
1296 (*obj)->ClearCommands();
1299 //================================================================================
1301 * \brief Release mutual handles of objects
1303 //================================================================================
1307 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1308 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1309 id_mesh->second->Free();
1312 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1313 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1314 id_ed->second->Free();
1315 myMeshEditors.clear();
1317 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1318 for ( ; id_obj != myObjects.end(); ++id_obj )
1319 id_obj->second->Free();
1322 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1323 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1324 if ( !id_hyp->second.IsNull() )
1325 id_hyp->second->Free();
1328 myFile2ExportedMesh.clear();
1330 //myKeepAgrCmdsIDs.Print();
1333 //================================================================================
1335 * \brief Add access method to mesh that is an argument
1336 * \param theCmd - command to add access method
1337 * \retval bool - true if added
1339 //================================================================================
1341 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1344 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1345 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1346 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1352 //================================================================================
1354 * \brief Add access method to algo that is an object or an argument
1355 * \param theCmd - command to add access method
1356 * \retval bool - true if added
1358 //================================================================================
1360 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1363 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1364 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1365 if ( !id_hyp->second.IsNull() &&
1366 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1367 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1368 id_hyp->second->AccessorMethod() ))
1374 //================================================================================
1376 * \brief Find hypothesis by ID (entry)
1377 * \param theHypID - The hypothesis ID
1378 * \retval Handle(_pyHypothesis) - The found hypothesis
1380 //================================================================================
1382 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1384 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1385 if ( id_hyp != myHypos.end() &&
1386 !id_hyp->second.IsNull() &&
1387 theHypID == id_hyp->second->GetID() )
1388 return id_hyp->second;
1389 return Handle(_pyHypothesis)();
1392 //================================================================================
1394 * \brief Find algorithm able to create a hypothesis
1395 * \param theGeom - The shape ID the algorithm was created on
1396 * \param theMesh - The mesh ID that created the algorithm
1397 * \param theHypothesis - The hypothesis the algorithm should be able to create
1398 * \retval Handle(_pyHypothesis) - The found algo
1400 //================================================================================
1402 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1403 const Handle(_pyHypothesis)& theHypothesis )
1405 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1406 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1407 if ( !id_hyp->second.IsNull() &&
1408 id_hyp->second->IsAlgo() &&
1409 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1410 id_hyp->second->GetGeom() == theGeom &&
1411 id_hyp->second->GetMesh() == theMesh )
1412 return id_hyp->second;
1413 return Handle(_pyHypothesis)();
1416 //================================================================================
1418 * \brief Find subMesh by ID (entry)
1419 * \param theSubMeshID - The subMesh ID
1420 * \retval Handle(_pySubMesh) - The found subMesh
1422 //================================================================================
1424 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1426 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1427 if ( id_subMesh != myObjects.end() )
1428 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1429 return Handle(_pySubMesh)();
1433 //================================================================================
1435 * \brief Change order of commands in the script
1436 * \param theCmd1 - One command
1437 * \param theCmd2 - Another command
1439 //================================================================================
1441 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1443 list< Handle(_pyCommand) >::iterator pos1, pos2;
1444 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1445 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1446 myCommands.insert( pos1, theCmd2 );
1447 myCommands.insert( pos2, theCmd1 );
1448 myCommands.erase( pos1 );
1449 myCommands.erase( pos2 );
1451 int nb1 = theCmd1->GetOrderNb();
1452 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1453 theCmd2->SetOrderNb( nb1 );
1454 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1455 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1458 //================================================================================
1460 * \brief Set one command after the other
1461 * \param theCmd - Command to move
1462 * \param theAfterCmd - Command ater which to insert the first one
1464 //================================================================================
1466 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1468 setNeighbourCommand( theCmd, theAfterCmd, true );
1471 //================================================================================
1473 * \brief Set one command before the other
1474 * \param theCmd - Command to move
1475 * \param theBeforeCmd - Command before which to insert the first one
1477 //================================================================================
1479 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1481 setNeighbourCommand( theCmd, theBeforeCmd, false );
1484 //================================================================================
1486 * \brief Set one command before or after the other
1487 * \param theCmd - Command to move
1488 * \param theOtherCmd - Command ater or before which to insert the first one
1490 //================================================================================
1492 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1493 Handle(_pyCommand)& theOtherCmd,
1494 const bool theIsAfter )
1496 list< Handle(_pyCommand) >::iterator pos;
1497 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1498 myCommands.erase( pos );
1499 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1500 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1503 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1504 (*pos)->SetOrderNb( i++ );
1507 //================================================================================
1509 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1511 //================================================================================
1513 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1515 // No more needed after adding _pyObject::myArgCommands
1517 // const char filterPrefix[] = "aFilter0x";
1518 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1521 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1523 // const _AString & arg = theCommand->GetArg( i );
1524 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1525 // if ( arg.Search( filterPrefix ) != 1 )
1528 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1529 // if ( !filter.IsNull() )
1531 // filter->AddUser( user );
1532 // if ( !filter->GetNewID().IsEmpty() )
1533 // theCommand->SetArg( i, filter->GetNewID() );
1538 //================================================================================
1540 * \brief Set command be last in list of commands
1541 * \param theCmd - Command to be last
1543 //================================================================================
1545 Handle(_pyCommand)& _pyGen::GetLastCommand()
1547 return myLastCommand;
1550 //================================================================================
1552 * \brief Set method to access to object wrapped with python class
1553 * \param theID - The wrapped object entry
1554 * \param theMethod - The accessor method
1556 //================================================================================
1558 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1560 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1563 //================================================================================
1565 * \brief Generated new ID for object and assign with existing name
1566 * \param theID - ID of existing object
1568 //================================================================================
1570 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1575 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1577 while ( myObjectNames.IsBound( aNewID ) );
1579 if ( myObjectNames.IsBound( theID ) )
1580 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1582 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1586 //================================================================================
1588 * \brief Stores theObj in myObjects
1590 //================================================================================
1592 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1594 if ( theObj.IsNull() ) return false;
1596 CheckObjectIsReCreated( theObj );
1600 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1601 add = myMeshes.insert( make_pair( theObj->GetID(),
1602 Handle(_pyMesh)::DownCast( theObj ))).second;
1604 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1605 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1606 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1609 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1610 if ( add ) myOrderedObjects.push_back( theObj );
1615 //================================================================================
1617 * \brief Erases an existing object with the same ID. This method should be called
1618 * before storing theObj in _pyGen
1620 //================================================================================
1622 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1624 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1627 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1628 Handle(_pyObject) existing;
1630 existing = FindHyp( theObj->GetID() );
1632 existing = FindObject( theObj->GetID() );
1633 if ( !existing.IsNull() && existing != theObj )
1635 existing->SetRemovedFromStudy( true );
1636 existing->ClearCommands();
1639 if ( myHypos.count( theObj->GetID() ))
1640 myHypos.erase( theObj->GetID() );
1642 else if ( myMeshes.count( theObj->GetID() ))
1644 myMeshes.erase( theObj->GetID() );
1646 else if ( myObjects.count( theObj->GetID() ))
1648 myObjects.erase( theObj->GetID() );
1653 //================================================================================
1655 * \brief Re-register an object with other ID to make it Process() commands of
1656 * other object having this ID
1658 //================================================================================
1660 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1662 if ( theObj.IsNull() ) return;
1664 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1665 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1667 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1668 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1671 myObjects.insert( make_pair( theID, theObj ));
1674 //================================================================================
1676 * \brief Finds a _pyObject by ID
1678 //================================================================================
1680 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1683 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1684 if ( id_obj != myObjects.end() )
1685 return id_obj->second;
1688 _pyGen* me = const_cast< _pyGen* >( this );
1689 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1690 if ( id_obj != myMeshes.end() )
1691 return id_obj->second;
1694 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1695 // if ( id_obj != myMeshEditors.end() )
1696 // return id_obj->second;
1698 return Handle(_pyObject)();
1701 //================================================================================
1703 * \brief Check if a study entry is under GEOM component
1705 //================================================================================
1707 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1709 bool isGeom = myGeomIDNb && myGeomIDIndex <= theObjID.Length() &&
1710 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb;
1711 bool isShaper = myShaperIDNb && myShaperIDIndex <= theObjID.Length() &&
1712 int( theObjID.Value( myShaperIDIndex )) == myShaperIDNb;
1713 return ((isGeom || isShaper) && _pyCommand::IsStudyEntry( theObjID ));
1716 //================================================================================
1718 * \brief Returns true if an object is not present in a study
1720 //================================================================================
1722 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1724 if ( theObjID.IsEmpty() ) return false;
1726 if ( myObjectNames.IsBound( theObjID ))
1727 return false; // SMESH object is in study
1729 // either the SMESH object is not in study or it is a GEOM object
1730 if ( IsGeomObject( theObjID ))
1732 SALOMEDS::SObject_wrap so = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( theObjID.ToCString() );
1733 if ( so->_is_nil() ) return true;
1734 CORBA::Object_var obj = so->GetObject();
1735 return CORBA::is_nil( obj );
1737 return true; // SMESH object not in study
1740 //================================================================================
1742 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1743 * this object is not dumped
1744 * \param [in] theObjID - entry of the object whose creation command was eliminated
1746 //================================================================================
1748 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1750 myRemovedObjIDs.insert( theObjID );
1753 //================================================================================
1755 * \brief Return reader of hypotheses of plugins
1757 //================================================================================
1759 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1761 if (myHypReader.IsNull() )
1762 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1768 //================================================================================
1770 * \brief Mesh created by SMESH_Gen
1772 //================================================================================
1774 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1775 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1777 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1778 myGeomNotInStudy = true;
1780 // convert my creation command --> smeshpy.Mesh(...)
1781 Handle(_pyCommand) creationCmd = GetCreationCmd();
1782 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1783 creationCmd->SetMethod( "Mesh" );
1784 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1787 //================================================================================
1789 * \brief Mesh created by SMESH_MeshEditor
1791 //================================================================================
1793 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1794 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1796 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1798 // this mesh depends on the exported mesh
1799 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1800 if ( !file.IsEmpty() )
1802 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1803 addFatherMesh( exportData.myMesh );
1804 if ( !exportData.myLastComputeCmd.IsNull() )
1806 // restore cleared Compute() by which the exported mesh was generated
1807 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1808 // protect that Compute() cmd from clearing
1809 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1810 exportData.myMesh->myLastComputeCmd.Nullify();
1814 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1816 // this mesh depends on concatenated meshes
1817 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1818 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1819 list< _pyID >::iterator meshID = idList.begin();
1820 for ( ; meshID != idList.end(); ++meshID )
1821 addFatherMesh( *meshID );
1823 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1825 // this mesh depends on a copied IdSource
1826 const _pyID& objID = theCreationCmd->GetArg( 1 );
1827 addFatherMesh( objID );
1829 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1830 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1831 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1833 // this mesh depends on a source mesh
1834 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1835 const _pyID& meshID = theCreationCmd->GetObject();
1836 addFatherMesh( meshID );
1839 // convert my creation command
1840 Handle(_pyCommand) creationCmd = GetCreationCmd();
1841 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1842 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1845 //================================================================================
1847 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1848 * \param theCommand - Engine method called for this mesh
1850 //================================================================================
1852 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1854 // some methods of SMESH_Mesh interface need special conversion
1855 // to methods of Mesh python class
1857 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1858 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1859 // 2. AddHypothesis(geom, hyp)
1860 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1861 // 3. CreateGroupFromGEOM(type, name, grp)
1862 // --> in Mesh.Group(grp, name="")
1863 // 4. ExportToMED(f, auto_groups, version)
1864 // --> in Mesh.ExportMED( f, auto_groups, version )
1867 const TCollection_AsciiString& method = theCommand->GetMethod();
1868 // ----------------------------------------------------------------------
1869 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1871 if ( !theGen->IsToKeepAllCommands() ) // !historical
1873 list< Handle(_pyHypothesis) >::iterator hyp;
1874 if ( !myLastComputeCmd.IsNull() )
1876 // check if the previously computed mesh has been edited,
1877 // if so then we do not clear the previous Compute()
1878 bool toClear = true;
1879 if ( myLastComputeCmd->GetMethod() == "Compute" )
1881 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1882 for ( ; e != myEditors.end() && toClear; ++e )
1884 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1885 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1886 if ( cmd != cmds.rend() &&
1887 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1893 // clear hyp commands called before myLastComputeCmd
1894 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1895 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1897 myLastComputeCmd->Clear();
1900 myLastComputeCmd = theCommand;
1902 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1903 (*hyp)->MeshComputed( myLastComputeCmd );
1907 // ----------------------------------------------------------------------
1908 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1910 if ( !theGen->IsToKeepAllCommands() ) // !historical
1913 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1914 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1915 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1917 if ( !myLastComputeCmd.IsNull() )
1919 list< Handle(_pyHypothesis) >::iterator hyp;
1920 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1921 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1923 myLastComputeCmd->Clear();
1926 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1927 for ( ; e != myEditors.end(); ++e )
1929 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1930 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1931 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1932 if ( !(*cmd)->IsEmpty() )
1934 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1938 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1941 // ----------------------------------------------------------------------
1942 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1943 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1944 if ( !subMesh.IsNull() ) {
1945 subMesh->SetCreator( this );
1946 mySubmeshes.push_back( subMesh );
1949 // ----------------------------------------------------------------------
1950 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1951 theCommand->Clear();
1953 // ----------------------------------------------------------------------
1954 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1955 myAddHypCmds.push_back( theCommand );
1957 const _pyID& hypID = theCommand->GetArg( 2 );
1958 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1959 if ( !hyp.IsNull() ) {
1960 myHypos.push_back( hyp );
1961 if ( hyp->GetMesh().IsEmpty() )
1962 hyp->SetMesh( this->GetID() );
1965 // ----------------------------------------------------------------------
1966 else if ( method == "CreateGroup" ||
1967 method == "CreateGroupFromGEOM" ||
1968 method == "CreateGroupFromFilter" ||
1969 method == "CreateDimGroup" )
1971 Handle(_pyGroup) group = new _pyGroup( theCommand );
1972 myGroups.push_back( group );
1973 theGen->AddObject( group );
1975 // ----------------------------------------------------------------------
1976 // update list of groups
1977 else if ( method == "GetGroups" )
1979 bool allGroupsRemoved = true;
1980 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1981 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1982 list< _pyID >::iterator grID = idList.begin();
1983 const size_t nbGroupsBefore = myGroups.size();
1984 Handle(_pyObject) obj;
1985 for ( ; grID != idList.end(); ++grID )
1987 obj = theGen->FindObject( *grID );
1990 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1991 theGen->AddObject( group );
1992 myGroups.push_back( group );
1995 if ( !obj->CanClear() )
1996 allGroupsRemoved = false;
1998 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
1999 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
2001 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
2003 // check if the preceding command is Compute();
2004 // if GetGroups() is just after Compute(), this can mean that the groups
2005 // were created by some algorithm and hence Compute() should not be discarded
2006 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
2007 std::list< Handle(_pyCommand) >::reverse_iterator cmd = cmdList.rbegin();
2008 while ( (*cmd)->GetMethod() == "GetGroups" )
2010 if ( myLastComputeCmd == (*cmd))
2011 // protect last Compute() from clearing by the next Compute()
2012 myLastComputeCmd.Nullify();
2015 // ----------------------------------------------------------------------
2016 // notify a group about full removal
2017 else if ( method == "RemoveGroupWithContents" ||
2018 method == "RemoveGroup")
2020 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
2021 const _pyID groupID = theCommand->GetArg( 1 );
2022 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
2023 if ( !grp.IsNull() )
2025 if ( method == "RemoveGroupWithContents" )
2026 grp->RemovedWithContents();
2027 // to clear RemoveGroup() if the group creation is cleared
2028 grp->AddProcessedCmd( theCommand );
2032 // ----------------------------------------------------------------------
2033 else if ( theCommand->MethodStartsFrom( "Export" ))
2035 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2036 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2037 method == "ExportMED" )
2039 theCommand->SetMethod( "ExportMED" );
2040 // filter out deprecated version parameter
2041 vector< _AString > args;
2042 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2043 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2044 args.push_back( theCommand->GetArg( i ) );
2046 theCommand->RemoveArgs();
2047 for ( unsigned int i = 0; i < args.size(); i++ )
2048 theCommand->SetArg( i+1, args[i] );
2049 if ( theCommand->GetNbArgs() == 4 )
2051 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2052 _AString autoDimension = theCommand->GetArg( 4 );
2053 theCommand->SetArg( 4, "None" );
2054 theCommand->SetArg( 5, autoDimension );
2057 else if ( method == "ExportCGNS" )
2058 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2059 _pyID partID = theCommand->GetArg( 1 );
2060 int nbArgs = theCommand->GetNbArgs();
2061 for ( int i = 2; i <= nbArgs; ++i )
2062 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2063 theCommand->SetArg( nbArgs, partID );
2065 else if ( method == "ExportGMF" )
2066 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2067 _pyID partID = theCommand->GetArg( 1 );
2068 _AString file = theCommand->GetArg( 2 );
2069 theCommand->RemoveArgs();
2070 theCommand->SetArg( 1, file );
2071 theCommand->SetArg( 2, partID );
2073 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2074 { // ExportPartTo*(part, ...) -> Export*(..., part)
2076 // remove "PartTo" from the method
2077 TCollection_AsciiString newMethod = method;
2078 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2079 theCommand->SetMethod( newMethod );
2080 // replace version parameter by minor
2081 std::list< _AString > args;
2082 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2083 if ( _FilterArg( theCommand->GetArg( i )))
2084 args.push_back( "minor=0");
2086 args.push_back( theCommand->GetArg( i ));
2088 // check the 1st arg meshPart, it must be SMESH_IDSource
2089 _AString meshPart = args.front();
2090 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2091 meshPart.Search( "Filter" ) > 0 ||
2092 meshPart.Search( "GetIDSource" ) > 0 ||
2093 meshPart.Search( "meshPart" ) > 0 )
2095 // set the 1st arg meshPart
2096 // - to 5th place for ExportMED command
2097 // - to last place for the rest commands
2098 std::list< _AString >::iterator newPos = args.end();
2099 if ( newMethod == "ExportMED" )
2100 std::advance( newPos = args.begin(), 5 );
2101 args.splice( newPos, args, args.begin() );
2103 std::list< _AString >::iterator a = args.begin();
2104 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2105 theCommand->SetArg( i, *a );
2107 // remember file name
2108 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2109 ExportedMeshData( this, myLastComputeCmd ));
2111 // ----------------------------------------------------------------------
2112 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2114 _pyID hypID = theCommand->GetArg( 2 );
2115 _pyID geomID = theCommand->GetArg( 1 );
2116 bool isLocal = ( geomID != GetGeom() );
2118 // check if this mesh still has corresponding addition command
2119 Handle(_pyCommand) addCmd;
2120 list< Handle(_pyCommand) >::iterator cmd;
2121 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2122 for ( int i = 0; i < 2; ++i )
2124 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2125 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2127 bool sameHyp = true;
2128 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2129 sameHyp = false; // other hyp
2130 if ( (*cmd)->GetNbArgs() == 2 &&
2131 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2132 sameHyp = false; // other geom
2133 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2134 sameHyp = false; // other geom
2138 cmd = addHypCmds.erase( cmd );
2139 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2141 theCommand->Clear();
2145 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2146 addCmd->RemoveArgs();
2147 addCmd->SetArg( 1, hypID );
2149 addCmd->SetArg( 2, geomID );
2158 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2159 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2160 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2161 _pyID geom = theCommand->GetArg( 1 );
2162 theCommand->RemoveArgs();
2163 theCommand->SetArg( 1, hypID );
2164 if ( geom != GetGeom() )
2165 theCommand->SetArg( 2, geom );
2167 // remove hyp from myHypos
2168 myHypos.remove( hyp );
2170 // check for SubMesh order commands
2171 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2173 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2174 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2175 // commands are moved at the end of the script
2176 TCollection_AsciiString subIDs =
2177 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2178 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2179 list< _pyID >::iterator subID = idList.begin();
2180 for ( ; subID != idList.end(); ++subID )
2182 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2183 if ( !subMesh.IsNull() )
2184 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2187 // add accessor method if necessary
2190 if ( NeedMeshAccess( theCommand ))
2191 // apply theCommand to the mesh wrapped by smeshpy mesh
2192 AddMeshAccess( theCommand );
2196 //================================================================================
2198 * \brief Return True if addition of accesor method is needed
2200 //================================================================================
2202 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2204 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2205 // so no conversion is needed for them at all:
2206 static TStringSet sameMethods;
2207 if ( sameMethods.empty() ) {
2208 const char * names[] =
2209 { "ExportDAT","ExportUNV","ExportSTL", "RemoveGroup","RemoveGroupWithContents",
2210 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2211 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2212 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2213 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2214 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2215 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2216 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2217 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2218 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2219 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2220 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2221 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2222 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder",
2224 ,"" }; // <- mark of end
2225 sameMethods.Insert( names );
2228 return !sameMethods.Contains( theCommand->GetMethod() );
2231 //================================================================================
2233 * \brief Convert creation and addition of all algos and hypos
2235 //================================================================================
2237 void _pyMesh::Flush()
2240 // get the meshes this mesh depends on via hypotheses
2241 list< Handle(_pyMesh) > fatherMeshes;
2242 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2243 for ( ; hyp != myHypos.end(); ++hyp )
2244 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2245 myGeomNotInStudy = true;
2247 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2248 for ( ; m != fatherMeshes.end(); ++m )
2249 addFatherMesh( *m );
2250 // if ( removedGeom )
2251 // SetRemovedFromStudy(); // as referred geometry not in study
2253 if ( myGeomNotInStudy )
2256 list < Handle(_pyCommand) >::iterator cmd;
2258 // try to convert algo addition like this:
2259 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2260 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2262 Handle(_pyCommand) addCmd = *cmd;
2264 _pyID algoID = addCmd->GetArg( 2 );
2265 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2266 if ( algo.IsNull() || !algo->IsAlgo() )
2269 // check and create new algorithm instance if it is already wrapped
2270 if ( algo->IsWrapped() ) {
2271 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2272 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2273 TCollection_AsciiString( " = " ) + theGen->GetID() +
2274 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2275 TCollection_AsciiString( "\" )" );
2277 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2278 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2279 if ( !newAlgo.IsNull() ) {
2280 newAlgo->Assign( algo, this->GetID() );
2281 newAlgo->SetCreationCmd( newCmd );
2283 // set algorithm creation
2284 theGen->SetCommandBefore( newCmd, addCmd );
2285 myHypos.push_back( newAlgo );
2286 if ( !myLastComputeCmd.IsNull() &&
2287 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2288 newAlgo->MeshComputed( myLastComputeCmd );
2293 _pyID geom = addCmd->GetArg( 1 );
2294 bool isLocalAlgo = ( geom != GetGeom() );
2297 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2299 // wrapped algo is created after mesh creation
2300 GetCreationCmd()->AddDependantCmd( addCmd );
2302 if ( isLocalAlgo ) {
2303 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2304 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2305 TCollection_AsciiString( "geom=" ) + geom );
2306 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2307 list < Handle(_pySubMesh) >::iterator smIt;
2308 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2309 Handle(_pySubMesh) subMesh = *smIt;
2310 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2311 if ( geom == subCmd->GetArg( 1 )) {
2312 subCmd->SetObject( algo->GetID() );
2313 subCmd->RemoveArgs();
2314 subMesh->SetCreator( algo );
2319 else // KO - ALGO was already created
2321 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2322 addCmd->RemoveArgs();
2323 addCmd->SetArg( 1, algoID );
2325 addCmd->SetArg( 2, geom );
2326 myNotConvertedAddHypCmds.push_back( addCmd );
2330 // try to convert hypo addition like this:
2331 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2332 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2334 Handle(_pyCommand) addCmd = *cmd;
2335 _pyID hypID = addCmd->GetArg( 2 );
2336 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2337 if ( hyp.IsNull() || hyp->IsAlgo() )
2339 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2341 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2342 _pyID geom = addCmd->GetArg( 1 );
2343 addCmd->RemoveArgs();
2344 addCmd->SetArg( 1, hypID );
2345 if ( geom != GetGeom() )
2346 addCmd->SetArg( 2, geom );
2347 myNotConvertedAddHypCmds.push_back( addCmd );
2351 myAddHypCmds.clear();
2352 mySubmeshes.clear();
2355 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2356 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2360 //================================================================================
2362 * \brief Sets myIsPublished of me and of all objects depending on me.
2364 //================================================================================
2366 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2368 _pyObject::SetRemovedFromStudy(isRemoved);
2370 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2371 for ( ; sm != mySubmeshes.end(); ++sm )
2372 (*sm)->SetRemovedFromStudy(isRemoved);
2374 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2375 for ( ; gr != myGroups.end(); ++gr )
2376 (*gr)->SetRemovedFromStudy(isRemoved);
2378 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2379 for ( ; m != myChildMeshes.end(); ++m )
2380 (*m)->SetRemovedFromStudy(isRemoved);
2382 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2383 for ( ; e != myEditors.end(); ++e )
2384 (*e)->SetRemovedFromStudy(isRemoved);
2387 //================================================================================
2389 * \brief Return true if none of myChildMeshes is in study
2391 //================================================================================
2393 bool _pyMesh::CanClear()
2398 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2399 for ( ; m != myChildMeshes.end(); ++m )
2400 if ( !(*m)->CanClear() )
2406 //================================================================================
2408 * \brief Clear my commands and commands of mesh editor
2410 //================================================================================
2412 void _pyMesh::ClearCommands()
2418 // mark all sub-objects as not removed, except child meshes
2419 list< Handle(_pyMesh) > children;
2420 children.swap( myChildMeshes );
2421 SetRemovedFromStudy( false );
2422 children.swap( myChildMeshes );
2426 _pyObject::ClearCommands();
2428 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2429 for ( ; sm != mySubmeshes.end(); ++sm )
2430 (*sm)->ClearCommands();
2432 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2433 for ( ; gr != myGroups.end(); ++gr )
2434 (*gr)->ClearCommands();
2436 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2437 for ( ; e != myEditors.end(); ++e )
2438 (*e)->ClearCommands();
2441 //================================================================================
2443 * \brief Add a father mesh by ID
2445 //================================================================================
2447 void _pyMesh::addFatherMesh( const _pyID& meshID )
2449 if ( !meshID.IsEmpty() && meshID != GetID() )
2450 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2453 //================================================================================
2455 * \brief Add a father mesh
2457 //================================================================================
2459 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2461 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2463 //myFatherMeshes.push_back( mesh );
2464 mesh->myChildMeshes.push_back( this );
2466 // protect last Compute() from clearing by the next Compute()
2467 mesh->myLastComputeCmd.Nullify();
2471 //================================================================================
2473 * \brief MeshEditor convert its commands to ones of mesh
2475 //================================================================================
2477 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2478 _pyObject( theCreationCmd )
2480 myMesh = theCreationCmd->GetObject();
2481 myCreationCmdStr = theCreationCmd->GetString();
2482 theCreationCmd->Clear();
2484 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2485 if ( !mesh.IsNull() )
2486 mesh->AddEditor( this );
2489 //================================================================================
2491 * \brief convert its commands to ones of mesh
2493 //================================================================================
2495 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2497 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2498 // commands calling these methods are converted to calls of Mesh methods without
2499 // additional modifs, only object is changed from MeshEditor to Mesh.
2500 static TStringSet sameMethods;
2501 if ( sameMethods.empty() ) {
2502 const char * names[] = {
2503 "RemoveElements","RemoveNodes","RemoveOrphanNodes","RemoveNodeWithReconnection",
2504 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2505 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","AddNodeOnSegment",
2506 "MoveNode", "MoveClosestNodeToPoint","InverseDiag","DeleteDiag","AddNodeOnFace",
2507 "Reorient","ReorientObject","Reorient2DBy3D","Reorient2DByNeighbours",
2508 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2509 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2510 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2511 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2512 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2513 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2514 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2515 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2516 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject","Offset",
2517 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2518 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2519 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2520 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2521 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2522 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2523 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2524 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2525 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2526 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2527 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2528 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2529 ,"" }; // <- mark of the end
2530 sameMethods.Insert( names );
2533 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2534 TStringMap diffMethods;
2535 if ( diffMethods.empty() ) {
2536 const char * orig2newName[] = {
2537 // original name --------------> new name
2538 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2539 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2540 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2541 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2542 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2543 ""};// <- mark of the end
2544 diffMethods.Insert( orig2newName );
2547 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2548 // only by last two arguments
2549 static TStringSet diffLastTwoArgsMethods;
2550 if (diffLastTwoArgsMethods.empty() ) {
2551 const char * names[] = {
2552 "MirrorMakeGroups","MirrorObjectMakeGroups",
2553 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2554 "RotateMakeGroups","RotateObjectMakeGroups",
2555 ""};// <- mark of the end
2556 diffLastTwoArgsMethods.Insert( names );
2559 // only a method name is to change?
2560 const TCollection_AsciiString & method = theCommand->GetMethod();
2561 bool isPyMeshMethod = sameMethods.Contains( method );
2562 if ( !isPyMeshMethod )
2564 TCollection_AsciiString newMethod = diffMethods.Value( method );
2565 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2566 theCommand->SetMethod( newMethod );
2568 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2569 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2571 isPyMeshMethod = true;
2572 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2573 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2576 if ( !isPyMeshMethod )
2578 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2579 // functions with the flag "theMakeGroups = True" like:
2580 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2581 int pos = method.Search("MakeGroups");
2584 isPyMeshMethod = true;
2585 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2586 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2588 // 1. Remove "MakeGroups" from the Command
2589 TCollection_AsciiString aMethod = theCommand->GetMethod();
2590 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2593 pos = pos-2; //Remove "0D" from the Command too
2594 aMethod.Trunc(pos-1);
2595 theCommand->SetMethod(aMethod);
2597 // 2. And add last "True" argument(s)
2598 while(nbArgsToAdd--)
2599 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2600 if( is0DmethId || is0DmethObj )
2601 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2605 // ExtrusionSweep0D() -> ExtrusionSweep()
2606 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2607 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2608 method == "ExtrusionSweepObject0D" ))
2610 isPyMeshMethod = true;
2611 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2612 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2613 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2616 // DoubleNode...New(...) -> DoubleNode...(...,True)
2617 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2618 method == "DoubleNodeElemGroupsNew" ||
2619 method == "DoubleNodeGroupNew" ||
2620 method == "DoubleNodeGroupsNew" ||
2621 method == "DoubleNodeElemGroup2New" ||
2622 method == "DoubleNodeElemGroups2New"))
2624 isPyMeshMethod = true;
2625 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2626 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2627 if ( excessLen == 3 )
2629 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2631 else if ( theCommand->GetArg(4) == "0" ||
2632 theCommand->GetArg(5) == "0" )
2634 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2635 // Group = DoubleNodeGroup2New(,,,False, True)
2636 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2637 theCommand->SetResultValue( groupID );
2640 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2641 // FindElementsByPoint(x, y, z, elementType, meshPart)
2642 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2644 isPyMeshMethod = true;
2645 theCommand->SetMethod( "FindElementsByPoint" );
2646 // make the 1st arg be the last one
2647 _pyID partID = theCommand->GetArg( 1 );
2648 int nbArgs = theCommand->GetNbArgs();
2649 for ( int i = 2; i <= nbArgs; ++i )
2650 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2651 theCommand->SetArg( nbArgs, partID );
2653 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2654 if ( !isPyMeshMethod && method == "Reorient2D" )
2656 isPyMeshMethod = true;
2657 _AString mesh = theCommand->GetArg( 1 );
2658 _AString dir = theCommand->GetArg( 2 );
2659 _AString face = theCommand->GetArg( 3 );
2660 _AString point = theCommand->GetArg( 4 );
2661 theCommand->RemoveArgs();
2662 theCommand->SetArg( 1, mesh );
2663 theCommand->SetArg( 2, dir );
2664 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2665 theCommand->SetArg( 3, point );
2667 theCommand->SetArg( 3, face );
2670 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2672 isPyMeshMethod = true;
2673 int crit_arg = theCommand->GetNbArgs();
2674 const _AString& crit = theCommand->GetArg(crit_arg);
2675 if (crit.Search("MaxElementLength2D") != -1)
2676 theCommand->SetArg(crit_arg, "");
2679 if ( isPyMeshMethod )
2681 theCommand->SetObject( myMesh );
2685 // editor creation command is needed only if any editor function is called
2686 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2687 if ( !myCreationCmdStr.IsEmpty() ) {
2688 GetCreationCmd()->GetString() = myCreationCmdStr;
2689 myCreationCmdStr.Clear();
2694 //================================================================================
2696 * \brief Return true if my mesh can be removed
2698 //================================================================================
2700 bool _pyMeshEditor::CanClear()
2702 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2703 return mesh.IsNull() ? true : mesh->CanClear();
2706 //================================================================================
2708 * \brief _pyHypothesis constructor
2709 * \param theCreationCmd -
2711 //================================================================================
2713 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2714 _pyObject( theCreationCmd ), myCurCrMethod(0)
2716 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2719 //================================================================================
2721 * \brief Creates algorithm or hypothesis
2722 * \param theCreationCmd - The engine command creating a hypothesis
2723 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2725 //================================================================================
2727 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2729 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2730 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2732 Handle(_pyHypothesis) hyp, algo;
2735 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2736 if ( hypTypeQuoted.IsEmpty() )
2739 TCollection_AsciiString hypType =
2740 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2742 algo = new _pyAlgorithm( theCreationCmd );
2743 hyp = new _pyHypothesis( theCreationCmd );
2745 if ( hypType == "NumberOfSegments" ) {
2746 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2747 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2748 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2749 hyp->AddArgMethod( "SetNumberOfSegments" );
2750 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2751 hyp->AddArgMethod( "SetScaleFactor" );
2752 hyp->AddArgMethod( "SetReversedEdges" );
2753 // same for ""CompositeSegment_1D:
2754 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2755 hyp->AddArgMethod( "SetNumberOfSegments" );
2756 hyp->AddArgMethod( "SetScaleFactor" );
2757 hyp->AddArgMethod( "SetReversedEdges" );
2759 else if ( hypType == "SegmentLengthAroundVertex" ) {
2760 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2761 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2762 hyp->AddArgMethod( "SetLength" );
2763 // same for ""CompositeSegment_1D:
2764 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2765 hyp->AddArgMethod( "SetLength" );
2767 else if ( hypType == "LayerDistribution2D" ) {
2768 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2769 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2771 else if ( hypType == "LayerDistribution" ) {
2772 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2773 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2775 else if ( hypType == "CartesianParameters3D" ) {
2776 hyp = new _pyComplexParamHypo( theCreationCmd );
2777 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2778 for ( int iArg = 0; iArg < 4; ++iArg )
2779 hyp->setCreationArg( iArg+1, "[]");
2780 hyp->AddAccumulativeMethod( "SetGrid" );
2781 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2785 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2788 return algo->IsValid() ? algo : hyp;
2791 //================================================================================
2793 * \brief Returns true if addition of this hypothesis to a given mesh can be
2794 * wrapped into hypothesis creation
2796 //================================================================================
2798 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2800 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2802 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2803 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2809 //================================================================================
2811 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2812 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2813 * \param theAlgo - The algo that can create this hypo
2814 * \retval bool - false if the command can't be converted
2816 //================================================================================
2818 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2819 const _pyID& theMesh)
2821 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2823 if ( !IsWrappable( theMesh ))
2826 myGeom = theCmd->GetArg( 1 );
2828 Handle(_pyHypothesis) algo;
2830 // find algo created on myGeom in theMesh
2831 algo = theGen->FindAlgo( myGeom, theMesh, this );
2832 if ( algo.IsNull() )
2834 // attach hypothesis creation command to be after algo creation command
2835 // because it can be new created instance of algorithm
2836 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2840 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2841 theCmd->SetResultValue( GetID() );
2842 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2843 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2844 // set args (geom will be set by _pyMesh calling this method)
2845 theCmd->RemoveArgs();
2846 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2847 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2848 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2850 theCmd->SetArg( i+1, "[]");
2852 // set a new creation command
2853 GetCreationCmd()->Clear();
2854 // replace creation command by wrapped instance
2855 // please note, that hypothesis attaches to algo creation command (see upper)
2856 SetCreationCmd( theCmd );
2859 // clear commands setting arg values
2860 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2861 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2864 // set unknown arg commands after hypo creation
2865 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2866 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2867 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2868 afterCmd->AddDependantCmd( *cmd );
2874 //================================================================================
2876 * \brief Remember hypothesis parameter values
2877 * \param theCommand - The called hypothesis method
2879 //================================================================================
2881 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2883 ASSERT( !myIsAlgo );
2884 if ( !theGen->IsToKeepAllCommands() )
2885 rememberCmdOfParameter( theCommand );
2887 bool usedCommand = false;
2888 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2889 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2891 CreationMethod& crMethod = type2meth->second;
2892 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2893 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2895 myArgCommands.push_back( theCommand );
2897 while ( crMethod.myArgs.size() < i+1 )
2898 crMethod.myArgs.push_back( "None" );
2899 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2904 myUnusedCommands.push_back( theCommand );
2907 //================================================================================
2909 * \brief Finish conversion
2911 //================================================================================
2913 void _pyHypothesis::Flush()
2917 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2918 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2919 // Add access to a wrapped mesh
2920 theGen->AddMeshAccessorMethod( *cmd );
2921 // Add access to a wrapped algorithm
2922 theGen->AddAlgoAccessorMethod( *cmd );
2924 cmd = myUnusedCommands.begin();
2925 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2926 // Add access to a wrapped mesh
2927 theGen->AddMeshAccessorMethod( *cmd );
2928 // Add access to a wrapped algorithm
2929 theGen->AddAlgoAccessorMethod( *cmd );
2932 // forget previous hypothesis modifications
2933 myArgCommands.clear();
2934 myUnusedCommands.clear();
2937 //================================================================================
2939 * \brief clear creation, arg and unknown commands
2941 //================================================================================
2943 void _pyHypothesis::ClearAllCommands()
2945 GetCreationCmd()->Clear();
2946 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2947 for ( ; cmd != myArgCommands.end(); ++cmd )
2949 cmd = myUnusedCommands.begin();
2950 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2955 //================================================================================
2957 * \brief Assign fields of theOther to me except myIsWrapped
2959 //================================================================================
2961 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2962 const _pyID& theMesh )
2964 // myCreationCmd = theOther->myCreationCmd;
2965 myIsAlgo = theOther->myIsAlgo;
2966 myIsWrapped = false;
2967 myGeom = theOther->myGeom;
2969 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2970 myAccumulativeMethods = theOther->myAccumulativeMethods;
2971 //myUnusedCommands = theOther->myUnusedCommands;
2972 // init myCurCrMethod
2973 GetCreationMethod( theOther->GetAlgoType() );
2976 //================================================================================
2978 * \brief Analyze my erasability depending on myReferredObjs
2980 //================================================================================
2982 bool _pyHypothesis::CanClear()
2986 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2987 for ( ; obj != myReferredObjs.end(); ++obj )
2988 if ( (*obj)->CanClear() )
2995 //================================================================================
2997 * \brief Clear my commands depending on usage by meshes
2999 //================================================================================
3001 void _pyHypothesis::ClearCommands()
3003 // if ( !theGen->IsToKeepAllCommands() )
3005 // bool isUsed = false;
3006 // int lastComputeOrder = 0;
3007 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
3008 // for ( ; cmd != myComputeCmds.end(); ++cmd )
3009 // if ( ! (*cmd)->IsEmpty() )
3012 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
3013 // lastComputeOrder = (*cmd)->GetOrderNb();
3017 // SetRemovedFromStudy( true );
3021 // // clear my commands invoked after lastComputeOrder
3022 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3023 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3025 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3026 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3027 // // cmds.back()->Clear();
3031 _pyObject::ClearCommands();
3034 //================================================================================
3036 * \brief Find arguments that are objects like mesh, group, geometry
3037 * \param meshes - referred meshes (directly or indirrectly)
3038 * \retval bool - false if a referred geometry is not in the study
3040 //================================================================================
3042 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3044 if ( IsAlgo() ) return true;
3046 bool geomPublished = true;
3047 vector< _AString > args;
3048 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3049 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3051 CreationMethod& crMethod = type2meth->second;
3052 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3054 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3055 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3056 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3057 args.push_back( (*cmd)->GetArg( nb ));
3060 for ( size_t i = 0; i < args.size(); ++i )
3062 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3063 if ( idList.empty() && !args[ i ].IsEmpty() )
3064 idList.push_back( args[ i ]);
3065 list< _pyID >::iterator id = idList.begin();
3066 for ( ; id != idList.end(); ++id )
3068 Handle(_pyObject) obj = theGen->FindObject( *id );
3069 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3072 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3073 geomPublished = false;
3077 myReferredObjs.push_back( obj );
3078 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3079 if ( !mesh.IsNull() )
3080 meshes.push_back( mesh );
3081 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3082 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3083 obj->SetRemovedFromStudy( false );
3087 return geomPublished;
3090 //================================================================================
3092 * \brief Remember theCommand setting a parameter
3094 //================================================================================
3096 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3098 // parameters are discriminated by method name
3099 _AString method = theCommand->GetMethod();
3100 if ( myAccumulativeMethods.count( method ))
3101 return; // this method adds values and not override the previous value
3103 // discriminate commands setting different parameters via one method
3104 // by passing parameter names like e.g. SetOption("size", "0.2")
3105 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3106 theCommand->GetNbArgs() > 1 )
3108 // mangle method by appending a 1st textual arg
3109 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3111 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3112 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3113 if ( !isalpha( arg.Value(2))) continue;
3118 // parameters are discriminated by method name
3119 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3120 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3122 cmds.back()->Clear(); // previous parameter value has not been used
3123 cmds.back() = theCommand;
3127 cmds.push_back( theCommand );
3131 //================================================================================
3133 * \brief Return true if a setting parameter command ha been used to compute mesh
3135 //================================================================================
3137 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3138 _pyCommand::TAddr avoidComputeAddr ) const
3140 bool isUsed = false;
3141 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3142 myComputeAddr2Cmds.begin();
3143 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3145 if ( addr2cmds->first == avoidComputeAddr ) continue;
3146 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3147 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3152 //================================================================================
3154 * \brief Save commands setting parameters as they are used for a mesh computation
3156 //================================================================================
3158 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3160 myComputeCmds.push_back( theComputeCmd );
3161 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3163 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3164 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3165 savedCmds.push_back( m2c->second.back() );
3168 //================================================================================
3170 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3172 //================================================================================
3174 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3176 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3178 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3179 for ( ; cmd != savedCmds.end(); ++cmd )
3181 // check if a cmd has been used to compute another mesh
3182 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3184 // check if a cmd is a sole command setting its parameter;
3185 // don't use method name for search as it can change
3186 map<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3187 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3189 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3190 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3191 if ( cmdIt != cmds.end() )
3193 if ( cmds.back() != *cmd )
3195 cmds.erase( cmdIt );
3202 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3205 //================================================================================
3207 * \brief Sets an argNb-th argument of current creation command
3208 * \param argNb - argument index countered from 1
3210 //================================================================================
3212 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3214 if ( myCurCrMethod )
3216 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3217 myCurCrMethod->myArgs.push_back( "None" );
3218 if ( arg.IsEmpty() )
3219 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3221 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3226 //================================================================================
3228 * \brief Remember hypothesis parameter values
3229 * \param theCommand - The called hypothesis method
3231 //================================================================================
3233 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3235 if ( GetAlgoType() == "Cartesian_3D" )
3237 // CartesianParameters3D hyp
3239 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3240 theCommand->GetMethod() == "SetToAddEdges" )
3242 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3243 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3244 myArgCommands.push_back( theCommand );
3247 if ( theCommand->GetMethod() == "SetGrid" ||
3248 theCommand->GetMethod() == "SetGridSpacing" )
3250 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3251 int iArg = axis.Value(1) - '0';
3252 if ( theCommand->GetMethod() == "SetGrid" )
3254 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3258 myCurCrMethod->myArgs[ iArg ] = "[ ";
3259 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3260 myCurCrMethod->myArgs[ iArg ] += ", ";
3261 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3262 myCurCrMethod->myArgs[ iArg ] += "]";
3264 myArgCommands.push_back( theCommand );
3265 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3266 // accumulative, else, if the creation
3267 // is not converted, commands for axes 1 and 2 are lost
3272 if( theCommand->GetMethod() == "SetLength" )
3274 // NOW it is OBSOLETE
3275 // ex: hyp.SetLength(start, 1)
3276 // hyp.SetLength(end, 0)
3277 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3278 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3279 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3280 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3282 CreationMethod& crMethod = type2meth->second;
3283 while ( (int) crMethod.myArgs.size() < i+1 )
3284 crMethod.myArgs.push_back( "[]" );
3285 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3287 myArgCommands.push_back( theCommand );
3291 _pyHypothesis::Process( theCommand );
3294 //================================================================================
3296 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3298 //================================================================================
3300 void _pyComplexParamHypo::Flush()
3302 list < Handle(_pyCommand) >::iterator cmd;
3305 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3306 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3310 // if ( GetAlgoType() == "Cartesian_3D" )
3312 // _pyID algo = myCreationCmd->GetObject();
3313 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3315 // if ( IsWrapped() )
3317 // StructToList( *cmd, /*checkMethod=*/false );
3318 // const _AString & method = (*cmd)->GetMethod();
3319 // if ( method == "SetFixedPoint" )
3320 // (*cmd)->SetObject( algo );
3326 //================================================================================
3328 * \brief Convert methods of 1D hypotheses to my own methods
3329 * \param theCommand - The called hypothesis method
3331 //================================================================================
3333 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3335 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3338 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3339 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3340 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3342 // TCollection_AsciiString cmd =
3343 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3344 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3345 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3348 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3350 // // 1D hypo is already set, so distribution changes and the old
3351 // // 1D hypo is thrown away
3352 // my1dHyp->ClearAllCommands();
3355 // //my1dHyp->SetRemovedFromStudy( false );
3357 // if ( !myArgCommands.empty() )
3358 // myArgCommands.back()->Clear();
3359 myCurCrMethod->myArgs.push_back( hyp1dID );
3360 myArgCommands.push_back( theCommand );
3363 //================================================================================
3366 * \param theAdditionCmd - command to be converted
3367 * \param theMesh - mesh instance
3368 * \retval bool - status
3370 //================================================================================
3372 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3373 const _pyID& theMesh)
3375 myIsWrapped = false;
3377 if ( my1dHyp.IsNull() )
3380 // set "SetLayerDistribution()" after addition cmd
3381 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3383 _pyID geom = theAdditionCmd->GetArg( 1 );
3385 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3386 if ( !algo.IsNull() )
3388 my1dHyp->SetMesh( theMesh );
3389 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3390 algo->GetAlgoType().ToCString());
3391 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3394 // clear "SetLayerDistribution()" cmd
3395 myArgCommands.back()->Clear();
3397 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3399 // find RadialPrism algo created on <geom> for theMesh
3400 GetCreationCmd()->SetObject( algo->GetID() );
3401 GetCreationCmd()->SetMethod( myAlgoMethod );
3402 GetCreationCmd()->RemoveArgs();
3403 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3409 //================================================================================
3413 //================================================================================
3415 void _pyLayerDistributionHypo::Flush()
3417 // as creation of 1D hyp was written later then it's edition,
3418 // we need to find all it's edition calls and process them
3419 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3421 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3423 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3424 if ( hyp1dID.IsEmpty() ) continue;
3426 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3428 // make a new name for 1D hyp = "HypType" + "_Distribution"
3430 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3432 if ( prevNewName.IsEmpty() ) continue;
3433 newName = prevNewName;
3437 if ( hyp1d->IsWrapped() ) {
3438 newName = hyp1d->GetCreationCmd()->GetMethod();
3441 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3442 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3444 newName += "_Distribution";
3445 prevNewName = newName;
3447 hyp1d->GetCreationCmd()->SetResultValue( newName );
3449 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3450 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3451 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3452 const _pyID& objID = (*cmdIt)->GetObject();
3453 if ( objID == hyp1dID ) {
3454 if ( !hyp1d.IsNull() )
3456 hyp1d->Process( *cmdIt );
3457 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3459 ( *cmdIt )->SetObject( newName );
3462 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3463 (*cmd)->SetArg( 1, newName );
3467 //================================================================================
3469 * \brief additionally to Addition2Creation, clears SetDistrType() command
3470 * \param theCmd - AddHypothesis() command
3471 * \param theMesh - mesh to which a hypothesis is added
3472 * \retval bool - conversion result
3474 //================================================================================
3476 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3477 const _pyID& theMesh)
3479 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3480 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3481 bool scaleDistrType = false;
3482 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3483 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3484 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3485 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3486 scaleDistrType = true;
3489 else if ( !scaleDistrType ) {
3490 // distribution type changed: remove scale factor from args
3491 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3492 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3494 CreationMethod& crMethod = type2meth->second;
3495 if ( crMethod.myArgs.size() == 2 )
3496 crMethod.myArgs.pop_back();
3503 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3506 //================================================================================
3508 * \brief remove repeated commands defining distribution
3510 //================================================================================
3512 void _pyNumberOfSegmentsHyp::Flush()
3514 // find number of the last SetDistrType() command
3515 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3516 int distrTypeNb = 0;
3517 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3518 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3519 if ( cmd != myUnusedCommands.rbegin() )
3520 distrTypeNb = (*cmd)->GetOrderNb();
3522 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3525 // clear commands before the last SetDistrType()
3526 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3527 set< int > treatedCmdNbs; // avoid treating same cmd twice
3528 for ( int i = 0; i < 2; ++i ) {
3529 set<TCollection_AsciiString> uniqueMethods;
3530 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3531 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3533 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3534 continue;// avoid treating same cmd twice
3535 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3536 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3537 if ( !clear || method == "SetNumberOfSegments" ) {
3538 bool isNewInSet = uniqueMethods.insert( method ).second;
3539 clear = !isNewInSet;
3548 //================================================================================
3550 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3551 * into regular1D.LengthNearVertex( length, vertex )
3552 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3553 * \param theMesh - The mesh needing this hypo
3554 * \retval bool - false if the command can't be converted
3556 //================================================================================
3558 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3559 const _pyID& theMeshID)
3561 if ( IsWrappable( theMeshID )) {
3563 _pyID vertex = theCmd->GetArg( 1 );
3565 // the problem here is that segment algo can be not found
3566 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3567 // geometry where segment algorithm is assigned
3568 _pyID geom = vertex;
3569 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3570 while ( algo.IsNull() && !geom.IsEmpty()) {
3571 // try to find geom as a father of <vertex>
3572 geom = FatherID( geom );
3573 algo = theGen->FindAlgo( geom, theMeshID, this );
3575 if ( algo.IsNull() || geom.IsEmpty() )
3576 return false; // also possible to find geom as brother of veretex...
3578 // set geom instead of vertex
3579 theCmd->SetArg( 1, geom );
3581 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3582 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3583 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3585 // set vertex as a second arg
3586 theCmd->SetArg( 2, vertex );
3594 //================================================================================
3596 * \brief _pyAlgorithm constructor
3597 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3599 //================================================================================
3601 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3602 : _pyHypothesis( theCreationCmd )
3607 //================================================================================
3609 * \brief Convert the command adding an algorithm to mesh
3610 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3611 * \param theMesh - The mesh needing this algo
3612 * \retval bool - false if the command can't be converted
3614 //================================================================================
3616 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3617 const _pyID& theMeshID)
3619 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3620 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3621 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3627 //================================================================================
3629 * \brief Return starting position of a part of python command
3630 * \param thePartIndex - The index of command part
3631 * \retval int - Part position
3633 //================================================================================
3635 int _pyCommand::GetBegPos( int thePartIndex ) const
3639 if ( myBegPos.Length() < thePartIndex )
3641 ASSERT( thePartIndex > 0 );
3642 return myBegPos( thePartIndex );
3645 //================================================================================
3647 * \brief Store starting position of a part of python command
3648 * \param thePartIndex - The index of command part
3649 * \param thePosition - Part position
3651 //================================================================================
3653 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3655 while ( myBegPos.Length() < thePartIndex )
3656 myBegPos.Append( UNKNOWN );
3657 ASSERT( thePartIndex > 0 );
3658 myBegPos( thePartIndex ) = thePosition;
3661 //================================================================================
3663 * \brief Returns whitespace symbols at the line beginning
3664 * \retval TCollection_AsciiString - result
3666 //================================================================================
3668 TCollection_AsciiString _pyCommand::GetIndentation()
3671 //while ( end <= Length() && isblank( myString.Value( end )))
3672 //ANA: isblank() function isn't provided in VC2010 compiler
3673 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3675 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3678 //================================================================================
3680 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3681 * \retval const TCollection_AsciiString & - ResultValue substring
3683 //================================================================================
3685 const TCollection_AsciiString & _pyCommand::GetResultValue()
3687 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3689 SetBegPos( RESULT_IND, EMPTY );
3690 int begPos, endPos = myString.Location( "=", 1, Length() );
3694 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3695 if ( begPos < endPos )
3697 SetBegPos( RESULT_IND, begPos );
3699 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3700 myRes = myString.SubString( begPos, endPos );
3707 //================================================================================
3709 * \brief Return number of python command result value ResultValue = Obj.Meth()
3711 //================================================================================
3713 int _pyCommand::GetNbResultValues()
3716 return myResults.Length();
3720 //================================================================================
3722 * \brief Return substring of python command looking like
3723 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3724 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3726 //================================================================================
3727 const _AString& _pyCommand::GetResultValue(int res)
3729 if ( GetResultValue().IsEmpty() )
3730 return theEmptyString;
3732 if ( myResults.IsEmpty() )
3735 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3736 ++begPos; // skip [, else the whole list is returned
3737 while ( begPos < myRes.Length() ) {
3738 _AString result = GetWord( myRes, begPos, true );
3739 begPos += result.Length();
3741 // result.RemoveAll('[');
3742 // result.RemoveAll(']');
3747 myResults.Append( result );
3750 if ( res > 0 && res <= myResults.Length() )
3751 return myResults( res );
3752 return theEmptyString;
3755 //================================================================================
3757 * \brief Return substring of python command looking like ResVal = Object.Meth()
3758 * \retval const TCollection_AsciiString & - Object substring
3760 //================================================================================
3762 const TCollection_AsciiString & _pyCommand::GetObject()
3764 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3767 int begPos = GetBegPos( RESULT_IND );
3769 begPos = myString.Location( "=", 1, Length() ) + 1;
3770 // is '=' in the string argument (for example, name) or not
3771 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3772 for ( int i = 1; i < begPos-1; i++ )
3773 switch ( myString.Value( i )) {
3774 case '\'': nb[0]++; break;
3775 case '"' : nb[1]++; break;
3776 case '(' : nb[2]++; break;
3777 case ')' : nb[3]++; break;
3779 // if = is inside a string or a list
3780 // then get an object at the start of the command
3781 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3785 begPos += myRes.Length();
3787 myObj = GetWord( myString, begPos, true );
3788 if ( begPos != EMPTY )
3790 // check if object is complex,
3791 // so far consider case like "smesh.Method()"
3792 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3793 //if ( bracketPos==0 ) bracketPos = Length();
3794 int dotPos = begPos+myObj.Length();
3795 while ( dotPos+1 < bracketPos ) {
3796 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3801 if ( dotPos > begPos+myObj.Length() )
3802 myObj = myString.SubString( begPos, dotPos-1 );
3805 // 1st word after '=' is an object
3806 // else // no method -> no object
3812 SetBegPos( OBJECT_IND, begPos );
3818 //================================================================================
3820 * \brief Return substring of python command looking like ResVal = Obj.Method()
3821 * \retval const TCollection_AsciiString & - Method substring
3823 //================================================================================
3825 const TCollection_AsciiString & _pyCommand::GetMethod()
3827 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3830 int begPos = GetBegPos( OBJECT_IND );
3831 bool forward = true;
3833 begPos = myString.Location( "(", 1, Length() ) - 1;
3837 begPos += myObj.Length();
3840 myMeth = GetWord( myString, begPos, forward );
3841 SetBegPos( METHOD_IND, begPos );
3847 //================================================================================
3849 * \brief Returns true if there are brackets after the method
3851 //================================================================================
3853 bool _pyCommand::IsMethodCall()
3855 if ( GetMethod().IsEmpty() )
3857 if ( myString.StartsWith("#") )
3859 if ( myString.StartsWith("SHAPERSTUDY") ) // skip shaperstudy specific dump string analysis
3861 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3862 return ( s[0] == '(' || s[1] == '(' );
3865 //================================================================================
3867 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3868 * \retval const TCollection_AsciiString & - Arg<index> substring
3870 //================================================================================
3872 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3874 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3878 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3880 pos = myString.Location( "(", 1, Length() );
3884 // we are at or before '(', skip it if present
3886 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3887 if ( pos > Length() )
3891 SetBegPos( ARG1_IND, 0 ); // even no '('
3892 return theEmptyString;
3896 list< TCollection_AsciiString > separatorStack( 1, ",)");
3897 bool ignoreNesting = false;
3899 while ( pos <= Length() )
3901 const char chr = myString.Value( pos );
3903 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3905 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3907 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3909 TCollection_AsciiString arg;
3910 if ( pos-1 >= prevPos ) {
3911 arg = myString.SubString( prevPos, pos-1 );
3912 arg.RightAdjust(); // remove spaces
3915 if ( !arg.IsEmpty() || chr == ',' )
3917 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3918 myArgs.Append( arg );
3924 else // end of nesting args found
3926 separatorStack.pop_back();
3927 ignoreNesting = false;
3930 else if ( !ignoreNesting )
3933 case '(' : separatorStack.push_back(")"); break;
3934 case '[' : separatorStack.push_back("]"); break;
3935 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3936 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3943 if ( myArgs.Length() < index )
3944 return theEmptyString;
3945 return myArgs( index );
3948 //================================================================================
3950 * \brief Return position where arguments begin
3952 //================================================================================
3954 int _pyCommand::GetArgBeginning() const
3956 int pos = GetBegPos( ARG1_IND );
3957 if ( pos == UNKNOWN )
3959 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3960 if ( pos < 1 && Length() >= 4 )
3961 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3966 //================================================================================
3968 * \brief Check if char is a word part
3969 * \param c - The character to check
3970 * \retval bool - The check result
3972 //================================================================================
3974 static inline bool isWord(const char c, const bool dotIsWord)
3977 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3980 //================================================================================
3982 * \brief Looks for a word in the string and returns word's beginning
3983 * \param theString - The input string
3984 * \param theStartPos - The position to start the search, returning word's beginning
3985 * \param theForward - The search direction
3986 * \retval TCollection_AsciiString - The found word
3988 //================================================================================
3990 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3992 const bool theForward,
3993 const bool dotIsWord )
3995 int beg = theStartPos, end = theStartPos;
3996 theStartPos = EMPTY;
3997 if ( beg < 1 || beg > theString.Length() )
3998 return theEmptyString;
4000 if ( theForward ) { // search forward
4002 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
4004 if ( beg > theString.Length() )
4005 return theEmptyString; // no word found
4008 char begChar = theString.Value( beg );
4009 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
4010 char endChar = ( begChar == '[' ) ? ']' : begChar;
4011 // end is at the corresponding quoting mark or bracket
4012 while ( end < theString.Length() &&
4013 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
4017 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
4022 else { // search backward
4024 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4027 return theEmptyString; // no word found
4029 char endChar = theString.Value( end );
4030 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4031 char begChar = ( endChar == ']' ) ? '[' : endChar;
4032 // beg is at the corresponding quoting mark
4034 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4038 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4044 //cout << theString << " ---- " << beg << " - " << end << endl;
4045 if ( end > theString.Length() )
4047 theStartPos = EMPTY;
4048 return theEmptyString;
4050 return theString.SubString( beg, end );
4053 //================================================================================
4055 * \brief Returns true if the string looks like a study entry
4057 //================================================================================
4059 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4061 if ( str.Length() < 5 ) return false;
4063 int nbColons = 0, isColon;
4064 for ( int i = 1; i <= str.Length(); ++i )
4066 char c = str.Value(i);
4067 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4069 nbColons += isColon;
4071 return nbColons > 2 && str.Length()-nbColons > 2;
4074 //================================================================================
4076 * \brief Returns true if the string looks like an object ID but not like a list,
4077 * string, command etc.
4079 //================================================================================
4081 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4083 if ( str.Length() < 1 ) return false;
4085 const char* s = str.ToCString();
4087 for ( int i = 0; i < str.Length(); ++i )
4088 if ( !IsIDChar( s[i] ))
4094 //================================================================================
4096 * \brief Finds entries in a string
4098 //================================================================================
4100 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4102 std::list< _pyID > resList;
4104 while ( ++pos <= str.Length() )
4106 if ( !isdigit( str.Value( pos ))) continue;
4107 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4110 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4111 _pyID entry = str.SubString( pos, end-1 );
4113 if ( IsStudyEntry( entry ))
4114 resList.push_back( entry );
4119 //================================================================================
4121 * \brief Look for position where not space char is
4122 * \param theString - The string
4123 * \param thePos - The position to search from and which returns result
4124 * \retval bool - false if there are only space after thePos in theString
4126 //================================================================================
4128 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4130 if ( thePos < 1 || thePos > theString.Length() )
4133 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4136 return thePos <= theString.Length();
4139 //================================================================================
4141 * \brief Modify a part of the command
4142 * \param thePartIndex - The index of the part
4143 * \param thePart - The new part string
4144 * \param theOldPart - The old part
4146 //================================================================================
4148 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4149 TCollection_AsciiString& theOldPart)
4151 int pos = GetBegPos( thePartIndex );
4152 if ( pos <= Length() && theOldPart != thePart)
4154 TCollection_AsciiString seperator;
4156 pos = GetBegPos( thePartIndex + 1 );
4157 if ( pos < 1 ) return;
4158 switch ( thePartIndex ) {
4159 case RESULT_IND: seperator = " = "; break;
4160 case OBJECT_IND: seperator = "."; break;
4161 case METHOD_IND: seperator = "()"; break;
4165 myString.Remove( pos, theOldPart.Length() );
4166 if ( !seperator.IsEmpty() )
4167 myString.Insert( pos , seperator );
4168 myString.Insert( pos, thePart );
4169 // update starting positions of the following parts
4170 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4171 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4172 if ( myBegPos( i ) > 0 )
4173 myBegPos( i ) += posDelta;
4175 theOldPart = thePart;
4179 //================================================================================
4181 * \brief Set argument
4182 * \param index - The argument index, it counts from 1
4183 * \param theArg - The argument string
4185 //================================================================================
4187 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4190 int argInd = ARG1_IND + index - 1;
4191 int pos = GetBegPos( argInd );
4192 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4194 // find a closing parenthesis
4195 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4196 int lastArgInd = GetNbArgs();
4197 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4198 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4203 while ( pos > 0 && myString.Value( pos ) != ')' )
4206 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4210 while ( myArgs.Length() < index ) {
4211 if ( myArgs.Length() )
4212 myString.Insert( pos++, "," );
4213 myArgs.Append("None");
4214 myString.Insert( pos, myArgs.Last() );
4215 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4216 pos += myArgs.Last().Length();
4219 SetPart( argInd, theArg, myArgs( index ));
4222 //================================================================================
4224 * \brief Empty arg list
4226 //================================================================================
4228 void _pyCommand::RemoveArgs()
4230 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4231 myString.Trunc( pos );
4234 if ( myBegPos.Length() >= ARG1_IND )
4235 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4238 //================================================================================
4240 * \brief Comment a python command
4242 //================================================================================
4244 void _pyCommand::Comment()
4246 if ( IsEmpty() ) return;
4249 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4250 if ( i <= Length() )
4252 myString.Insert( i, "#" );
4253 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4255 int begPos = GetBegPos( iPart );
4256 if ( begPos != UNKNOWN && begPos != EMPTY )
4257 SetBegPos( iPart, begPos + 1 );
4262 //================================================================================
4264 * \brief Set dependent commands after this one
4266 //================================================================================
4268 bool _pyCommand::SetDependentCmdsAfter() const
4270 bool orderChanged = false;
4271 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4272 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4273 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4274 orderChanged = true;
4275 theGen->SetCommandAfter( *cmd, this );
4276 (*cmd)->SetDependentCmdsAfter();
4279 return orderChanged;
4281 //================================================================================
4283 * \brief Insert accessor method after theObjectID
4284 * \param theObjectID - id of the accessed object
4285 * \param theAcsMethod - name of the method giving access to the object
4286 * \retval bool - false if theObjectID is not found in the command string
4288 //================================================================================
4290 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4292 if ( !theAcsMethod )
4294 // start object search from the object, i.e. ignore result
4296 int beg = GetBegPos( OBJECT_IND );
4297 if ( beg < 1 || beg > Length() )
4300 while (( beg = myString.Location( theObjectID, beg, Length() )))
4302 // check that theObjectID is not just a part of a longer ID
4303 int afterEnd = beg + theObjectID.Length();
4304 Standard_Character c = myString.Value( afterEnd );
4305 if ( !IsIDChar( c ))
4307 // check if accessor method already present
4309 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4311 int oldLen = Length();
4312 myString.Insert( afterEnd, (char*) theAcsMethod );
4313 myString.Insert( afterEnd, "." );
4314 // update starting positions of the parts following the modified one
4315 int posDelta = Length() - oldLen;
4316 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4317 if ( myBegPos( i ) > afterEnd )
4318 myBegPos( i ) += posDelta;
4323 beg = afterEnd; // is a part -> next search
4328 //================================================================================
4330 * \brief Creates pyObject
4332 //================================================================================
4334 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4335 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4340 //================================================================================
4342 * \brief Set up myID and myIsPublished
4344 //================================================================================
4346 void _pyObject::setID(const _pyID& theID)
4349 myIsPublished = !theGen->IsNotPublished( GetID() );
4352 //================================================================================
4354 * \brief Clear myCreationCmd and myProcessedCmds
4356 //================================================================================
4358 void _pyObject::ClearCommands()
4363 if ( !myCreationCmd.IsNull() )
4364 myCreationCmd->Clear();
4366 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4367 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4371 //================================================================================
4373 * \brief Return method name giving access to an interaface object wrapped by python class
4374 * \retval const char* - method name
4376 //================================================================================
4378 const char* _pyObject::AccessorMethod() const
4382 //================================================================================
4384 * \brief Return ID of a father
4386 //================================================================================
4388 _pyID _pyObject::FatherID(const _pyID & childID)
4390 int colPos = childID.SearchFromEnd(':');
4392 return childID.SubString( 1, colPos-1 );
4396 //================================================================================
4398 * \brief SelfEraser erases creation command if none of it's commands invoked
4399 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4401 //================================================================================
4403 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4404 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4406 myIsPublished = true; // prevent clearing as a not published
4407 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4410 //================================================================================
4412 * \brief SelfEraser erases creation command if none of it's commands invoked
4413 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4415 //================================================================================
4417 bool _pySelfEraser::CanClear()
4419 bool toErase = false;
4420 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4423 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4424 for ( ; cmd != myArgCmds.end(); ++cmd )
4425 nbArgUses += IsAliveCmd( *cmd );
4427 toErase = ( nbArgUses < 1 );
4432 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4433 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4434 for ( ; cmd != cmds.end(); )
4435 // check of cmd emptiness is not enough as object can change
4436 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4439 cmd = cmds.erase( cmd ); // save the cmd from clearing
4441 toErase = ( nbCalls < 1 );
4446 //================================================================================
4448 * \brief Check if a command is or can be cleared
4450 //================================================================================
4452 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4454 if ( theCmd->IsEmpty() )
4457 if ( !theGen->IsToKeepAllCommands() )
4459 const _pyID& objID = theCmd->GetObject();
4460 Handle( _pyObject ) obj = theGen->FindObject( objID );
4461 if ( !obj.IsNull() )
4462 return !obj->CanClear();
4467 //================================================================================
4469 * \brief SelfEraser erases creation command if none of it's commands invoked
4470 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4472 //================================================================================
4474 void _pySelfEraser::Flush()
4478 myIsPublished = false;
4479 _pyObject::ClearCommands();
4483 //================================================================================
4485 * \brief _pySubMesh constructor
4487 //================================================================================
4489 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4490 _pyObject(theCreationCmd)
4492 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4493 if ( toKeepAgrCmds )
4494 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4497 //================================================================================
4499 * \brief Return true if a sub-mesh can be used as argument of the given method
4501 //================================================================================
4503 bool _pySubMesh::CanBeArgOfMethod(const _AString& /*theMethodName*/)
4506 // names of all methods where a sub-mesh can be used as argument
4507 // static TStringSet methods;
4508 // if ( methods.empty() ) {
4509 // const char * names[] = {
4510 // // methods of SMESH_Gen
4512 // // methods of SMESH_Group
4514 // // methods of SMESH_Measurements
4516 // // methods of SMESH_Mesh
4517 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4519 // // methods of SMESH_MeshEditor
4520 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4521 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4522 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4523 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4524 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4525 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4526 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4527 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4528 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4529 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4530 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4531 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4532 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4533 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4534 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4535 // "" }; // <- mark of end
4536 // methods.Insert( names );
4538 // return methods.Contains( theMethodName );
4541 //================================================================================
4543 * \brief count invoked commands
4545 //================================================================================
4547 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4549 _pyObject::Process(theCommand); // count calls of Process()
4552 //================================================================================
4554 * \brief Move creation command depending on invoked commands
4556 //================================================================================
4558 void _pySubMesh::Flush()
4560 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4561 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4562 else if ( !myCreator.IsNull() )
4563 // move to be just after creator
4564 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4566 // move sub-mesh usage after creation cmd
4567 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4568 for ( ; cmd != myArgCmds.end(); ++cmd )
4569 if ( !(*cmd)->IsEmpty() )
4570 GetCreationCmd()->AddDependantCmd( *cmd );
4573 //================================================================================
4575 * \brief Creates _pyGroup
4577 //================================================================================
4579 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4580 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4582 if ( !id.IsEmpty() )
4585 myCanClearCreationCmd = true;
4587 const _AString& method = theCreationCmd->GetMethod();
4588 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4590 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4592 // ----------------------------------------------------------------------
4593 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4595 _pyID geom = theCreationCmd->GetArg( 3 );
4596 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4597 // next if(){...} section is commented
4598 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4599 // theCreationCmd->SetMethod( "Group" );
4600 // theCreationCmd->RemoveArgs();
4601 // theCreationCmd->SetArg( 1, geom );
4604 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4605 _pyID type = theCreationCmd->GetArg( 1 );
4606 _pyID name = theCreationCmd->GetArg( 2 );
4607 theCreationCmd->SetMethod( "GroupOnGeom" );
4608 theCreationCmd->RemoveArgs();
4609 theCreationCmd->SetArg( 1, geom );
4610 theCreationCmd->SetArg( 2, name );
4611 theCreationCmd->SetArg( 3, type );
4614 else if ( method == "CreateGroupFromFilter" )
4616 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4617 theCreationCmd->SetMethod( "GroupOnFilter" );
4619 _pyID filterID = theCreationCmd->GetArg(3);
4620 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4621 if ( !filter.IsNull())
4623 if ( !filter->GetNewID().IsEmpty() )
4624 theCreationCmd->SetArg( 3, filter->GetNewID() );
4625 //filter->AddUser( this );
4629 else if ( method == "GetGroups" )
4631 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4635 // theCreationCmd does something else apart from creation of this group
4636 // and thus it can't be cleared if this group is removed
4637 myCanClearCreationCmd = false;
4641 //================================================================================
4643 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4646 //================================================================================
4648 bool _pyGroup::CanClear()
4653 if ( !myCanClearCreationCmd &&
4654 !myCreationCmd.IsNull() &&
4655 myCreationCmd->GetMethod() == "GetGroups" )
4657 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4658 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4659 list< _pyID >::iterator grID = idList.begin();
4660 if ( GetID() == *grID )
4662 myCanClearCreationCmd = true;
4663 list< Handle(_pyGroup ) > groups;
4664 for ( ; grID != idList.end(); ++grID )
4666 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4667 if ( group.IsNull() ) continue;
4668 groups.push_back( group );
4669 if ( group->IsInStudy() )
4670 myCanClearCreationCmd = false;
4672 // set myCanClearCreationCmd == true to all groups
4673 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4674 for ( ; group != groups.end(); ++group )
4675 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4679 return myCanClearCreationCmd;
4682 //================================================================================
4684 * \brief set myCanClearCreationCmd = true if the main action of the creation
4685 * command is discarded
4687 //================================================================================
4689 void _pyGroup::RemovedWithContents()
4691 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4692 // via a created group
4693 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4694 // myCanClearCreationCmd = true;
4697 //================================================================================
4699 * \brief To convert creation of a group by filter
4701 //================================================================================
4703 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4705 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4706 // group = mesh.CreateEmptyGroup( elemType, groupName )
4707 // aFilter.SetMesh(mesh)
4708 // nbAdd = group.AddFrom( aFilter )
4709 Handle(_pyFilter) filter;
4710 if ( theCommand->GetMethod() == "AddFrom" )
4712 _pyID idSource = theCommand->GetArg(1);
4713 // check if idSource is a filter
4714 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4715 if ( !filter.IsNull() )
4717 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4718 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4719 while ( *cmdIt != theCommand ) ++cmdIt;
4720 while ( (*cmdIt)->GetOrderNb() != 1 )
4722 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4723 if ((setMeshCmd->GetObject() == idSource ||
4724 setMeshCmd->GetObject() == filter->GetNewID() )
4726 setMeshCmd->GetMethod() == "SetMesh")
4728 setMeshCmd->Clear();
4732 // replace 3 commands by one
4733 theCommand->Clear();
4734 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4735 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4736 if ( !filter->GetNewID().IsEmpty() )
4737 idSource = filter->GetNewID();
4738 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4739 makeGroupCmd->SetArg( 1, name );
4740 makeGroupCmd->SetArg( 2, idSource );
4741 filter->AddArgCmd( makeGroupCmd );
4744 else if ( theCommand->GetMethod() == "SetFilter" )
4746 // set new name of a filter or clear the command if the same filter is set
4747 _pyID filterID = theCommand->GetArg(1);
4748 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4749 if ( !myFilter.IsNull() && filter == myFilter )
4750 theCommand->Clear();
4751 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4752 theCommand->SetArg( 1, filter->GetNewID() );
4755 else if ( theCommand->GetMethod() == "GetFilter" )
4757 // GetFilter() returns a filter with other ID, make myFilter process
4758 // calls of the returned filter
4759 if ( !myFilter.IsNull() )
4761 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4762 theCommand->Clear();
4766 // if ( !filter.IsNull() )
4767 // filter->AddUser( this );
4769 theGen->AddMeshAccessorMethod( theCommand );
4772 //================================================================================
4774 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4776 //================================================================================
4778 void _pyGroup::Flush()
4780 if ( !theGen->IsToKeepAllCommands() &&
4781 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4783 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4787 //================================================================================
4789 * \brief Constructor of _pyFilter
4791 //================================================================================
4793 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4794 :_pyObject(theCreationCmd), myNewID( newID )
4796 //myIsPublished = true; // prevent clearing as a not published
4797 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4800 //================================================================================
4802 * \brief To convert creation of a filter by criteria and
4803 * to replace an old name by a new one
4805 //================================================================================
4807 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4809 if ( theCommand->GetObject() == GetID() )
4810 _pyObject::Process(theCommand); // count commands
4812 if ( !myNewID.IsEmpty() )
4813 theCommand->SetObject( myNewID );
4815 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4816 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4817 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4818 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4819 theCommand->GetMethod() == "SetCriteria")
4821 // aFilter.SetCriteria(aCriteria) ->
4822 // aFilter = smesh.GetFilterFromCriteria(criteria)
4823 if ( myNewID.IsEmpty() )
4824 theCommand->SetResultValue( GetID() );
4826 theCommand->SetResultValue( myNewID );
4827 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4828 theCommand->SetMethod( "GetFilterFromCriteria" );
4830 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4831 GetCreationCmd()->Clear();
4832 GetCreationCmd()->GetString() = theCommand->GetString();
4833 theCommand->Clear();
4834 theCommand->AddDependantCmd( GetCreationCmd() );
4835 // why swap? -- it's needed
4836 //GetCreationCmd()->Clear();
4838 else if ( theCommand->GetMethod() == "SetMesh" )
4840 if ( myMesh == theCommand->GetArg( 1 ))
4841 theCommand->Clear();
4843 myMesh = theCommand->GetArg( 1 );
4844 theGen->AddMeshAccessorMethod( theCommand );
4848 //================================================================================
4850 * \brief Set new filter name to the creation command and to myArgCmds
4852 //================================================================================
4854 void _pyFilter::Flush()
4856 if ( myNewID.IsEmpty() ) return;
4858 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4859 for ( ; cmd != myArgCmds.end(); ++cmd )
4860 if ( !(*cmd)->IsEmpty() )
4862 _AString cmdStr = (*cmd)->GetString();
4863 _AString id = GetID();
4864 int pos = cmdStr.Search( id );
4867 cmdStr.Remove( pos, id.Length() );
4868 cmdStr.Insert( pos, myNewID );
4871 (*cmd)->GetString() = cmdStr;
4874 if ( !GetCreationCmd()->IsEmpty() )
4875 GetCreationCmd()->SetResultValue( myNewID );
4878 //================================================================================
4880 * \brief Return true if all my users can be cleared
4882 //================================================================================
4884 bool _pyObject::CanClear()
4886 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4887 for ( ; cmd != myArgCmds.end(); ++cmd )
4888 if ( !(*cmd)->IsEmpty() )
4890 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4891 if ( !obj.IsNull() && !obj->CanClear() )
4894 return ( !myIsPublished );
4897 //================================================================================
4899 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4901 //================================================================================
4903 _pyHypothesisReader::_pyHypothesisReader()
4906 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4907 LDOMParser xmlParser;
4908 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4910 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4914 INFOS( xmlParser.GetError(data) );
4917 // <algorithm type="Regular_1D"
4918 // label-id="Wire discretisation"
4921 // <algo>Regular_1D=Segment()</algo>
4922 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4924 LDOM_Document xmlDoc = xmlParser.getDocument();
4925 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4926 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4928 LDOM_Node algoNode = algoNodeList.item( i );
4929 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4930 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4931 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4933 _AString text, algoType, method, arg;
4934 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4936 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4937 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4938 text = textNode.getNodeValue();
4939 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4940 algoType = algoCmd->GetResultValue();
4941 method = algoCmd->GetMethod();
4942 arg = algoCmd->GetArg(1);
4943 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4945 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4946 algo->SetConvMethodAndType( method, algoType );
4947 if ( !arg.IsEmpty() )
4948 algo->setCreationArg( 1, arg );
4950 myType2Hyp[ algoType ] = algo;
4954 if ( algoType.IsEmpty() ) continue;
4956 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4958 Handle( _pyHypothesis ) hyp;
4959 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4961 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4962 LDOM_Node textNode = pyHypoNode.getFirstChild();
4963 text = textNode.getNodeValue();
4964 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4965 hypType = hypoCmd->GetResultValue();
4966 method = hypoCmd->GetMethod();
4967 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4969 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4970 if ( type2hyp == myType2Hyp.end() )
4971 hyp = new _pyHypothesis( hypoCmd );
4973 hyp = type2hyp->second;
4974 hyp->SetConvMethodAndType( method, algoType );
4975 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4977 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4978 _AString argMethod = argCmd.GetMethod();
4979 _AString argNbText = argCmd.GetArg( 1 );
4980 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4981 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4983 hyp->AddArgMethod( argMethod,
4984 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4986 myType2Hyp[ hypType ] = hyp;
4990 // <hypothesis type="BLSURF_Parameters"
4994 // <accumulative-methods>
4995 // SetEnforcedVertex,
4996 // SetEnforcedVertexNamed
4997 // </accumulative-methods>
5001 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
5002 for ( int i = 0; i < hypNodeList.getLength(); ++i )
5004 LDOM_Node hypNode = hypNodeList.item( i );
5005 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
5006 _AString hypType = hypElem.getAttribute("type");
5007 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
5008 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
5010 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5011 if ( type2hyp == myType2Hyp.end() ) continue;
5013 LDOM_Node methNode = methNodeList.item( 0 );
5014 LDOM_Node textNode = methNode.getFirstChild();
5015 _AString text = textNode.getNodeValue();
5019 method = _pyCommand::GetWord( text, pos, /*forward= */true );
5020 pos += method.Length();
5021 type2hyp->second->AddAccumulativeMethod( method );
5023 while ( !method.IsEmpty() );
5026 } // loop on xmlPaths
5029 //================================================================================
5031 * \brief Returns a new hypothesis initialized according to the read information
5033 //================================================================================
5035 Handle(_pyHypothesis)
5036 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5037 const Handle(_pyCommand)& creationCmd) const
5039 Handle(_pyHypothesis) resHyp, sampleHyp;
5041 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5042 if ( type2hyp != myType2Hyp.end() )
5043 sampleHyp = type2hyp->second;
5045 if ( sampleHyp.IsNull() )
5047 resHyp = new _pyHypothesis(creationCmd);
5051 if ( sampleHyp->IsAlgo() )
5052 resHyp = new _pyAlgorithm( creationCmd );
5054 resHyp = new _pyHypothesis(creationCmd);
5055 resHyp->Assign( sampleHyp, _pyID() );
5060 //================================================================================
5062 * \brief Adds an object ID to some family of IDs with a common prefix
5063 * \param [in] str - the object ID
5064 * \return bool - \c false if \a str does not have the same prefix as \a this family
5065 * (for internal usage)
5067 //================================================================================
5069 bool _pyStringFamily::Add( const char* str )
5071 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5072 return false; // expected prefix is missing
5074 str += _prefix.Length(); // skip _prefix
5076 // try to add to some of child falimies
5077 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5078 for ( ; itSub != _subFams.end(); ++itSub )
5079 if ( itSub->Add( str ))
5082 // no suitable family found - add str to _strings or create a new child family
5084 // look for a proper place within sorted _strings
5085 std::list< _AString >::iterator itStr = _strings.begin();
5086 while ( itStr != _strings.end() && itStr->IsLess( str ))
5088 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5089 return true; // same ID already kept
5091 const int minPrefixSize = 4;
5093 // count "smaller" strings with the same prefix
5095 std::list< _AString >::iterator itLess = itStr;
5096 while ( itLess != _strings.begin() )
5099 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5107 // itLess points to the 1st string with same prefix
5109 // count "greater" strings with the same prefix
5111 std::list< _AString >::iterator itMore = itStr;
5112 for ( ; itMore != _strings.end(); ++itMore )
5113 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5117 // itMore points to the 1st string with greater prefix
5119 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5121 int prefixSize = minPrefixSize;
5122 _AString newPrefix ( str, prefixSize );
5124 // look for a proper place within _subFams sorted by _prefix
5125 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5126 if ( !itSub->_prefix.IsLess( newPrefix ))
5129 // add the new _pyStringFamily
5130 itSub = _subFams.insert( itSub, _pyStringFamily());
5131 _pyStringFamily& newSubFam = *itSub;
5132 newSubFam._prefix = newPrefix;
5134 // pass this->_strings to newSubFam._strings
5135 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5136 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5137 newSubFam._strings.push_back( str + prefixSize );
5138 for ( ; nbMore > 0; --nbMore, ++itStr )
5139 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5141 _strings.erase( itLess, itMore );
5143 else // too few string to make a family for them
5145 _strings.insert( itStr, str );
5150 //================================================================================
5152 * \brief Finds an object ID in the command
5153 * \param [in] longStr - the command string
5154 * \param [out] subStr - the found object ID
5155 * \return bool - \c true if the object ID found
5157 //================================================================================
5159 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5161 const _AString& longStr = cmd->GetString();
5162 const char* s = longStr.ToCString();
5165 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5166 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5167 if ( argBeg < 4 || argBeg > longStr.Length() )
5169 for ( ; itSub != _subFams.end(); ++itSub )
5172 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5173 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5175 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5176 from = pos + len + itSub->_prefix.Length();
5181 from += itSub->_prefix.Length();
5184 // look among _strings
5185 std::list< _AString >::iterator itStr = _strings.begin();
5186 for ( ; itStr != _strings.end(); ++itStr )
5187 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5188 // check that object ID does not continue after len
5189 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5191 subStr.push_back( *itStr );
5197 //================================================================================
5199 * \brief Return remainder length of the object ID after my _prefix
5200 * \param [in] str - remainder of the command after my _prefix
5201 * \return int - length of the object ID or -1 if not found
5203 //================================================================================
5205 int _pyStringFamily::isIn( const char* str )
5207 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5209 for ( ; itSub != _subFams.end(); ++itSub )
5211 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5214 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5215 return itSub->_prefix.Length() + len;
5220 if ( !_strings.empty() )
5222 std::list< _AString >::iterator itStr = _strings.begin();
5223 bool firstEmpty = itStr->IsEmpty();
5226 for ( ; itStr != _strings.end(); ++itStr )
5228 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5231 len = itStr->Length();
5240 // check that object ID does not continue after len
5241 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5248 //================================================================================
5252 //================================================================================
5254 void _pyStringFamily::Print( int level )
5256 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5257 std::list< _AString >::iterator itStr = _strings.begin();
5258 for ( ; itStr != _strings.end(); ++itStr )
5259 cout << *itStr << " | ";
5261 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5262 for ( ; itSub != _subFams.end(); ++itSub )
5263 itSub->Print( level + 1 );
5265 cout << string( 70, '-' ) << endl;