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 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 OCCT_IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 OCCT_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 coresponding 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
298 // It's necessary to continue recording this history and to fill
299 // undef2newItems (see below) accordingly.
301 typedef map< int, vector< int > > TUndef2newItems;
302 static TUndef2newItems undef2newItems;
303 if ( undef2newItems.empty() )
305 undef2newItems[ 26 ].push_back( 7 );
306 undef2newItems[ 27 ].push_back( 17 );
307 { int items[] = { 10, 11, 23, 24, 25 };
308 undef2newItems[ 32 ].assign( items, items+5 ); }
309 undef2newItems[ 33 ].push_back( 26 );
310 { int items[] = { 8, 9, 25, 26, 27, 28 };
311 undef2newItems[ 39 ].assign( items, items+6 ); }
312 { int items[] = { 14, 15, 16, 17 };
313 undef2newItems[ 43 ].assign( items, items+4 ); }
314 undef2newItems[ 44 ].push_back( 37 );
315 undef2newItems[ 45 ].push_back( 36 );
316 undef2newItems[ 46 ].push_back( 39 );
317 undef2newItems[ 47 ].push_back( 22 );
318 undef2newItems[ 48 ].push_back( 22 );
320 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
323 int iType = Type.IntegerValue();
324 int iCompare = Compare.IntegerValue();
325 int iUnaryOp = UnaryOp.IntegerValue();
326 int iBinaryOp = BinaryOp.IntegerValue();
328 // find out integer value of FT_Undefined at the moment of dump
329 int oldUndefined = iBinaryOp;
330 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
333 // apply history to args
334 TUndef2newItems::const_iterator undef_items =
335 undef2newItems.upper_bound( oldUndefined );
336 if ( undef_items != undef2newItems.end() )
338 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
339 for ( ; undef_items != undef2newItems.end(); ++undef_items )
341 const vector< int > & addedItems = undef_items->second;
342 for ( size_t i = 0; i < addedItems.size(); ++i )
343 for ( int iArg = 0; iArg < 4; ++iArg )
345 int& arg = *pArg[iArg];
346 if ( arg >= addedItems[i] )
350 Type = TCollection_AsciiString( iType );
351 Compare = TCollection_AsciiString( iCompare );
352 UnaryOp = TCollection_AsciiString( iUnaryOp );
353 BinaryOp = TCollection_AsciiString( iBinaryOp );
357 //================================================================================
359 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
360 * arguments of a given command by a list "[x,y,z]" if the list is accesible
363 //================================================================================
365 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
367 static TStringSet methodsAcceptingList;
368 if ( methodsAcceptingList.empty() ) {
369 const char * methodNames[] = {
370 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
371 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
372 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
373 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
374 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
375 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
376 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
377 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
378 "Translate","TranslateMakeGroups","TranslateMakeMesh",
379 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
380 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
381 ,"" }; // <- mark of the end
382 methodsAcceptingList.Insert( methodNames );
384 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
386 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
388 const _AString & arg = theCommand->GetArg( i );
389 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
390 arg.Search( "SMESH.DirStruct" ) == 1 )
392 Handle(_pyCommand) workCmd = new _pyCommand( arg );
393 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
395 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
397 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
399 _AString newArg = "[ ";
400 newArg += ( workCmd->GetArg( 1 ) + ", " +
401 workCmd->GetArg( 2 ) + ", " +
402 workCmd->GetArg( 3 ) + " ]");
403 theCommand->SetArg( i, newArg );
409 //================================================================================
411 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
412 * a list "[id1,id2]" if the list is an accesible type of argument.
414 //================================================================================
416 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
418 static TStringSet methodsAcceptingList;
419 if ( methodsAcceptingList.empty() ) {
420 const char * methodNames[] = {
421 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
422 "ExportCGNS","ExportGMF",
423 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
424 "ScaleMakeGroups","Scale","ScaleMakeMesh",
425 "FindCoincidentNodesOnPartBut","DoubleElements",
426 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
427 ,"" }; // <- mark of the end
428 methodsAcceptingList.Insert( methodNames );
430 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
432 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
434 _pyCommand argCmd( theCommand->GetArg( i ));
435 if ( argCmd.GetMethod() == "GetIDSource" &&
436 argCmd.GetNbArgs() == 2 )
438 theCommand->SetArg( i, argCmd.GetArg( 1 ));
445 //================================================================================
447 * \brief Convert a python script using commands of smeshBuilder.py
448 * \param theScriptLines - Lines of the input script
449 * \param theEntry2AccessorMethod - returns method names to access to
450 * objects wrapped with python class
451 * \param theObjectNames - names of objects
452 * \param theRemovedObjIDs - entries of objects whose created commands were removed
453 * \param theHistoricalDump - true means to keep all commands, false means
454 * to exclude commands relating to objects removed from study
455 * \retval TCollection_AsciiString - Conversion result
457 //================================================================================
460 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
461 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
462 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
463 std::set< TCollection_AsciiString >& theRemovedObjIDs,
464 const bool theToKeepAllCommands)
466 std::list< TCollection_AsciiString >::iterator lineIt;
467 // process notebook variables
469 SMESH_NoteBook aNoteBook;
471 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
472 aNoteBook.AddCommand( *lineIt );
474 theScriptLines.clear();
476 aNoteBook.ReplaceVariables();
478 aNoteBook.GetResultLines( theScriptLines );
481 // convert to smeshBuilder.py API
483 theGen = new _pyGen( theEntry2AccessorMethod,
486 theToKeepAllCommands );
488 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
489 theGen->AddCommand( *lineIt );
491 theScriptLines.clear();
495 #ifdef DUMP_CONVERSION
496 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
499 // clean commmands of removed objects depending on myIsPublished flag
500 theGen->ClearCommands();
502 // reorder commands after conversion
503 list< Handle(_pyCommand) >::iterator cmd;
506 orderChanges = false;
507 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
508 if ( (*cmd)->SetDependentCmdsAfter() )
510 } while ( orderChanges );
512 // concat commands back into a script
513 TCollection_AsciiString aPrevCmd;
514 set<_pyID> createdObjects;
515 createdObjects.insert( "smeshBuilder" );
516 createdObjects.insert( "smesh" );
517 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
519 #ifdef DUMP_CONVERSION
520 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
522 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
523 CheckObjectPresence( *cmd, createdObjects );
524 if ( !(*cmd)->IsEmpty() ) {
525 aPrevCmd = (*cmd)->GetString();
526 theScriptLines.push_back( aPrevCmd );
535 //================================================================================
537 * \brief _pyGen constructor
539 //================================================================================
541 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
542 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
543 std::set< TCollection_AsciiString >& theRemovedObjIDs,
544 const bool theToKeepAllCommands)
545 : _pyObject( new _pyCommand( "", 0 )),
547 myID2AccessorMethod( theEntry2AccessorMethod ),
548 myObjectNames( theObjectNames ),
549 myRemovedObjIDs( theRemovedObjIDs ),
551 myToKeepAllCommands( theToKeepAllCommands ),
552 myGeomIDNb(0), myGeomIDIndex(-1)
554 // make that GetID() to return TPythonDump::SMESHGenName()
555 GetCreationCmd()->Clear();
556 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
557 GetCreationCmd()->GetString() += "=";
559 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
560 if ( !theObjectNames.IsEmpty() )
564 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
565 if ( geomComp->_is_nil() ) return;
566 CORBA::String_var entry = geomComp->GetID();
569 // find a SMESH entry
571 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
572 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
573 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
576 // find 1st difference between smeshID and geomID
577 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
578 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
579 if ( geomID.Value( i ) != smeshID.Value( i ))
581 myGeomIDNb = geomID.Value( i );
587 //================================================================================
589 * \brief name of SMESH_Gen in smeshBuilder.py
591 //================================================================================
593 const char* _pyGen::AccessorMethod() const
595 return SMESH_2smeshpy::GenName();
598 //================================================================================
600 * \brief Convert a command using a specific converter
601 * \param theCommand - the command to convert
603 //================================================================================
605 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
607 // store theCommand in the sequence
608 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
610 Handle(_pyCommand) aCommand = myCommands.back();
611 #ifdef DUMP_CONVERSION
612 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
615 const _pyID& objID = aCommand->GetObject();
617 if ( objID.IsEmpty() )
620 // Prevent moving a command creating a sub-mesh to the end of the script
621 // if the sub-mesh is used in theCommand as argument
622 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
624 // PlaceSubmeshAfterItsCreation( aCommand );
627 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
628 StructToList( aCommand );
630 const TCollection_AsciiString& method = aCommand->GetMethod();
632 // not to erase _pySelfEraser's etc. used as args in some commands
634 #ifdef USE_STRING_FAMILY
635 std::list<_pyID> objIDs;
636 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
638 std::list<_pyID>::iterator objID = objIDs.begin();
639 for ( ; objID != objIDs.end(); ++objID )
641 Handle(_pyObject) obj = FindObject( *objID );
644 obj->AddArgCmd( aCommand );
645 //cout << objID << " found in " << theCommand << endl;
650 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
651 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
652 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
654 Handle(_pyObject) obj = FindObject( *id );
656 obj->AddArgCmd( aCommand );
661 // Find an object to process theCommand
664 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
666 this->Process( aCommand );
667 //addFilterUser( aCommand, theGen ); // protect filters from clearing
671 // SMESH_Mesh method?
672 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
673 if ( id_mesh != myMeshes.end() )
675 //id_mesh->second->AddProcessedCmd( aCommand );
677 // Wrap Export*() into try-except
678 if ( aCommand->MethodStartsFrom("Export"))
681 _AString indent = aCommand->GetIndentation();
682 _AString tryStr = indent + "try:";
683 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
684 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
685 _AString excStr = indent + "except:";
686 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
688 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
690 aCommand->GetString() = newCmd;
691 aCommand->SetOrderNb( ++myNbCommands );
692 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
693 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
694 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
696 // check for mesh editor object
697 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
698 _pyID editorID = aCommand->GetResultValue();
699 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
700 myMeshEditors.insert( make_pair( editorID, editor ));
703 // check for SubMesh objects
704 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
705 _pyID subMeshID = aCommand->GetResultValue();
706 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
707 AddObject( subMesh );
710 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
711 GetIDSourceToList( aCommand );
713 //addFilterUser( aCommand, theGen ); // protect filters from clearing
715 id_mesh->second->Process( aCommand );
716 id_mesh->second->AddProcessedCmd( aCommand );
720 // SMESH_MeshEditor method?
721 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
722 if ( id_editor != myMeshEditors.end() )
724 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
725 GetIDSourceToList( aCommand );
727 //addFilterUser( aCommand, theGen ); // protect filters from clearing
729 // some commands of SMESH_MeshEditor create meshes and groups
730 _pyID meshID, groups;
731 if ( method.Search("MakeMesh") != -1 )
732 meshID = aCommand->GetResultValue();
733 else if ( method == "MakeBoundaryMesh")
734 meshID = aCommand->GetResultValue(1);
735 else if ( method == "MakeBoundaryElements")
736 meshID = aCommand->GetResultValue(2);
738 if ( method.Search("MakeGroups") != -1 ||
739 method == "ExtrusionAlongPathX" ||
740 method == "ExtrusionAlongPathObjX" ||
741 method == "DoubleNodeGroupNew" ||
742 method == "DoubleNodeGroupsNew" ||
743 method == "DoubleNodeElemGroupNew" ||
744 method == "DoubleNodeElemGroupsNew"||
745 method == "DoubleNodeElemGroup2New"||
746 method == "DoubleNodeElemGroups2New"
748 groups = aCommand->GetResultValue();
749 else if ( method == "MakeBoundaryMesh" )
750 groups = aCommand->GetResultValue(2);
751 else if ( method == "MakeBoundaryElements")
752 groups = aCommand->GetResultValue(3);
753 else if ( method == "Create0DElementsOnAllNodes" &&
754 aCommand->GetArg(2).Length() > 2 ) // group name != ''
755 groups = aCommand->GetResultValue();
757 id_editor->second->Process( aCommand );
758 id_editor->second->AddProcessedCmd( aCommand );
761 if ( !meshID.IsEmpty() &&
762 !myMeshes.count( meshID ) &&
763 aCommand->IsStudyEntry( meshID ))
765 _AString processedCommand = aCommand->GetString();
766 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
767 CheckObjectIsReCreated( mesh );
768 myMeshes.insert( make_pair( meshID, mesh ));
770 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
773 if ( !groups.IsEmpty() )
775 if ( !aCommand->IsStudyEntry( meshID ))
776 meshID = id_editor->second->GetMesh();
777 Handle(_pyMesh) mesh = myMeshes[ meshID ];
779 list< _pyID > idList = aCommand->GetStudyEntries( groups );
780 list< _pyID >::iterator grID = idList.begin();
781 for ( ; grID != idList.end(); ++grID )
782 if ( !myObjects.count( *grID ))
784 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
786 if ( !mesh.IsNull() ) mesh->AddGroup( group );
790 } // SMESH_MeshEditor methods
792 // SMESH_Hypothesis method?
793 Handle(_pyHypothesis) hyp = FindHyp( objID );
794 if ( !hyp.IsNull() && !hyp->IsAlgo() )
796 hyp->Process( aCommand );
797 hyp->AddProcessedCmd( aCommand );
801 // aFilterManager.CreateFilter() ?
802 if ( aCommand->GetMethod() == "CreateFilter" )
804 // Set a more human readable name to a filter
805 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
806 _pyID newID, filterID = aCommand->GetResultValue();
807 int pos = filterID.Search( "0x" );
809 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
811 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
814 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
815 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
817 // create _pySelfEraser for functors
818 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
819 functor->IgnoreOwnCalls(); // to erase if not used as an argument
820 AddObject( functor );
823 // other object method?
824 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
825 if ( id_obj != myObjects.end() ) {
826 id_obj->second->Process( aCommand );
827 id_obj->second->AddProcessedCmd( aCommand );
831 // Add access to a wrapped mesh
832 AddMeshAccessorMethod( aCommand );
834 // Add access to a wrapped algorithm
835 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
837 // PAL12227. PythonDump was not updated at proper time; result is
838 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
839 // TypeError: __init__() takes exactly 11 arguments (10 given)
840 const char wrongCommand[] = "SMESH.Filter.Criterion(";
841 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
843 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
844 // there must be 10 arguments, 5-th arg ThresholdID is missing,
845 const int wrongNbArgs = 9, missingArg = 5;
846 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
848 for ( int i = wrongNbArgs; i > missingArg; --i )
849 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
850 tmpCmd.SetArg( missingArg, "''");
851 aCommand->GetString().Trunc( beg - 1 );
852 aCommand->GetString() += tmpCmd.GetString();
855 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
857 // instead of "SMESH.Filter.Criterion(
858 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
859 // 1 2 3 4 5 6 7 8 9 10
860 // in order to avoid the problem of type mismatch of long and FunctorType
861 const TCollection_AsciiString
862 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
863 TCollection_AsciiString
864 Type = aCommand->GetArg(1), // long
865 Compare = aCommand->GetArg(2), // long
866 Threshold = aCommand->GetArg(3), // double
867 ThresholdStr = aCommand->GetArg(4), // string
868 ThresholdID = aCommand->GetArg(5), // string
869 UnaryOp = aCommand->GetArg(6), // long
870 BinaryOp = aCommand->GetArg(7), // long
871 Tolerance = aCommand->GetArg(8), // double
872 TypeOfElement = aCommand->GetArg(9), // ElementType
873 Precision = aCommand->GetArg(10); // long
874 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
875 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
876 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
877 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
878 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
880 if ( Compare == "SMESH.FT_EqualTo" )
883 aCommand->RemoveArgs();
884 aCommand->SetObject( SMESH_2smeshpy::GenName() );
885 aCommand->SetMethod( "GetCriterion" );
887 aCommand->SetArg( 1, TypeOfElement );
888 aCommand->SetArg( 2, Type );
889 aCommand->SetArg( 3, Compare );
891 if ( Threshold.IsIntegerValue() )
893 int iGeom = Threshold.IntegerValue();
894 if ( Type == "SMESH.FT_ElemGeomType" )
896 // set SMESH.GeometryType instead of a numerical Threshold
897 const int nbTypes = SMESH::Geom_LAST;
898 const char* types[] = {
899 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
900 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
901 "Geom_POLYHEDRA", "Geom_BALL" };
902 if ( -1 < iGeom && iGeom < nbTypes )
903 Threshold = SMESH + types[ iGeom ];
905 // is types complete? (compilation failure mains that enum GeometryType changed)
906 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
909 if (Type == "SMESH.FT_EntityType")
911 // set SMESH.EntityType instead of a numerical Threshold
912 const int nbTypes = SMESH::Entity_Last;
913 const char* types[] = {
914 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
915 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
916 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
917 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
918 "Entity_Pyramid", "Entity_Quad_Pyramid",
919 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
920 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
921 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
922 if ( -1 < iGeom && iGeom < nbTypes )
923 Threshold = SMESH + types[ iGeom ];
925 // is 'types' complete? (compilation failure mains that enum EntityType changed)
926 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
930 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
931 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
932 else if ( ThresholdStr.Length() != 2 )
933 aCommand->SetArg( 4, ThresholdStr );
934 else if ( ThresholdID.Length() != 2 )
935 aCommand->SetArg( 4, ThresholdID );
937 aCommand->SetArg( 4, Threshold );
938 // find the last not default arg
940 if ( Tolerance == dfltTol ) {
942 if ( BinaryOp == dfltFunctor ) {
944 if ( UnaryOp == dfltFunctor )
948 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
949 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
950 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
951 if ( Precision != dfltPreci )
953 TCollection_AsciiString crit = aCommand->GetResultValue();
954 aCommand->GetString() += "; ";
955 aCommand->GetString() += crit + ".Precision = " + Precision;
961 //================================================================================
963 * \brief Convert the command or remember it for later conversion
964 * \param theCommand - The python command calling a method of SMESH_Gen
966 //================================================================================
968 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
970 // there are methods to convert:
971 // CreateMesh( shape )
972 // Concatenate( [mesh1, ...], ... )
973 // CreateHypothesis( theHypType, theLibName )
974 // Compute( mesh, geom )
975 // Evaluate( mesh, geom )
977 TCollection_AsciiString method = theCommand->GetMethod();
979 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
981 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
985 if ( method == "CreateMeshesFromUNV" ||
986 method == "CreateMeshesFromSTL" ||
987 method == "CopyMesh" ) // command result is a mesh
989 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
993 if( method == "CreateMeshesFromMED" ||
994 method == "CreateMeshesFromSAUV"||
995 method == "CreateMeshesFromCGNS" ||
996 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
998 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
999 std::list< _pyID >::iterator meshID = meshIDs.begin();
1000 for ( ; meshID != meshIDs.end(); ++meshID )
1002 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1005 if ( method == "CreateMeshesFromGMF" )
1007 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1008 // CreateMeshesFromGMF( theFileName )
1009 _AString file = theCommand->GetArg(1);
1010 theCommand->RemoveArgs();
1011 theCommand->SetArg( 1, file );
1015 // CreateHypothesis()
1016 if ( method == "CreateHypothesis" )
1018 // issue 199929, remove standard library name (default parameter)
1019 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1020 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1021 // keep the first argument
1022 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1023 theCommand->RemoveArgs();
1024 theCommand->SetArg( 1, arg );
1027 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1028 CheckObjectIsReCreated( hyp );
1029 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1034 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1035 if ( method == "Compute" )
1037 const _pyID& meshID = theCommand->GetArg( 1 );
1038 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1039 if ( id_mesh != myMeshes.end() ) {
1040 theCommand->SetObject( meshID );
1041 theCommand->RemoveArgs();
1042 id_mesh->second->Process( theCommand );
1043 id_mesh->second->AddProcessedCmd( theCommand );
1048 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1049 if ( method == "Evaluate" )
1051 const _pyID& meshID = theCommand->GetArg( 1 );
1052 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1053 if ( id_mesh != myMeshes.end() ) {
1054 theCommand->SetObject( meshID );
1055 _pyID geom = theCommand->GetArg( 2 );
1056 theCommand->RemoveArgs();
1057 theCommand->SetArg( 1, geom );
1058 id_mesh->second->AddProcessedCmd( theCommand );
1063 // objects erasing creation command if no more its commands invoked:
1064 // SMESH_Pattern, FilterManager
1065 if ( method == "GetPattern" ||
1066 method == "CreateFilterManager" ||
1067 method == "CreateMeasurements" )
1069 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1070 if ( !AddObject( obj ) )
1071 theCommand->Clear(); // already created
1073 // Concatenate( [mesh1, ...], ... )
1074 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1076 if ( method == "ConcatenateWithGroups" ) {
1077 theCommand->SetMethod( "Concatenate" );
1078 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1080 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1082 AddMeshAccessorMethod( theCommand );
1084 else if ( method == "SetName" ) // SetName(obj,name)
1086 // store theCommand as one of object commands to erase it along with the object
1087 const _pyID& objID = theCommand->GetArg( 1 );
1088 Handle(_pyObject) obj = FindObject( objID );
1089 if ( !obj.IsNull() )
1090 obj->AddProcessedCmd( theCommand );
1093 // Replace name of SMESH_Gen
1095 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1096 static TStringSet smeshpyMethods;
1097 if ( smeshpyMethods.empty() ) {
1098 const char * names[] =
1099 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1100 "GetPattern","GetSubShapesId",
1101 "" }; // <- mark of array end
1102 smeshpyMethods.Insert( names );
1104 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1105 // smeshgen.Method() --> smesh.Method()
1106 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1108 // smeshgen.Method() --> smesh.Method()
1109 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1112 //================================================================================
1114 * \brief Convert the remembered commands
1116 //================================================================================
1118 void _pyGen::Flush()
1120 // create an empty command
1121 myLastCommand = new _pyCommand();
1123 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1124 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1125 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1127 if ( IsToKeepAllCommands() ) // historical dump
1129 // set myIsPublished = true to all objects
1130 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1131 id_mesh->second->SetRemovedFromStudy( false );
1132 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1133 id_hyp->second->SetRemovedFromStudy( false );
1134 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1135 id_obj->second->SetRemovedFromStudy( false );
1139 // let hypotheses find referred objects in order to prevent clearing
1140 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1141 list< Handle(_pyMesh) > fatherMeshes;
1142 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1143 if ( !id_hyp->second.IsNull() )
1144 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1146 // set myIsPublished = false to all objects depending on
1147 // meshes built on a removed geometry
1148 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1149 if ( id_mesh->second->IsNotGeomPublished() )
1150 id_mesh->second->SetRemovedFromStudy( true );
1153 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1154 if ( ! id_mesh->second.IsNull() )
1155 id_mesh->second->Flush();
1158 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1159 if ( !id_hyp->second.IsNull() ) {
1160 id_hyp->second->Flush();
1161 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1162 if ( !id_hyp->second->IsWrapped() )
1163 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1166 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1167 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1168 for ( ; robj != myOrderedObjects.rend(); ++robj )
1169 if ( ! robj->IsNull() )
1171 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1172 for ( ; obj != myOrderedObjects.end(); ++obj )
1173 if ( ! obj->IsNull() )
1176 myLastCommand->SetOrderNb( ++myNbCommands );
1177 myCommands.push_back( myLastCommand );
1180 //================================================================================
1182 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1183 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1185 //================================================================================
1187 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1189 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1190 // for ( ; id_obj != myObjects.end(); ++id_obj )
1192 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1193 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1195 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1196 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1198 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1199 // list< _pyID >::iterator id = idList.begin();
1200 // for ( ; id != idList.end(); ++id )
1201 // if ( id_obj->first == *id )
1202 // // _pySubMesh::Process() does what we need
1203 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1208 //================================================================================
1210 * \brief Clean commmands of removed objects depending on myIsPublished flag
1212 //================================================================================
1214 void _pyGen::ClearCommands()
1216 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1217 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1218 id_mesh->second->ClearCommands();
1220 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1221 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1222 if ( !id_hyp->second.IsNull() )
1223 id_hyp->second->ClearCommands();
1225 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1226 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1227 for ( ; robj != myOrderedObjects.rend(); ++robj )
1228 if ( ! robj->IsNull() )
1229 (*robj)->ClearCommands();
1230 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1231 for ( ; obj != myOrderedObjects.end(); ++obj )
1232 if ( ! obj->IsNull() )
1233 (*obj)->ClearCommands();
1236 //================================================================================
1238 * \brief Release mutual handles of objects
1240 //================================================================================
1244 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1245 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1246 id_mesh->second->Free();
1249 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1250 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1251 id_ed->second->Free();
1252 myMeshEditors.clear();
1254 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1255 for ( ; id_obj != myObjects.end(); ++id_obj )
1256 id_obj->second->Free();
1259 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1260 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1261 if ( !id_hyp->second.IsNull() )
1262 id_hyp->second->Free();
1265 myFile2ExportedMesh.clear();
1267 //myKeepAgrCmdsIDs.Print();
1270 //================================================================================
1272 * \brief Add access method to mesh that is an argument
1273 * \param theCmd - command to add access method
1274 * \retval bool - true if added
1276 //================================================================================
1278 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1281 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1282 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1283 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1289 //================================================================================
1291 * \brief Add access method to algo that is an object or an argument
1292 * \param theCmd - command to add access method
1293 * \retval bool - true if added
1295 //================================================================================
1297 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1300 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1301 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1302 if ( !id_hyp->second.IsNull() &&
1303 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1304 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1305 id_hyp->second->AccessorMethod() ))
1311 //================================================================================
1313 * \brief Find hypothesis by ID (entry)
1314 * \param theHypID - The hypothesis ID
1315 * \retval Handle(_pyHypothesis) - The found hypothesis
1317 //================================================================================
1319 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1321 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1322 if ( id_hyp != myHypos.end() &&
1323 !id_hyp->second.IsNull() &&
1324 theHypID == id_hyp->second->GetID() )
1325 return id_hyp->second;
1326 return Handle(_pyHypothesis)();
1329 //================================================================================
1331 * \brief Find algorithm able to create a hypothesis
1332 * \param theGeom - The shape ID the algorithm was created on
1333 * \param theMesh - The mesh ID that created the algorithm
1334 * \param theHypothesis - The hypothesis the algorithm should be able to create
1335 * \retval Handle(_pyHypothesis) - The found algo
1337 //================================================================================
1339 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1340 const Handle(_pyHypothesis)& theHypothesis )
1342 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1343 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1344 if ( !id_hyp->second.IsNull() &&
1345 id_hyp->second->IsAlgo() &&
1346 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1347 id_hyp->second->GetGeom() == theGeom &&
1348 id_hyp->second->GetMesh() == theMesh )
1349 return id_hyp->second;
1350 return Handle(_pyHypothesis)();
1353 //================================================================================
1355 * \brief Find subMesh by ID (entry)
1356 * \param theSubMeshID - The subMesh ID
1357 * \retval Handle(_pySubMesh) - The found subMesh
1359 //================================================================================
1361 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1363 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1364 if ( id_subMesh != myObjects.end() )
1365 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1366 return Handle(_pySubMesh)();
1370 //================================================================================
1372 * \brief Change order of commands in the script
1373 * \param theCmd1 - One command
1374 * \param theCmd2 - Another command
1376 //================================================================================
1378 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1380 list< Handle(_pyCommand) >::iterator pos1, pos2;
1381 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1382 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1383 myCommands.insert( pos1, theCmd2 );
1384 myCommands.insert( pos2, theCmd1 );
1385 myCommands.erase( pos1 );
1386 myCommands.erase( pos2 );
1388 int nb1 = theCmd1->GetOrderNb();
1389 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1390 theCmd2->SetOrderNb( nb1 );
1391 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1392 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1395 //================================================================================
1397 * \brief Set one command after the other
1398 * \param theCmd - Command to move
1399 * \param theAfterCmd - Command ater which to insert the first one
1401 //================================================================================
1403 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1405 setNeighbourCommand( theCmd, theAfterCmd, true );
1408 //================================================================================
1410 * \brief Set one command before the other
1411 * \param theCmd - Command to move
1412 * \param theBeforeCmd - Command before which to insert the first one
1414 //================================================================================
1416 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1418 setNeighbourCommand( theCmd, theBeforeCmd, false );
1421 //================================================================================
1423 * \brief Set one command before or after the other
1424 * \param theCmd - Command to move
1425 * \param theOtherCmd - Command ater or before which to insert the first one
1427 //================================================================================
1429 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1430 Handle(_pyCommand)& theOtherCmd,
1431 const bool theIsAfter )
1433 list< Handle(_pyCommand) >::iterator pos;
1434 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1435 myCommands.erase( pos );
1436 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1437 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1440 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1441 (*pos)->SetOrderNb( i++ );
1444 //================================================================================
1446 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1448 //================================================================================
1450 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1452 // No more needed after adding _pyObject::myArgCommands
1454 // const char filterPrefix[] = "aFilter0x";
1455 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1458 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1460 // const _AString & arg = theCommand->GetArg( i );
1461 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1462 // if ( arg.Search( filterPrefix ) != 1 )
1465 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1466 // if ( !filter.IsNull() )
1468 // filter->AddUser( user );
1469 // if ( !filter->GetNewID().IsEmpty() )
1470 // theCommand->SetArg( i, filter->GetNewID() );
1475 //================================================================================
1477 * \brief Set command be last in list of commands
1478 * \param theCmd - Command to be last
1480 //================================================================================
1482 Handle(_pyCommand)& _pyGen::GetLastCommand()
1484 return myLastCommand;
1487 //================================================================================
1489 * \brief Set method to access to object wrapped with python class
1490 * \param theID - The wrapped object entry
1491 * \param theMethod - The accessor method
1493 //================================================================================
1495 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1497 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1500 //================================================================================
1502 * \brief Generated new ID for object and assign with existing name
1503 * \param theID - ID of existing object
1505 //================================================================================
1507 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1512 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1514 while ( myObjectNames.IsBound( aNewID ) );
1516 if ( myObjectNames.IsBound( theID ) )
1517 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1519 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1523 //================================================================================
1525 * \brief Stores theObj in myObjects
1527 //================================================================================
1529 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1531 if ( theObj.IsNull() ) return false;
1533 CheckObjectIsReCreated( theObj );
1537 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1538 add = myMeshes.insert( make_pair( theObj->GetID(),
1539 Handle(_pyMesh)::DownCast( theObj ))).second;
1541 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1542 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1543 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1546 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1547 if ( add ) myOrderedObjects.push_back( theObj );
1552 //================================================================================
1554 * \brief Erases an existing object with the same ID. This method should be called
1555 * before storing theObj in _pyGen
1557 //================================================================================
1559 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1561 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1564 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1565 Handle(_pyObject) existing;
1567 existing = FindHyp( theObj->GetID() );
1569 existing = FindObject( theObj->GetID() );
1570 if ( !existing.IsNull() && existing != theObj )
1572 existing->SetRemovedFromStudy( true );
1573 existing->ClearCommands();
1576 if ( myHypos.count( theObj->GetID() ))
1577 myHypos.erase( theObj->GetID() );
1579 else if ( myMeshes.count( theObj->GetID() ))
1581 myMeshes.erase( theObj->GetID() );
1583 else if ( myObjects.count( theObj->GetID() ))
1585 myObjects.erase( theObj->GetID() );
1590 //================================================================================
1592 * \brief Re-register an object with other ID to make it Process() commands of
1593 * other object having this ID
1595 //================================================================================
1597 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1599 if ( theObj.IsNull() ) return;
1601 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1602 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1604 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1605 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1608 myObjects.insert( make_pair( theID, theObj ));
1611 //================================================================================
1613 * \brief Finds a _pyObject by ID
1615 //================================================================================
1617 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1620 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1621 if ( id_obj != myObjects.end() )
1622 return id_obj->second;
1625 _pyGen* me = const_cast< _pyGen* >( this );
1626 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1627 if ( id_obj != myMeshes.end() )
1628 return id_obj->second;
1631 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1632 // if ( id_obj != myMeshEditors.end() )
1633 // return id_obj->second;
1635 return Handle(_pyObject)();
1638 //================================================================================
1640 * \brief Check if a study entry is under GEOM component
1642 //================================================================================
1644 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1648 return ( myGeomIDIndex <= theObjID.Length() &&
1649 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1650 _pyCommand::IsStudyEntry( theObjID ));
1655 //================================================================================
1657 * \brief Returns true if an object is not present in a study
1659 //================================================================================
1661 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1663 if ( theObjID.IsEmpty() ) return false;
1665 if ( myObjectNames.IsBound( theObjID ))
1666 return false; // SMESH object is in study
1668 // either the SMESH object is not in study or it is a GEOM object
1669 if ( IsGeomObject( theObjID ))
1671 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1672 if ( so->_is_nil() ) return true;
1673 CORBA::Object_var obj = so->GetObject();
1674 return CORBA::is_nil( obj );
1676 return true; // SMESH object not in study
1679 //================================================================================
1681 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1682 * this object is not dumped
1683 * \param [in] theObjID - entry of the object whose creation command was eliminated
1685 //================================================================================
1687 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1689 myRemovedObjIDs.insert( theObjID );
1692 //================================================================================
1694 * \brief Return reader of hypotheses of plugins
1696 //================================================================================
1698 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1700 if (myHypReader.IsNull() )
1701 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1707 //================================================================================
1709 * \brief Mesh created by SMESH_Gen
1711 //================================================================================
1713 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1714 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1716 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1717 myGeomNotInStudy = true;
1719 // convert my creation command --> smeshpy.Mesh(...)
1720 Handle(_pyCommand) creationCmd = GetCreationCmd();
1721 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1722 creationCmd->SetMethod( "Mesh" );
1723 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1726 //================================================================================
1728 * \brief Mesh created by SMESH_MeshEditor
1730 //================================================================================
1732 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1733 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1735 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1737 // this mesh depends on the exported mesh
1738 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1739 if ( !file.IsEmpty() )
1741 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1742 addFatherMesh( exportData.myMesh );
1743 if ( !exportData.myLastComputeCmd.IsNull() )
1745 // restore cleared Compute() by which the exported mesh was generated
1746 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1747 // protect that Compute() cmd from clearing
1748 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1749 exportData.myMesh->myLastComputeCmd.Nullify();
1753 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1755 // this mesh depends on concatenated meshes
1756 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1757 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1758 list< _pyID >::iterator meshID = idList.begin();
1759 for ( ; meshID != idList.end(); ++meshID )
1760 addFatherMesh( *meshID );
1762 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1764 // this mesh depends on a copied IdSource
1765 const _pyID& objID = theCreationCmd->GetArg( 1 );
1766 addFatherMesh( objID );
1768 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1769 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1770 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1772 // this mesh depends on a source mesh
1773 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1774 const _pyID& meshID = theCreationCmd->GetObject();
1775 addFatherMesh( meshID );
1778 // convert my creation command
1779 Handle(_pyCommand) creationCmd = GetCreationCmd();
1780 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1781 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1784 //================================================================================
1786 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1787 * \param theCommand - Engine method called for this mesh
1789 //================================================================================
1791 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1793 // some methods of SMESH_Mesh interface needs special conversion
1794 // to methods of Mesh python class
1796 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1797 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1798 // 2. AddHypothesis(geom, hyp)
1799 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1800 // 3. CreateGroupFromGEOM(type, name, grp)
1801 // --> in Mesh.Group(grp, name="")
1802 // 4. ExportToMED(f, auto_groups, version)
1803 // --> in Mesh.ExportMED( f, auto_groups, version )
1806 const TCollection_AsciiString& method = theCommand->GetMethod();
1807 // ----------------------------------------------------------------------
1808 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1810 if ( !theGen->IsToKeepAllCommands() ) // !historical
1812 list< Handle(_pyHypothesis) >::iterator hyp;
1813 if ( !myLastComputeCmd.IsNull() )
1815 // check if the previously computed mesh has been edited,
1816 // if so then we do not clear the previous Compute()
1817 bool toClear = true;
1818 if ( myLastComputeCmd->GetMethod() == "Compute" )
1820 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1821 for ( ; e != myEditors.end() && toClear; ++e )
1823 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1824 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1825 if ( cmd != cmds.rend() &&
1826 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1832 // clear hyp commands called before myLastComputeCmd
1833 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1834 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1836 myLastComputeCmd->Clear();
1839 myLastComputeCmd = theCommand;
1841 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1842 (*hyp)->MeshComputed( myLastComputeCmd );
1846 // ----------------------------------------------------------------------
1847 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1849 if ( !theGen->IsToKeepAllCommands() ) // !historical
1852 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1853 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1854 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1856 if ( !myLastComputeCmd.IsNull() )
1858 list< Handle(_pyHypothesis) >::iterator hyp;
1859 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1860 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1862 myLastComputeCmd->Clear();
1865 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1866 for ( ; e != myEditors.end(); ++e )
1868 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1869 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1870 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1871 if ( !(*cmd)->IsEmpty() )
1873 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1877 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1880 // ----------------------------------------------------------------------
1881 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1882 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1883 if ( !subMesh.IsNull() ) {
1884 subMesh->SetCreator( this );
1885 mySubmeshes.push_back( subMesh );
1888 // ----------------------------------------------------------------------
1889 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1890 theCommand->Clear();
1892 // ----------------------------------------------------------------------
1893 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1894 myAddHypCmds.push_back( theCommand );
1896 const _pyID& hypID = theCommand->GetArg( 2 );
1897 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1898 if ( !hyp.IsNull() ) {
1899 myHypos.push_back( hyp );
1900 if ( hyp->GetMesh().IsEmpty() )
1901 hyp->SetMesh( this->GetID() );
1904 // ----------------------------------------------------------------------
1905 else if ( method == "CreateGroup" ||
1906 method == "CreateGroupFromGEOM" ||
1907 method == "CreateGroupFromFilter" ||
1908 method == "CreateDimGroup" )
1910 Handle(_pyGroup) group = new _pyGroup( theCommand );
1911 myGroups.push_back( group );
1912 theGen->AddObject( group );
1914 // ----------------------------------------------------------------------
1915 // update list of groups
1916 else if ( method == "GetGroups" )
1918 bool allGroupsRemoved = true;
1919 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1920 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1921 list< _pyID >::iterator grID = idList.begin();
1922 const size_t nbGroupsBefore = myGroups.size();
1923 Handle(_pyObject) obj;
1924 for ( ; grID != idList.end(); ++grID )
1926 obj = theGen->FindObject( *grID );
1929 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1930 theGen->AddObject( group );
1931 myGroups.push_back( group );
1934 if ( !obj->CanClear() )
1935 allGroupsRemoved = false;
1937 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1938 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1940 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1942 // check if the preceding command is Compute();
1943 // if GetGroups() is just after Compute(), this can mean that the groups
1944 // were created by some algorithm and hence Compute() should not be discarded
1945 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1946 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1947 while ( (*cmd)->GetMethod() == "GetGroups" )
1949 if ( myLastComputeCmd == (*cmd))
1950 // protect last Compute() from clearing by the next Compute()
1951 myLastComputeCmd.Nullify();
1954 // ----------------------------------------------------------------------
1955 // notify a group about full removal
1956 else if ( method == "RemoveGroupWithContents" ||
1957 method == "RemoveGroup")
1959 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1960 const _pyID groupID = theCommand->GetArg( 1 );
1961 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1962 if ( !grp.IsNull() )
1964 if ( method == "RemoveGroupWithContents" )
1965 grp->RemovedWithContents();
1966 // to clear RemoveGroup() if the group creation is cleared
1967 grp->AddProcessedCmd( theCommand );
1971 // ----------------------------------------------------------------------
1972 else if ( theCommand->MethodStartsFrom( "Export" ))
1974 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1975 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1977 theCommand->SetMethod( "ExportMED" );
1978 if ( theCommand->GetNbArgs() == 5 )
1980 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1981 _AString autoDimension = theCommand->GetArg( 5 );
1982 theCommand->SetArg( 5, "None" );
1983 theCommand->SetArg( 6, autoDimension );
1986 else if ( method == "ExportCGNS" )
1987 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1988 _pyID partID = theCommand->GetArg( 1 );
1989 int nbArgs = theCommand->GetNbArgs();
1990 for ( int i = 2; i <= nbArgs; ++i )
1991 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1992 theCommand->SetArg( nbArgs, partID );
1994 else if ( method == "ExportGMF" )
1995 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1996 _pyID partID = theCommand->GetArg( 1 );
1997 _AString file = theCommand->GetArg( 2 );
1998 theCommand->RemoveArgs();
1999 theCommand->SetArg( 1, file );
2000 theCommand->SetArg( 2, partID );
2002 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2003 { // ExportPartTo*(part, ...) -> Export*(..., part)
2005 // remove "PartTo" from the method
2006 TCollection_AsciiString newMethod = method;
2007 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2008 theCommand->SetMethod( newMethod );
2009 // make the 1st arg be the last one (or last but three for ExportMED())
2010 _pyID partID = theCommand->GetArg( 1 );
2011 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2012 for ( int i = 2; i <= nbArgs; ++i )
2013 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2014 theCommand->SetArg( nbArgs, partID );
2016 // remember file name
2017 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2018 ExportedMeshData( this, myLastComputeCmd ));
2020 // ----------------------------------------------------------------------
2021 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2023 _pyID hypID = theCommand->GetArg( 2 );
2024 _pyID geomID = theCommand->GetArg( 1 );
2025 bool isLocal = ( geomID != GetGeom() );
2027 // check if this mesh still has corresponding addition command
2028 Handle(_pyCommand) addCmd;
2029 list< Handle(_pyCommand) >::iterator cmd;
2030 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2031 for ( int i = 0; i < 2; ++i )
2033 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2034 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2036 bool sameHyp = true;
2037 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2038 sameHyp = false; // other hyp
2039 if ( (*cmd)->GetNbArgs() == 2 &&
2040 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2041 sameHyp = false; // other geom
2042 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2043 sameHyp = false; // other geom
2047 cmd = addHypCmds.erase( cmd );
2048 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2050 theCommand->Clear();
2054 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2055 addCmd->RemoveArgs();
2056 addCmd->SetArg( 1, hypID );
2058 addCmd->SetArg( 2, geomID );
2067 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2068 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2069 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2070 _pyID geom = theCommand->GetArg( 1 );
2071 theCommand->RemoveArgs();
2072 theCommand->SetArg( 1, hypID );
2073 if ( geom != GetGeom() )
2074 theCommand->SetArg( 2, geom );
2076 // remove hyp from myHypos
2077 myHypos.remove( hyp );
2079 // check for SubMesh order commands
2080 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2082 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2083 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2084 // commands are moved at the end of the script
2085 TCollection_AsciiString subIDs =
2086 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2087 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2088 list< _pyID >::iterator subID = idList.begin();
2089 for ( ; subID != idList.end(); ++subID )
2091 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2092 if ( !subMesh.IsNull() )
2093 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2096 // add accessor method if necessary
2099 if ( NeedMeshAccess( theCommand ))
2100 // apply theCommand to the mesh wrapped by smeshpy mesh
2101 AddMeshAccess( theCommand );
2105 //================================================================================
2107 * \brief Return True if addition of accesor method is needed
2109 //================================================================================
2111 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2113 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2114 // so no conversion is needed for them at all:
2115 static TStringSet sameMethods;
2116 if ( sameMethods.empty() ) {
2117 const char * names[] =
2118 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2119 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2120 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2121 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2122 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2123 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2124 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2125 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2126 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2127 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2128 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2129 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2130 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2131 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2132 ,"" }; // <- mark of end
2133 sameMethods.Insert( names );
2136 return !sameMethods.Contains( theCommand->GetMethod() );
2139 //================================================================================
2141 * \brief Convert creation and addition of all algos and hypos
2143 //================================================================================
2145 void _pyMesh::Flush()
2148 // get the meshes this mesh depends on via hypotheses
2149 list< Handle(_pyMesh) > fatherMeshes;
2150 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2151 for ( ; hyp != myHypos.end(); ++hyp )
2152 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2153 myGeomNotInStudy = true;
2155 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2156 for ( ; m != fatherMeshes.end(); ++m )
2157 addFatherMesh( *m );
2158 // if ( removedGeom )
2159 // SetRemovedFromStudy(); // as referred geometry not in study
2161 if ( myGeomNotInStudy )
2164 list < Handle(_pyCommand) >::iterator cmd;
2166 // try to convert algo addition like this:
2167 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2168 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2170 Handle(_pyCommand) addCmd = *cmd;
2172 _pyID algoID = addCmd->GetArg( 2 );
2173 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2174 if ( algo.IsNull() || !algo->IsAlgo() )
2177 // check and create new algorithm instance if it is already wrapped
2178 if ( algo->IsWrapped() ) {
2179 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2180 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2181 TCollection_AsciiString( " = " ) + theGen->GetID() +
2182 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2183 TCollection_AsciiString( "\" )" );
2185 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2186 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2187 if ( !newAlgo.IsNull() ) {
2188 newAlgo->Assign( algo, this->GetID() );
2189 newAlgo->SetCreationCmd( newCmd );
2191 // set algorithm creation
2192 theGen->SetCommandBefore( newCmd, addCmd );
2193 myHypos.push_back( newAlgo );
2194 if ( !myLastComputeCmd.IsNull() &&
2195 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2196 newAlgo->MeshComputed( myLastComputeCmd );
2201 _pyID geom = addCmd->GetArg( 1 );
2202 bool isLocalAlgo = ( geom != GetGeom() );
2205 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2207 // wrapped algo is created after mesh creation
2208 GetCreationCmd()->AddDependantCmd( addCmd );
2210 if ( isLocalAlgo ) {
2211 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2212 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2213 TCollection_AsciiString( "geom=" ) + geom );
2214 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2215 list < Handle(_pySubMesh) >::iterator smIt;
2216 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2217 Handle(_pySubMesh) subMesh = *smIt;
2218 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2219 if ( geom == subCmd->GetArg( 1 )) {
2220 subCmd->SetObject( algo->GetID() );
2221 subCmd->RemoveArgs();
2222 subMesh->SetCreator( algo );
2227 else // KO - ALGO was already created
2229 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2230 addCmd->RemoveArgs();
2231 addCmd->SetArg( 1, algoID );
2233 addCmd->SetArg( 2, geom );
2234 myNotConvertedAddHypCmds.push_back( addCmd );
2238 // try to convert hypo addition like this:
2239 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2240 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2242 Handle(_pyCommand) addCmd = *cmd;
2243 _pyID hypID = addCmd->GetArg( 2 );
2244 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2245 if ( hyp.IsNull() || hyp->IsAlgo() )
2247 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2249 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2250 _pyID geom = addCmd->GetArg( 1 );
2251 addCmd->RemoveArgs();
2252 addCmd->SetArg( 1, hypID );
2253 if ( geom != GetGeom() )
2254 addCmd->SetArg( 2, geom );
2255 myNotConvertedAddHypCmds.push_back( addCmd );
2259 myAddHypCmds.clear();
2260 mySubmeshes.clear();
2263 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2264 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2268 //================================================================================
2270 * \brief Sets myIsPublished of me and of all objects depending on me.
2272 //================================================================================
2274 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2276 _pyObject::SetRemovedFromStudy(isRemoved);
2278 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2279 for ( ; sm != mySubmeshes.end(); ++sm )
2280 (*sm)->SetRemovedFromStudy(isRemoved);
2282 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2283 for ( ; gr != myGroups.end(); ++gr )
2284 (*gr)->SetRemovedFromStudy(isRemoved);
2286 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2287 for ( ; m != myChildMeshes.end(); ++m )
2288 (*m)->SetRemovedFromStudy(isRemoved);
2290 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2291 for ( ; e != myEditors.end(); ++e )
2292 (*e)->SetRemovedFromStudy(isRemoved);
2295 //================================================================================
2297 * \brief Return true if none of myChildMeshes is in study
2299 //================================================================================
2301 bool _pyMesh::CanClear()
2306 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2307 for ( ; m != myChildMeshes.end(); ++m )
2308 if ( !(*m)->CanClear() )
2314 //================================================================================
2316 * \brief Clear my commands and commands of mesh editor
2318 //================================================================================
2320 void _pyMesh::ClearCommands()
2326 // mark all sub-objects as not removed, except child meshes
2327 list< Handle(_pyMesh) > children;
2328 children.swap( myChildMeshes );
2329 SetRemovedFromStudy( false );
2330 children.swap( myChildMeshes );
2334 _pyObject::ClearCommands();
2336 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2337 for ( ; sm != mySubmeshes.end(); ++sm )
2338 (*sm)->ClearCommands();
2340 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2341 for ( ; gr != myGroups.end(); ++gr )
2342 (*gr)->ClearCommands();
2344 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2345 for ( ; e != myEditors.end(); ++e )
2346 (*e)->ClearCommands();
2349 //================================================================================
2351 * \brief Add a father mesh by ID
2353 //================================================================================
2355 void _pyMesh::addFatherMesh( const _pyID& meshID )
2357 if ( !meshID.IsEmpty() && meshID != GetID() )
2358 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2361 //================================================================================
2363 * \brief Add a father mesh
2365 //================================================================================
2367 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2369 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2371 //myFatherMeshes.push_back( mesh );
2372 mesh->myChildMeshes.push_back( this );
2374 // protect last Compute() from clearing by the next Compute()
2375 mesh->myLastComputeCmd.Nullify();
2379 //================================================================================
2381 * \brief MeshEditor convert its commands to ones of mesh
2383 //================================================================================
2385 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2386 _pyObject( theCreationCmd )
2388 myMesh = theCreationCmd->GetObject();
2389 myCreationCmdStr = theCreationCmd->GetString();
2390 theCreationCmd->Clear();
2392 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2393 if ( !mesh.IsNull() )
2394 mesh->AddEditor( this );
2397 //================================================================================
2399 * \brief convert its commands to ones of mesh
2401 //================================================================================
2403 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2405 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2406 // commands calling these methods are converted to calls of Mesh methods without
2407 // additional modifs, only object is changed from MeshEditor to Mesh.
2408 static TStringSet sameMethods;
2409 if ( sameMethods.empty() ) {
2410 const char * names[] = {
2411 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2412 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2413 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2414 "MoveNode", "MoveClosestNodeToPoint",
2415 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2416 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2417 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2418 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2419 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2420 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2421 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2422 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2423 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2424 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2425 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2426 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2427 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2428 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2429 "GetLastCreatedElems",
2430 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2431 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2432 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2433 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2434 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2435 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2436 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2437 ,"" }; // <- mark of the end
2438 sameMethods.Insert( names );
2441 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2442 TStringMap diffMethods;
2443 if ( diffMethods.empty() ) {
2444 const char * orig2newName[] = {
2445 // original name --------------> new name
2446 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2447 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2448 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2449 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2450 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2451 ""};// <- mark of the end
2452 diffMethods.Insert( orig2newName );
2455 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2456 // only by last two arguments
2457 static TStringSet diffLastTwoArgsMethods;
2458 if (diffLastTwoArgsMethods.empty() ) {
2459 const char * names[] = {
2460 "MirrorMakeGroups","MirrorObjectMakeGroups",
2461 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2462 "RotateMakeGroups","RotateObjectMakeGroups",
2463 ""};// <- mark of the end
2464 diffLastTwoArgsMethods.Insert( names );
2467 // only a method name is to change?
2468 const TCollection_AsciiString & method = theCommand->GetMethod();
2469 bool isPyMeshMethod = sameMethods.Contains( method );
2470 if ( !isPyMeshMethod )
2472 TCollection_AsciiString newMethod = diffMethods.Value( method );
2473 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2474 theCommand->SetMethod( newMethod );
2476 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2477 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2479 isPyMeshMethod = true;
2480 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2481 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2484 if ( !isPyMeshMethod )
2486 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2487 // functions with the flag "theMakeGroups = True" like:
2488 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2489 int pos = method.Search("MakeGroups");
2492 isPyMeshMethod = true;
2493 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2494 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2496 // 1. Remove "MakeGroups" from the Command
2497 TCollection_AsciiString aMethod = theCommand->GetMethod();
2498 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2501 pos = pos-2; //Remove "0D" from the Command too
2502 aMethod.Trunc(pos-1);
2503 theCommand->SetMethod(aMethod);
2505 // 2. And add last "True" argument(s)
2506 while(nbArgsToAdd--)
2507 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2508 if( is0DmethId || is0DmethObj )
2509 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2513 // ExtrusionSweep0D() -> ExtrusionSweep()
2514 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2515 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2516 method == "ExtrusionSweepObject0D" ))
2518 isPyMeshMethod = true;
2519 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2520 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2521 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2524 // DoubleNode...New(...) -> DoubleNode...(...,True)
2525 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2526 method == "DoubleNodeElemGroupsNew" ||
2527 method == "DoubleNodeGroupNew" ||
2528 method == "DoubleNodeGroupsNew" ||
2529 method == "DoubleNodeElemGroup2New" ||
2530 method == "DoubleNodeElemGroups2New"))
2532 isPyMeshMethod = true;
2533 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2534 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2535 if ( excessLen == 3 )
2537 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2539 else if ( theCommand->GetArg(4) == "0" ||
2540 theCommand->GetArg(5) == "0" )
2542 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2543 // Group = DoubleNodeGroup2New(,,,False, True)
2544 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2545 theCommand->SetResultValue( groupID );
2548 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2549 // FindElementsByPoint(x, y, z, elementType, meshPart)
2550 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2552 isPyMeshMethod = true;
2553 theCommand->SetMethod( "FindElementsByPoint" );
2554 // make the 1st arg be the last one
2555 _pyID partID = theCommand->GetArg( 1 );
2556 int nbArgs = theCommand->GetNbArgs();
2557 for ( int i = 2; i <= nbArgs; ++i )
2558 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2559 theCommand->SetArg( nbArgs, partID );
2561 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2562 if ( !isPyMeshMethod && method == "Reorient2D" )
2564 isPyMeshMethod = true;
2565 _AString mesh = theCommand->GetArg( 1 );
2566 _AString dir = theCommand->GetArg( 2 );
2567 _AString face = theCommand->GetArg( 3 );
2568 _AString point = theCommand->GetArg( 4 );
2569 theCommand->RemoveArgs();
2570 theCommand->SetArg( 1, mesh );
2571 theCommand->SetArg( 2, dir );
2572 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2573 theCommand->SetArg( 3, point );
2575 theCommand->SetArg( 3, face );
2578 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2580 isPyMeshMethod = true;
2581 int crit_arg = theCommand->GetNbArgs();
2582 const _AString& crit = theCommand->GetArg(crit_arg);
2583 if (crit.Search("MaxElementLength2D") != -1)
2584 theCommand->SetArg(crit_arg, "");
2587 if ( isPyMeshMethod )
2589 theCommand->SetObject( myMesh );
2593 // editor creation command is needed only if any editor function is called
2594 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2595 if ( !myCreationCmdStr.IsEmpty() ) {
2596 GetCreationCmd()->GetString() = myCreationCmdStr;
2597 myCreationCmdStr.Clear();
2602 //================================================================================
2604 * \brief Return true if my mesh can be removed
2606 //================================================================================
2608 bool _pyMeshEditor::CanClear()
2610 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2611 return mesh.IsNull() ? true : mesh->CanClear();
2614 //================================================================================
2616 * \brief _pyHypothesis constructor
2617 * \param theCreationCmd -
2619 //================================================================================
2621 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2622 _pyObject( theCreationCmd ), myCurCrMethod(0)
2624 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2627 //================================================================================
2629 * \brief Creates algorithm or hypothesis
2630 * \param theCreationCmd - The engine command creating a hypothesis
2631 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2633 //================================================================================
2635 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2637 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2638 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2640 Handle(_pyHypothesis) hyp, algo;
2643 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2644 if ( hypTypeQuoted.IsEmpty() )
2647 TCollection_AsciiString hypType =
2648 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2650 algo = new _pyAlgorithm( theCreationCmd );
2651 hyp = new _pyHypothesis( theCreationCmd );
2653 if ( hypType == "NumberOfSegments" ) {
2654 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2655 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2656 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2657 hyp->AddArgMethod( "SetNumberOfSegments" );
2658 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2659 hyp->AddArgMethod( "SetScaleFactor" );
2660 hyp->AddArgMethod( "SetReversedEdges" );
2661 // same for ""CompositeSegment_1D:
2662 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2663 hyp->AddArgMethod( "SetNumberOfSegments" );
2664 hyp->AddArgMethod( "SetScaleFactor" );
2665 hyp->AddArgMethod( "SetReversedEdges" );
2667 else if ( hypType == "SegmentLengthAroundVertex" ) {
2668 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2669 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2670 hyp->AddArgMethod( "SetLength" );
2671 // same for ""CompositeSegment_1D:
2672 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2673 hyp->AddArgMethod( "SetLength" );
2675 else if ( hypType == "LayerDistribution2D" ) {
2676 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2677 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2679 else if ( hypType == "LayerDistribution" ) {
2680 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2681 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2683 else if ( hypType == "CartesianParameters3D" ) {
2684 hyp = new _pyComplexParamHypo( theCreationCmd );
2685 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2686 for ( int iArg = 0; iArg < 4; ++iArg )
2687 hyp->setCreationArg( iArg+1, "[]");
2688 hyp->AddAccumulativeMethod( "SetGrid" );
2689 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2693 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2696 return algo->IsValid() ? algo : hyp;
2699 //================================================================================
2701 * \brief Returns true if addition of this hypothesis to a given mesh can be
2702 * wrapped into hypothesis creation
2704 //================================================================================
2706 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2708 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2710 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2711 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2717 //================================================================================
2719 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2720 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2721 * \param theAlgo - The algo that can create this hypo
2722 * \retval bool - false if the command can't be converted
2724 //================================================================================
2726 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2727 const _pyID& theMesh)
2729 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2731 if ( !IsWrappable( theMesh ))
2734 myGeom = theCmd->GetArg( 1 );
2736 Handle(_pyHypothesis) algo;
2738 // find algo created on myGeom in theMesh
2739 algo = theGen->FindAlgo( myGeom, theMesh, this );
2740 if ( algo.IsNull() )
2742 // attach hypothesis creation command to be after algo creation command
2743 // because it can be new created instance of algorithm
2744 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2748 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2749 theCmd->SetResultValue( GetID() );
2750 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2751 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2752 // set args (geom will be set by _pyMesh calling this method)
2753 theCmd->RemoveArgs();
2754 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2755 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2756 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2758 theCmd->SetArg( i+1, "[]");
2760 // set a new creation command
2761 GetCreationCmd()->Clear();
2762 // replace creation command by wrapped instance
2763 // please note, that hypothesis attaches to algo creation command (see upper)
2764 SetCreationCmd( theCmd );
2767 // clear commands setting arg values
2768 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2769 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2772 // set unknown arg commands after hypo creation
2773 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2774 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2775 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2776 afterCmd->AddDependantCmd( *cmd );
2782 //================================================================================
2784 * \brief Remember hypothesis parameter values
2785 * \param theCommand - The called hypothesis method
2787 //================================================================================
2789 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2791 ASSERT( !myIsAlgo );
2792 if ( !theGen->IsToKeepAllCommands() )
2793 rememberCmdOfParameter( theCommand );
2795 bool usedCommand = false;
2796 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2797 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2799 CreationMethod& crMethod = type2meth->second;
2800 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2801 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2803 myArgCommands.push_back( theCommand );
2805 while ( crMethod.myArgs.size() < i+1 )
2806 crMethod.myArgs.push_back( "None" );
2807 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2812 myUnusedCommands.push_back( theCommand );
2815 //================================================================================
2817 * \brief Finish conversion
2819 //================================================================================
2821 void _pyHypothesis::Flush()
2825 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2826 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2827 // Add access to a wrapped mesh
2828 theGen->AddMeshAccessorMethod( *cmd );
2829 // Add access to a wrapped algorithm
2830 theGen->AddAlgoAccessorMethod( *cmd );
2832 cmd = myUnusedCommands.begin();
2833 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2834 // Add access to a wrapped mesh
2835 theGen->AddMeshAccessorMethod( *cmd );
2836 // Add access to a wrapped algorithm
2837 theGen->AddAlgoAccessorMethod( *cmd );
2840 // forget previous hypothesis modifications
2841 myArgCommands.clear();
2842 myUnusedCommands.clear();
2845 //================================================================================
2847 * \brief clear creation, arg and unknown commands
2849 //================================================================================
2851 void _pyHypothesis::ClearAllCommands()
2853 GetCreationCmd()->Clear();
2854 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2855 for ( ; cmd != myArgCommands.end(); ++cmd )
2857 cmd = myUnusedCommands.begin();
2858 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2863 //================================================================================
2865 * \brief Assign fields of theOther to me except myIsWrapped
2867 //================================================================================
2869 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2870 const _pyID& theMesh )
2872 // myCreationCmd = theOther->myCreationCmd;
2873 myIsAlgo = theOther->myIsAlgo;
2874 myIsWrapped = false;
2875 myGeom = theOther->myGeom;
2877 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2878 myAccumulativeMethods = theOther->myAccumulativeMethods;
2879 //myUnusedCommands = theOther->myUnusedCommands;
2880 // init myCurCrMethod
2881 GetCreationMethod( theOther->GetAlgoType() );
2884 //================================================================================
2886 * \brief Analyze my erasability depending on myReferredObjs
2888 //================================================================================
2890 bool _pyHypothesis::CanClear()
2894 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2895 for ( ; obj != myReferredObjs.end(); ++obj )
2896 if ( (*obj)->CanClear() )
2903 //================================================================================
2905 * \brief Clear my commands depending on usage by meshes
2907 //================================================================================
2909 void _pyHypothesis::ClearCommands()
2911 // if ( !theGen->IsToKeepAllCommands() )
2913 // bool isUsed = false;
2914 // int lastComputeOrder = 0;
2915 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2916 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2917 // if ( ! (*cmd)->IsEmpty() )
2920 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2921 // lastComputeOrder = (*cmd)->GetOrderNb();
2925 // SetRemovedFromStudy( true );
2929 // // clear my commands invoked after lastComputeOrder
2930 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2931 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2933 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2934 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2935 // // cmds.back()->Clear();
2939 _pyObject::ClearCommands();
2942 //================================================================================
2944 * \brief Find arguments that are objects like mesh, group, geometry
2945 * \param meshes - referred meshes (directly or indirrectly)
2946 * \retval bool - false if a referred geometry is not in the study
2948 //================================================================================
2950 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2952 if ( IsAlgo() ) return true;
2954 bool geomPublished = true;
2955 vector< _AString > args;
2956 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2957 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2959 CreationMethod& crMethod = type2meth->second;
2960 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2962 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2963 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2964 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2965 args.push_back( (*cmd)->GetArg( nb ));
2968 for ( size_t i = 0; i < args.size(); ++i )
2970 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2971 if ( idList.empty() && !args[ i ].IsEmpty() )
2972 idList.push_back( args[ i ]);
2973 list< _pyID >::iterator id = idList.begin();
2974 for ( ; id != idList.end(); ++id )
2976 Handle(_pyObject) obj = theGen->FindObject( *id );
2977 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2980 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2981 geomPublished = false;
2985 myReferredObjs.push_back( obj );
2986 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2987 if ( !mesh.IsNull() )
2988 meshes.push_back( mesh );
2989 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2990 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2991 obj->SetRemovedFromStudy( false );
2995 return geomPublished;
2998 //================================================================================
3000 * \brief Remember theCommand setting a parameter
3002 //================================================================================
3004 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3006 // parameters are discriminated by method name
3007 _AString method = theCommand->GetMethod();
3008 if ( myAccumulativeMethods.count( method ))
3009 return; // this method adds values and not override the previus value
3011 // discriminate commands setting different parameters via one method
3012 // by passing parameter names like e.g. SetOption("size", "0.2")
3013 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3014 theCommand->GetNbArgs() > 1 )
3016 // mangle method by appending a 1st textual arg
3017 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3019 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3020 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3021 if ( !isalpha( arg.Value(2))) continue;
3026 // parameters are discriminated by method name
3027 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3028 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3030 cmds.back()->Clear(); // previous parameter value has not been used
3031 cmds.back() = theCommand;
3035 cmds.push_back( theCommand );
3039 //================================================================================
3041 * \brief Return true if a setting parameter command ha been used to compute mesh
3043 //================================================================================
3045 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3046 _pyCommand::TAddr avoidComputeAddr ) const
3048 bool isUsed = false;
3049 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3050 myComputeAddr2Cmds.begin();
3051 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3053 if ( addr2cmds->first == avoidComputeAddr ) continue;
3054 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3055 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3060 //================================================================================
3062 * \brief Save commands setting parameters as they are used for a mesh computation
3064 //================================================================================
3066 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3068 myComputeCmds.push_back( theComputeCmd );
3069 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3071 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3072 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3073 savedCmds.push_back( m2c->second.back() );
3076 //================================================================================
3078 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3080 //================================================================================
3082 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3084 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3086 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3087 for ( ; cmd != savedCmds.end(); ++cmd )
3089 // check if a cmd has been used to compute another mesh
3090 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3092 // check if a cmd is a sole command setting its parameter;
3093 // don't use method name for search as it can change
3094 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3095 m2cmds = myMeth2Commands.begin();
3096 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3098 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3099 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3100 if ( cmdIt != cmds.end() )
3102 if ( cmds.back() != *cmd )
3104 cmds.erase( cmdIt );
3111 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3114 //================================================================================
3116 * \brief Sets an argNb-th argument of current creation command
3117 * \param argNb - argument index countered from 1
3119 //================================================================================
3121 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3123 if ( myCurCrMethod )
3125 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3126 myCurCrMethod->myArgs.push_back( "None" );
3127 if ( arg.IsEmpty() )
3128 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3130 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3135 //================================================================================
3137 * \brief Remember hypothesis parameter values
3138 * \param theCommand - The called hypothesis method
3140 //================================================================================
3142 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3144 if ( GetAlgoType() == "Cartesian_3D" )
3146 // CartesianParameters3D hyp
3148 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3149 theCommand->GetMethod() == "SetToAddEdges" )
3151 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3152 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3153 myArgCommands.push_back( theCommand );
3156 if ( theCommand->GetMethod() == "SetGrid" ||
3157 theCommand->GetMethod() == "SetGridSpacing" )
3159 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3160 int iArg = axis.Value(1) - '0';
3161 if ( theCommand->GetMethod() == "SetGrid" )
3163 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3167 myCurCrMethod->myArgs[ iArg ] = "[ ";
3168 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3169 myCurCrMethod->myArgs[ iArg ] += ", ";
3170 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3171 myCurCrMethod->myArgs[ iArg ] += "]";
3173 myArgCommands.push_back( theCommand );
3174 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3175 // accumulative, else, if the creation
3176 // is not converted, commands for axes 1 and 2 are lost
3181 if( theCommand->GetMethod() == "SetLength" )
3183 // NOW it is OBSOLETE
3184 // ex: hyp.SetLength(start, 1)
3185 // hyp.SetLength(end, 0)
3186 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3187 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3188 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3189 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3191 CreationMethod& crMethod = type2meth->second;
3192 while ( (int) crMethod.myArgs.size() < i+1 )
3193 crMethod.myArgs.push_back( "[]" );
3194 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3196 myArgCommands.push_back( theCommand );
3200 _pyHypothesis::Process( theCommand );
3203 //================================================================================
3205 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3207 //================================================================================
3209 void _pyComplexParamHypo::Flush()
3211 list < Handle(_pyCommand) >::iterator cmd;
3214 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3215 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3219 // if ( GetAlgoType() == "Cartesian_3D" )
3221 // _pyID algo = myCreationCmd->GetObject();
3222 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3224 // if ( IsWrapped() )
3226 // StructToList( *cmd, /*checkMethod=*/false );
3227 // const _AString & method = (*cmd)->GetMethod();
3228 // if ( method == "SetFixedPoint" )
3229 // (*cmd)->SetObject( algo );
3235 //================================================================================
3237 * \brief Convert methods of 1D hypotheses to my own methods
3238 * \param theCommand - The called hypothesis method
3240 //================================================================================
3242 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3244 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3247 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3248 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3249 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3251 // TCollection_AsciiString cmd =
3252 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3253 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3254 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3257 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3259 // // 1D hypo is already set, so distribution changes and the old
3260 // // 1D hypo is thrown away
3261 // my1dHyp->ClearAllCommands();
3264 // //my1dHyp->SetRemovedFromStudy( false );
3266 // if ( !myArgCommands.empty() )
3267 // myArgCommands.back()->Clear();
3268 myCurCrMethod->myArgs.push_back( hyp1dID );
3269 myArgCommands.push_back( theCommand );
3272 //================================================================================
3275 * \param theAdditionCmd - command to be converted
3276 * \param theMesh - mesh instance
3277 * \retval bool - status
3279 //================================================================================
3281 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3282 const _pyID& theMesh)
3284 myIsWrapped = false;
3286 if ( my1dHyp.IsNull() )
3289 // set "SetLayerDistribution()" after addition cmd
3290 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3292 _pyID geom = theAdditionCmd->GetArg( 1 );
3294 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3295 if ( !algo.IsNull() )
3297 my1dHyp->SetMesh( theMesh );
3298 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3299 algo->GetAlgoType().ToCString());
3300 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3303 // clear "SetLayerDistribution()" cmd
3304 myArgCommands.back()->Clear();
3306 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3308 // find RadialPrism algo created on <geom> for theMesh
3309 GetCreationCmd()->SetObject( algo->GetID() );
3310 GetCreationCmd()->SetMethod( myAlgoMethod );
3311 GetCreationCmd()->RemoveArgs();
3312 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3318 //================================================================================
3322 //================================================================================
3324 void _pyLayerDistributionHypo::Flush()
3326 // as creation of 1D hyp was written later then it's edition,
3327 // we need to find all it's edition calls and process them
3328 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3330 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3332 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3333 if ( hyp1dID.IsEmpty() ) continue;
3335 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3337 // make a new name for 1D hyp = "HypType" + "_Distribution"
3339 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3341 if ( prevNewName.IsEmpty() ) continue;
3342 newName = prevNewName;
3346 if ( hyp1d->IsWrapped() ) {
3347 newName = hyp1d->GetCreationCmd()->GetMethod();
3350 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3351 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3353 newName += "_Distribution";
3354 prevNewName = newName;
3356 hyp1d->GetCreationCmd()->SetResultValue( newName );
3358 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3359 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3360 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3361 const _pyID& objID = (*cmdIt)->GetObject();
3362 if ( objID == hyp1dID ) {
3363 if ( !hyp1d.IsNull() )
3365 hyp1d->Process( *cmdIt );
3366 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3368 ( *cmdIt )->SetObject( newName );
3371 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3372 (*cmd)->SetArg( 1, newName );
3376 //================================================================================
3378 * \brief additionally to Addition2Creation, clears SetDistrType() command
3379 * \param theCmd - AddHypothesis() command
3380 * \param theMesh - mesh to which a hypothesis is added
3381 * \retval bool - conversion result
3383 //================================================================================
3385 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3386 const _pyID& theMesh)
3388 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3389 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3390 bool scaleDistrType = false;
3391 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3392 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3393 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3394 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3395 scaleDistrType = true;
3398 else if ( !scaleDistrType ) {
3399 // distribution type changed: remove scale factor from args
3400 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3401 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3403 CreationMethod& crMethod = type2meth->second;
3404 if ( crMethod.myArgs.size() == 2 )
3405 crMethod.myArgs.pop_back();
3412 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3415 //================================================================================
3417 * \brief remove repeated commands defining distribution
3419 //================================================================================
3421 void _pyNumberOfSegmentsHyp::Flush()
3423 // find number of the last SetDistrType() command
3424 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3425 int distrTypeNb = 0;
3426 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3427 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3428 if ( cmd != myUnusedCommands.rbegin() )
3429 distrTypeNb = (*cmd)->GetOrderNb();
3431 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3434 // clear commands before the last SetDistrType()
3435 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3436 set< int > treatedCmdNbs; // avoid treating same cmd twice
3437 for ( int i = 0; i < 2; ++i ) {
3438 set<TCollection_AsciiString> uniqueMethods;
3439 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3440 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3442 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3443 continue;// avoid treating same cmd twice
3444 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3445 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3446 if ( !clear || method == "SetNumberOfSegments" ) {
3447 bool isNewInSet = uniqueMethods.insert( method ).second;
3448 clear = !isNewInSet;
3457 //================================================================================
3459 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3460 * into regular1D.LengthNearVertex( length, vertex )
3461 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3462 * \param theMesh - The mesh needing this hypo
3463 * \retval bool - false if the command can't be converted
3465 //================================================================================
3467 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3468 const _pyID& theMeshID)
3470 if ( IsWrappable( theMeshID )) {
3472 _pyID vertex = theCmd->GetArg( 1 );
3474 // the problem here is that segment algo can be not found
3475 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3476 // geometry where segment algorithm is assigned
3477 _pyID geom = vertex;
3478 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3479 while ( algo.IsNull() && !geom.IsEmpty()) {
3480 // try to find geom as a father of <vertex>
3481 geom = FatherID( geom );
3482 algo = theGen->FindAlgo( geom, theMeshID, this );
3484 if ( algo.IsNull() || geom.IsEmpty() )
3485 return false; // also possible to find geom as brother of veretex...
3487 // set geom instead of vertex
3488 theCmd->SetArg( 1, geom );
3490 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3491 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3492 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3494 // set vertex as a second arg
3495 theCmd->SetArg( 2, vertex );
3503 //================================================================================
3505 * \brief _pyAlgorithm constructor
3506 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3508 //================================================================================
3510 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3511 : _pyHypothesis( theCreationCmd )
3516 //================================================================================
3518 * \brief Convert the command adding an algorithm to mesh
3519 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3520 * \param theMesh - The mesh needing this algo
3521 * \retval bool - false if the command can't be converted
3523 //================================================================================
3525 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3526 const _pyID& theMeshID)
3528 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3529 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3530 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3536 //================================================================================
3538 * \brief Return starting position of a part of python command
3539 * \param thePartIndex - The index of command part
3540 * \retval int - Part position
3542 //================================================================================
3544 int _pyCommand::GetBegPos( int thePartIndex ) const
3548 if ( myBegPos.Length() < thePartIndex )
3550 ASSERT( thePartIndex > 0 );
3551 return myBegPos( thePartIndex );
3554 //================================================================================
3556 * \brief Store starting position of a part of python command
3557 * \param thePartIndex - The index of command part
3558 * \param thePosition - Part position
3560 //================================================================================
3562 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3564 while ( myBegPos.Length() < thePartIndex )
3565 myBegPos.Append( UNKNOWN );
3566 ASSERT( thePartIndex > 0 );
3567 myBegPos( thePartIndex ) = thePosition;
3570 //================================================================================
3572 * \brief Returns whitespace symbols at the line beginning
3573 * \retval TCollection_AsciiString - result
3575 //================================================================================
3577 TCollection_AsciiString _pyCommand::GetIndentation()
3580 //while ( end <= Length() && isblank( myString.Value( end )))
3581 //ANA: isblank() function isn't provided in VC2010 compiler
3582 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3584 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3587 //================================================================================
3589 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3590 * \retval const TCollection_AsciiString & - ResultValue substring
3592 //================================================================================
3594 const TCollection_AsciiString & _pyCommand::GetResultValue()
3596 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3598 SetBegPos( RESULT_IND, EMPTY );
3599 int begPos, endPos = myString.Location( "=", 1, Length() );
3603 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3604 if ( begPos < endPos )
3606 SetBegPos( RESULT_IND, begPos );
3608 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3609 myRes = myString.SubString( begPos, endPos );
3616 //================================================================================
3618 * \brief Return number of python command result value ResultValue = Obj.Meth()
3620 //================================================================================
3622 int _pyCommand::GetNbResultValues()
3625 return myResults.Length();
3629 //================================================================================
3631 * \brief Return substring of python command looking like
3632 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3633 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3635 //================================================================================
3636 const _AString& _pyCommand::GetResultValue(int res)
3638 if ( GetResultValue().IsEmpty() )
3639 return theEmptyString;
3641 if ( myResults.IsEmpty() )
3644 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3645 ++begPos; // skip [, else the whole list is returned
3646 while ( begPos < myRes.Length() ) {
3647 _AString result = GetWord( myRes, begPos, true );
3648 begPos += result.Length();
3650 // result.RemoveAll('[');
3651 // result.RemoveAll(']');
3656 myResults.Append( result );
3659 if ( res > 0 && res <= myResults.Length() )
3660 return myResults( res );
3661 return theEmptyString;
3664 //================================================================================
3666 * \brief Return substring of python command looking like ResVal = Object.Meth()
3667 * \retval const TCollection_AsciiString & - Object substring
3669 //================================================================================
3671 const TCollection_AsciiString & _pyCommand::GetObject()
3673 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3676 int begPos = GetBegPos( RESULT_IND );
3678 begPos = myString.Location( "=", 1, Length() ) + 1;
3679 // is '=' in the string argument (for example, name) or not
3680 int nb1 = 0; // number of ' character at the left of =
3681 int nb2 = 0; // number of " character at the left of =
3682 for ( int i = 1; i < begPos-1; i++ ) {
3683 if ( myString.Value( i )=='\'' )
3685 else if ( myString.Value( i )=='"' )
3688 // if number of ' or " is not divisible by 2,
3689 // then get an object at the start of the command
3690 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3694 begPos += myRes.Length();
3696 myObj = GetWord( myString, begPos, true );
3697 if ( begPos != EMPTY )
3699 // check if object is complex,
3700 // so far consider case like "smesh.Method()"
3701 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3702 //if ( bracketPos==0 ) bracketPos = Length();
3703 int dotPos = begPos+myObj.Length();
3704 while ( dotPos+1 < bracketPos ) {
3705 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3710 if ( dotPos > begPos+myObj.Length() )
3711 myObj = myString.SubString( begPos, dotPos-1 );
3714 // 1st word after '=' is an object
3715 // else // no method -> no object
3721 SetBegPos( OBJECT_IND, begPos );
3727 //================================================================================
3729 * \brief Return substring of python command looking like ResVal = Obj.Method()
3730 * \retval const TCollection_AsciiString & - Method substring
3732 //================================================================================
3734 const TCollection_AsciiString & _pyCommand::GetMethod()
3736 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3739 int begPos = GetBegPos( OBJECT_IND );
3740 bool forward = true;
3742 begPos = myString.Location( "(", 1, Length() ) - 1;
3746 begPos += myObj.Length();
3749 myMeth = GetWord( myString, begPos, forward );
3750 SetBegPos( METHOD_IND, begPos );
3756 //================================================================================
3758 * \brief Returns true if there are brackets after the method
3760 //================================================================================
3762 bool _pyCommand::IsMethodCall()
3764 if ( GetMethod().IsEmpty() )
3766 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3767 return ( s[0] == '(' || s[1] == '(' );
3770 //================================================================================
3772 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3773 * \retval const TCollection_AsciiString & - Arg<index> substring
3775 //================================================================================
3777 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3779 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3783 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3785 pos = myString.Location( "(", 1, Length() );
3789 // we are at or before '(', skip it if present
3791 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3792 if ( pos > Length() )
3796 SetBegPos( ARG1_IND, 0 ); // even no '('
3797 return theEmptyString;
3801 list< TCollection_AsciiString > separatorStack( 1, ",)");
3802 bool ignoreNesting = false;
3804 while ( pos <= Length() )
3806 const char chr = myString.Value( pos );
3808 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3810 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3812 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3814 TCollection_AsciiString arg;
3815 if ( pos-1 >= prevPos ) {
3816 arg = myString.SubString( prevPos, pos-1 );
3817 arg.RightAdjust(); // remove spaces
3820 if ( !arg.IsEmpty() || chr == ',' )
3822 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3823 myArgs.Append( arg );
3829 else // end of nesting args found
3831 separatorStack.pop_back();
3832 ignoreNesting = false;
3835 else if ( !ignoreNesting )
3838 case '(' : separatorStack.push_back(")"); break;
3839 case '[' : separatorStack.push_back("]"); break;
3840 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3841 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3848 if ( myArgs.Length() < index )
3849 return theEmptyString;
3850 return myArgs( index );
3853 //================================================================================
3855 * \brief Return position where arguments begin
3857 //================================================================================
3859 int _pyCommand::GetArgBeginning() const
3861 int pos = GetBegPos( ARG1_IND );
3862 if ( pos == UNKNOWN )
3864 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3866 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3871 //================================================================================
3873 * \brief Check if char is a word part
3874 * \param c - The character to check
3875 * \retval bool - The check result
3877 //================================================================================
3879 static inline bool isWord(const char c, const bool dotIsWord)
3882 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3885 //================================================================================
3887 * \brief Looks for a word in the string and returns word's beginning
3888 * \param theString - The input string
3889 * \param theStartPos - The position to start the search, returning word's beginning
3890 * \param theForward - The search direction
3891 * \retval TCollection_AsciiString - The found word
3893 //================================================================================
3895 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3897 const bool theForward,
3898 const bool dotIsWord )
3900 int beg = theStartPos, end = theStartPos;
3901 theStartPos = EMPTY;
3902 if ( beg < 1 || beg > theString.Length() )
3903 return theEmptyString;
3905 if ( theForward ) { // search forward
3907 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3909 if ( beg > theString.Length() )
3910 return theEmptyString; // no word found
3913 char begChar = theString.Value( beg );
3914 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3915 char endChar = ( begChar == '[' ) ? ']' : begChar;
3916 // end is at the corresponding quoting mark or bracket
3917 while ( end < theString.Length() &&
3918 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3922 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3927 else { // search backward
3929 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3932 return theEmptyString; // no word found
3934 char endChar = theString.Value( end );
3935 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3936 char begChar = ( endChar == ']' ) ? '[' : endChar;
3937 // beg is at the corresponding quoting mark
3939 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3943 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3949 //cout << theString << " ---- " << beg << " - " << end << endl;
3950 return theString.SubString( beg, end );
3953 //================================================================================
3955 * \brief Returns true if the string looks like a study entry
3957 //================================================================================
3959 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3961 if ( str.Length() < 5 ) return false;
3963 int nbColons = 0, isColon;
3964 for ( int i = 1; i <= str.Length(); ++i )
3966 char c = str.Value(i);
3967 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3969 nbColons += isColon;
3971 return nbColons > 2 && str.Length()-nbColons > 2;
3974 //================================================================================
3976 * \brief Returns true if the string looks like an object ID but not like a list,
3977 * string, command etc.
3979 //================================================================================
3981 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3983 if ( str.Length() < 1 ) return false;
3985 const char* s = str.ToCString();
3987 for ( int i = 0; i < str.Length(); ++i )
3988 if ( !IsIDChar( s[i] ))
3994 //================================================================================
3996 * \brief Finds entries in a sting
3998 //================================================================================
4000 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4002 std::list< _pyID > resList;
4004 while ( ++pos <= str.Length() )
4006 if ( !isdigit( str.Value( pos ))) continue;
4007 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4010 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4011 _pyID entry = str.SubString( pos, end-1 );
4013 if ( IsStudyEntry( entry ))
4014 resList.push_back( entry );
4019 //================================================================================
4021 * \brief Look for position where not space char is
4022 * \param theString - The string
4023 * \param thePos - The position to search from and which returns result
4024 * \retval bool - false if there are only space after thePos in theString
4026 //================================================================================
4028 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4030 if ( thePos < 1 || thePos > theString.Length() )
4033 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4036 return thePos <= theString.Length();
4039 //================================================================================
4041 * \brief Modify a part of the command
4042 * \param thePartIndex - The index of the part
4043 * \param thePart - The new part string
4044 * \param theOldPart - The old part
4046 //================================================================================
4048 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4049 TCollection_AsciiString& theOldPart)
4051 int pos = GetBegPos( thePartIndex );
4052 if ( pos <= Length() && theOldPart != thePart)
4054 TCollection_AsciiString seperator;
4056 pos = GetBegPos( thePartIndex + 1 );
4057 if ( pos < 1 ) return;
4058 switch ( thePartIndex ) {
4059 case RESULT_IND: seperator = " = "; break;
4060 case OBJECT_IND: seperator = "."; break;
4061 case METHOD_IND: seperator = "()"; break;
4065 myString.Remove( pos, theOldPart.Length() );
4066 if ( !seperator.IsEmpty() )
4067 myString.Insert( pos , seperator );
4068 myString.Insert( pos, thePart );
4069 // update starting positions of the following parts
4070 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4071 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4072 if ( myBegPos( i ) > 0 )
4073 myBegPos( i ) += posDelta;
4075 theOldPart = thePart;
4079 //================================================================================
4081 * \brief Set agrument
4082 * \param index - The argument index, it counts from 1
4083 * \param theArg - The argument string
4085 //================================================================================
4087 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4090 int argInd = ARG1_IND + index - 1;
4091 int pos = GetBegPos( argInd );
4092 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4094 // find a closing parenthesis
4095 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4096 int lastArgInd = GetNbArgs();
4097 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4098 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4103 while ( pos > 0 && myString.Value( pos ) != ')' )
4106 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4110 while ( myArgs.Length() < index ) {
4111 if ( myArgs.Length() )
4112 myString.Insert( pos++, "," );
4113 myArgs.Append("None");
4114 myString.Insert( pos, myArgs.Last() );
4115 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4116 pos += myArgs.Last().Length();
4119 SetPart( argInd, theArg, myArgs( index ));
4122 //================================================================================
4124 * \brief Empty arg list
4126 //================================================================================
4128 void _pyCommand::RemoveArgs()
4130 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4131 myString.Trunc( pos );
4134 if ( myBegPos.Length() >= ARG1_IND )
4135 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4138 //================================================================================
4140 * \brief Comment a python command
4142 //================================================================================
4144 void _pyCommand::Comment()
4146 if ( IsEmpty() ) return;
4149 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4150 if ( i <= Length() )
4152 myString.Insert( i, "#" );
4153 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4155 int begPos = GetBegPos( iPart );
4156 if ( begPos != UNKNOWN && begPos != EMPTY )
4157 SetBegPos( iPart, begPos + 1 );
4162 //================================================================================
4164 * \brief Set dependent commands after this one
4166 //================================================================================
4168 bool _pyCommand::SetDependentCmdsAfter() const
4170 bool orderChanged = false;
4171 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4172 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4173 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4174 orderChanged = true;
4175 theGen->SetCommandAfter( *cmd, this );
4176 (*cmd)->SetDependentCmdsAfter();
4179 return orderChanged;
4181 //================================================================================
4183 * \brief Insert accessor method after theObjectID
4184 * \param theObjectID - id of the accessed object
4185 * \param theAcsMethod - name of the method giving access to the object
4186 * \retval bool - false if theObjectID is not found in the command string
4188 //================================================================================
4190 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4192 if ( !theAcsMethod )
4194 // start object search from the object, i.e. ignore result
4196 int beg = GetBegPos( OBJECT_IND );
4197 if ( beg < 1 || beg > Length() )
4200 while (( beg = myString.Location( theObjectID, beg, Length() )))
4202 // check that theObjectID is not just a part of a longer ID
4203 int afterEnd = beg + theObjectID.Length();
4204 Standard_Character c = myString.Value( afterEnd );
4205 if ( !IsIDChar( c ))
4207 // check if accessor method already present
4209 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4211 int oldLen = Length();
4212 myString.Insert( afterEnd, (char*) theAcsMethod );
4213 myString.Insert( afterEnd, "." );
4214 // update starting positions of the parts following the modified one
4215 int posDelta = Length() - oldLen;
4216 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4217 if ( myBegPos( i ) > afterEnd )
4218 myBegPos( i ) += posDelta;
4223 beg = afterEnd; // is a part -> next search
4228 //================================================================================
4230 * \brief Creates pyObject
4232 //================================================================================
4234 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4235 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4240 //================================================================================
4242 * \brief Set up myID and myIsPublished
4244 //================================================================================
4246 void _pyObject::setID(const _pyID& theID)
4249 myIsPublished = !theGen->IsNotPublished( GetID() );
4252 //================================================================================
4254 * \brief Clear myCreationCmd and myProcessedCmds
4256 //================================================================================
4258 void _pyObject::ClearCommands()
4263 if ( !myCreationCmd.IsNull() )
4264 myCreationCmd->Clear();
4266 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4267 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4271 //================================================================================
4273 * \brief Return method name giving access to an interaface object wrapped by python class
4274 * \retval const char* - method name
4276 //================================================================================
4278 const char* _pyObject::AccessorMethod() const
4282 //================================================================================
4284 * \brief Return ID of a father
4286 //================================================================================
4288 _pyID _pyObject::FatherID(const _pyID & childID)
4290 int colPos = childID.SearchFromEnd(':');
4292 return childID.SubString( 1, colPos-1 );
4296 //================================================================================
4298 * \brief SelfEraser erases creation command if none of it's commands invoked
4299 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4301 //================================================================================
4303 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4304 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4306 myIsPublished = true; // prevent clearing as a not published
4307 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4310 //================================================================================
4312 * \brief SelfEraser erases creation command if none of it's commands invoked
4313 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4315 //================================================================================
4317 bool _pySelfEraser::CanClear()
4319 bool toErase = false;
4320 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4323 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4324 for ( ; cmd != myArgCmds.end(); ++cmd )
4325 nbArgUses += IsAliveCmd( *cmd );
4327 toErase = ( nbArgUses < 1 );
4332 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4333 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4334 for ( ; cmd != cmds.end(); )
4335 // check of cmd emptiness is not enough as object can change
4336 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4339 cmd = cmds.erase( cmd ); // save the cmd from clearing
4341 toErase = ( nbCalls < 1 );
4346 //================================================================================
4348 * \brief Check if a command is or can be cleared
4350 //================================================================================
4352 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4354 if ( theCmd->IsEmpty() )
4357 if ( !theGen->IsToKeepAllCommands() )
4359 const _pyID& objID = theCmd->GetObject();
4360 Handle( _pyObject ) obj = theGen->FindObject( objID );
4361 if ( !obj.IsNull() )
4362 return !obj->CanClear();
4367 //================================================================================
4369 * \brief SelfEraser erases creation command if none of it's commands invoked
4370 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4372 //================================================================================
4374 void _pySelfEraser::Flush()
4378 myIsPublished = false;
4379 _pyObject::ClearCommands();
4383 //================================================================================
4385 * \brief _pySubMesh constructor
4387 //================================================================================
4389 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4390 _pyObject(theCreationCmd)
4392 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4393 if ( toKeepAgrCmds )
4394 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4397 //================================================================================
4399 * \brief Return true if a sub-mesh can be used as argument of the given method
4401 //================================================================================
4403 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4406 // // names of all methods where a sub-mesh can be used as argument
4407 // static TStringSet methods;
4408 // if ( methods.empty() ) {
4409 // const char * names[] = {
4410 // // methods of SMESH_Gen
4412 // // methods of SMESH_Group
4414 // // methods of SMESH_Measurements
4416 // // methods of SMESH_Mesh
4417 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4419 // // methods of SMESH_MeshEditor
4420 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4421 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4422 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4423 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4424 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4425 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4426 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4427 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4428 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4429 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4430 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4431 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4432 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4433 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4434 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4435 // "" }; // <- mark of end
4436 // methods.Insert( names );
4438 // return methods.Contains( theMethodName );
4441 //================================================================================
4443 * \brief count invoked commands
4445 //================================================================================
4447 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4449 _pyObject::Process(theCommand); // count calls of Process()
4452 //================================================================================
4454 * \brief Move creation command depending on invoked commands
4456 //================================================================================
4458 void _pySubMesh::Flush()
4460 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4461 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4462 else if ( !myCreator.IsNull() )
4463 // move to be just after creator
4464 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4466 // move sub-mesh usage after creation cmd
4467 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4468 for ( ; cmd != myArgCmds.end(); ++cmd )
4469 if ( !(*cmd)->IsEmpty() )
4470 GetCreationCmd()->AddDependantCmd( *cmd );
4473 //================================================================================
4475 * \brief Creates _pyGroup
4477 //================================================================================
4479 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4480 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4482 if ( !id.IsEmpty() )
4485 myCanClearCreationCmd = true;
4487 const _AString& method = theCreationCmd->GetMethod();
4488 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4490 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4492 // ----------------------------------------------------------------------
4493 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4495 _pyID geom = theCreationCmd->GetArg( 3 );
4496 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4497 // next if(){...} section is commented
4498 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4499 // theCreationCmd->SetMethod( "Group" );
4500 // theCreationCmd->RemoveArgs();
4501 // theCreationCmd->SetArg( 1, geom );
4504 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4505 _pyID type = theCreationCmd->GetArg( 1 );
4506 _pyID name = theCreationCmd->GetArg( 2 );
4507 theCreationCmd->SetMethod( "GroupOnGeom" );
4508 theCreationCmd->RemoveArgs();
4509 theCreationCmd->SetArg( 1, geom );
4510 theCreationCmd->SetArg( 2, name );
4511 theCreationCmd->SetArg( 3, type );
4514 else if ( method == "CreateGroupFromFilter" )
4516 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4517 theCreationCmd->SetMethod( "GroupOnFilter" );
4519 _pyID filterID = theCreationCmd->GetArg(3);
4520 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4521 if ( !filter.IsNull())
4523 if ( !filter->GetNewID().IsEmpty() )
4524 theCreationCmd->SetArg( 3, filter->GetNewID() );
4525 //filter->AddUser( this );
4529 else if ( method == "GetGroups" )
4531 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4535 // theCreationCmd does something else apart from creation of this group
4536 // and thus it can't be cleared if this group is removed
4537 myCanClearCreationCmd = false;
4541 //================================================================================
4543 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4546 //================================================================================
4548 bool _pyGroup::CanClear()
4553 if ( !myCanClearCreationCmd &&
4554 !myCreationCmd.IsNull() &&
4555 myCreationCmd->GetMethod() == "GetGroups" )
4557 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4558 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4559 list< _pyID >::iterator grID = idList.begin();
4560 if ( GetID() == *grID )
4562 myCanClearCreationCmd = true;
4563 list< Handle(_pyGroup ) > groups;
4564 for ( ; grID != idList.end(); ++grID )
4566 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4567 if ( group.IsNull() ) continue;
4568 groups.push_back( group );
4569 if ( group->IsInStudy() )
4570 myCanClearCreationCmd = false;
4572 // set myCanClearCreationCmd == true to all groups
4573 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4574 for ( ; group != groups.end(); ++group )
4575 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4579 return myCanClearCreationCmd;
4582 //================================================================================
4584 * \brief set myCanClearCreationCmd = true if the main action of the creation
4585 * command is discarded
4587 //================================================================================
4589 void _pyGroup::RemovedWithContents()
4591 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4592 // via a created group
4593 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4594 // myCanClearCreationCmd = true;
4597 //================================================================================
4599 * \brief To convert creation of a group by filter
4601 //================================================================================
4603 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4605 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4606 // group = mesh.CreateEmptyGroup( elemType, groupName )
4607 // aFilter.SetMesh(mesh)
4608 // nbAdd = group.AddFrom( aFilter )
4609 Handle(_pyFilter) filter;
4610 if ( theCommand->GetMethod() == "AddFrom" )
4612 _pyID idSource = theCommand->GetArg(1);
4613 // check if idSource is a filter
4614 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4615 if ( !filter.IsNull() )
4617 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4618 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4619 while ( *cmdIt != theCommand ) ++cmdIt;
4620 while ( (*cmdIt)->GetOrderNb() != 1 )
4622 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4623 if ((setMeshCmd->GetObject() == idSource ||
4624 setMeshCmd->GetObject() == filter->GetNewID() )
4626 setMeshCmd->GetMethod() == "SetMesh")
4628 setMeshCmd->Clear();
4632 // replace 3 commands by one
4633 theCommand->Clear();
4634 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4635 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4636 if ( !filter->GetNewID().IsEmpty() )
4637 idSource = filter->GetNewID();
4638 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4639 makeGroupCmd->SetArg( 1, name );
4640 makeGroupCmd->SetArg( 2, idSource );
4641 filter->AddArgCmd( makeGroupCmd );
4644 else if ( theCommand->GetMethod() == "SetFilter" )
4646 // set new name of a filter or clear the command if the same filter is set
4647 _pyID filterID = theCommand->GetArg(1);
4648 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4649 if ( !myFilter.IsNull() && filter == myFilter )
4650 theCommand->Clear();
4651 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4652 theCommand->SetArg( 1, filter->GetNewID() );
4655 else if ( theCommand->GetMethod() == "GetFilter" )
4657 // GetFilter() returns a filter with other ID, make myFilter process
4658 // calls of the returned filter
4659 if ( !myFilter.IsNull() )
4661 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4662 theCommand->Clear();
4666 // if ( !filter.IsNull() )
4667 // filter->AddUser( this );
4669 theGen->AddMeshAccessorMethod( theCommand );
4672 //================================================================================
4674 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4676 //================================================================================
4678 void _pyGroup::Flush()
4680 if ( !theGen->IsToKeepAllCommands() &&
4681 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4683 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4687 //================================================================================
4689 * \brief Constructor of _pyFilter
4691 //================================================================================
4693 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4694 :_pyObject(theCreationCmd), myNewID( newID )
4696 //myIsPublished = true; // prevent clearing as a not published
4697 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4700 //================================================================================
4702 * \brief To convert creation of a filter by criteria and
4703 * to replace an old name by a new one
4705 //================================================================================
4707 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4709 if ( theCommand->GetObject() == GetID() )
4710 _pyObject::Process(theCommand); // count commands
4712 if ( !myNewID.IsEmpty() )
4713 theCommand->SetObject( myNewID );
4715 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4716 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4717 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4718 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4719 theCommand->GetMethod() == "SetCriteria")
4721 // aFilter.SetCriteria(aCriteria) ->
4722 // aFilter = smesh.GetFilterFromCriteria(criteria)
4723 if ( myNewID.IsEmpty() )
4724 theCommand->SetResultValue( GetID() );
4726 theCommand->SetResultValue( myNewID );
4727 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4728 theCommand->SetMethod( "GetFilterFromCriteria" );
4730 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4731 GetCreationCmd()->Clear();
4732 GetCreationCmd()->GetString() = theCommand->GetString();
4733 theCommand->Clear();
4734 theCommand->AddDependantCmd( GetCreationCmd() );
4735 // why swap? -- it's needed
4736 //GetCreationCmd()->Clear();
4738 else if ( theCommand->GetMethod() == "SetMesh" )
4740 if ( myMesh == theCommand->GetArg( 1 ))
4741 theCommand->Clear();
4743 myMesh = theCommand->GetArg( 1 );
4744 theGen->AddMeshAccessorMethod( theCommand );
4748 //================================================================================
4750 * \brief Set new filter name to the creation command and to myArgCmds
4752 //================================================================================
4754 void _pyFilter::Flush()
4756 if ( myNewID.IsEmpty() ) return;
4758 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4759 for ( ; cmd != myArgCmds.end(); ++cmd )
4760 if ( !(*cmd)->IsEmpty() )
4762 _AString cmdStr = (*cmd)->GetString();
4763 _AString id = GetID();
4764 int pos = cmdStr.Search( id );
4767 cmdStr.Remove( pos, id.Length() );
4768 cmdStr.Insert( pos, myNewID );
4771 (*cmd)->GetString() = cmdStr;
4774 if ( !GetCreationCmd()->IsEmpty() )
4775 GetCreationCmd()->SetResultValue( myNewID );
4778 //================================================================================
4780 * \brief Return true if all my users can be cleared
4782 //================================================================================
4784 bool _pyObject::CanClear()
4786 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4787 for ( ; cmd != myArgCmds.end(); ++cmd )
4788 if ( !(*cmd)->IsEmpty() )
4790 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4791 if ( !obj.IsNull() && !obj->CanClear() )
4794 return ( !myIsPublished );
4797 //================================================================================
4799 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4801 //================================================================================
4803 _pyHypothesisReader::_pyHypothesisReader()
4806 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4807 LDOMParser xmlParser;
4808 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4810 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4814 INFOS( xmlParser.GetError(data) );
4817 // <algorithm type="Regular_1D"
4818 // label-id="Wire discretisation"
4821 // <algo>Regular_1D=Segment()</algo>
4822 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4824 LDOM_Document xmlDoc = xmlParser.getDocument();
4825 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4826 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4828 LDOM_Node algoNode = algoNodeList.item( i );
4829 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4830 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4831 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4833 _AString text, algoType, method, arg;
4834 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4836 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4837 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4838 text = textNode.getNodeValue();
4839 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4840 algoType = algoCmd->GetResultValue();
4841 method = algoCmd->GetMethod();
4842 arg = algoCmd->GetArg(1);
4843 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4845 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4846 algo->SetConvMethodAndType( method, algoType );
4847 if ( !arg.IsEmpty() )
4848 algo->setCreationArg( 1, arg );
4850 myType2Hyp[ algoType ] = algo;
4854 if ( algoType.IsEmpty() ) continue;
4856 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4858 Handle( _pyHypothesis ) hyp;
4859 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4861 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4862 LDOM_Node textNode = pyHypoNode.getFirstChild();
4863 text = textNode.getNodeValue();
4864 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4865 hypType = hypoCmd->GetResultValue();
4866 method = hypoCmd->GetMethod();
4867 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4869 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4870 if ( type2hyp == myType2Hyp.end() )
4871 hyp = new _pyHypothesis( hypoCmd );
4873 hyp = type2hyp->second;
4874 hyp->SetConvMethodAndType( method, algoType );
4875 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4877 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4878 _AString argMethod = argCmd.GetMethod();
4879 _AString argNbText = argCmd.GetArg( 1 );
4880 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4881 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4883 hyp->AddArgMethod( argMethod,
4884 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4886 myType2Hyp[ hypType ] = hyp;
4890 // <hypothesis type="BLSURF_Parameters"
4894 // <accumulative-methods>
4895 // SetEnforcedVertex,
4896 // SetEnforcedVertexNamed
4897 // </accumulative-methods>
4901 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4902 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4904 LDOM_Node hypNode = hypNodeList.item( i );
4905 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4906 _AString hypType = hypElem.getAttribute("type");
4907 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4908 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4910 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4911 if ( type2hyp == myType2Hyp.end() ) continue;
4913 LDOM_Node methNode = methNodeList.item( 0 );
4914 LDOM_Node textNode = methNode.getFirstChild();
4915 _AString text = textNode.getNodeValue();
4919 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4920 pos += method.Length();
4921 type2hyp->second->AddAccumulativeMethod( method );
4923 while ( !method.IsEmpty() );
4926 } // loop on xmlPaths
4929 //================================================================================
4931 * \brief Returns a new hypothesis initialized according to the read information
4933 //================================================================================
4935 Handle(_pyHypothesis)
4936 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4937 const Handle(_pyCommand)& creationCmd) const
4939 Handle(_pyHypothesis) resHyp, sampleHyp;
4941 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4942 if ( type2hyp != myType2Hyp.end() )
4943 sampleHyp = type2hyp->second;
4945 if ( sampleHyp.IsNull() )
4947 resHyp = new _pyHypothesis(creationCmd);
4951 if ( sampleHyp->IsAlgo() )
4952 resHyp = new _pyAlgorithm( creationCmd );
4954 resHyp = new _pyHypothesis(creationCmd);
4955 resHyp->Assign( sampleHyp, _pyID() );
4960 //================================================================================
4962 * \brief Adds an object ID to some family of IDs with a common prefix
4963 * \param [in] str - the object ID
4964 * \return bool - \c false if \a str does not have the same prefix as \a this family
4965 * (for internal usage)
4967 //================================================================================
4969 bool _pyStringFamily::Add( const char* str )
4971 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4972 return false; // expected prefix is missing
4974 str += _prefix.Length(); // skip _prefix
4976 // try to add to some of child falimies
4977 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4978 for ( ; itSub != _subFams.end(); ++itSub )
4979 if ( itSub->Add( str ))
4982 // no suitable family found - add str to _strings or create a new child family
4984 // look for a proper place within sorted _strings
4985 std::list< _AString >::iterator itStr = _strings.begin();
4986 while ( itStr != _strings.end() && itStr->IsLess( str ))
4988 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4989 return true; // same ID already kept
4991 const int minPrefixSize = 4;
4993 // count "smaller" strings with the same prefix
4994 std::list< _AString >::iterator itLess = itStr; --itLess;
4996 for ( ; itLess != _strings.end(); --itLess )
4997 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5002 // count "greater" strings with the same prefix
5003 std::list< _AString >::iterator itMore = itStr;
5005 for ( ; itMore != _strings.end(); ++itMore )
5006 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5011 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5013 // look for a maximal prefix length
5014 // int lessPrefSize = 3, morePrefSize = 3;
5015 // if ( nbLess > 0 )
5016 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5018 // if ( nbMore > 0 )
5019 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5021 // int prefixSize = 3;
5022 // if ( nbLess == 0 )
5023 // prefixSize = morePrefSize;
5024 // else if ( nbMore == 0 )
5025 // prefixSize = lessPrefSize;
5027 // prefixSize = Min( lessPrefSize, morePrefSize );
5028 int prefixSize = minPrefixSize;
5029 _AString newPrefix ( str, prefixSize );
5031 // look for a proper place within _subFams sorted by _prefix
5032 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5033 if ( !itSub->_prefix.IsLess( newPrefix ))
5036 // add the new _pyStringFamily
5037 itSub = _subFams.insert( itSub, _pyStringFamily());
5038 _pyStringFamily& newSubFam = *itSub;
5039 newSubFam._prefix = newPrefix;
5041 // pass this->_strings to newSubFam._strings
5042 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5043 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5044 newSubFam._strings.push_back( str + prefixSize );
5045 for ( ; nbMore > 0; --nbMore, ++itStr )
5046 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5048 _strings.erase( itLess, ++itMore );
5050 else // to few string to make a family fot them
5052 _strings.insert( itStr, str );
5057 //================================================================================
5059 * \brief Finds an object ID in the command
5060 * \param [in] longStr - the command string
5061 * \param [out] subStr - the found object ID
5062 * \return bool - \c true if the object ID found
5064 //================================================================================
5066 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5068 const _AString& longStr = cmd->GetString();
5069 const char* s = longStr.ToCString();
5072 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5073 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5074 if ( argBeg < 4 || argBeg > longStr.Length() )
5076 for ( ; itSub != _subFams.end(); ++itSub )
5079 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5080 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5082 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5083 from = pos + len + itSub->_prefix.Length();
5088 from += itSub->_prefix.Length();
5091 // look among _strings
5092 std::list< _AString >::iterator itStr = _strings.begin();
5093 for ( ; itStr != _strings.end(); ++itStr )
5094 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5095 // check that object ID does not continue after len
5096 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5098 subStr.push_back( *itStr );
5104 //================================================================================
5106 * \brief Return remainder length of the object ID after my _prefix
5107 * \param [in] str - remainder of the command after my _prefix
5108 * \return int - length of the object ID or -1 if not found
5110 //================================================================================
5112 int _pyStringFamily::isIn( const char* str )
5114 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5116 for ( ; itSub != _subFams.end(); ++itSub )
5118 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5121 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5122 return itSub->_prefix.Length() + len;
5127 if ( !_strings.empty() )
5129 std::list< _AString >::iterator itStr = _strings.begin();
5130 bool firstEmpty = itStr->IsEmpty();
5133 for ( ; itStr != _strings.end(); ++itStr )
5135 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5138 len = itStr->Length();
5147 // check that object ID does not continue after len
5148 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5155 //================================================================================
5159 //================================================================================
5161 void _pyStringFamily::Print( int level )
5163 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5164 std::list< _AString >::iterator itStr = _strings.begin();
5165 for ( ; itStr != _strings.end(); ++itStr )
5166 cout << *itStr << " | ";
5168 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5169 for ( ; itSub != _subFams.end(); ++itSub )
5170 itSub->Print( level + 1 );
5172 cout << string( 70, '-' ) << endl;