1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print(" ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
300 // It's necessary to continue recording this history and to fill
301 // undef2newItems (see below) accordingly.
303 typedef map< int, vector< int > > TUndef2newItems;
304 static TUndef2newItems undef2newItems;
305 if ( undef2newItems.empty() )
307 undef2newItems[ 26 ].push_back( 7 );
308 undef2newItems[ 27 ].push_back( 17 );
309 { int items[] = { 10, 11, 23, 24, 25 };
310 undef2newItems[ 32 ].assign( items, items+5 ); }
311 undef2newItems[ 33 ].push_back( 26 );
312 { int items[] = { 8, 9, 25, 26, 27, 28 };
313 undef2newItems[ 39 ].assign( items, items+6 ); }
314 { int items[] = { 14, 15, 16, 17 };
315 undef2newItems[ 43 ].assign( items, items+4 ); }
316 undef2newItems[ 44 ].push_back( 37 );
317 undef2newItems[ 45 ].push_back( 36 );
318 undef2newItems[ 46 ].push_back( 39 );
319 undef2newItems[ 47 ].push_back( 22 );
320 undef2newItems[ 48 ].push_back( 22 );
321 undef2newItems[ 49 ].push_back( 22 );
323 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
326 int iType = Type.IntegerValue();
327 int iCompare = Compare.IntegerValue();
328 int iUnaryOp = UnaryOp.IntegerValue();
329 int iBinaryOp = BinaryOp.IntegerValue();
331 // find out integer value of FT_Undefined at the moment of dump
332 int oldUndefined = iBinaryOp;
333 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
336 // apply history to args
337 TUndef2newItems::const_iterator undef_items =
338 undef2newItems.upper_bound( oldUndefined );
339 if ( undef_items != undef2newItems.end() )
341 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
342 for ( ; undef_items != undef2newItems.end(); ++undef_items )
344 const vector< int > & addedItems = undef_items->second;
345 for ( size_t i = 0; i < addedItems.size(); ++i )
346 for ( int iArg = 0; iArg < 4; ++iArg )
348 int& arg = *pArg[iArg];
349 if ( arg >= addedItems[i] )
353 Type = TCollection_AsciiString( iType );
354 Compare = TCollection_AsciiString( iCompare );
355 UnaryOp = TCollection_AsciiString( iUnaryOp );
356 BinaryOp = TCollection_AsciiString( iBinaryOp );
360 //================================================================================
362 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
363 * arguments of a given command by a list "[x,y,z]" if the list is accessible
366 //================================================================================
368 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
370 static TStringSet methodsAcceptingList;
371 if ( methodsAcceptingList.empty() ) {
372 const char * methodNames[] = {
373 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
374 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
375 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
376 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
377 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
378 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
379 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
380 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
381 "Translate","TranslateMakeGroups","TranslateMakeMesh",
382 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
383 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
384 ,"" }; // <- mark of the end
385 methodsAcceptingList.Insert( methodNames );
387 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
389 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
391 const _AString & arg = theCommand->GetArg( i );
392 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
393 arg.Search( "SMESH.DirStruct" ) == 1 )
395 Handle(_pyCommand) workCmd = new _pyCommand( arg );
396 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
398 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
400 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
402 _AString newArg = "[ ";
403 newArg += ( workCmd->GetArg( 1 ) + ", " +
404 workCmd->GetArg( 2 ) + ", " +
405 workCmd->GetArg( 3 ) + " ]");
406 theCommand->SetArg( i, newArg );
412 //================================================================================
414 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
415 * a list "[id1,id2]" if the list is an accessible type of argument.
417 //================================================================================
419 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
421 static TStringSet methodsAcceptingList;
422 if ( methodsAcceptingList.empty() ) {
423 const char * methodNames[] = {
424 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
425 "ExportCGNS","ExportGMF",
426 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
427 "ScaleMakeGroups","Scale","ScaleMakeMesh",
428 "FindCoincidentNodesOnPartBut","DoubleElements",
429 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
430 ,"" }; // <- mark of the end
431 methodsAcceptingList.Insert( methodNames );
433 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
435 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
437 _pyCommand argCmd( theCommand->GetArg( i ));
438 if ( argCmd.GetMethod() == "GetIDSource" &&
439 argCmd.GetNbArgs() == 2 )
441 theCommand->SetArg( i, argCmd.GetArg( 1 ));
447 bool _FilterArg( const _AString& theArg )
449 static std::list<_AString> filteredArgs;
450 static bool initialized = false;
451 if ( !initialized ) {
453 filteredArgs.push_back( "SMESH.MED_V2_1" );
454 filteredArgs.push_back( "SMESH.MED_V2_2" );
456 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
460 //================================================================================
462 * \brief Convert a python script using commands of smeshBuilder.py
463 * \param theScriptLines - Lines of the input script
464 * \param theEntry2AccessorMethod - returns method names to access to
465 * objects wrapped with python class
466 * \param theObjectNames - names of objects
467 * \param theRemovedObjIDs - entries of objects whose created commands were removed
468 * \param theHistoricalDump - true means to keep all commands, false means
469 * to exclude commands relating to objects removed from study
470 * \retval TCollection_AsciiString - Conversion result
472 //================================================================================
475 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
476 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
477 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
478 std::set< TCollection_AsciiString >& theRemovedObjIDs,
479 const bool theToKeepAllCommands)
481 std::list< TCollection_AsciiString >::iterator lineIt;
482 // process notebook variables
484 SMESH_NoteBook aNoteBook;
486 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
487 aNoteBook.AddCommand( *lineIt );
489 theScriptLines.clear();
491 aNoteBook.ReplaceVariables();
493 aNoteBook.GetResultLines( theScriptLines );
496 // convert to smeshBuilder.py API
498 theGen = new _pyGen( theEntry2AccessorMethod,
501 theToKeepAllCommands );
503 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504 theGen->AddCommand( *lineIt );
506 theScriptLines.clear();
510 #ifdef DUMP_CONVERSION
511 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
514 // clean commands of removed objects depending on myIsPublished flag
515 theGen->ClearCommands();
517 // reorder commands after conversion
518 list< Handle(_pyCommand) >::iterator cmd;
521 orderChanges = false;
522 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523 if ( (*cmd)->SetDependentCmdsAfter() )
525 } while ( orderChanges );
527 // concat commands back into a script
528 TCollection_AsciiString aPrevCmd;
529 set<_pyID> createdObjects;
530 createdObjects.insert( "smeshBuilder" );
531 createdObjects.insert( "smesh" );
532 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
534 #ifdef DUMP_CONVERSION
535 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
537 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
538 CheckObjectPresence( *cmd, createdObjects );
539 if ( !(*cmd)->IsEmpty() ) {
540 aPrevCmd = (*cmd)->GetString();
541 theScriptLines.push_back( aPrevCmd );
550 //================================================================================
552 * \brief _pyGen constructor
554 //================================================================================
556 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
557 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
558 std::set< TCollection_AsciiString >& theRemovedObjIDs,
559 const bool theToKeepAllCommands)
560 : _pyObject( new _pyCommand( "", 0 )),
562 myID2AccessorMethod( theEntry2AccessorMethod ),
563 myObjectNames( theObjectNames ),
564 myRemovedObjIDs( theRemovedObjIDs ),
566 myToKeepAllCommands( theToKeepAllCommands ),
567 myGeomIDNb(0), myGeomIDIndex(-1)
569 // make that GetID() to return TPythonDump::SMESHGenName()
570 GetCreationCmd()->Clear();
571 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
572 GetCreationCmd()->GetString() += "=";
574 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
575 if ( !theObjectNames.IsEmpty() )
579 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
580 if ( geomComp->_is_nil() ) return;
581 CORBA::String_var entry = geomComp->GetID();
584 // find a SMESH entry
586 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
587 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
588 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
591 // find 1st difference between smeshID and geomID
592 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
593 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
594 if ( geomID.Value( i ) != smeshID.Value( i ))
596 myGeomIDNb = geomID.Value( i );
602 //================================================================================
604 * \brief name of SMESH_Gen in smeshBuilder.py
606 //================================================================================
608 const char* _pyGen::AccessorMethod() const
610 return SMESH_2smeshpy::GenName();
613 //================================================================================
615 * \brief Convert a command using a specific converter
616 * \param theCommand - the command to convert
618 //================================================================================
620 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
622 // store theCommand in the sequence
623 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
625 Handle(_pyCommand) aCommand = myCommands.back();
626 #ifdef DUMP_CONVERSION
627 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
630 const _pyID& objID = aCommand->GetObject();
632 if ( objID.IsEmpty() )
635 // Prevent moving a command creating a sub-mesh to the end of the script
636 // if the sub-mesh is used in theCommand as argument
637 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
639 // PlaceSubmeshAfterItsCreation( aCommand );
642 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
643 StructToList( aCommand );
645 const TCollection_AsciiString& method = aCommand->GetMethod();
647 // not to erase _pySelfEraser's etc. used as args in some commands
649 #ifdef USE_STRING_FAMILY
650 std::list<_pyID> objIDs;
651 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
653 std::list<_pyID>::iterator objID = objIDs.begin();
654 for ( ; objID != objIDs.end(); ++objID )
656 Handle(_pyObject) obj = FindObject( *objID );
659 obj->AddArgCmd( aCommand );
660 //cout << objID << " found in " << theCommand << endl;
665 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
666 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
667 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
669 Handle(_pyObject) obj = FindObject( *id );
671 obj->AddArgCmd( aCommand );
676 // Find an object to process theCommand
679 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
681 this->Process( aCommand );
682 //addFilterUser( aCommand, theGen ); // protect filters from clearing
686 // SMESH_Mesh method?
687 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
688 if ( id_mesh != myMeshes.end() )
690 //id_mesh->second->AddProcessedCmd( aCommand );
692 // Wrap Export*() into try-except
693 if ( aCommand->MethodStartsFrom("Export"))
696 _AString indent = aCommand->GetIndentation();
697 _AString tryStr = indent + "try:";
698 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
699 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
700 _AString excStr = indent + "except:";
701 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
703 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
705 aCommand->GetString() = newCmd;
706 aCommand->SetOrderNb( ++myNbCommands );
707 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
708 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
709 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
711 // check for mesh editor object
712 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
713 _pyID editorID = aCommand->GetResultValue();
714 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
715 myMeshEditors.insert( make_pair( editorID, editor ));
718 // check for SubMesh objects
719 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
720 _pyID subMeshID = aCommand->GetResultValue();
721 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
722 AddObject( subMesh );
725 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
726 GetIDSourceToList( aCommand );
728 //addFilterUser( aCommand, theGen ); // protect filters from clearing
730 id_mesh->second->Process( aCommand );
731 id_mesh->second->AddProcessedCmd( aCommand );
735 // SMESH_MeshEditor method?
736 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
737 if ( id_editor != myMeshEditors.end() )
739 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
740 GetIDSourceToList( aCommand );
742 //addFilterUser( aCommand, theGen ); // protect filters from clearing
744 // some commands of SMESH_MeshEditor create meshes and groups
745 _pyID meshID, groups;
746 if ( method.Search("MakeMesh") != -1 )
747 meshID = aCommand->GetResultValue();
748 else if ( method == "MakeBoundaryMesh")
749 meshID = aCommand->GetResultValue(1);
750 else if ( method == "MakeBoundaryElements")
751 meshID = aCommand->GetResultValue(2);
753 if ( method.Search("MakeGroups") != -1 ||
754 method == "ExtrusionAlongPathX" ||
755 method == "ExtrusionAlongPathObjX" ||
756 method == "DoubleNodeGroupNew" ||
757 method == "DoubleNodeGroupsNew" ||
758 method == "DoubleNodeElemGroupNew" ||
759 method == "DoubleNodeElemGroupsNew" ||
760 method == "DoubleNodeElemGroup2New" ||
761 method == "DoubleNodeElemGroups2New" ||
762 method == "AffectedElemGroupsInRegion"
764 groups = aCommand->GetResultValue();
765 else if ( method == "MakeBoundaryMesh" )
766 groups = aCommand->GetResultValue(2);
767 else if ( method == "MakeBoundaryElements")
768 groups = aCommand->GetResultValue(3);
769 else if ( method == "Create0DElementsOnAllNodes" &&
770 aCommand->GetArg(2).Length() > 2 ) // group name != ''
771 groups = aCommand->GetResultValue();
773 id_editor->second->Process( aCommand );
774 id_editor->second->AddProcessedCmd( aCommand );
777 if ( !meshID.IsEmpty() &&
778 !myMeshes.count( meshID ) &&
779 aCommand->IsStudyEntry( meshID ))
781 _AString processedCommand = aCommand->GetString();
782 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
783 CheckObjectIsReCreated( mesh );
784 myMeshes.insert( make_pair( meshID, mesh ));
786 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
789 if ( !groups.IsEmpty() )
791 if ( !aCommand->IsStudyEntry( meshID ))
792 meshID = id_editor->second->GetMesh();
793 Handle(_pyMesh) mesh = myMeshes[ meshID ];
795 list< _pyID > idList = aCommand->GetStudyEntries( groups );
796 list< _pyID >::iterator grID = idList.begin();
797 for ( ; grID != idList.end(); ++grID )
798 if ( !myObjects.count( *grID ))
800 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
802 if ( !mesh.IsNull() ) mesh->AddGroup( group );
806 } // SMESH_MeshEditor methods
808 // SMESH_Hypothesis method?
809 Handle(_pyHypothesis) hyp = FindHyp( objID );
810 if ( !hyp.IsNull() && !hyp->IsAlgo() )
812 hyp->Process( aCommand );
813 hyp->AddProcessedCmd( aCommand );
817 // aFilterManager.CreateFilter() ?
818 if ( aCommand->GetMethod() == "CreateFilter" )
820 // Set a more human readable name to a filter
821 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
822 _pyID newID, filterID = aCommand->GetResultValue();
823 int pos = filterID.Search( "0x" );
825 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
827 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
830 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
831 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
833 // create _pySelfEraser for functors
834 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
835 functor->IgnoreOwnCalls(); // to erase if not used as an argument
836 AddObject( functor );
839 // other object method?
840 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
841 if ( id_obj != myObjects.end() ) {
842 id_obj->second->Process( aCommand );
843 id_obj->second->AddProcessedCmd( aCommand );
847 // Add access to a wrapped mesh
848 AddMeshAccessorMethod( aCommand );
850 // Add access to a wrapped algorithm
851 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
853 // PAL12227. PythonDump was not updated at proper time; result is
854 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
855 // TypeError: __init__() takes exactly 11 arguments (10 given)
856 const char wrongCommand[] = "SMESH.Filter.Criterion(";
857 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
859 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
860 // there must be 10 arguments, 5-th arg ThresholdID is missing,
861 const int wrongNbArgs = 9, missingArg = 5;
862 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
864 for ( int i = wrongNbArgs; i > missingArg; --i )
865 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
866 tmpCmd.SetArg( missingArg, "''");
867 aCommand->GetString().Trunc( beg - 1 );
868 aCommand->GetString() += tmpCmd.GetString();
871 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
873 // instead of "SMESH.Filter.Criterion(
874 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
875 // 1 2 3 4 5 6 7 8 9 10
876 // in order to avoid the problem of type mismatch of long and FunctorType
877 const TCollection_AsciiString
878 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
879 TCollection_AsciiString
880 Type = aCommand->GetArg(1), // long
881 Compare = aCommand->GetArg(2), // long
882 Threshold = aCommand->GetArg(3), // double
883 ThresholdStr = aCommand->GetArg(4), // string
884 ThresholdID = aCommand->GetArg(5), // string
885 UnaryOp = aCommand->GetArg(6), // long
886 BinaryOp = aCommand->GetArg(7), // long
887 Tolerance = aCommand->GetArg(8), // double
888 TypeOfElement = aCommand->GetArg(9), // ElementType
889 Precision = aCommand->GetArg(10); // long
890 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
891 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
892 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
893 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
894 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
896 if ( Compare == "SMESH.FT_EqualTo" )
899 aCommand->RemoveArgs();
900 aCommand->SetObject( SMESH_2smeshpy::GenName() );
901 aCommand->SetMethod( "GetCriterion" );
903 aCommand->SetArg( 1, TypeOfElement );
904 aCommand->SetArg( 2, Type );
905 aCommand->SetArg( 3, Compare );
907 if ( Threshold.IsIntegerValue() )
909 int iGeom = Threshold.IntegerValue();
910 if ( Type == "SMESH.FT_ElemGeomType" )
912 // set SMESH.GeometryType instead of a numerical Threshold
913 const int nbTypes = SMESH::Geom_LAST;
914 const char* types[] = {
915 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
916 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
917 "Geom_POLYHEDRA", "Geom_BALL" };
918 if ( -1 < iGeom && iGeom < nbTypes )
919 Threshold = SMESH + types[ iGeom ];
921 // is types complete? (compilation failure mains that enum GeometryType changed)
922 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
925 if (Type == "SMESH.FT_EntityType")
927 // set SMESH.EntityType instead of a numerical Threshold
928 const int nbTypes = SMESH::Entity_Last;
929 const char* types[] = {
930 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
931 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
932 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
933 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
934 "Entity_Pyramid", "Entity_Quad_Pyramid",
935 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
936 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
937 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
938 if ( -1 < iGeom && iGeom < nbTypes )
939 Threshold = SMESH + types[ iGeom ];
941 // is 'types' complete? (compilation failure mains that enum EntityType changed)
942 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
946 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
947 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
948 else if ( ThresholdStr.Length() != 2 )
949 aCommand->SetArg( 4, ThresholdStr );
950 else if ( ThresholdID.Length() != 2 )
951 aCommand->SetArg( 4, ThresholdID );
953 aCommand->SetArg( 4, Threshold );
954 // find the last not default arg
956 if ( Tolerance == dfltTol ) {
958 if ( BinaryOp == dfltFunctor ) {
960 if ( UnaryOp == dfltFunctor )
964 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
965 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
966 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
967 if ( Precision != dfltPreci )
969 TCollection_AsciiString crit = aCommand->GetResultValue();
970 aCommand->GetString() += "; ";
971 aCommand->GetString() += crit + ".Precision = " + Precision;
977 //================================================================================
979 * \brief Convert the command or remember it for later conversion
980 * \param theCommand - The python command calling a method of SMESH_Gen
982 //================================================================================
984 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
986 // there are methods to convert:
987 // CreateMesh( shape )
988 // Concatenate( [mesh1, ...], ... )
989 // CreateHypothesis( theHypType, theLibName )
990 // Compute( mesh, geom )
991 // Evaluate( mesh, geom )
993 TCollection_AsciiString method = theCommand->GetMethod();
995 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
997 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1001 if ( method == "CreateMeshesFromUNV" ||
1002 method == "CreateMeshesFromSTL" ||
1003 method == "CopyMesh" ) // command result is a mesh
1005 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1009 if ( method == "CreateMeshesFromMED" ||
1010 method == "CreateMeshesFromSAUV"||
1011 method == "CreateMeshesFromCGNS" ||
1012 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1014 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1015 std::list< _pyID >::iterator meshID = meshIDs.begin();
1016 for ( ; meshID != meshIDs.end(); ++meshID )
1018 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1021 if ( method == "CreateMeshesFromGMF" )
1023 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1024 // CreateMeshesFromGMF( theFileName )
1025 _AString file = theCommand->GetArg(1);
1026 theCommand->RemoveArgs();
1027 theCommand->SetArg( 1, file );
1030 if ( method == "CopyMeshWithGeom" )
1032 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1033 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1037 // CreateHypothesis()
1038 if ( method == "CreateHypothesis" )
1040 // issue 199929, remove standard library name (default parameter)
1041 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1042 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1043 // keep the first argument
1044 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1045 theCommand->RemoveArgs();
1046 theCommand->SetArg( 1, arg );
1049 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1050 CheckObjectIsReCreated( hyp );
1051 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1056 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1057 if ( method == "Compute" )
1059 const _pyID& meshID = theCommand->GetArg( 1 );
1060 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1061 if ( id_mesh != myMeshes.end() ) {
1062 theCommand->SetObject( meshID );
1063 theCommand->RemoveArgs();
1064 id_mesh->second->Process( theCommand );
1065 id_mesh->second->AddProcessedCmd( theCommand );
1070 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1071 if ( method == "Evaluate" )
1073 const _pyID& meshID = theCommand->GetArg( 1 );
1074 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1075 if ( id_mesh != myMeshes.end() ) {
1076 theCommand->SetObject( meshID );
1077 _pyID geom = theCommand->GetArg( 2 );
1078 theCommand->RemoveArgs();
1079 theCommand->SetArg( 1, geom );
1080 id_mesh->second->AddProcessedCmd( theCommand );
1085 // objects erasing creation command if no more its commands invoked:
1086 // SMESH_Pattern, FilterManager
1087 if ( method == "GetPattern" ||
1088 method == "CreateFilterManager" ||
1089 method == "CreateMeasurements" )
1091 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1092 if ( !AddObject( obj ) )
1093 theCommand->Clear(); // already created
1095 // Concatenate( [mesh1, ...], ... )
1096 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1098 if ( method == "ConcatenateWithGroups" ) {
1099 theCommand->SetMethod( "Concatenate" );
1100 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1102 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1104 AddMeshAccessorMethod( theCommand );
1106 else if ( method == "SetName" ) // SetName(obj,name)
1108 // store theCommand as one of object commands to erase it along with the object
1109 const _pyID& objID = theCommand->GetArg( 1 );
1110 Handle(_pyObject) obj = FindObject( objID );
1111 if ( !obj.IsNull() )
1112 obj->AddProcessedCmd( theCommand );
1115 // Replace name of SMESH_Gen
1117 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1118 static TStringSet smeshpyMethods;
1119 if ( smeshpyMethods.empty() ) {
1120 const char * names[] =
1121 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1122 "GetPattern","GetSubShapesId",
1123 "" }; // <- mark of array end
1124 smeshpyMethods.Insert( names );
1126 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1127 // smeshgen.Method() --> smesh.Method()
1128 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1130 // smeshgen.Method() --> smesh.Method()
1131 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1134 //================================================================================
1136 * \brief Convert the remembered commands
1138 //================================================================================
1140 void _pyGen::Flush()
1142 // create an empty command
1143 myLastCommand = new _pyCommand();
1145 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1146 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1147 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1149 if ( IsToKeepAllCommands() ) // historical dump
1151 // set myIsPublished = true to all objects
1152 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1153 id_mesh->second->SetRemovedFromStudy( false );
1154 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1155 id_hyp->second->SetRemovedFromStudy( false );
1156 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1157 id_obj->second->SetRemovedFromStudy( false );
1161 // let hypotheses find referred objects in order to prevent clearing
1162 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1163 list< Handle(_pyMesh) > fatherMeshes;
1164 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1165 if ( !id_hyp->second.IsNull() )
1166 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1168 // set myIsPublished = false to all objects depending on
1169 // meshes built on a removed geometry
1170 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1171 if ( id_mesh->second->IsNotGeomPublished() )
1172 id_mesh->second->SetRemovedFromStudy( true );
1175 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1176 if ( ! id_mesh->second.IsNull() )
1177 id_mesh->second->Flush();
1180 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1181 if ( !id_hyp->second.IsNull() ) {
1182 id_hyp->second->Flush();
1183 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1184 if ( !id_hyp->second->IsWrapped() )
1185 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1188 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1189 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1190 for ( ; robj != myOrderedObjects.rend(); ++robj )
1191 if ( ! robj->IsNull() )
1193 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1194 for ( ; obj != myOrderedObjects.end(); ++obj )
1195 if ( ! obj->IsNull() )
1198 myLastCommand->SetOrderNb( ++myNbCommands );
1199 myCommands.push_back( myLastCommand );
1202 //================================================================================
1204 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1205 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1207 //================================================================================
1209 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1211 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1212 // for ( ; id_obj != myObjects.end(); ++id_obj )
1214 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1215 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1217 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1218 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1220 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1221 // list< _pyID >::iterator id = idList.begin();
1222 // for ( ; id != idList.end(); ++id )
1223 // if ( id_obj->first == *id )
1224 // // _pySubMesh::Process() does what we need
1225 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1230 //================================================================================
1232 * \brief Clean commands of removed objects depending on myIsPublished flag
1234 //================================================================================
1236 void _pyGen::ClearCommands()
1238 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1239 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1240 id_mesh->second->ClearCommands();
1242 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1243 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1244 if ( !id_hyp->second.IsNull() )
1245 id_hyp->second->ClearCommands();
1247 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1248 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1249 for ( ; robj != myOrderedObjects.rend(); ++robj )
1250 if ( ! robj->IsNull() )
1251 (*robj)->ClearCommands();
1252 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1253 for ( ; obj != myOrderedObjects.end(); ++obj )
1254 if ( ! obj->IsNull() )
1255 (*obj)->ClearCommands();
1258 //================================================================================
1260 * \brief Release mutual handles of objects
1262 //================================================================================
1266 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1267 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1268 id_mesh->second->Free();
1271 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1272 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1273 id_ed->second->Free();
1274 myMeshEditors.clear();
1276 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1277 for ( ; id_obj != myObjects.end(); ++id_obj )
1278 id_obj->second->Free();
1281 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1282 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1283 if ( !id_hyp->second.IsNull() )
1284 id_hyp->second->Free();
1287 myFile2ExportedMesh.clear();
1289 //myKeepAgrCmdsIDs.Print();
1292 //================================================================================
1294 * \brief Add access method to mesh that is an argument
1295 * \param theCmd - command to add access method
1296 * \retval bool - true if added
1298 //================================================================================
1300 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1303 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1304 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1305 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1311 //================================================================================
1313 * \brief Add access method to algo that is an object or an argument
1314 * \param theCmd - command to add access method
1315 * \retval bool - true if added
1317 //================================================================================
1319 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1322 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1323 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1324 if ( !id_hyp->second.IsNull() &&
1325 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1326 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1327 id_hyp->second->AccessorMethod() ))
1333 //================================================================================
1335 * \brief Find hypothesis by ID (entry)
1336 * \param theHypID - The hypothesis ID
1337 * \retval Handle(_pyHypothesis) - The found hypothesis
1339 //================================================================================
1341 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1343 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1344 if ( id_hyp != myHypos.end() &&
1345 !id_hyp->second.IsNull() &&
1346 theHypID == id_hyp->second->GetID() )
1347 return id_hyp->second;
1348 return Handle(_pyHypothesis)();
1351 //================================================================================
1353 * \brief Find algorithm able to create a hypothesis
1354 * \param theGeom - The shape ID the algorithm was created on
1355 * \param theMesh - The mesh ID that created the algorithm
1356 * \param theHypothesis - The hypothesis the algorithm should be able to create
1357 * \retval Handle(_pyHypothesis) - The found algo
1359 //================================================================================
1361 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1362 const Handle(_pyHypothesis)& theHypothesis )
1364 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1365 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1366 if ( !id_hyp->second.IsNull() &&
1367 id_hyp->second->IsAlgo() &&
1368 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1369 id_hyp->second->GetGeom() == theGeom &&
1370 id_hyp->second->GetMesh() == theMesh )
1371 return id_hyp->second;
1372 return Handle(_pyHypothesis)();
1375 //================================================================================
1377 * \brief Find subMesh by ID (entry)
1378 * \param theSubMeshID - The subMesh ID
1379 * \retval Handle(_pySubMesh) - The found subMesh
1381 //================================================================================
1383 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1385 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1386 if ( id_subMesh != myObjects.end() )
1387 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1388 return Handle(_pySubMesh)();
1392 //================================================================================
1394 * \brief Change order of commands in the script
1395 * \param theCmd1 - One command
1396 * \param theCmd2 - Another command
1398 //================================================================================
1400 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1402 list< Handle(_pyCommand) >::iterator pos1, pos2;
1403 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1404 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1405 myCommands.insert( pos1, theCmd2 );
1406 myCommands.insert( pos2, theCmd1 );
1407 myCommands.erase( pos1 );
1408 myCommands.erase( pos2 );
1410 int nb1 = theCmd1->GetOrderNb();
1411 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1412 theCmd2->SetOrderNb( nb1 );
1413 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1414 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1417 //================================================================================
1419 * \brief Set one command after the other
1420 * \param theCmd - Command to move
1421 * \param theAfterCmd - Command ater which to insert the first one
1423 //================================================================================
1425 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1427 setNeighbourCommand( theCmd, theAfterCmd, true );
1430 //================================================================================
1432 * \brief Set one command before the other
1433 * \param theCmd - Command to move
1434 * \param theBeforeCmd - Command before which to insert the first one
1436 //================================================================================
1438 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1440 setNeighbourCommand( theCmd, theBeforeCmd, false );
1443 //================================================================================
1445 * \brief Set one command before or after the other
1446 * \param theCmd - Command to move
1447 * \param theOtherCmd - Command ater or before which to insert the first one
1449 //================================================================================
1451 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1452 Handle(_pyCommand)& theOtherCmd,
1453 const bool theIsAfter )
1455 list< Handle(_pyCommand) >::iterator pos;
1456 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1457 myCommands.erase( pos );
1458 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1459 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1462 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1463 (*pos)->SetOrderNb( i++ );
1466 //================================================================================
1468 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1470 //================================================================================
1472 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1474 // No more needed after adding _pyObject::myArgCommands
1476 // const char filterPrefix[] = "aFilter0x";
1477 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1480 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1482 // const _AString & arg = theCommand->GetArg( i );
1483 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1484 // if ( arg.Search( filterPrefix ) != 1 )
1487 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1488 // if ( !filter.IsNull() )
1490 // filter->AddUser( user );
1491 // if ( !filter->GetNewID().IsEmpty() )
1492 // theCommand->SetArg( i, filter->GetNewID() );
1497 //================================================================================
1499 * \brief Set command be last in list of commands
1500 * \param theCmd - Command to be last
1502 //================================================================================
1504 Handle(_pyCommand)& _pyGen::GetLastCommand()
1506 return myLastCommand;
1509 //================================================================================
1511 * \brief Set method to access to object wrapped with python class
1512 * \param theID - The wrapped object entry
1513 * \param theMethod - The accessor method
1515 //================================================================================
1517 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1519 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1522 //================================================================================
1524 * \brief Generated new ID for object and assign with existing name
1525 * \param theID - ID of existing object
1527 //================================================================================
1529 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1534 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1536 while ( myObjectNames.IsBound( aNewID ) );
1538 if ( myObjectNames.IsBound( theID ) )
1539 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1541 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1545 //================================================================================
1547 * \brief Stores theObj in myObjects
1549 //================================================================================
1551 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1553 if ( theObj.IsNull() ) return false;
1555 CheckObjectIsReCreated( theObj );
1559 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1560 add = myMeshes.insert( make_pair( theObj->GetID(),
1561 Handle(_pyMesh)::DownCast( theObj ))).second;
1563 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1564 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1565 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1568 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1569 if ( add ) myOrderedObjects.push_back( theObj );
1574 //================================================================================
1576 * \brief Erases an existing object with the same ID. This method should be called
1577 * before storing theObj in _pyGen
1579 //================================================================================
1581 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1583 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1586 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1587 Handle(_pyObject) existing;
1589 existing = FindHyp( theObj->GetID() );
1591 existing = FindObject( theObj->GetID() );
1592 if ( !existing.IsNull() && existing != theObj )
1594 existing->SetRemovedFromStudy( true );
1595 existing->ClearCommands();
1598 if ( myHypos.count( theObj->GetID() ))
1599 myHypos.erase( theObj->GetID() );
1601 else if ( myMeshes.count( theObj->GetID() ))
1603 myMeshes.erase( theObj->GetID() );
1605 else if ( myObjects.count( theObj->GetID() ))
1607 myObjects.erase( theObj->GetID() );
1612 //================================================================================
1614 * \brief Re-register an object with other ID to make it Process() commands of
1615 * other object having this ID
1617 //================================================================================
1619 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1621 if ( theObj.IsNull() ) return;
1623 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1624 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1626 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1627 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1630 myObjects.insert( make_pair( theID, theObj ));
1633 //================================================================================
1635 * \brief Finds a _pyObject by ID
1637 //================================================================================
1639 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1642 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1643 if ( id_obj != myObjects.end() )
1644 return id_obj->second;
1647 _pyGen* me = const_cast< _pyGen* >( this );
1648 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1649 if ( id_obj != myMeshes.end() )
1650 return id_obj->second;
1653 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1654 // if ( id_obj != myMeshEditors.end() )
1655 // return id_obj->second;
1657 return Handle(_pyObject)();
1660 //================================================================================
1662 * \brief Check if a study entry is under GEOM component
1664 //================================================================================
1666 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1670 return ( myGeomIDIndex <= theObjID.Length() &&
1671 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1672 _pyCommand::IsStudyEntry( theObjID ));
1677 //================================================================================
1679 * \brief Returns true if an object is not present in a study
1681 //================================================================================
1683 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1685 if ( theObjID.IsEmpty() ) return false;
1687 if ( myObjectNames.IsBound( theObjID ))
1688 return false; // SMESH object is in study
1690 // either the SMESH object is not in study or it is a GEOM object
1691 if ( IsGeomObject( theObjID ))
1693 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1694 if ( so->_is_nil() ) return true;
1695 CORBA::Object_var obj = so->GetObject();
1696 return CORBA::is_nil( obj );
1698 return true; // SMESH object not in study
1701 //================================================================================
1703 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1704 * this object is not dumped
1705 * \param [in] theObjID - entry of the object whose creation command was eliminated
1707 //================================================================================
1709 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1711 myRemovedObjIDs.insert( theObjID );
1714 //================================================================================
1716 * \brief Return reader of hypotheses of plugins
1718 //================================================================================
1720 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1722 if (myHypReader.IsNull() )
1723 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1729 //================================================================================
1731 * \brief Mesh created by SMESH_Gen
1733 //================================================================================
1735 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1736 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1738 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1739 myGeomNotInStudy = true;
1741 // convert my creation command --> smeshpy.Mesh(...)
1742 Handle(_pyCommand) creationCmd = GetCreationCmd();
1743 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1744 creationCmd->SetMethod( "Mesh" );
1745 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1748 //================================================================================
1750 * \brief Mesh created by SMESH_MeshEditor
1752 //================================================================================
1754 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1755 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1757 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1759 // this mesh depends on the exported mesh
1760 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1761 if ( !file.IsEmpty() )
1763 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1764 addFatherMesh( exportData.myMesh );
1765 if ( !exportData.myLastComputeCmd.IsNull() )
1767 // restore cleared Compute() by which the exported mesh was generated
1768 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1769 // protect that Compute() cmd from clearing
1770 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1771 exportData.myMesh->myLastComputeCmd.Nullify();
1775 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1777 // this mesh depends on concatenated meshes
1778 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1779 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1780 list< _pyID >::iterator meshID = idList.begin();
1781 for ( ; meshID != idList.end(); ++meshID )
1782 addFatherMesh( *meshID );
1784 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1786 // this mesh depends on a copied IdSource
1787 const _pyID& objID = theCreationCmd->GetArg( 1 );
1788 addFatherMesh( objID );
1790 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1791 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1792 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1794 // this mesh depends on a source mesh
1795 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1796 const _pyID& meshID = theCreationCmd->GetObject();
1797 addFatherMesh( meshID );
1800 // convert my creation command
1801 Handle(_pyCommand) creationCmd = GetCreationCmd();
1802 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1803 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1806 //================================================================================
1808 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1809 * \param theCommand - Engine method called for this mesh
1811 //================================================================================
1813 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1815 // some methods of SMESH_Mesh interface needs special conversion
1816 // to methods of Mesh python class
1818 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1819 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1820 // 2. AddHypothesis(geom, hyp)
1821 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1822 // 3. CreateGroupFromGEOM(type, name, grp)
1823 // --> in Mesh.Group(grp, name="")
1824 // 4. ExportToMED(f, auto_groups, version)
1825 // --> in Mesh.ExportMED( f, auto_groups, version )
1828 const TCollection_AsciiString& method = theCommand->GetMethod();
1829 // ----------------------------------------------------------------------
1830 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1832 if ( !theGen->IsToKeepAllCommands() ) // !historical
1834 list< Handle(_pyHypothesis) >::iterator hyp;
1835 if ( !myLastComputeCmd.IsNull() )
1837 // check if the previously computed mesh has been edited,
1838 // if so then we do not clear the previous Compute()
1839 bool toClear = true;
1840 if ( myLastComputeCmd->GetMethod() == "Compute" )
1842 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1843 for ( ; e != myEditors.end() && toClear; ++e )
1845 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1846 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1847 if ( cmd != cmds.rend() &&
1848 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1854 // clear hyp commands called before myLastComputeCmd
1855 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1856 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1858 myLastComputeCmd->Clear();
1861 myLastComputeCmd = theCommand;
1863 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1864 (*hyp)->MeshComputed( myLastComputeCmd );
1868 // ----------------------------------------------------------------------
1869 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1871 if ( !theGen->IsToKeepAllCommands() ) // !historical
1874 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1875 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1876 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1878 if ( !myLastComputeCmd.IsNull() )
1880 list< Handle(_pyHypothesis) >::iterator hyp;
1881 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1882 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1884 myLastComputeCmd->Clear();
1887 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1888 for ( ; e != myEditors.end(); ++e )
1890 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1891 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1892 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1893 if ( !(*cmd)->IsEmpty() )
1895 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1899 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1902 // ----------------------------------------------------------------------
1903 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1904 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1905 if ( !subMesh.IsNull() ) {
1906 subMesh->SetCreator( this );
1907 mySubmeshes.push_back( subMesh );
1910 // ----------------------------------------------------------------------
1911 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1912 theCommand->Clear();
1914 // ----------------------------------------------------------------------
1915 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1916 myAddHypCmds.push_back( theCommand );
1918 const _pyID& hypID = theCommand->GetArg( 2 );
1919 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1920 if ( !hyp.IsNull() ) {
1921 myHypos.push_back( hyp );
1922 if ( hyp->GetMesh().IsEmpty() )
1923 hyp->SetMesh( this->GetID() );
1926 // ----------------------------------------------------------------------
1927 else if ( method == "CreateGroup" ||
1928 method == "CreateGroupFromGEOM" ||
1929 method == "CreateGroupFromFilter" ||
1930 method == "CreateDimGroup" )
1932 Handle(_pyGroup) group = new _pyGroup( theCommand );
1933 myGroups.push_back( group );
1934 theGen->AddObject( group );
1936 // ----------------------------------------------------------------------
1937 // update list of groups
1938 else if ( method == "GetGroups" )
1940 bool allGroupsRemoved = true;
1941 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1942 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1943 list< _pyID >::iterator grID = idList.begin();
1944 const size_t nbGroupsBefore = myGroups.size();
1945 Handle(_pyObject) obj;
1946 for ( ; grID != idList.end(); ++grID )
1948 obj = theGen->FindObject( *grID );
1951 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1952 theGen->AddObject( group );
1953 myGroups.push_back( group );
1956 if ( !obj->CanClear() )
1957 allGroupsRemoved = false;
1959 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1960 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1962 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1964 // check if the preceding command is Compute();
1965 // if GetGroups() is just after Compute(), this can mean that the groups
1966 // were created by some algorithm and hence Compute() should not be discarded
1967 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1968 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1969 while ( (*cmd)->GetMethod() == "GetGroups" )
1971 if ( myLastComputeCmd == (*cmd))
1972 // protect last Compute() from clearing by the next Compute()
1973 myLastComputeCmd.Nullify();
1976 // ----------------------------------------------------------------------
1977 // notify a group about full removal
1978 else if ( method == "RemoveGroupWithContents" ||
1979 method == "RemoveGroup")
1981 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1982 const _pyID groupID = theCommand->GetArg( 1 );
1983 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1984 if ( !grp.IsNull() )
1986 if ( method == "RemoveGroupWithContents" )
1987 grp->RemovedWithContents();
1988 // to clear RemoveGroup() if the group creation is cleared
1989 grp->AddProcessedCmd( theCommand );
1993 // ----------------------------------------------------------------------
1994 else if ( theCommand->MethodStartsFrom( "Export" ))
1996 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1997 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
1998 method == "ExportMED" )
2000 theCommand->SetMethod( "ExportMED" );
2001 // filter out deprecated version parameter
2002 vector< _AString > args;
2003 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2004 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2005 args.push_back( theCommand->GetArg( i ) );
2007 theCommand->RemoveArgs();
2008 for ( unsigned int i = 0; i < args.size(); i++ )
2009 theCommand->SetArg( i+1, args[i] );
2010 if ( theCommand->GetNbArgs() == 4 )
2012 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2013 _AString autoDimension = theCommand->GetArg( 4 );
2014 theCommand->SetArg( 4, "None" );
2015 theCommand->SetArg( 5, autoDimension );
2018 else if ( method == "ExportCGNS" )
2019 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2020 _pyID partID = theCommand->GetArg( 1 );
2021 int nbArgs = theCommand->GetNbArgs();
2022 for ( int i = 2; i <= nbArgs; ++i )
2023 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2024 theCommand->SetArg( nbArgs, partID );
2026 else if ( method == "ExportGMF" )
2027 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2028 _pyID partID = theCommand->GetArg( 1 );
2029 _AString file = theCommand->GetArg( 2 );
2030 theCommand->RemoveArgs();
2031 theCommand->SetArg( 1, file );
2032 theCommand->SetArg( 2, partID );
2034 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2035 { // ExportPartTo*(part, ...) -> Export*(..., part)
2037 // remove "PartTo" from the method
2038 TCollection_AsciiString newMethod = method;
2039 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2040 theCommand->SetMethod( newMethod );
2041 // replace version parameter by minor
2042 std::list< _AString > args;
2043 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2044 if ( _FilterArg( theCommand->GetArg( i )))
2045 args.push_back( "minor=0");
2047 args.push_back( theCommand->GetArg( i ));
2049 // check the 1st arg meshPart, it must be SMESH_IDSource
2050 _AString meshPart = args.front();
2051 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2052 meshPart.Search( "Filter" ) > 0 ||
2053 meshPart.Search( "GetIDSource" ) > 0 ||
2054 meshPart.Search( "meshPart" ) > 0 )
2056 // set the 1st arg meshPart
2057 // - to 5th place for ExportMED command
2058 // - to last place for the rest commands
2059 std::list< _AString >::iterator newPos = args.end();
2060 if ( newMethod == "ExportMED" )
2061 std::advance( newPos = args.begin(), 5 );
2062 args.splice( newPos, args, args.begin() );
2064 std::list< _AString >::iterator a = args.begin();
2065 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2066 theCommand->SetArg( i, *a );
2068 // remember file name
2069 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2070 ExportedMeshData( this, myLastComputeCmd ));
2072 // ----------------------------------------------------------------------
2073 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2075 _pyID hypID = theCommand->GetArg( 2 );
2076 _pyID geomID = theCommand->GetArg( 1 );
2077 bool isLocal = ( geomID != GetGeom() );
2079 // check if this mesh still has corresponding addition command
2080 Handle(_pyCommand) addCmd;
2081 list< Handle(_pyCommand) >::iterator cmd;
2082 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2083 for ( int i = 0; i < 2; ++i )
2085 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2086 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2088 bool sameHyp = true;
2089 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2090 sameHyp = false; // other hyp
2091 if ( (*cmd)->GetNbArgs() == 2 &&
2092 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2093 sameHyp = false; // other geom
2094 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2095 sameHyp = false; // other geom
2099 cmd = addHypCmds.erase( cmd );
2100 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2102 theCommand->Clear();
2106 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2107 addCmd->RemoveArgs();
2108 addCmd->SetArg( 1, hypID );
2110 addCmd->SetArg( 2, geomID );
2119 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2120 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2121 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2122 _pyID geom = theCommand->GetArg( 1 );
2123 theCommand->RemoveArgs();
2124 theCommand->SetArg( 1, hypID );
2125 if ( geom != GetGeom() )
2126 theCommand->SetArg( 2, geom );
2128 // remove hyp from myHypos
2129 myHypos.remove( hyp );
2131 // check for SubMesh order commands
2132 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2134 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2135 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2136 // commands are moved at the end of the script
2137 TCollection_AsciiString subIDs =
2138 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2139 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2140 list< _pyID >::iterator subID = idList.begin();
2141 for ( ; subID != idList.end(); ++subID )
2143 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2144 if ( !subMesh.IsNull() )
2145 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2148 // add accessor method if necessary
2151 if ( NeedMeshAccess( theCommand ))
2152 // apply theCommand to the mesh wrapped by smeshpy mesh
2153 AddMeshAccess( theCommand );
2157 //================================================================================
2159 * \brief Return True if addition of accesor method is needed
2161 //================================================================================
2163 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2165 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2166 // so no conversion is needed for them at all:
2167 static TStringSet sameMethods;
2168 if ( sameMethods.empty() ) {
2169 const char * names[] =
2170 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2171 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2172 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2173 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2174 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2175 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2176 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2177 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2178 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2179 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2180 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2181 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2182 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2183 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2184 ,"" }; // <- mark of end
2185 sameMethods.Insert( names );
2188 return !sameMethods.Contains( theCommand->GetMethod() );
2191 //================================================================================
2193 * \brief Convert creation and addition of all algos and hypos
2195 //================================================================================
2197 void _pyMesh::Flush()
2200 // get the meshes this mesh depends on via hypotheses
2201 list< Handle(_pyMesh) > fatherMeshes;
2202 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2203 for ( ; hyp != myHypos.end(); ++hyp )
2204 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2205 myGeomNotInStudy = true;
2207 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2208 for ( ; m != fatherMeshes.end(); ++m )
2209 addFatherMesh( *m );
2210 // if ( removedGeom )
2211 // SetRemovedFromStudy(); // as referred geometry not in study
2213 if ( myGeomNotInStudy )
2216 list < Handle(_pyCommand) >::iterator cmd;
2218 // try to convert algo addition like this:
2219 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2220 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2222 Handle(_pyCommand) addCmd = *cmd;
2224 _pyID algoID = addCmd->GetArg( 2 );
2225 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2226 if ( algo.IsNull() || !algo->IsAlgo() )
2229 // check and create new algorithm instance if it is already wrapped
2230 if ( algo->IsWrapped() ) {
2231 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2232 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2233 TCollection_AsciiString( " = " ) + theGen->GetID() +
2234 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2235 TCollection_AsciiString( "\" )" );
2237 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2238 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2239 if ( !newAlgo.IsNull() ) {
2240 newAlgo->Assign( algo, this->GetID() );
2241 newAlgo->SetCreationCmd( newCmd );
2243 // set algorithm creation
2244 theGen->SetCommandBefore( newCmd, addCmd );
2245 myHypos.push_back( newAlgo );
2246 if ( !myLastComputeCmd.IsNull() &&
2247 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2248 newAlgo->MeshComputed( myLastComputeCmd );
2253 _pyID geom = addCmd->GetArg( 1 );
2254 bool isLocalAlgo = ( geom != GetGeom() );
2257 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2259 // wrapped algo is created after mesh creation
2260 GetCreationCmd()->AddDependantCmd( addCmd );
2262 if ( isLocalAlgo ) {
2263 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2264 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2265 TCollection_AsciiString( "geom=" ) + geom );
2266 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2267 list < Handle(_pySubMesh) >::iterator smIt;
2268 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2269 Handle(_pySubMesh) subMesh = *smIt;
2270 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2271 if ( geom == subCmd->GetArg( 1 )) {
2272 subCmd->SetObject( algo->GetID() );
2273 subCmd->RemoveArgs();
2274 subMesh->SetCreator( algo );
2279 else // KO - ALGO was already created
2281 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2282 addCmd->RemoveArgs();
2283 addCmd->SetArg( 1, algoID );
2285 addCmd->SetArg( 2, geom );
2286 myNotConvertedAddHypCmds.push_back( addCmd );
2290 // try to convert hypo addition like this:
2291 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2292 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2294 Handle(_pyCommand) addCmd = *cmd;
2295 _pyID hypID = addCmd->GetArg( 2 );
2296 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2297 if ( hyp.IsNull() || hyp->IsAlgo() )
2299 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2301 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2302 _pyID geom = addCmd->GetArg( 1 );
2303 addCmd->RemoveArgs();
2304 addCmd->SetArg( 1, hypID );
2305 if ( geom != GetGeom() )
2306 addCmd->SetArg( 2, geom );
2307 myNotConvertedAddHypCmds.push_back( addCmd );
2311 myAddHypCmds.clear();
2312 mySubmeshes.clear();
2315 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2316 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2320 //================================================================================
2322 * \brief Sets myIsPublished of me and of all objects depending on me.
2324 //================================================================================
2326 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2328 _pyObject::SetRemovedFromStudy(isRemoved);
2330 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2331 for ( ; sm != mySubmeshes.end(); ++sm )
2332 (*sm)->SetRemovedFromStudy(isRemoved);
2334 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2335 for ( ; gr != myGroups.end(); ++gr )
2336 (*gr)->SetRemovedFromStudy(isRemoved);
2338 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2339 for ( ; m != myChildMeshes.end(); ++m )
2340 (*m)->SetRemovedFromStudy(isRemoved);
2342 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2343 for ( ; e != myEditors.end(); ++e )
2344 (*e)->SetRemovedFromStudy(isRemoved);
2347 //================================================================================
2349 * \brief Return true if none of myChildMeshes is in study
2351 //================================================================================
2353 bool _pyMesh::CanClear()
2358 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2359 for ( ; m != myChildMeshes.end(); ++m )
2360 if ( !(*m)->CanClear() )
2366 //================================================================================
2368 * \brief Clear my commands and commands of mesh editor
2370 //================================================================================
2372 void _pyMesh::ClearCommands()
2378 // mark all sub-objects as not removed, except child meshes
2379 list< Handle(_pyMesh) > children;
2380 children.swap( myChildMeshes );
2381 SetRemovedFromStudy( false );
2382 children.swap( myChildMeshes );
2386 _pyObject::ClearCommands();
2388 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2389 for ( ; sm != mySubmeshes.end(); ++sm )
2390 (*sm)->ClearCommands();
2392 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2393 for ( ; gr != myGroups.end(); ++gr )
2394 (*gr)->ClearCommands();
2396 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2397 for ( ; e != myEditors.end(); ++e )
2398 (*e)->ClearCommands();
2401 //================================================================================
2403 * \brief Add a father mesh by ID
2405 //================================================================================
2407 void _pyMesh::addFatherMesh( const _pyID& meshID )
2409 if ( !meshID.IsEmpty() && meshID != GetID() )
2410 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2413 //================================================================================
2415 * \brief Add a father mesh
2417 //================================================================================
2419 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2421 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2423 //myFatherMeshes.push_back( mesh );
2424 mesh->myChildMeshes.push_back( this );
2426 // protect last Compute() from clearing by the next Compute()
2427 mesh->myLastComputeCmd.Nullify();
2431 //================================================================================
2433 * \brief MeshEditor convert its commands to ones of mesh
2435 //================================================================================
2437 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2438 _pyObject( theCreationCmd )
2440 myMesh = theCreationCmd->GetObject();
2441 myCreationCmdStr = theCreationCmd->GetString();
2442 theCreationCmd->Clear();
2444 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2445 if ( !mesh.IsNull() )
2446 mesh->AddEditor( this );
2449 //================================================================================
2451 * \brief convert its commands to ones of mesh
2453 //================================================================================
2455 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2457 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2458 // commands calling these methods are converted to calls of Mesh methods without
2459 // additional modifs, only object is changed from MeshEditor to Mesh.
2460 static TStringSet sameMethods;
2461 if ( sameMethods.empty() ) {
2462 const char * names[] = {
2463 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2464 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2465 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2466 "MoveNode", "MoveClosestNodeToPoint",
2467 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2468 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2469 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2470 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2471 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2472 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2473 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2474 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2475 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2476 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2477 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2478 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2479 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2480 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2481 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2482 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2483 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2484 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2485 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2486 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2487 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2488 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2489 ,"" }; // <- mark of the end
2490 sameMethods.Insert( names );
2493 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2494 TStringMap diffMethods;
2495 if ( diffMethods.empty() ) {
2496 const char * orig2newName[] = {
2497 // original name --------------> new name
2498 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2499 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2500 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2501 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2502 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2503 ""};// <- mark of the end
2504 diffMethods.Insert( orig2newName );
2507 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2508 // only by last two arguments
2509 static TStringSet diffLastTwoArgsMethods;
2510 if (diffLastTwoArgsMethods.empty() ) {
2511 const char * names[] = {
2512 "MirrorMakeGroups","MirrorObjectMakeGroups",
2513 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2514 "RotateMakeGroups","RotateObjectMakeGroups",
2515 ""};// <- mark of the end
2516 diffLastTwoArgsMethods.Insert( names );
2519 // only a method name is to change?
2520 const TCollection_AsciiString & method = theCommand->GetMethod();
2521 bool isPyMeshMethod = sameMethods.Contains( method );
2522 if ( !isPyMeshMethod )
2524 TCollection_AsciiString newMethod = diffMethods.Value( method );
2525 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2526 theCommand->SetMethod( newMethod );
2528 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2529 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2531 isPyMeshMethod = true;
2532 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2533 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2536 if ( !isPyMeshMethod )
2538 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2539 // functions with the flag "theMakeGroups = True" like:
2540 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2541 int pos = method.Search("MakeGroups");
2544 isPyMeshMethod = true;
2545 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2546 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2548 // 1. Remove "MakeGroups" from the Command
2549 TCollection_AsciiString aMethod = theCommand->GetMethod();
2550 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2553 pos = pos-2; //Remove "0D" from the Command too
2554 aMethod.Trunc(pos-1);
2555 theCommand->SetMethod(aMethod);
2557 // 2. And add last "True" argument(s)
2558 while(nbArgsToAdd--)
2559 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2560 if( is0DmethId || is0DmethObj )
2561 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2565 // ExtrusionSweep0D() -> ExtrusionSweep()
2566 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2567 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2568 method == "ExtrusionSweepObject0D" ))
2570 isPyMeshMethod = true;
2571 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2572 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2573 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2576 // DoubleNode...New(...) -> DoubleNode...(...,True)
2577 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2578 method == "DoubleNodeElemGroupsNew" ||
2579 method == "DoubleNodeGroupNew" ||
2580 method == "DoubleNodeGroupsNew" ||
2581 method == "DoubleNodeElemGroup2New" ||
2582 method == "DoubleNodeElemGroups2New"))
2584 isPyMeshMethod = true;
2585 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2586 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2587 if ( excessLen == 3 )
2589 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2591 else if ( theCommand->GetArg(4) == "0" ||
2592 theCommand->GetArg(5) == "0" )
2594 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2595 // Group = DoubleNodeGroup2New(,,,False, True)
2596 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2597 theCommand->SetResultValue( groupID );
2600 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2601 // FindElementsByPoint(x, y, z, elementType, meshPart)
2602 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2604 isPyMeshMethod = true;
2605 theCommand->SetMethod( "FindElementsByPoint" );
2606 // make the 1st arg be the last one
2607 _pyID partID = theCommand->GetArg( 1 );
2608 int nbArgs = theCommand->GetNbArgs();
2609 for ( int i = 2; i <= nbArgs; ++i )
2610 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2611 theCommand->SetArg( nbArgs, partID );
2613 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2614 if ( !isPyMeshMethod && method == "Reorient2D" )
2616 isPyMeshMethod = true;
2617 _AString mesh = theCommand->GetArg( 1 );
2618 _AString dir = theCommand->GetArg( 2 );
2619 _AString face = theCommand->GetArg( 3 );
2620 _AString point = theCommand->GetArg( 4 );
2621 theCommand->RemoveArgs();
2622 theCommand->SetArg( 1, mesh );
2623 theCommand->SetArg( 2, dir );
2624 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2625 theCommand->SetArg( 3, point );
2627 theCommand->SetArg( 3, face );
2630 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2632 isPyMeshMethod = true;
2633 int crit_arg = theCommand->GetNbArgs();
2634 const _AString& crit = theCommand->GetArg(crit_arg);
2635 if (crit.Search("MaxElementLength2D") != -1)
2636 theCommand->SetArg(crit_arg, "");
2639 if ( isPyMeshMethod )
2641 theCommand->SetObject( myMesh );
2645 // editor creation command is needed only if any editor function is called
2646 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2647 if ( !myCreationCmdStr.IsEmpty() ) {
2648 GetCreationCmd()->GetString() = myCreationCmdStr;
2649 myCreationCmdStr.Clear();
2654 //================================================================================
2656 * \brief Return true if my mesh can be removed
2658 //================================================================================
2660 bool _pyMeshEditor::CanClear()
2662 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2663 return mesh.IsNull() ? true : mesh->CanClear();
2666 //================================================================================
2668 * \brief _pyHypothesis constructor
2669 * \param theCreationCmd -
2671 //================================================================================
2673 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2674 _pyObject( theCreationCmd ), myCurCrMethod(0)
2676 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2679 //================================================================================
2681 * \brief Creates algorithm or hypothesis
2682 * \param theCreationCmd - The engine command creating a hypothesis
2683 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2685 //================================================================================
2687 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2689 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2690 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2692 Handle(_pyHypothesis) hyp, algo;
2695 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2696 if ( hypTypeQuoted.IsEmpty() )
2699 TCollection_AsciiString hypType =
2700 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2702 algo = new _pyAlgorithm( theCreationCmd );
2703 hyp = new _pyHypothesis( theCreationCmd );
2705 if ( hypType == "NumberOfSegments" ) {
2706 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2707 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2708 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2709 hyp->AddArgMethod( "SetNumberOfSegments" );
2710 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2711 hyp->AddArgMethod( "SetScaleFactor" );
2712 hyp->AddArgMethod( "SetReversedEdges" );
2713 // same for ""CompositeSegment_1D:
2714 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2715 hyp->AddArgMethod( "SetNumberOfSegments" );
2716 hyp->AddArgMethod( "SetScaleFactor" );
2717 hyp->AddArgMethod( "SetReversedEdges" );
2719 else if ( hypType == "SegmentLengthAroundVertex" ) {
2720 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2721 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2722 hyp->AddArgMethod( "SetLength" );
2723 // same for ""CompositeSegment_1D:
2724 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2725 hyp->AddArgMethod( "SetLength" );
2727 else if ( hypType == "LayerDistribution2D" ) {
2728 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2729 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2731 else if ( hypType == "LayerDistribution" ) {
2732 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2733 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2735 else if ( hypType == "CartesianParameters3D" ) {
2736 hyp = new _pyComplexParamHypo( theCreationCmd );
2737 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2738 for ( int iArg = 0; iArg < 4; ++iArg )
2739 hyp->setCreationArg( iArg+1, "[]");
2740 hyp->AddAccumulativeMethod( "SetGrid" );
2741 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2745 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2748 return algo->IsValid() ? algo : hyp;
2751 //================================================================================
2753 * \brief Returns true if addition of this hypothesis to a given mesh can be
2754 * wrapped into hypothesis creation
2756 //================================================================================
2758 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2760 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2762 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2763 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2769 //================================================================================
2771 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2772 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2773 * \param theAlgo - The algo that can create this hypo
2774 * \retval bool - false if the command can't be converted
2776 //================================================================================
2778 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2779 const _pyID& theMesh)
2781 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2783 if ( !IsWrappable( theMesh ))
2786 myGeom = theCmd->GetArg( 1 );
2788 Handle(_pyHypothesis) algo;
2790 // find algo created on myGeom in theMesh
2791 algo = theGen->FindAlgo( myGeom, theMesh, this );
2792 if ( algo.IsNull() )
2794 // attach hypothesis creation command to be after algo creation command
2795 // because it can be new created instance of algorithm
2796 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2800 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2801 theCmd->SetResultValue( GetID() );
2802 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2803 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2804 // set args (geom will be set by _pyMesh calling this method)
2805 theCmd->RemoveArgs();
2806 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2807 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2808 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2810 theCmd->SetArg( i+1, "[]");
2812 // set a new creation command
2813 GetCreationCmd()->Clear();
2814 // replace creation command by wrapped instance
2815 // please note, that hypothesis attaches to algo creation command (see upper)
2816 SetCreationCmd( theCmd );
2819 // clear commands setting arg values
2820 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2821 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2824 // set unknown arg commands after hypo creation
2825 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2826 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2827 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2828 afterCmd->AddDependantCmd( *cmd );
2834 //================================================================================
2836 * \brief Remember hypothesis parameter values
2837 * \param theCommand - The called hypothesis method
2839 //================================================================================
2841 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2843 ASSERT( !myIsAlgo );
2844 if ( !theGen->IsToKeepAllCommands() )
2845 rememberCmdOfParameter( theCommand );
2847 bool usedCommand = false;
2848 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2849 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2851 CreationMethod& crMethod = type2meth->second;
2852 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2853 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2855 myArgCommands.push_back( theCommand );
2857 while ( crMethod.myArgs.size() < i+1 )
2858 crMethod.myArgs.push_back( "None" );
2859 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2864 myUnusedCommands.push_back( theCommand );
2867 //================================================================================
2869 * \brief Finish conversion
2871 //================================================================================
2873 void _pyHypothesis::Flush()
2877 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2878 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2879 // Add access to a wrapped mesh
2880 theGen->AddMeshAccessorMethod( *cmd );
2881 // Add access to a wrapped algorithm
2882 theGen->AddAlgoAccessorMethod( *cmd );
2884 cmd = myUnusedCommands.begin();
2885 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2886 // Add access to a wrapped mesh
2887 theGen->AddMeshAccessorMethod( *cmd );
2888 // Add access to a wrapped algorithm
2889 theGen->AddAlgoAccessorMethod( *cmd );
2892 // forget previous hypothesis modifications
2893 myArgCommands.clear();
2894 myUnusedCommands.clear();
2897 //================================================================================
2899 * \brief clear creation, arg and unknown commands
2901 //================================================================================
2903 void _pyHypothesis::ClearAllCommands()
2905 GetCreationCmd()->Clear();
2906 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2907 for ( ; cmd != myArgCommands.end(); ++cmd )
2909 cmd = myUnusedCommands.begin();
2910 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2915 //================================================================================
2917 * \brief Assign fields of theOther to me except myIsWrapped
2919 //================================================================================
2921 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2922 const _pyID& theMesh )
2924 // myCreationCmd = theOther->myCreationCmd;
2925 myIsAlgo = theOther->myIsAlgo;
2926 myIsWrapped = false;
2927 myGeom = theOther->myGeom;
2929 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2930 myAccumulativeMethods = theOther->myAccumulativeMethods;
2931 //myUnusedCommands = theOther->myUnusedCommands;
2932 // init myCurCrMethod
2933 GetCreationMethod( theOther->GetAlgoType() );
2936 //================================================================================
2938 * \brief Analyze my erasability depending on myReferredObjs
2940 //================================================================================
2942 bool _pyHypothesis::CanClear()
2946 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2947 for ( ; obj != myReferredObjs.end(); ++obj )
2948 if ( (*obj)->CanClear() )
2955 //================================================================================
2957 * \brief Clear my commands depending on usage by meshes
2959 //================================================================================
2961 void _pyHypothesis::ClearCommands()
2963 // if ( !theGen->IsToKeepAllCommands() )
2965 // bool isUsed = false;
2966 // int lastComputeOrder = 0;
2967 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2968 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2969 // if ( ! (*cmd)->IsEmpty() )
2972 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2973 // lastComputeOrder = (*cmd)->GetOrderNb();
2977 // SetRemovedFromStudy( true );
2981 // // clear my commands invoked after lastComputeOrder
2982 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2983 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2985 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2986 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2987 // // cmds.back()->Clear();
2991 _pyObject::ClearCommands();
2994 //================================================================================
2996 * \brief Find arguments that are objects like mesh, group, geometry
2997 * \param meshes - referred meshes (directly or indirrectly)
2998 * \retval bool - false if a referred geometry is not in the study
3000 //================================================================================
3002 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3004 if ( IsAlgo() ) return true;
3006 bool geomPublished = true;
3007 vector< _AString > args;
3008 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3009 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3011 CreationMethod& crMethod = type2meth->second;
3012 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3014 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3015 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3016 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3017 args.push_back( (*cmd)->GetArg( nb ));
3020 for ( size_t i = 0; i < args.size(); ++i )
3022 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3023 if ( idList.empty() && !args[ i ].IsEmpty() )
3024 idList.push_back( args[ i ]);
3025 list< _pyID >::iterator id = idList.begin();
3026 for ( ; id != idList.end(); ++id )
3028 Handle(_pyObject) obj = theGen->FindObject( *id );
3029 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3032 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3033 geomPublished = false;
3037 myReferredObjs.push_back( obj );
3038 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3039 if ( !mesh.IsNull() )
3040 meshes.push_back( mesh );
3041 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3042 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3043 obj->SetRemovedFromStudy( false );
3047 return geomPublished;
3050 //================================================================================
3052 * \brief Remember theCommand setting a parameter
3054 //================================================================================
3056 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3058 // parameters are discriminated by method name
3059 _AString method = theCommand->GetMethod();
3060 if ( myAccumulativeMethods.count( method ))
3061 return; // this method adds values and not override the previous value
3063 // discriminate commands setting different parameters via one method
3064 // by passing parameter names like e.g. SetOption("size", "0.2")
3065 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3066 theCommand->GetNbArgs() > 1 )
3068 // mangle method by appending a 1st textual arg
3069 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3071 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3072 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3073 if ( !isalpha( arg.Value(2))) continue;
3078 // parameters are discriminated by method name
3079 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3080 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3082 cmds.back()->Clear(); // previous parameter value has not been used
3083 cmds.back() = theCommand;
3087 cmds.push_back( theCommand );
3091 //================================================================================
3093 * \brief Return true if a setting parameter command ha been used to compute mesh
3095 //================================================================================
3097 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3098 _pyCommand::TAddr avoidComputeAddr ) const
3100 bool isUsed = false;
3101 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3102 myComputeAddr2Cmds.begin();
3103 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3105 if ( addr2cmds->first == avoidComputeAddr ) continue;
3106 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3107 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3112 //================================================================================
3114 * \brief Save commands setting parameters as they are used for a mesh computation
3116 //================================================================================
3118 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3120 myComputeCmds.push_back( theComputeCmd );
3121 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3123 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3124 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3125 savedCmds.push_back( m2c->second.back() );
3128 //================================================================================
3130 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3132 //================================================================================
3134 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3136 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3138 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3139 for ( ; cmd != savedCmds.end(); ++cmd )
3141 // check if a cmd has been used to compute another mesh
3142 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3144 // check if a cmd is a sole command setting its parameter;
3145 // don't use method name for search as it can change
3146 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3147 m2cmds = myMeth2Commands.begin();
3148 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3150 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3151 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3152 if ( cmdIt != cmds.end() )
3154 if ( cmds.back() != *cmd )
3156 cmds.erase( cmdIt );
3163 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3166 //================================================================================
3168 * \brief Sets an argNb-th argument of current creation command
3169 * \param argNb - argument index countered from 1
3171 //================================================================================
3173 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3175 if ( myCurCrMethod )
3177 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3178 myCurCrMethod->myArgs.push_back( "None" );
3179 if ( arg.IsEmpty() )
3180 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3182 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3187 //================================================================================
3189 * \brief Remember hypothesis parameter values
3190 * \param theCommand - The called hypothesis method
3192 //================================================================================
3194 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3196 if ( GetAlgoType() == "Cartesian_3D" )
3198 // CartesianParameters3D hyp
3200 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3201 theCommand->GetMethod() == "SetToAddEdges" )
3203 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3204 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3205 myArgCommands.push_back( theCommand );
3208 if ( theCommand->GetMethod() == "SetGrid" ||
3209 theCommand->GetMethod() == "SetGridSpacing" )
3211 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3212 int iArg = axis.Value(1) - '0';
3213 if ( theCommand->GetMethod() == "SetGrid" )
3215 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3219 myCurCrMethod->myArgs[ iArg ] = "[ ";
3220 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3221 myCurCrMethod->myArgs[ iArg ] += ", ";
3222 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3223 myCurCrMethod->myArgs[ iArg ] += "]";
3225 myArgCommands.push_back( theCommand );
3226 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3227 // accumulative, else, if the creation
3228 // is not converted, commands for axes 1 and 2 are lost
3233 if( theCommand->GetMethod() == "SetLength" )
3235 // NOW it is OBSOLETE
3236 // ex: hyp.SetLength(start, 1)
3237 // hyp.SetLength(end, 0)
3238 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3239 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3240 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3241 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3243 CreationMethod& crMethod = type2meth->second;
3244 while ( (int) crMethod.myArgs.size() < i+1 )
3245 crMethod.myArgs.push_back( "[]" );
3246 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3248 myArgCommands.push_back( theCommand );
3252 _pyHypothesis::Process( theCommand );
3255 //================================================================================
3257 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3259 //================================================================================
3261 void _pyComplexParamHypo::Flush()
3263 list < Handle(_pyCommand) >::iterator cmd;
3266 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3267 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3271 // if ( GetAlgoType() == "Cartesian_3D" )
3273 // _pyID algo = myCreationCmd->GetObject();
3274 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3276 // if ( IsWrapped() )
3278 // StructToList( *cmd, /*checkMethod=*/false );
3279 // const _AString & method = (*cmd)->GetMethod();
3280 // if ( method == "SetFixedPoint" )
3281 // (*cmd)->SetObject( algo );
3287 //================================================================================
3289 * \brief Convert methods of 1D hypotheses to my own methods
3290 * \param theCommand - The called hypothesis method
3292 //================================================================================
3294 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3296 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3299 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3300 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3301 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3303 // TCollection_AsciiString cmd =
3304 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3305 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3306 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3309 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3311 // // 1D hypo is already set, so distribution changes and the old
3312 // // 1D hypo is thrown away
3313 // my1dHyp->ClearAllCommands();
3316 // //my1dHyp->SetRemovedFromStudy( false );
3318 // if ( !myArgCommands.empty() )
3319 // myArgCommands.back()->Clear();
3320 myCurCrMethod->myArgs.push_back( hyp1dID );
3321 myArgCommands.push_back( theCommand );
3324 //================================================================================
3327 * \param theAdditionCmd - command to be converted
3328 * \param theMesh - mesh instance
3329 * \retval bool - status
3331 //================================================================================
3333 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3334 const _pyID& theMesh)
3336 myIsWrapped = false;
3338 if ( my1dHyp.IsNull() )
3341 // set "SetLayerDistribution()" after addition cmd
3342 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3344 _pyID geom = theAdditionCmd->GetArg( 1 );
3346 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3347 if ( !algo.IsNull() )
3349 my1dHyp->SetMesh( theMesh );
3350 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3351 algo->GetAlgoType().ToCString());
3352 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3355 // clear "SetLayerDistribution()" cmd
3356 myArgCommands.back()->Clear();
3358 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3360 // find RadialPrism algo created on <geom> for theMesh
3361 GetCreationCmd()->SetObject( algo->GetID() );
3362 GetCreationCmd()->SetMethod( myAlgoMethod );
3363 GetCreationCmd()->RemoveArgs();
3364 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3370 //================================================================================
3374 //================================================================================
3376 void _pyLayerDistributionHypo::Flush()
3378 // as creation of 1D hyp was written later then it's edition,
3379 // we need to find all it's edition calls and process them
3380 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3382 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3384 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3385 if ( hyp1dID.IsEmpty() ) continue;
3387 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3389 // make a new name for 1D hyp = "HypType" + "_Distribution"
3391 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3393 if ( prevNewName.IsEmpty() ) continue;
3394 newName = prevNewName;
3398 if ( hyp1d->IsWrapped() ) {
3399 newName = hyp1d->GetCreationCmd()->GetMethod();
3402 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3403 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3405 newName += "_Distribution";
3406 prevNewName = newName;
3408 hyp1d->GetCreationCmd()->SetResultValue( newName );
3410 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3411 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3412 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3413 const _pyID& objID = (*cmdIt)->GetObject();
3414 if ( objID == hyp1dID ) {
3415 if ( !hyp1d.IsNull() )
3417 hyp1d->Process( *cmdIt );
3418 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3420 ( *cmdIt )->SetObject( newName );
3423 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3424 (*cmd)->SetArg( 1, newName );
3428 //================================================================================
3430 * \brief additionally to Addition2Creation, clears SetDistrType() command
3431 * \param theCmd - AddHypothesis() command
3432 * \param theMesh - mesh to which a hypothesis is added
3433 * \retval bool - conversion result
3435 //================================================================================
3437 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3438 const _pyID& theMesh)
3440 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3441 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3442 bool scaleDistrType = false;
3443 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3444 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3445 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3446 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3447 scaleDistrType = true;
3450 else if ( !scaleDistrType ) {
3451 // distribution type changed: remove scale factor from args
3452 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3453 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3455 CreationMethod& crMethod = type2meth->second;
3456 if ( crMethod.myArgs.size() == 2 )
3457 crMethod.myArgs.pop_back();
3464 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3467 //================================================================================
3469 * \brief remove repeated commands defining distribution
3471 //================================================================================
3473 void _pyNumberOfSegmentsHyp::Flush()
3475 // find number of the last SetDistrType() command
3476 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3477 int distrTypeNb = 0;
3478 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3479 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3480 if ( cmd != myUnusedCommands.rbegin() )
3481 distrTypeNb = (*cmd)->GetOrderNb();
3483 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3486 // clear commands before the last SetDistrType()
3487 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3488 set< int > treatedCmdNbs; // avoid treating same cmd twice
3489 for ( int i = 0; i < 2; ++i ) {
3490 set<TCollection_AsciiString> uniqueMethods;
3491 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3492 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3494 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3495 continue;// avoid treating same cmd twice
3496 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3497 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3498 if ( !clear || method == "SetNumberOfSegments" ) {
3499 bool isNewInSet = uniqueMethods.insert( method ).second;
3500 clear = !isNewInSet;
3509 //================================================================================
3511 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3512 * into regular1D.LengthNearVertex( length, vertex )
3513 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3514 * \param theMesh - The mesh needing this hypo
3515 * \retval bool - false if the command can't be converted
3517 //================================================================================
3519 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3520 const _pyID& theMeshID)
3522 if ( IsWrappable( theMeshID )) {
3524 _pyID vertex = theCmd->GetArg( 1 );
3526 // the problem here is that segment algo can be not found
3527 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3528 // geometry where segment algorithm is assigned
3529 _pyID geom = vertex;
3530 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3531 while ( algo.IsNull() && !geom.IsEmpty()) {
3532 // try to find geom as a father of <vertex>
3533 geom = FatherID( geom );
3534 algo = theGen->FindAlgo( geom, theMeshID, this );
3536 if ( algo.IsNull() || geom.IsEmpty() )
3537 return false; // also possible to find geom as brother of veretex...
3539 // set geom instead of vertex
3540 theCmd->SetArg( 1, geom );
3542 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3543 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3544 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3546 // set vertex as a second arg
3547 theCmd->SetArg( 2, vertex );
3555 //================================================================================
3557 * \brief _pyAlgorithm constructor
3558 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3560 //================================================================================
3562 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3563 : _pyHypothesis( theCreationCmd )
3568 //================================================================================
3570 * \brief Convert the command adding an algorithm to mesh
3571 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3572 * \param theMesh - The mesh needing this algo
3573 * \retval bool - false if the command can't be converted
3575 //================================================================================
3577 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3578 const _pyID& theMeshID)
3580 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3581 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3582 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3588 //================================================================================
3590 * \brief Return starting position of a part of python command
3591 * \param thePartIndex - The index of command part
3592 * \retval int - Part position
3594 //================================================================================
3596 int _pyCommand::GetBegPos( int thePartIndex ) const
3600 if ( myBegPos.Length() < thePartIndex )
3602 ASSERT( thePartIndex > 0 );
3603 return myBegPos( thePartIndex );
3606 //================================================================================
3608 * \brief Store starting position of a part of python command
3609 * \param thePartIndex - The index of command part
3610 * \param thePosition - Part position
3612 //================================================================================
3614 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3616 while ( myBegPos.Length() < thePartIndex )
3617 myBegPos.Append( UNKNOWN );
3618 ASSERT( thePartIndex > 0 );
3619 myBegPos( thePartIndex ) = thePosition;
3622 //================================================================================
3624 * \brief Returns whitespace symbols at the line beginning
3625 * \retval TCollection_AsciiString - result
3627 //================================================================================
3629 TCollection_AsciiString _pyCommand::GetIndentation()
3632 //while ( end <= Length() && isblank( myString.Value( end )))
3633 //ANA: isblank() function isn't provided in VC2010 compiler
3634 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3636 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3639 //================================================================================
3641 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3642 * \retval const TCollection_AsciiString & - ResultValue substring
3644 //================================================================================
3646 const TCollection_AsciiString & _pyCommand::GetResultValue()
3648 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3650 SetBegPos( RESULT_IND, EMPTY );
3651 int begPos, endPos = myString.Location( "=", 1, Length() );
3655 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3656 if ( begPos < endPos )
3658 SetBegPos( RESULT_IND, begPos );
3660 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3661 myRes = myString.SubString( begPos, endPos );
3668 //================================================================================
3670 * \brief Return number of python command result value ResultValue = Obj.Meth()
3672 //================================================================================
3674 int _pyCommand::GetNbResultValues()
3677 return myResults.Length();
3681 //================================================================================
3683 * \brief Return substring of python command looking like
3684 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3685 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3687 //================================================================================
3688 const _AString& _pyCommand::GetResultValue(int res)
3690 if ( GetResultValue().IsEmpty() )
3691 return theEmptyString;
3693 if ( myResults.IsEmpty() )
3696 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3697 ++begPos; // skip [, else the whole list is returned
3698 while ( begPos < myRes.Length() ) {
3699 _AString result = GetWord( myRes, begPos, true );
3700 begPos += result.Length();
3702 // result.RemoveAll('[');
3703 // result.RemoveAll(']');
3708 myResults.Append( result );
3711 if ( res > 0 && res <= myResults.Length() )
3712 return myResults( res );
3713 return theEmptyString;
3716 //================================================================================
3718 * \brief Return substring of python command looking like ResVal = Object.Meth()
3719 * \retval const TCollection_AsciiString & - Object substring
3721 //================================================================================
3723 const TCollection_AsciiString & _pyCommand::GetObject()
3725 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3728 int begPos = GetBegPos( RESULT_IND );
3730 begPos = myString.Location( "=", 1, Length() ) + 1;
3731 // is '=' in the string argument (for example, name) or not
3732 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3733 for ( int i = 1; i < begPos-1; i++ )
3734 switch ( myString.Value( i )) {
3735 case '\'': nb[0]++; break;
3736 case '"' : nb[1]++; break;
3737 case '(' : nb[2]++; break;
3738 case ')' : nb[3]++; break;
3740 // if = is inside a string or a list
3741 // then get an object at the start of the command
3742 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3746 begPos += myRes.Length();
3748 myObj = GetWord( myString, begPos, true );
3749 if ( begPos != EMPTY )
3751 // check if object is complex,
3752 // so far consider case like "smesh.Method()"
3753 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3754 //if ( bracketPos==0 ) bracketPos = Length();
3755 int dotPos = begPos+myObj.Length();
3756 while ( dotPos+1 < bracketPos ) {
3757 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3762 if ( dotPos > begPos+myObj.Length() )
3763 myObj = myString.SubString( begPos, dotPos-1 );
3766 // 1st word after '=' is an object
3767 // else // no method -> no object
3773 SetBegPos( OBJECT_IND, begPos );
3779 //================================================================================
3781 * \brief Return substring of python command looking like ResVal = Obj.Method()
3782 * \retval const TCollection_AsciiString & - Method substring
3784 //================================================================================
3786 const TCollection_AsciiString & _pyCommand::GetMethod()
3788 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3791 int begPos = GetBegPos( OBJECT_IND );
3792 bool forward = true;
3794 begPos = myString.Location( "(", 1, Length() ) - 1;
3798 begPos += myObj.Length();
3801 myMeth = GetWord( myString, begPos, forward );
3802 SetBegPos( METHOD_IND, begPos );
3808 //================================================================================
3810 * \brief Returns true if there are brackets after the method
3812 //================================================================================
3814 bool _pyCommand::IsMethodCall()
3816 if ( GetMethod().IsEmpty() )
3818 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3819 return ( s[0] == '(' || s[1] == '(' );
3822 //================================================================================
3824 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3825 * \retval const TCollection_AsciiString & - Arg<index> substring
3827 //================================================================================
3829 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3831 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3835 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3837 pos = myString.Location( "(", 1, Length() );
3841 // we are at or before '(', skip it if present
3843 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3844 if ( pos > Length() )
3848 SetBegPos( ARG1_IND, 0 ); // even no '('
3849 return theEmptyString;
3853 list< TCollection_AsciiString > separatorStack( 1, ",)");
3854 bool ignoreNesting = false;
3856 while ( pos <= Length() )
3858 const char chr = myString.Value( pos );
3860 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3862 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3864 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3866 TCollection_AsciiString arg;
3867 if ( pos-1 >= prevPos ) {
3868 arg = myString.SubString( prevPos, pos-1 );
3869 arg.RightAdjust(); // remove spaces
3872 if ( !arg.IsEmpty() || chr == ',' )
3874 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3875 myArgs.Append( arg );
3881 else // end of nesting args found
3883 separatorStack.pop_back();
3884 ignoreNesting = false;
3887 else if ( !ignoreNesting )
3890 case '(' : separatorStack.push_back(")"); break;
3891 case '[' : separatorStack.push_back("]"); break;
3892 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3893 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3900 if ( myArgs.Length() < index )
3901 return theEmptyString;
3902 return myArgs( index );
3905 //================================================================================
3907 * \brief Return position where arguments begin
3909 //================================================================================
3911 int _pyCommand::GetArgBeginning() const
3913 int pos = GetBegPos( ARG1_IND );
3914 if ( pos == UNKNOWN )
3916 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3918 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3923 //================================================================================
3925 * \brief Check if char is a word part
3926 * \param c - The character to check
3927 * \retval bool - The check result
3929 //================================================================================
3931 static inline bool isWord(const char c, const bool dotIsWord)
3934 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3937 //================================================================================
3939 * \brief Looks for a word in the string and returns word's beginning
3940 * \param theString - The input string
3941 * \param theStartPos - The position to start the search, returning word's beginning
3942 * \param theForward - The search direction
3943 * \retval TCollection_AsciiString - The found word
3945 //================================================================================
3947 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3949 const bool theForward,
3950 const bool dotIsWord )
3952 int beg = theStartPos, end = theStartPos;
3953 theStartPos = EMPTY;
3954 if ( beg < 1 || beg > theString.Length() )
3955 return theEmptyString;
3957 if ( theForward ) { // search forward
3959 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3961 if ( beg > theString.Length() )
3962 return theEmptyString; // no word found
3965 char begChar = theString.Value( beg );
3966 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3967 char endChar = ( begChar == '[' ) ? ']' : begChar;
3968 // end is at the corresponding quoting mark or bracket
3969 while ( end < theString.Length() &&
3970 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3974 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3979 else { // search backward
3981 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3984 return theEmptyString; // no word found
3986 char endChar = theString.Value( end );
3987 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3988 char begChar = ( endChar == ']' ) ? '[' : endChar;
3989 // beg is at the corresponding quoting mark
3991 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3995 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4001 //cout << theString << " ---- " << beg << " - " << end << endl;
4002 return theString.SubString( beg, end );
4005 //================================================================================
4007 * \brief Returns true if the string looks like a study entry
4009 //================================================================================
4011 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4013 if ( str.Length() < 5 ) return false;
4015 int nbColons = 0, isColon;
4016 for ( int i = 1; i <= str.Length(); ++i )
4018 char c = str.Value(i);
4019 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4021 nbColons += isColon;
4023 return nbColons > 2 && str.Length()-nbColons > 2;
4026 //================================================================================
4028 * \brief Returns true if the string looks like an object ID but not like a list,
4029 * string, command etc.
4031 //================================================================================
4033 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4035 if ( str.Length() < 1 ) return false;
4037 const char* s = str.ToCString();
4039 for ( int i = 0; i < str.Length(); ++i )
4040 if ( !IsIDChar( s[i] ))
4046 //================================================================================
4048 * \brief Finds entries in a string
4050 //================================================================================
4052 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4054 std::list< _pyID > resList;
4056 while ( ++pos <= str.Length() )
4058 if ( !isdigit( str.Value( pos ))) continue;
4059 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4062 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4063 _pyID entry = str.SubString( pos, end-1 );
4065 if ( IsStudyEntry( entry ))
4066 resList.push_back( entry );
4071 //================================================================================
4073 * \brief Look for position where not space char is
4074 * \param theString - The string
4075 * \param thePos - The position to search from and which returns result
4076 * \retval bool - false if there are only space after thePos in theString
4078 //================================================================================
4080 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4082 if ( thePos < 1 || thePos > theString.Length() )
4085 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4088 return thePos <= theString.Length();
4091 //================================================================================
4093 * \brief Modify a part of the command
4094 * \param thePartIndex - The index of the part
4095 * \param thePart - The new part string
4096 * \param theOldPart - The old part
4098 //================================================================================
4100 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4101 TCollection_AsciiString& theOldPart)
4103 int pos = GetBegPos( thePartIndex );
4104 if ( pos <= Length() && theOldPart != thePart)
4106 TCollection_AsciiString seperator;
4108 pos = GetBegPos( thePartIndex + 1 );
4109 if ( pos < 1 ) return;
4110 switch ( thePartIndex ) {
4111 case RESULT_IND: seperator = " = "; break;
4112 case OBJECT_IND: seperator = "."; break;
4113 case METHOD_IND: seperator = "()"; break;
4117 myString.Remove( pos, theOldPart.Length() );
4118 if ( !seperator.IsEmpty() )
4119 myString.Insert( pos , seperator );
4120 myString.Insert( pos, thePart );
4121 // update starting positions of the following parts
4122 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4123 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4124 if ( myBegPos( i ) > 0 )
4125 myBegPos( i ) += posDelta;
4127 theOldPart = thePart;
4131 //================================================================================
4133 * \brief Set argument
4134 * \param index - The argument index, it counts from 1
4135 * \param theArg - The argument string
4137 //================================================================================
4139 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4142 int argInd = ARG1_IND + index - 1;
4143 int pos = GetBegPos( argInd );
4144 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4146 // find a closing parenthesis
4147 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4148 int lastArgInd = GetNbArgs();
4149 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4150 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4155 while ( pos > 0 && myString.Value( pos ) != ')' )
4158 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4162 while ( myArgs.Length() < index ) {
4163 if ( myArgs.Length() )
4164 myString.Insert( pos++, "," );
4165 myArgs.Append("None");
4166 myString.Insert( pos, myArgs.Last() );
4167 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4168 pos += myArgs.Last().Length();
4171 SetPart( argInd, theArg, myArgs( index ));
4174 //================================================================================
4176 * \brief Empty arg list
4178 //================================================================================
4180 void _pyCommand::RemoveArgs()
4182 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4183 myString.Trunc( pos );
4186 if ( myBegPos.Length() >= ARG1_IND )
4187 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4190 //================================================================================
4192 * \brief Comment a python command
4194 //================================================================================
4196 void _pyCommand::Comment()
4198 if ( IsEmpty() ) return;
4201 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4202 if ( i <= Length() )
4204 myString.Insert( i, "#" );
4205 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4207 int begPos = GetBegPos( iPart );
4208 if ( begPos != UNKNOWN && begPos != EMPTY )
4209 SetBegPos( iPart, begPos + 1 );
4214 //================================================================================
4216 * \brief Set dependent commands after this one
4218 //================================================================================
4220 bool _pyCommand::SetDependentCmdsAfter() const
4222 bool orderChanged = false;
4223 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4224 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4225 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4226 orderChanged = true;
4227 theGen->SetCommandAfter( *cmd, this );
4228 (*cmd)->SetDependentCmdsAfter();
4231 return orderChanged;
4233 //================================================================================
4235 * \brief Insert accessor method after theObjectID
4236 * \param theObjectID - id of the accessed object
4237 * \param theAcsMethod - name of the method giving access to the object
4238 * \retval bool - false if theObjectID is not found in the command string
4240 //================================================================================
4242 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4244 if ( !theAcsMethod )
4246 // start object search from the object, i.e. ignore result
4248 int beg = GetBegPos( OBJECT_IND );
4249 if ( beg < 1 || beg > Length() )
4252 while (( beg = myString.Location( theObjectID, beg, Length() )))
4254 // check that theObjectID is not just a part of a longer ID
4255 int afterEnd = beg + theObjectID.Length();
4256 Standard_Character c = myString.Value( afterEnd );
4257 if ( !IsIDChar( c ))
4259 // check if accessor method already present
4261 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4263 int oldLen = Length();
4264 myString.Insert( afterEnd, (char*) theAcsMethod );
4265 myString.Insert( afterEnd, "." );
4266 // update starting positions of the parts following the modified one
4267 int posDelta = Length() - oldLen;
4268 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4269 if ( myBegPos( i ) > afterEnd )
4270 myBegPos( i ) += posDelta;
4275 beg = afterEnd; // is a part -> next search
4280 //================================================================================
4282 * \brief Creates pyObject
4284 //================================================================================
4286 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4287 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4292 //================================================================================
4294 * \brief Set up myID and myIsPublished
4296 //================================================================================
4298 void _pyObject::setID(const _pyID& theID)
4301 myIsPublished = !theGen->IsNotPublished( GetID() );
4304 //================================================================================
4306 * \brief Clear myCreationCmd and myProcessedCmds
4308 //================================================================================
4310 void _pyObject::ClearCommands()
4315 if ( !myCreationCmd.IsNull() )
4316 myCreationCmd->Clear();
4318 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4319 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4323 //================================================================================
4325 * \brief Return method name giving access to an interaface object wrapped by python class
4326 * \retval const char* - method name
4328 //================================================================================
4330 const char* _pyObject::AccessorMethod() const
4334 //================================================================================
4336 * \brief Return ID of a father
4338 //================================================================================
4340 _pyID _pyObject::FatherID(const _pyID & childID)
4342 int colPos = childID.SearchFromEnd(':');
4344 return childID.SubString( 1, colPos-1 );
4348 //================================================================================
4350 * \brief SelfEraser erases creation command if none of it's commands invoked
4351 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4353 //================================================================================
4355 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4356 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4358 myIsPublished = true; // prevent clearing as a not published
4359 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4362 //================================================================================
4364 * \brief SelfEraser erases creation command if none of it's commands invoked
4365 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4367 //================================================================================
4369 bool _pySelfEraser::CanClear()
4371 bool toErase = false;
4372 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4375 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4376 for ( ; cmd != myArgCmds.end(); ++cmd )
4377 nbArgUses += IsAliveCmd( *cmd );
4379 toErase = ( nbArgUses < 1 );
4384 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4385 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4386 for ( ; cmd != cmds.end(); )
4387 // check of cmd emptiness is not enough as object can change
4388 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4391 cmd = cmds.erase( cmd ); // save the cmd from clearing
4393 toErase = ( nbCalls < 1 );
4398 //================================================================================
4400 * \brief Check if a command is or can be cleared
4402 //================================================================================
4404 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4406 if ( theCmd->IsEmpty() )
4409 if ( !theGen->IsToKeepAllCommands() )
4411 const _pyID& objID = theCmd->GetObject();
4412 Handle( _pyObject ) obj = theGen->FindObject( objID );
4413 if ( !obj.IsNull() )
4414 return !obj->CanClear();
4419 //================================================================================
4421 * \brief SelfEraser erases creation command if none of it's commands invoked
4422 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4424 //================================================================================
4426 void _pySelfEraser::Flush()
4430 myIsPublished = false;
4431 _pyObject::ClearCommands();
4435 //================================================================================
4437 * \brief _pySubMesh constructor
4439 //================================================================================
4441 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4442 _pyObject(theCreationCmd)
4444 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4445 if ( toKeepAgrCmds )
4446 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4449 //================================================================================
4451 * \brief Return true if a sub-mesh can be used as argument of the given method
4453 //================================================================================
4455 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4458 // names of all methods where a sub-mesh can be used as argument
4459 // static TStringSet methods;
4460 // if ( methods.empty() ) {
4461 // const char * names[] = {
4462 // // methods of SMESH_Gen
4464 // // methods of SMESH_Group
4466 // // methods of SMESH_Measurements
4468 // // methods of SMESH_Mesh
4469 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4471 // // methods of SMESH_MeshEditor
4472 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4473 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4474 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4475 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4476 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4477 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4478 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4479 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4480 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4481 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4482 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4483 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4484 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4485 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4486 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4487 // "" }; // <- mark of end
4488 // methods.Insert( names );
4490 // return methods.Contains( theMethodName );
4493 //================================================================================
4495 * \brief count invoked commands
4497 //================================================================================
4499 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4501 _pyObject::Process(theCommand); // count calls of Process()
4504 //================================================================================
4506 * \brief Move creation command depending on invoked commands
4508 //================================================================================
4510 void _pySubMesh::Flush()
4512 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4513 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4514 else if ( !myCreator.IsNull() )
4515 // move to be just after creator
4516 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4518 // move sub-mesh usage after creation cmd
4519 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4520 for ( ; cmd != myArgCmds.end(); ++cmd )
4521 if ( !(*cmd)->IsEmpty() )
4522 GetCreationCmd()->AddDependantCmd( *cmd );
4525 //================================================================================
4527 * \brief Creates _pyGroup
4529 //================================================================================
4531 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4532 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4534 if ( !id.IsEmpty() )
4537 myCanClearCreationCmd = true;
4539 const _AString& method = theCreationCmd->GetMethod();
4540 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4542 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4544 // ----------------------------------------------------------------------
4545 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4547 _pyID geom = theCreationCmd->GetArg( 3 );
4548 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4549 // next if(){...} section is commented
4550 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4551 // theCreationCmd->SetMethod( "Group" );
4552 // theCreationCmd->RemoveArgs();
4553 // theCreationCmd->SetArg( 1, geom );
4556 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4557 _pyID type = theCreationCmd->GetArg( 1 );
4558 _pyID name = theCreationCmd->GetArg( 2 );
4559 theCreationCmd->SetMethod( "GroupOnGeom" );
4560 theCreationCmd->RemoveArgs();
4561 theCreationCmd->SetArg( 1, geom );
4562 theCreationCmd->SetArg( 2, name );
4563 theCreationCmd->SetArg( 3, type );
4566 else if ( method == "CreateGroupFromFilter" )
4568 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4569 theCreationCmd->SetMethod( "GroupOnFilter" );
4571 _pyID filterID = theCreationCmd->GetArg(3);
4572 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4573 if ( !filter.IsNull())
4575 if ( !filter->GetNewID().IsEmpty() )
4576 theCreationCmd->SetArg( 3, filter->GetNewID() );
4577 //filter->AddUser( this );
4581 else if ( method == "GetGroups" )
4583 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4587 // theCreationCmd does something else apart from creation of this group
4588 // and thus it can't be cleared if this group is removed
4589 myCanClearCreationCmd = false;
4593 //================================================================================
4595 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4598 //================================================================================
4600 bool _pyGroup::CanClear()
4605 if ( !myCanClearCreationCmd &&
4606 !myCreationCmd.IsNull() &&
4607 myCreationCmd->GetMethod() == "GetGroups" )
4609 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4610 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4611 list< _pyID >::iterator grID = idList.begin();
4612 if ( GetID() == *grID )
4614 myCanClearCreationCmd = true;
4615 list< Handle(_pyGroup ) > groups;
4616 for ( ; grID != idList.end(); ++grID )
4618 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4619 if ( group.IsNull() ) continue;
4620 groups.push_back( group );
4621 if ( group->IsInStudy() )
4622 myCanClearCreationCmd = false;
4624 // set myCanClearCreationCmd == true to all groups
4625 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4626 for ( ; group != groups.end(); ++group )
4627 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4631 return myCanClearCreationCmd;
4634 //================================================================================
4636 * \brief set myCanClearCreationCmd = true if the main action of the creation
4637 * command is discarded
4639 //================================================================================
4641 void _pyGroup::RemovedWithContents()
4643 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4644 // via a created group
4645 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4646 // myCanClearCreationCmd = true;
4649 //================================================================================
4651 * \brief To convert creation of a group by filter
4653 //================================================================================
4655 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4657 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4658 // group = mesh.CreateEmptyGroup( elemType, groupName )
4659 // aFilter.SetMesh(mesh)
4660 // nbAdd = group.AddFrom( aFilter )
4661 Handle(_pyFilter) filter;
4662 if ( theCommand->GetMethod() == "AddFrom" )
4664 _pyID idSource = theCommand->GetArg(1);
4665 // check if idSource is a filter
4666 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4667 if ( !filter.IsNull() )
4669 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4670 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4671 while ( *cmdIt != theCommand ) ++cmdIt;
4672 while ( (*cmdIt)->GetOrderNb() != 1 )
4674 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4675 if ((setMeshCmd->GetObject() == idSource ||
4676 setMeshCmd->GetObject() == filter->GetNewID() )
4678 setMeshCmd->GetMethod() == "SetMesh")
4680 setMeshCmd->Clear();
4684 // replace 3 commands by one
4685 theCommand->Clear();
4686 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4687 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4688 if ( !filter->GetNewID().IsEmpty() )
4689 idSource = filter->GetNewID();
4690 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4691 makeGroupCmd->SetArg( 1, name );
4692 makeGroupCmd->SetArg( 2, idSource );
4693 filter->AddArgCmd( makeGroupCmd );
4696 else if ( theCommand->GetMethod() == "SetFilter" )
4698 // set new name of a filter or clear the command if the same filter is set
4699 _pyID filterID = theCommand->GetArg(1);
4700 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4701 if ( !myFilter.IsNull() && filter == myFilter )
4702 theCommand->Clear();
4703 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4704 theCommand->SetArg( 1, filter->GetNewID() );
4707 else if ( theCommand->GetMethod() == "GetFilter" )
4709 // GetFilter() returns a filter with other ID, make myFilter process
4710 // calls of the returned filter
4711 if ( !myFilter.IsNull() )
4713 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4714 theCommand->Clear();
4718 // if ( !filter.IsNull() )
4719 // filter->AddUser( this );
4721 theGen->AddMeshAccessorMethod( theCommand );
4724 //================================================================================
4726 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4728 //================================================================================
4730 void _pyGroup::Flush()
4732 if ( !theGen->IsToKeepAllCommands() &&
4733 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4735 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4739 //================================================================================
4741 * \brief Constructor of _pyFilter
4743 //================================================================================
4745 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4746 :_pyObject(theCreationCmd), myNewID( newID )
4748 //myIsPublished = true; // prevent clearing as a not published
4749 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4752 //================================================================================
4754 * \brief To convert creation of a filter by criteria and
4755 * to replace an old name by a new one
4757 //================================================================================
4759 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4761 if ( theCommand->GetObject() == GetID() )
4762 _pyObject::Process(theCommand); // count commands
4764 if ( !myNewID.IsEmpty() )
4765 theCommand->SetObject( myNewID );
4767 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4768 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4769 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4770 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4771 theCommand->GetMethod() == "SetCriteria")
4773 // aFilter.SetCriteria(aCriteria) ->
4774 // aFilter = smesh.GetFilterFromCriteria(criteria)
4775 if ( myNewID.IsEmpty() )
4776 theCommand->SetResultValue( GetID() );
4778 theCommand->SetResultValue( myNewID );
4779 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4780 theCommand->SetMethod( "GetFilterFromCriteria" );
4782 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4783 GetCreationCmd()->Clear();
4784 GetCreationCmd()->GetString() = theCommand->GetString();
4785 theCommand->Clear();
4786 theCommand->AddDependantCmd( GetCreationCmd() );
4787 // why swap? -- it's needed
4788 //GetCreationCmd()->Clear();
4790 else if ( theCommand->GetMethod() == "SetMesh" )
4792 if ( myMesh == theCommand->GetArg( 1 ))
4793 theCommand->Clear();
4795 myMesh = theCommand->GetArg( 1 );
4796 theGen->AddMeshAccessorMethod( theCommand );
4800 //================================================================================
4802 * \brief Set new filter name to the creation command and to myArgCmds
4804 //================================================================================
4806 void _pyFilter::Flush()
4808 if ( myNewID.IsEmpty() ) return;
4810 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4811 for ( ; cmd != myArgCmds.end(); ++cmd )
4812 if ( !(*cmd)->IsEmpty() )
4814 _AString cmdStr = (*cmd)->GetString();
4815 _AString id = GetID();
4816 int pos = cmdStr.Search( id );
4819 cmdStr.Remove( pos, id.Length() );
4820 cmdStr.Insert( pos, myNewID );
4823 (*cmd)->GetString() = cmdStr;
4826 if ( !GetCreationCmd()->IsEmpty() )
4827 GetCreationCmd()->SetResultValue( myNewID );
4830 //================================================================================
4832 * \brief Return true if all my users can be cleared
4834 //================================================================================
4836 bool _pyObject::CanClear()
4838 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4839 for ( ; cmd != myArgCmds.end(); ++cmd )
4840 if ( !(*cmd)->IsEmpty() )
4842 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4843 if ( !obj.IsNull() && !obj->CanClear() )
4846 return ( !myIsPublished );
4849 //================================================================================
4851 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4853 //================================================================================
4855 _pyHypothesisReader::_pyHypothesisReader()
4858 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4859 LDOMParser xmlParser;
4860 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4862 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4866 INFOS( xmlParser.GetError(data) );
4869 // <algorithm type="Regular_1D"
4870 // label-id="Wire discretisation"
4873 // <algo>Regular_1D=Segment()</algo>
4874 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4876 LDOM_Document xmlDoc = xmlParser.getDocument();
4877 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4878 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4880 LDOM_Node algoNode = algoNodeList.item( i );
4881 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4882 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4883 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4885 _AString text, algoType, method, arg;
4886 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4888 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4889 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4890 text = textNode.getNodeValue();
4891 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4892 algoType = algoCmd->GetResultValue();
4893 method = algoCmd->GetMethod();
4894 arg = algoCmd->GetArg(1);
4895 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4897 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4898 algo->SetConvMethodAndType( method, algoType );
4899 if ( !arg.IsEmpty() )
4900 algo->setCreationArg( 1, arg );
4902 myType2Hyp[ algoType ] = algo;
4906 if ( algoType.IsEmpty() ) continue;
4908 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4910 Handle( _pyHypothesis ) hyp;
4911 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4913 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4914 LDOM_Node textNode = pyHypoNode.getFirstChild();
4915 text = textNode.getNodeValue();
4916 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4917 hypType = hypoCmd->GetResultValue();
4918 method = hypoCmd->GetMethod();
4919 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4921 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4922 if ( type2hyp == myType2Hyp.end() )
4923 hyp = new _pyHypothesis( hypoCmd );
4925 hyp = type2hyp->second;
4926 hyp->SetConvMethodAndType( method, algoType );
4927 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4929 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4930 _AString argMethod = argCmd.GetMethod();
4931 _AString argNbText = argCmd.GetArg( 1 );
4932 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4933 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4935 hyp->AddArgMethod( argMethod,
4936 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4938 myType2Hyp[ hypType ] = hyp;
4942 // <hypothesis type="BLSURF_Parameters"
4946 // <accumulative-methods>
4947 // SetEnforcedVertex,
4948 // SetEnforcedVertexNamed
4949 // </accumulative-methods>
4953 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4954 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4956 LDOM_Node hypNode = hypNodeList.item( i );
4957 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4958 _AString hypType = hypElem.getAttribute("type");
4959 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4960 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4962 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4963 if ( type2hyp == myType2Hyp.end() ) continue;
4965 LDOM_Node methNode = methNodeList.item( 0 );
4966 LDOM_Node textNode = methNode.getFirstChild();
4967 _AString text = textNode.getNodeValue();
4971 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4972 pos += method.Length();
4973 type2hyp->second->AddAccumulativeMethod( method );
4975 while ( !method.IsEmpty() );
4978 } // loop on xmlPaths
4981 //================================================================================
4983 * \brief Returns a new hypothesis initialized according to the read information
4985 //================================================================================
4987 Handle(_pyHypothesis)
4988 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4989 const Handle(_pyCommand)& creationCmd) const
4991 Handle(_pyHypothesis) resHyp, sampleHyp;
4993 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4994 if ( type2hyp != myType2Hyp.end() )
4995 sampleHyp = type2hyp->second;
4997 if ( sampleHyp.IsNull() )
4999 resHyp = new _pyHypothesis(creationCmd);
5003 if ( sampleHyp->IsAlgo() )
5004 resHyp = new _pyAlgorithm( creationCmd );
5006 resHyp = new _pyHypothesis(creationCmd);
5007 resHyp->Assign( sampleHyp, _pyID() );
5012 //================================================================================
5014 * \brief Adds an object ID to some family of IDs with a common prefix
5015 * \param [in] str - the object ID
5016 * \return bool - \c false if \a str does not have the same prefix as \a this family
5017 * (for internal usage)
5019 //================================================================================
5021 bool _pyStringFamily::Add( const char* str )
5023 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5024 return false; // expected prefix is missing
5026 str += _prefix.Length(); // skip _prefix
5028 // try to add to some of child falimies
5029 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5030 for ( ; itSub != _subFams.end(); ++itSub )
5031 if ( itSub->Add( str ))
5034 // no suitable family found - add str to _strings or create a new child family
5036 // look for a proper place within sorted _strings
5037 std::list< _AString >::iterator itStr = _strings.begin();
5038 while ( itStr != _strings.end() && itStr->IsLess( str ))
5040 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5041 return true; // same ID already kept
5043 const int minPrefixSize = 4;
5045 // count "smaller" strings with the same prefix
5046 std::list< _AString >::iterator itLess = itStr; --itLess;
5048 for ( ; itLess != _strings.end(); --itLess )
5049 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5054 // count "greater" strings with the same prefix
5055 std::list< _AString >::iterator itMore = itStr;
5057 for ( ; itMore != _strings.end(); ++itMore )
5058 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5063 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5065 // look for a maximal prefix length
5066 // int lessPrefSize = 3, morePrefSize = 3;
5067 // if ( nbLess > 0 )
5068 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5070 // if ( nbMore > 0 )
5071 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5073 // int prefixSize = 3;
5074 // if ( nbLess == 0 )
5075 // prefixSize = morePrefSize;
5076 // else if ( nbMore == 0 )
5077 // prefixSize = lessPrefSize;
5079 // prefixSize = Min( lessPrefSize, morePrefSize );
5080 int prefixSize = minPrefixSize;
5081 _AString newPrefix ( str, prefixSize );
5083 // look for a proper place within _subFams sorted by _prefix
5084 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5085 if ( !itSub->_prefix.IsLess( newPrefix ))
5088 // add the new _pyStringFamily
5089 itSub = _subFams.insert( itSub, _pyStringFamily());
5090 _pyStringFamily& newSubFam = *itSub;
5091 newSubFam._prefix = newPrefix;
5093 // pass this->_strings to newSubFam._strings
5094 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5095 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5096 newSubFam._strings.push_back( str + prefixSize );
5097 for ( ; nbMore > 0; --nbMore, ++itStr )
5098 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5100 _strings.erase( itLess, ++itMore );
5102 else // too few string to make a family for them
5104 _strings.insert( itStr, str );
5109 //================================================================================
5111 * \brief Finds an object ID in the command
5112 * \param [in] longStr - the command string
5113 * \param [out] subStr - the found object ID
5114 * \return bool - \c true if the object ID found
5116 //================================================================================
5118 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5120 const _AString& longStr = cmd->GetString();
5121 const char* s = longStr.ToCString();
5124 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5125 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5126 if ( argBeg < 4 || argBeg > longStr.Length() )
5128 for ( ; itSub != _subFams.end(); ++itSub )
5131 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5132 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5134 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5135 from = pos + len + itSub->_prefix.Length();
5140 from += itSub->_prefix.Length();
5143 // look among _strings
5144 std::list< _AString >::iterator itStr = _strings.begin();
5145 for ( ; itStr != _strings.end(); ++itStr )
5146 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5147 // check that object ID does not continue after len
5148 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5150 subStr.push_back( *itStr );
5156 //================================================================================
5158 * \brief Return remainder length of the object ID after my _prefix
5159 * \param [in] str - remainder of the command after my _prefix
5160 * \return int - length of the object ID or -1 if not found
5162 //================================================================================
5164 int _pyStringFamily::isIn( const char* str )
5166 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5168 for ( ; itSub != _subFams.end(); ++itSub )
5170 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5173 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5174 return itSub->_prefix.Length() + len;
5179 if ( !_strings.empty() )
5181 std::list< _AString >::iterator itStr = _strings.begin();
5182 bool firstEmpty = itStr->IsEmpty();
5185 for ( ; itStr != _strings.end(); ++itStr )
5187 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5190 len = itStr->Length();
5199 // check that object ID does not continue after len
5200 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5207 //================================================================================
5211 //================================================================================
5213 void _pyStringFamily::Print( int level )
5215 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5216 std::list< _AString >::iterator itStr = _strings.begin();
5217 for ( ; itStr != _strings.end(); ++itStr )
5218 cout << *itStr << " | ";
5220 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5221 for ( ; itSub != _subFams.end(); ++itSub )
5222 itSub->Print( level + 1 );
5224 cout << string( 70, '-' ) << endl;