1 // Copyright (C) 2007-2024 CEA, EDF, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Basics_OCCTVersion.hxx>
37 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
38 #if OCC_VERSION_LARGE < 0x07050000
39 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
42 #include "SMESH_Gen_i.hxx"
43 /* SALOME headers that include CORBA headers that include windows.h
44 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
45 * that declare methods named GetObject - to apply the same rules of GetObject renaming
46 * and thus to avoid mess with GetObject symbol on Windows */
48 #include <LDOMParser.hxx>
56 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient)
57 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient)
58 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient)
59 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject)
60 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject)
61 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject)
62 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject)
63 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject)
64 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject)
65 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject)
66 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject)
67 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis)
68 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis)
69 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis)
70 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis)
71 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis)
74 using SMESH::TPythonDump;
77 * \brief Container of commands into which the initial script is split.
78 * It also contains data corresponding to SMESH_Gen contents
80 static Handle(_pyGen) theGen;
82 static TCollection_AsciiString theEmptyString;
84 //#define DUMP_CONVERSION
86 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
87 #undef DUMP_CONVERSION
93 //================================================================================
95 * \brief Set of TCollection_AsciiString initialized by C array of C strings
97 //================================================================================
99 struct TStringSet: public set<TCollection_AsciiString>
102 * \brief Filling. The last string must be ""
104 void Insert(const char* names[]) {
105 for ( int i = 0; names[i][0] ; ++i )
106 insert( (char*) names[i] );
109 * \brief Check if a string is in
111 bool Contains(const TCollection_AsciiString& name ) {
112 return find( name ) != end();
116 //================================================================================
118 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
119 * Odd items of the C array are map keys, and even items are values
121 //================================================================================
123 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
126 * \brief Filling. The last string must be ""
128 void Insert(const char* names_values[]) {
129 for ( int i = 0; names_values[i][0] ; i += 2 )
130 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
133 * \brief Check if a string is in
135 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
136 map< _AString, _AString >::iterator it = find( name );
137 return it == end() ? "" : it->second;
141 //================================================================================
143 * \brief Returns a mesh by object
145 //================================================================================
147 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
151 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
152 return Handle(_pyMesh)::DownCast( obj );
153 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
154 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
155 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
156 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
158 return Handle(_pyMesh)();
161 //================================================================================
163 * \brief Check if objects used as args have been created by previous commands
165 //================================================================================
167 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
169 // either comment or erase a command including NotPublishedObjectName()
170 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
172 bool isResultPublished = false;
173 const int nbRes = cmd->GetNbResultValues();
174 for ( int i = 0; i < nbRes; i++ )
176 _pyID objID = cmd->GetResultValue( i+1 );
177 if ( cmd->IsStudyEntry( objID ))
178 isResultPublished = (! theGen->IsNotPublished( objID ));
179 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
181 if ( isResultPublished )
187 // check if an Object was created in the script
190 _pyID obj = cmd->GetObject();
191 if ( obj.Search( "print(" ) == 1 )
192 return; // print statement
194 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
195 // remove an accessor method
196 obj = _pyCommand( obj ).GetObject();
198 const bool isMethodCall = cmd->IsMethodCall();
199 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
201 comment = "not created Object";
202 theGen->ObjectCreationRemoved( obj );
204 // check if a command has not created args
205 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
207 const _pyID& arg = cmd->GetArg( iArg );
208 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
210 list< _pyID > idList = cmd->GetStudyEntries( arg );
211 list< _pyID >::iterator id = idList.begin();
212 for ( ; id != idList.end(); ++id )
213 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
215 comment += *id + " has not been yet created";
218 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
219 // comment += arg + " has not been yet created";
221 // treat result objects
222 const _pyID& result = cmd->GetResultValue();
223 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
225 list< _pyID > idList = cmd->GetStudyEntries( result );
226 list< _pyID >::iterator id = idList.begin();
227 for ( ; id != idList.end(); ++id )
229 if ( comment.IsEmpty() )
230 presentObjects.insert( *id );
232 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
234 if ( idList.empty() && cmd->IsID( result ))
235 presentObjects.insert( result );
237 // comment the command
238 if ( !comment.IsEmpty() )
241 cmd->GetString() += " ### ";
242 cmd->GetString() += comment;
246 //================================================================================
248 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
250 //================================================================================
252 void fixFunctorType( TCollection_AsciiString& Type,
253 TCollection_AsciiString& Compare,
254 TCollection_AsciiString& UnaryOp,
255 TCollection_AsciiString& BinaryOp )
257 // The problem is that dumps of old studies created using filters becomes invalid
258 // when new items are inserted in the enum SMESH::FunctorType since values
259 // of this enum are dumped as integer values.
260 // This function corrects enum values of old studies given as args (Type,Compare,...)
261 // We can find out how to correct them by value of BinaryOp which can have only two
262 // values: FT_Undefined or FT_LogicalNOT.
263 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
264 // where PythonDump appeared
265 // v 3.0.0: FT_Undefined == 25
266 // v 3.1.0: FT_Undefined == 26, new items:
268 // v 4.1.2: FT_Undefined == 27, new items:
269 // - FT_BelongToGenSurface = 17
270 // v 5.1.1: FT_Undefined == 32, new items:
271 // - FT_FreeNodes = 10
272 // - FT_FreeFaces = 11
273 // - FT_LinearOrQuadratic = 23
274 // - FT_GroupColor = 24
275 // - FT_ElemGeomType = 25
276 // v 5.1.5: FT_Undefined == 33, new items:
277 // - FT_CoplanarFaces = 26
278 // v 6.2.0: FT_Undefined == 39, new items:
279 // - FT_MaxElementLength2D = 8
280 // - FT_MaxElementLength3D = 9
281 // - FT_BareBorderVolume = 25
282 // - FT_BareBorderFace = 26
283 // - FT_OverConstrainedVolume = 27
284 // - FT_OverConstrainedFace = 28
285 // v 6.5.0: FT_Undefined == 43, new items:
286 // - FT_EqualNodes = 14
287 // - FT_EqualEdges = 15
288 // - FT_EqualFaces = 16
289 // - FT_EqualVolumes = 17
290 // v 6.6.0: FT_Undefined == 44, new items:
291 // - FT_BallDiameter = 37
292 // v 6.7.1: FT_Undefined == 45, new items:
293 // - FT_EntityType = 36
294 // v 7.3.0: FT_Undefined == 46, new items:
295 // - FT_ConnectedElements = 39
296 // v 7.6.0: FT_Undefined == 47, new items:
297 // - FT_BelongToMeshGroup = 22
298 // v 8.1.0: FT_Undefined == 48, new items:
299 // - FT_NodeConnectivityNumber= 22
300 // v 8.5.0: FT_Undefined == 49, new items:
301 // - FT_Deflection2D = 22
302 // v 9.3.0: FT_Undefined == 50, new items:
303 // - FT_Length3D = 22
304 // v 9.12.0: FT_Undefined == 51, new items:
305 // - FT_ScaledJacobian = 8
306 // v 9.12.0: FT_Undefined == 52, new items:
307 // - FT_Warping3D = 4
309 // It's necessary to continue recording this history and to fill
310 // undef2newItems (see below) accordingly.
312 typedef map< int, vector< int > > TUndef2newItems;
313 static TUndef2newItems undef2newItems;
314 if ( undef2newItems.empty() )
316 undef2newItems[ 26 ].push_back( 7 );
317 undef2newItems[ 27 ].push_back( 17 );
318 { int items[] = { 10, 11, 23, 24, 25 };
319 undef2newItems[ 32 ].assign( items, items+5 ); }
320 undef2newItems[ 33 ].push_back( 26 );
321 { int items[] = { 8, 9, 25, 26, 27, 28 };
322 undef2newItems[ 39 ].assign( items, items+6 ); }
323 { int items[] = { 14, 15, 16, 17 };
324 undef2newItems[ 43 ].assign( items, items+4 ); }
325 undef2newItems[ 44 ].push_back( 37 );
326 undef2newItems[ 45 ].push_back( 36 );
327 undef2newItems[ 46 ].push_back( 39 );
328 undef2newItems[ 47 ].push_back( 22 );
329 undef2newItems[ 48 ].push_back( 22 );
330 undef2newItems[ 49 ].push_back( 22 );
331 undef2newItems[ 50 ].push_back( 22 );
332 undef2newItems[ 51 ].push_back( 8 );
333 undef2newItems[ 52 ].push_back( 4 );
335 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
338 int iType = Type.IntegerValue();
339 int iCompare = Compare.IntegerValue();
340 int iUnaryOp = UnaryOp.IntegerValue();
341 int iBinaryOp = BinaryOp.IntegerValue();
343 // find out integer value of FT_Undefined at the moment of dump
344 int oldUndefined = iBinaryOp;
345 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
348 // apply history to args
349 TUndef2newItems::const_iterator undef_items =
350 undef2newItems.upper_bound( oldUndefined );
351 if ( undef_items != undef2newItems.end() )
353 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
354 for ( ; undef_items != undef2newItems.end(); ++undef_items )
356 const vector< int > & addedItems = undef_items->second;
357 for ( size_t i = 0; i < addedItems.size(); ++i )
358 for ( int iArg = 0; iArg < 4; ++iArg )
360 int& arg = *pArg[iArg];
361 if ( arg >= addedItems[i] )
365 Type = TCollection_AsciiString( iType );
366 Compare = TCollection_AsciiString( iCompare );
367 UnaryOp = TCollection_AsciiString( iUnaryOp );
368 BinaryOp = TCollection_AsciiString( iBinaryOp );
372 //================================================================================
374 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
375 * arguments of a given command by a list "[x,y,z]" if the list is accessible
378 //================================================================================
380 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
382 static TStringSet methodsAcceptingList;
383 if ( methodsAcceptingList.empty() ) {
384 const char * methodNames[] = {
385 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
386 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
387 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
388 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
389 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
390 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
391 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
392 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
393 "Translate","TranslateMakeGroups","TranslateMakeMesh",
394 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
395 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
396 ,"" }; // <- mark of the end
397 methodsAcceptingList.Insert( methodNames );
399 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
401 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
403 const _AString & arg = theCommand->GetArg( i );
404 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
405 arg.Search( "SMESH.DirStruct" ) == 1 )
407 Handle(_pyCommand) workCmd = new _pyCommand( arg );
408 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
410 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
412 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
414 _AString newArg = "[ ";
415 newArg += ( workCmd->GetArg( 1 ) + ", " +
416 workCmd->GetArg( 2 ) + ", " +
417 workCmd->GetArg( 3 ) + " ]");
418 theCommand->SetArg( i, newArg );
424 //================================================================================
426 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
427 * a list "[id1,id2]" if the list is an accessible type of argument.
429 //================================================================================
431 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
433 static TStringSet methodsAcceptingList;
434 if ( methodsAcceptingList.empty() ) {
435 const char * methodNames[] = {
436 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
437 "ExportCGNS","ExportGMF",
438 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
439 "ScaleMakeGroups","Scale","ScaleMakeMesh",
440 "FindCoincidentNodesOnPartBut","DoubleElements",
441 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
442 ,"" }; // <- mark of the end
443 methodsAcceptingList.Insert( methodNames );
445 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
447 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
449 _pyCommand argCmd( theCommand->GetArg( i ));
450 if ( argCmd.GetMethod() == "GetIDSource" &&
451 argCmd.GetNbArgs() == 2 )
453 theCommand->SetArg( i, argCmd.GetArg( 1 ));
459 bool _FilterArg( const _AString& theArg )
461 static std::list<_AString> filteredArgs;
462 static bool initialized = false;
463 if ( !initialized ) {
465 filteredArgs.push_back( "SMESH.MED_V2_1" );
466 filteredArgs.push_back( "SMESH.MED_V2_2" );
468 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
472 //================================================================================
474 * \brief Convert a python script using commands of smeshBuilder.py
475 * \param theScriptLines - Lines of the input script
476 * \param theEntry2AccessorMethod - returns method names to access to
477 * objects wrapped with python class
478 * \param theObjectNames - names of objects
479 * \param theRemovedObjIDs - entries of objects whose created commands were removed
480 * \param theHistoricalDump - true means to keep all commands, false means
481 * to exclude commands relating to objects removed from study
482 * \retval TCollection_AsciiString - Conversion result
484 //================================================================================
487 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
488 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
489 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
490 std::set< TCollection_AsciiString >& theRemovedObjIDs,
491 const bool theToKeepAllCommands)
493 std::list< TCollection_AsciiString >::iterator lineIt;
494 // process notebook variables
496 SMESH_NoteBook aNoteBook;
498 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
499 aNoteBook.AddCommand( *lineIt );
501 theScriptLines.clear();
503 aNoteBook.ReplaceVariables();
505 aNoteBook.GetResultLines( theScriptLines );
508 // convert to smeshBuilder.py API
510 theGen = new _pyGen( theEntry2AccessorMethod,
513 theToKeepAllCommands );
515 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
516 theGen->AddCommand( *lineIt );
518 theScriptLines.clear();
522 #ifdef DUMP_CONVERSION
523 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
526 // clean commands of removed objects depending on myIsPublished flag
527 theGen->ClearCommands();
529 // reorder commands after conversion
530 list< Handle(_pyCommand) >::iterator cmd;
533 orderChanges = false;
534 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
535 if ( (*cmd)->SetDependentCmdsAfter() )
537 } while ( orderChanges );
539 // concat commands back into a script
540 TCollection_AsciiString aPrevCmd;
541 set<_pyID> createdObjects;
542 createdObjects.insert( "smeshBuilder" );
543 createdObjects.insert( "smesh" );
544 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
546 #ifdef DUMP_CONVERSION
547 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
549 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
550 CheckObjectPresence( *cmd, createdObjects );
551 if ( !(*cmd)->IsEmpty() ) {
552 aPrevCmd = (*cmd)->GetString();
553 theScriptLines.push_back( aPrevCmd );
562 //================================================================================
564 * \brief _pyGen constructor
566 //================================================================================
568 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
569 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
570 std::set< TCollection_AsciiString >& theRemovedObjIDs,
571 const bool theToKeepAllCommands)
572 : _pyObject( new _pyCommand( "", 0 )),
574 myID2AccessorMethod( theEntry2AccessorMethod ),
575 myObjectNames( theObjectNames ),
576 myRemovedObjIDs( theRemovedObjIDs ),
578 myToKeepAllCommands( theToKeepAllCommands ),
579 myGeomIDNb(0), myGeomIDIndex(-1),
580 myShaperIDNb(0), myShaperIDIndex(-1)
582 // make that GetID() to return TPythonDump::SMESHGenName()
583 GetCreationCmd()->Clear();
584 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
585 GetCreationCmd()->GetString() += "=";
587 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
588 if (!theObjectNames.IsEmpty())
590 // find a GEOM (aPass == 0) and SHAPERSTUDY (aPass == 1) entries
591 for(int aPass = 0; aPass < 2; aPass++) {
593 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->
594 FindComponent(aPass == 0 ? "GEOM" : "SHAPERSTUDY");
595 if (geomComp->_is_nil()) continue;
596 CORBA::String_var entry = geomComp->GetID();
599 // find a SMESH entry
601 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n(theObjectNames);
602 for (; e2n.More() && smeshID.IsEmpty(); e2n.Next())
603 if (_pyCommand::IsStudyEntry(e2n.Key()))
606 // find 1st difference between smeshID and geomID
607 if (!geomID.IsEmpty() && !smeshID.IsEmpty())
608 for (int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i)
609 if (geomID.Value(i) != smeshID.Value(i))
612 myGeomIDNb = geomID.Value(i);
615 myShaperIDNb = geomID.Value(i);
623 //================================================================================
625 * \brief name of SMESH_Gen in smeshBuilder.py
627 //================================================================================
629 const char* _pyGen::AccessorMethod() const
631 return SMESH_2smeshpy::GenName();
634 //================================================================================
636 * \brief Convert a command using a specific converter
637 * \param theCommand - the command to convert
639 //================================================================================
641 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
643 // store theCommand in the sequence
644 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
646 Handle(_pyCommand) aCommand = myCommands.back();
647 #ifdef DUMP_CONVERSION
648 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
651 const _pyID& objID = aCommand->GetObject();
653 if ( objID.IsEmpty() )
656 // Prevent moving a command creating a sub-mesh to the end of the script
657 // if the sub-mesh is used in theCommand as argument
658 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
660 // PlaceSubmeshAfterItsCreation( aCommand );
663 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
664 StructToList( aCommand );
666 const TCollection_AsciiString& method = aCommand->GetMethod();
668 // not to erase _pySelfEraser's etc. used as args in some commands
670 #ifdef USE_STRING_FAMILY
671 std::list<_pyID> objIDs;
672 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
674 std::list<_pyID>::iterator objID = objIDs.begin();
675 for ( ; objID != objIDs.end(); ++objID )
677 Handle(_pyObject) obj = FindObject( *objID );
680 obj->AddArgCmd( aCommand );
681 //cout << objID << " found in " << theCommand << endl;
686 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
687 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
688 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
690 Handle(_pyObject) obj = FindObject( *id );
692 obj->AddArgCmd( aCommand );
697 // Find an object to process theCommand
700 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
702 this->Process( aCommand );
703 //addFilterUser( aCommand, theGen ); // protect filters from clearing
707 // SMESH_Mesh method?
708 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
709 if ( id_mesh != myMeshes.end() )
711 //id_mesh->second->AddProcessedCmd( aCommand );
713 // Wrap Export*() into try-except
714 if ( aCommand->MethodStartsFrom("Export"))
717 _AString indent = aCommand->GetIndentation();
718 _AString tryStr = indent + "try:";
719 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
720 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
721 _AString excStr = indent + "except:";
722 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
724 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
726 aCommand->GetString() = newCmd;
727 aCommand->SetOrderNb( ++myNbCommands );
728 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
729 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
730 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
732 // check for mesh editor object
733 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
734 _pyID editorID = aCommand->GetResultValue();
735 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
736 myMeshEditors.insert( make_pair( editorID, editor ));
739 // check for SubMesh objects
740 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
741 _pyID subMeshID = aCommand->GetResultValue();
742 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
743 AddObject( subMesh );
746 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
747 GetIDSourceToList( aCommand );
749 //addFilterUser( aCommand, theGen ); // protect filters from clearing
751 id_mesh->second->Process( aCommand );
752 id_mesh->second->AddProcessedCmd( aCommand );
756 // SMESH_MeshEditor method?
757 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
758 if ( id_editor != myMeshEditors.end() )
760 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
761 GetIDSourceToList( aCommand );
763 //addFilterUser( aCommand, theGen ); // protect filters from clearing
765 // some commands of SMESH_MeshEditor create meshes and groups
766 _pyID meshID, groups;
767 if ( method.Search("MakeMesh") != -1 )
768 meshID = aCommand->GetResultValue();
769 else if ( method == "MakeBoundaryMesh")
770 meshID = aCommand->GetResultValue(1);
771 else if ( method == "MakeBoundaryElements" || method == "MakeBoundaryOfEachElement" )
772 meshID = aCommand->GetResultValue(2);
774 if ( method.Search("MakeGroups") != -1 ||
775 method == "ExtrusionAlongPathX" ||
776 method == "ExtrusionAlongPathObjX" ||
777 method == "DoubleNodeGroupNew" ||
778 method == "DoubleNodeGroupsNew" ||
779 method == "DoubleNodeElemGroupNew" ||
780 method == "DoubleNodeElemGroupsNew" ||
781 method == "DoubleNodeElemGroup2New" ||
782 method == "DoubleNodeElemGroups2New" ||
783 method == "AffectedElemGroupsInRegion"
785 groups = aCommand->GetResultValue();
786 else if ( method == "MakeBoundaryMesh" )
787 groups = aCommand->GetResultValue(2);
788 else if ( method == "MakeBoundaryElements" || method == "MakeBoundaryOfEachElement" )
789 groups = aCommand->GetResultValue(3);
790 else if ( method == "Create0DElementsOnAllNodes" &&
791 aCommand->GetArg(2).Length() > 2 ) // group name != ''
792 groups = aCommand->GetResultValue();
794 id_editor->second->Process( aCommand );
795 id_editor->second->AddProcessedCmd( aCommand );
798 if ( !meshID.IsEmpty() &&
799 !myMeshes.count( meshID ) &&
800 aCommand->IsStudyEntry( meshID ))
802 _AString processedCommand = aCommand->GetString();
803 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
804 CheckObjectIsReCreated( mesh );
805 myMeshes.insert( make_pair( meshID, mesh ));
807 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
810 if ( !groups.IsEmpty() )
812 if ( !aCommand->IsStudyEntry( meshID ))
813 meshID = id_editor->second->GetMesh();
814 Handle(_pyMesh) mesh = myMeshes[ meshID ];
816 list< _pyID > idList = aCommand->GetStudyEntries( groups );
817 list< _pyID >::iterator grID = idList.begin();
818 for ( ; grID != idList.end(); ++grID )
819 if ( !myObjects.count( *grID ))
821 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
823 if ( !mesh.IsNull() ) mesh->AddGroup( group );
827 } // SMESH_MeshEditor methods
829 // SMESH_Hypothesis method?
830 Handle(_pyHypothesis) hyp = FindHyp( objID );
831 if ( !hyp.IsNull() && !hyp->IsAlgo() )
833 hyp->Process( aCommand );
834 hyp->AddProcessedCmd( aCommand );
838 // aFilterManager.CreateFilter() ?
839 if ( aCommand->GetMethod() == "CreateFilter" )
841 // Set a more human readable name to a filter
842 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
843 _pyID newID, filterID = aCommand->GetResultValue();
844 int pos = filterID.Search( "0x" );
846 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
848 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
851 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
852 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
854 // create _pySelfEraser for functors
855 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
856 functor->IgnoreOwnCalls(); // to erase if not used as an argument
857 AddObject( functor );
860 // other object method?
861 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
862 if ( id_obj != myObjects.end() ) {
863 id_obj->second->Process( aCommand );
864 id_obj->second->AddProcessedCmd( aCommand );
868 // Add access to a wrapped mesh
869 AddMeshAccessorMethod( aCommand );
871 // Add access to a wrapped algorithm
872 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
874 // PAL12227. PythonDump was not updated at proper time; result is
875 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
876 // TypeError: __init__() takes exactly 11 arguments (10 given)
877 const char wrongCommand[] = "SMESH.Filter.Criterion(";
878 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
880 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
881 // there must be 10 arguments, 5-th arg ThresholdID is missing,
882 const int wrongNbArgs = 9, missingArg = 5;
883 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
885 for ( int i = wrongNbArgs; i > missingArg; --i )
886 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
887 tmpCmd.SetArg( missingArg, "''");
888 aCommand->GetString().Trunc( beg - 1 );
889 aCommand->GetString() += tmpCmd.GetString();
892 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
894 // instead of "SMESH.Filter.Criterion(
895 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
896 // 1 2 3 4 5 6 7 8 9 10
897 // in order to avoid the problem of type mismatch of long and FunctorType
898 const TCollection_AsciiString
899 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
900 TCollection_AsciiString
901 Type = aCommand->GetArg(1), // long
902 Compare = aCommand->GetArg(2), // long
903 Threshold = aCommand->GetArg(3), // double
904 ThresholdStr = aCommand->GetArg(4), // string
905 ThresholdID = aCommand->GetArg(5), // string
906 UnaryOp = aCommand->GetArg(6), // long
907 BinaryOp = aCommand->GetArg(7), // long
908 Tolerance = aCommand->GetArg(8), // double
909 TypeOfElement = aCommand->GetArg(9), // ElementType
910 Precision = aCommand->GetArg(10); // long
911 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
912 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
913 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
914 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
915 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
917 if ( Compare == "SMESH.FT_EqualTo" )
920 aCommand->RemoveArgs();
921 aCommand->SetObject( SMESH_2smeshpy::GenName() );
922 aCommand->SetMethod( "GetCriterion" );
924 aCommand->SetArg( 1, TypeOfElement );
925 aCommand->SetArg( 2, Type );
926 aCommand->SetArg( 3, Compare );
928 if ( Threshold.IsIntegerValue() )
930 int iGeom = Threshold.IntegerValue();
931 if ( Type == "SMESH.FT_ElemGeomType" )
933 // set SMESH.GeometryType instead of a numerical Threshold
934 const int nbTypes = SMESH::Geom_LAST;
935 const char* types[] = {
936 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
937 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
938 "Geom_POLYHEDRA", "Geom_BALL" };
939 if ( -1 < iGeom && iGeom < nbTypes )
940 Threshold = SMESH + types[ iGeom ];
942 if (SALOME::VerbosityActivated())
944 // is types complete? (compilation failure means that enum GeometryType changed)
945 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
946 "Update names of GeometryType's!!!" );
949 if (Type == "SMESH.FT_EntityType")
951 // set SMESH.EntityType instead of a numerical Threshold
952 const int nbTypes = SMESH::Entity_Last;
953 const char* types[] = {
954 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
955 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
956 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
957 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
958 "Entity_Pyramid", "Entity_Quad_Pyramid",
959 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
960 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
961 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
962 if ( -1 < iGeom && iGeom < nbTypes )
963 Threshold = SMESH + types[ iGeom ];
965 if (SALOME::VerbosityActivated())
967 // is 'types' complete? (compilation failure means that enum EntityType changed)
968 static_assert( sizeof(types) / sizeof(const char*) == nbTypes,
969 "Update names of EntityType's!!!" );
973 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
974 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
975 else if ( ThresholdStr.Length() != 2 )
976 aCommand->SetArg( 4, ThresholdStr );
977 else if ( ThresholdID.Length() != 2 )
978 aCommand->SetArg( 4, ThresholdID );
980 aCommand->SetArg( 4, Threshold );
981 // find the last not default arg
983 if ( Tolerance == dfltTol ) {
985 if ( BinaryOp == dfltFunctor ) {
987 if ( UnaryOp == dfltFunctor )
991 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
992 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
993 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
994 if ( Precision != dfltPreci )
996 TCollection_AsciiString crit = aCommand->GetResultValue();
997 aCommand->GetString() += "; ";
998 aCommand->GetString() += crit + ".Precision = " + Precision;
1004 //================================================================================
1006 * \brief Convert the command or remember it for later conversion
1007 * \param theCommand - The python command calling a method of SMESH_Gen
1009 //================================================================================
1011 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
1013 // there are methods to convert:
1014 // CreateMesh( shape )
1015 // Concatenate( [mesh1, ...], ... )
1016 // CreateHypothesis( theHypType, theLibName )
1017 // Compute( mesh, geom )
1018 // Evaluate( mesh, geom )
1020 TCollection_AsciiString method = theCommand->GetMethod();
1022 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
1024 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1027 _pyID id = mesh->GetID(), comma("'");
1028 if ( myObjectNames.IsBound( id ))
1029 theCommand->SetArg( theCommand->GetNbArgs() + 1,
1030 comma + myObjectNames( id ) + comma);
1033 if ( method == "CreateMeshesFromUNV" ||
1034 method == "CreateMeshesFromSTL" ||
1035 method == "CreateDualMesh" ||
1036 method == "CopyMesh" ) // command result is a mesh
1038 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1042 if ( method == "CreateMeshesFromMED" ||
1043 method == "CreateMeshesFromCGNS" ||
1044 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1046 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1047 std::list< _pyID >::iterator meshID = meshIDs.begin();
1048 for ( ; meshID != meshIDs.end(); ++meshID )
1050 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1053 if ( method == "CreateMeshesFromGMF" )
1055 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1056 // CreateMeshesFromGMF( theFileName )
1057 _AString file = theCommand->GetArg(1);
1058 theCommand->RemoveArgs();
1059 theCommand->SetArg( 1, file );
1062 if ( method == "CopyMeshWithGeom" )
1064 std::list< _pyID > entries = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1065 Handle(_pyMesh) mesh = new _pyMesh( theCommand, entries.front() );
1069 // CreateHypothesis()
1070 if ( method == "CreateHypothesis" )
1072 // issue 199929, remove standard library name (default parameter)
1073 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1074 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1075 // keep the first argument
1076 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1077 theCommand->RemoveArgs();
1078 theCommand->SetArg( 1, arg );
1081 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1082 CheckObjectIsReCreated( hyp );
1083 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1088 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1089 if ( method == "Compute" )
1091 const _pyID& meshID = theCommand->GetArg( 1 );
1092 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1093 if ( id_mesh != myMeshes.end() ) {
1094 theCommand->SetObject( meshID );
1095 theCommand->RemoveArgs();
1096 id_mesh->second->Process( theCommand );
1097 id_mesh->second->AddProcessedCmd( theCommand );
1102 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1103 if ( method == "Evaluate" )
1105 const _pyID& meshID = theCommand->GetArg( 1 );
1106 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1107 if ( id_mesh != myMeshes.end() ) {
1108 theCommand->SetObject( meshID );
1109 _pyID geom = theCommand->GetArg( 2 );
1110 theCommand->RemoveArgs();
1111 theCommand->SetArg( 1, geom );
1112 id_mesh->second->AddProcessedCmd( theCommand );
1117 // objects erasing creation command if no more its commands invoked:
1118 // SMESH_Pattern, FilterManager
1119 if ( method == "GetPattern" ||
1120 method == "CreateFilterManager" ||
1121 method == "CreateMeasurements" )
1123 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1124 if ( !AddObject( obj ) )
1125 theCommand->Clear(); // already created
1127 // Concatenate( [mesh1, ...], ... )
1128 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1130 // OLD IDL: ( meshes, uniteGroups, toMerge, tol )
1131 // IDL: ( meshes, uniteGroups, toMerge, tol, meshToAppendTo )
1132 // PY: ( meshes, uniteGroups, toMerge, tol, allGroups=False, name="", meshToAppendTo=None )
1133 _pyID appendMesh = theCommand->GetArg( 5 );
1134 if ( method == "ConcatenateWithGroups" ) {
1135 theCommand->SetMethod( "Concatenate" );
1136 theCommand->SetArg( 5, "True" );
1139 theCommand->SetArg( 5, "False" );
1141 if ( !appendMesh.IsEmpty() && appendMesh != "None" )
1143 appendMesh.Insert( 1, "meshToAppendTo=" );
1144 theCommand->SetArg( theCommand->GetNbArgs() + 1, appendMesh );
1146 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1148 AddMeshAccessorMethod( theCommand );
1150 else if ( method == "SetName" ) // SetName(obj,name)
1152 // store theCommand as one of object commands to erase it along with the object
1153 const _pyID& objID = theCommand->GetArg( 1 );
1154 Handle(_pyObject) obj = FindObject( objID );
1155 if ( !obj.IsNull() )
1156 obj->AddProcessedCmd( theCommand );
1159 // Replace name of SMESH_Gen
1161 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1162 static TStringSet smeshpyMethods;
1163 if ( smeshpyMethods.empty() ) {
1164 const char * names[] =
1165 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1166 "GetPattern","GetSubShapesId",
1167 "" }; // <- mark of array end
1168 smeshpyMethods.Insert( names );
1170 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1171 // smeshgen.Method() --> smesh.Method()
1172 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1174 // smeshgen.Method() --> smesh.Method()
1175 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1178 //================================================================================
1180 * \brief Convert the remembered commands
1182 //================================================================================
1184 void _pyGen::Flush()
1186 // create an empty command
1187 myLastCommand = new _pyCommand();
1189 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1190 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1191 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1193 if ( IsToKeepAllCommands() ) // historical dump
1195 // set myIsPublished = true to all objects
1196 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1197 id_mesh->second->SetRemovedFromStudy( false );
1198 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1199 id_hyp->second->SetRemovedFromStudy( false );
1200 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1201 id_obj->second->SetRemovedFromStudy( false );
1205 // let hypotheses find referred objects in order to prevent clearing
1206 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1207 list< Handle(_pyMesh) > fatherMeshes;
1208 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1209 if ( !id_hyp->second.IsNull() )
1210 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1212 // set myIsPublished = false to all objects depending on
1213 // meshes built on a removed geometry
1214 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1215 if ( id_mesh->second->IsNotGeomPublished() )
1216 id_mesh->second->SetRemovedFromStudy( true );
1219 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1220 if ( ! id_mesh->second.IsNull() )
1221 id_mesh->second->Flush();
1224 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1225 if ( !id_hyp->second.IsNull() ) {
1226 id_hyp->second->Flush();
1227 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1228 if ( !id_hyp->second->IsWrapped() )
1229 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1232 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1233 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1234 for ( ; robj != myOrderedObjects.rend(); ++robj )
1235 if ( ! robj->IsNull() )
1237 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1238 for ( ; obj != myOrderedObjects.end(); ++obj )
1239 if ( ! obj->IsNull() )
1242 myLastCommand->SetOrderNb( ++myNbCommands );
1243 myCommands.push_back( myLastCommand );
1246 //================================================================================
1248 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1249 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1251 //================================================================================
1253 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) /*theCmdUsingSubmesh*/ ) const
1255 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1256 // for ( ; id_obj != myObjects.end(); ++id_obj )
1258 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1259 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1261 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1262 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1264 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1265 // list< _pyID >::iterator id = idList.begin();
1266 // for ( ; id != idList.end(); ++id )
1267 // if ( id_obj->first == *id )
1268 // // _pySubMesh::Process() does what we need
1269 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1274 //================================================================================
1276 * \brief Clean commands of removed objects depending on myIsPublished flag
1278 //================================================================================
1280 void _pyGen::ClearCommands()
1282 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1283 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1284 id_mesh->second->ClearCommands();
1286 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1287 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1288 if ( !id_hyp->second.IsNull() )
1289 id_hyp->second->ClearCommands();
1291 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1292 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1293 for ( ; robj != myOrderedObjects.rend(); ++robj )
1294 if ( ! robj->IsNull() )
1295 (*robj)->ClearCommands();
1296 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1297 for ( ; obj != myOrderedObjects.end(); ++obj )
1298 if ( ! obj->IsNull() )
1299 (*obj)->ClearCommands();
1302 //================================================================================
1304 * \brief Release mutual handles of objects
1306 //================================================================================
1310 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1311 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1312 id_mesh->second->Free();
1315 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1316 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1317 id_ed->second->Free();
1318 myMeshEditors.clear();
1320 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1321 for ( ; id_obj != myObjects.end(); ++id_obj )
1322 id_obj->second->Free();
1325 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1326 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1327 if ( !id_hyp->second.IsNull() )
1328 id_hyp->second->Free();
1331 myFile2ExportedMesh.clear();
1333 //myKeepAgrCmdsIDs.Print();
1336 //================================================================================
1338 * \brief Add access method to mesh that is an argument
1339 * \param theCmd - command to add access method
1340 * \retval bool - true if added
1342 //================================================================================
1344 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1347 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1348 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1349 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1355 //================================================================================
1357 * \brief Add access method to algo that is an object or an argument
1358 * \param theCmd - command to add access method
1359 * \retval bool - true if added
1361 //================================================================================
1363 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1366 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1367 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1368 if ( !id_hyp->second.IsNull() &&
1369 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1370 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1371 id_hyp->second->AccessorMethod() ))
1377 //================================================================================
1379 * \brief Find hypothesis by ID (entry)
1380 * \param theHypID - The hypothesis ID
1381 * \retval Handle(_pyHypothesis) - The found hypothesis
1383 //================================================================================
1385 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1387 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1388 if ( id_hyp != myHypos.end() &&
1389 !id_hyp->second.IsNull() &&
1390 theHypID == id_hyp->second->GetID() )
1391 return id_hyp->second;
1392 return Handle(_pyHypothesis)();
1395 //================================================================================
1397 * \brief Find algorithm able to create a hypothesis
1398 * \param theGeom - The shape ID the algorithm was created on
1399 * \param theMesh - The mesh ID that created the algorithm
1400 * \param theHypothesis - The hypothesis the algorithm should be able to create
1401 * \retval Handle(_pyHypothesis) - The found algo
1403 //================================================================================
1405 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1406 const Handle(_pyHypothesis)& theHypothesis )
1408 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1409 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1410 if ( !id_hyp->second.IsNull() &&
1411 id_hyp->second->IsAlgo() &&
1412 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1413 id_hyp->second->GetGeom() == theGeom &&
1414 id_hyp->second->GetMesh() == theMesh )
1415 return id_hyp->second;
1416 return Handle(_pyHypothesis)();
1419 //================================================================================
1421 * \brief Find subMesh by ID (entry)
1422 * \param theSubMeshID - The subMesh ID
1423 * \retval Handle(_pySubMesh) - The found subMesh
1425 //================================================================================
1427 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1429 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1430 if ( id_subMesh != myObjects.end() )
1431 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1432 return Handle(_pySubMesh)();
1436 //================================================================================
1438 * \brief Change order of commands in the script
1439 * \param theCmd1 - One command
1440 * \param theCmd2 - Another command
1442 //================================================================================
1444 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1446 list< Handle(_pyCommand) >::iterator pos1, pos2;
1447 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1448 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1449 myCommands.insert( pos1, theCmd2 );
1450 myCommands.insert( pos2, theCmd1 );
1451 myCommands.erase( pos1 );
1452 myCommands.erase( pos2 );
1454 int nb1 = theCmd1->GetOrderNb();
1455 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1456 theCmd2->SetOrderNb( nb1 );
1457 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1458 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1461 //================================================================================
1463 * \brief Set one command after the other
1464 * \param theCmd - Command to move
1465 * \param theAfterCmd - Command ater which to insert the first one
1467 //================================================================================
1469 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1471 setNeighbourCommand( theCmd, theAfterCmd, true );
1474 //================================================================================
1476 * \brief Set one command before the other
1477 * \param theCmd - Command to move
1478 * \param theBeforeCmd - Command before which to insert the first one
1480 //================================================================================
1482 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1484 setNeighbourCommand( theCmd, theBeforeCmd, false );
1487 //================================================================================
1489 * \brief Set one command before or after the other
1490 * \param theCmd - Command to move
1491 * \param theOtherCmd - Command ater or before which to insert the first one
1493 //================================================================================
1495 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1496 Handle(_pyCommand)& theOtherCmd,
1497 const bool theIsAfter )
1499 list< Handle(_pyCommand) >::iterator pos;
1500 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1501 myCommands.erase( pos );
1502 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1503 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1506 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1507 (*pos)->SetOrderNb( i++ );
1510 //================================================================================
1512 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1514 //================================================================================
1516 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1518 // No more needed after adding _pyObject::myArgCommands
1520 // const char filterPrefix[] = "aFilter0x";
1521 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1524 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1526 // const _AString & arg = theCommand->GetArg( i );
1527 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1528 // if ( arg.Search( filterPrefix ) != 1 )
1531 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1532 // if ( !filter.IsNull() )
1534 // filter->AddUser( user );
1535 // if ( !filter->GetNewID().IsEmpty() )
1536 // theCommand->SetArg( i, filter->GetNewID() );
1541 //================================================================================
1543 * \brief Set command be last in list of commands
1544 * \param theCmd - Command to be last
1546 //================================================================================
1548 Handle(_pyCommand)& _pyGen::GetLastCommand()
1550 return myLastCommand;
1553 //================================================================================
1555 * \brief Set method to access to object wrapped with python class
1556 * \param theID - The wrapped object entry
1557 * \param theMethod - The accessor method
1559 //================================================================================
1561 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1563 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1566 //================================================================================
1568 * \brief Generated new ID for object and assign with existing name
1569 * \param theID - ID of existing object
1571 //================================================================================
1573 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1578 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1580 while ( myObjectNames.IsBound( aNewID ) );
1582 if ( myObjectNames.IsBound( theID ) )
1583 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1585 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1589 //================================================================================
1591 * \brief Stores theObj in myObjects
1593 //================================================================================
1595 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1597 if ( theObj.IsNull() ) return false;
1599 CheckObjectIsReCreated( theObj );
1603 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1604 add = myMeshes.insert( make_pair( theObj->GetID(),
1605 Handle(_pyMesh)::DownCast( theObj ))).second;
1607 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1608 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1609 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1612 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1613 if ( add ) myOrderedObjects.push_back( theObj );
1618 //================================================================================
1620 * \brief Erases an existing object with the same ID. This method should be called
1621 * before storing theObj in _pyGen
1623 //================================================================================
1625 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1627 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1630 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1631 Handle(_pyObject) existing;
1633 existing = FindHyp( theObj->GetID() );
1635 existing = FindObject( theObj->GetID() );
1636 if ( !existing.IsNull() && existing != theObj )
1638 existing->SetRemovedFromStudy( true );
1639 existing->ClearCommands();
1642 if ( myHypos.count( theObj->GetID() ))
1643 myHypos.erase( theObj->GetID() );
1645 else if ( myMeshes.count( theObj->GetID() ))
1647 myMeshes.erase( theObj->GetID() );
1649 else if ( myObjects.count( theObj->GetID() ))
1651 myObjects.erase( theObj->GetID() );
1656 //================================================================================
1658 * \brief Re-register an object with other ID to make it Process() commands of
1659 * other object having this ID
1661 //================================================================================
1663 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1665 if ( theObj.IsNull() ) return;
1667 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1668 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1670 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1671 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1674 myObjects.insert( make_pair( theID, theObj ));
1677 //================================================================================
1679 * \brief Finds a _pyObject by ID
1681 //================================================================================
1683 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1686 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1687 if ( id_obj != myObjects.end() )
1688 return id_obj->second;
1691 _pyGen* me = const_cast< _pyGen* >( this );
1692 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1693 if ( id_obj != myMeshes.end() )
1694 return id_obj->second;
1697 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1698 // if ( id_obj != myMeshEditors.end() )
1699 // return id_obj->second;
1701 return Handle(_pyObject)();
1704 //================================================================================
1706 * \brief Check if a study entry is under GEOM component
1708 //================================================================================
1710 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1712 bool isGeom = myGeomIDNb && myGeomIDIndex <= theObjID.Length() &&
1713 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb;
1714 bool isShaper = myShaperIDNb && myShaperIDIndex <= theObjID.Length() &&
1715 int( theObjID.Value( myShaperIDIndex )) == myShaperIDNb;
1716 return ((isGeom || isShaper) && _pyCommand::IsStudyEntry( theObjID ));
1719 //================================================================================
1721 * \brief Returns true if an object is not present in a study
1723 //================================================================================
1725 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1727 if ( theObjID.IsEmpty() ) return false;
1729 if ( myObjectNames.IsBound( theObjID ))
1730 return false; // SMESH object is in study
1732 // either the SMESH object is not in study or it is a GEOM object
1733 if ( IsGeomObject( theObjID ))
1735 SALOMEDS::SObject_wrap so = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( theObjID.ToCString() );
1736 if ( so->_is_nil() ) return true;
1737 CORBA::Object_var obj = so->GetObject();
1738 return CORBA::is_nil( obj );
1740 return true; // SMESH object not in study
1743 //================================================================================
1745 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1746 * this object is not dumped
1747 * \param [in] theObjID - entry of the object whose creation command was eliminated
1749 //================================================================================
1751 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1753 myRemovedObjIDs.insert( theObjID );
1756 //================================================================================
1758 * \brief Return reader of hypotheses of plugins
1760 //================================================================================
1762 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1764 if (myHypReader.IsNull() )
1765 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1771 //================================================================================
1773 * \brief Mesh created by SMESH_Gen
1775 //================================================================================
1777 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1778 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1780 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1781 myGeomNotInStudy = true;
1783 // convert my creation command --> smeshpy.Mesh(...)
1784 Handle(_pyCommand) creationCmd = GetCreationCmd();
1785 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1786 creationCmd->SetMethod( "Mesh" );
1787 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1790 //================================================================================
1792 * \brief Mesh created by SMESH_MeshEditor
1794 //================================================================================
1796 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1797 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1799 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1801 // this mesh depends on the exported mesh
1802 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1803 if ( !file.IsEmpty() )
1805 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1806 addFatherMesh( exportData.myMesh );
1807 if ( !exportData.myLastComputeCmd.IsNull() )
1809 // restore cleared Compute() by which the exported mesh was generated
1810 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1811 // protect that Compute() cmd from clearing
1812 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1813 exportData.myMesh->myLastComputeCmd.Nullify();
1817 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1819 // this mesh depends on concatenated meshes
1820 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1821 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1822 list< _pyID >::iterator meshID = idList.begin();
1823 for ( ; meshID != idList.end(); ++meshID )
1824 addFatherMesh( *meshID );
1826 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1828 // this mesh depends on a copied IdSource
1829 const _pyID& objID = theCreationCmd->GetArg( 1 );
1830 addFatherMesh( objID );
1832 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1833 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1834 theCreationCmd->GetMethod() == "MakeBoundaryElements" ||
1835 theCreationCmd->GetMethod() == "MakeBoundaryOfEachElement" )
1837 // this mesh depends on a source mesh
1838 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1839 const _pyID& meshID = theCreationCmd->GetObject();
1840 addFatherMesh( meshID );
1843 // convert my creation command
1844 Handle(_pyCommand) creationCmd = GetCreationCmd();
1845 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1846 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1849 //================================================================================
1851 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1852 * \param theCommand - Engine method called for this mesh
1854 //================================================================================
1856 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1858 // some methods of SMESH_Mesh interface need special conversion
1859 // to methods of Mesh python class
1861 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1862 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1863 // 2. AddHypothesis(geom, hyp)
1864 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1865 // 3. CreateGroupFromGEOM(type, name, grp)
1866 // --> in Mesh.Group(grp, name="")
1867 // 4. ExportToMED(f, auto_groups, version)
1868 // --> in Mesh.ExportMED( f, auto_groups, version )
1871 const TCollection_AsciiString& method = theCommand->GetMethod();
1872 // ----------------------------------------------------------------------
1873 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1875 if ( !theGen->IsToKeepAllCommands() ) // !historical
1877 list< Handle(_pyHypothesis) >::iterator hyp;
1878 if ( !myLastComputeCmd.IsNull() )
1880 // check if the previously computed mesh has been edited,
1881 // if so then we do not clear the previous Compute()
1882 bool toClear = true;
1883 if ( myLastComputeCmd->GetMethod() == "Compute" )
1885 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1886 for ( ; e != myEditors.end() && toClear; ++e )
1888 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1889 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1890 if ( cmd != cmds.rend() &&
1891 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1897 // clear hyp commands called before myLastComputeCmd
1898 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1899 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1901 myLastComputeCmd->Clear();
1904 myLastComputeCmd = theCommand;
1906 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1907 (*hyp)->MeshComputed( myLastComputeCmd );
1911 // ----------------------------------------------------------------------
1912 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1914 if ( !theGen->IsToKeepAllCommands() ) // !historical
1917 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1918 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1919 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1921 if ( !myLastComputeCmd.IsNull() )
1923 list< Handle(_pyHypothesis) >::iterator hyp;
1924 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1925 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1927 myLastComputeCmd->Clear();
1930 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1931 for ( ; e != myEditors.end(); ++e )
1933 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1934 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1935 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1936 if ( !(*cmd)->IsEmpty() )
1938 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1942 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1945 // ----------------------------------------------------------------------
1946 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1947 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1948 if ( !subMesh.IsNull() ) {
1949 subMesh->SetCreator( this );
1950 mySubmeshes.push_back( subMesh );
1953 // ----------------------------------------------------------------------
1954 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1955 theCommand->Clear();
1957 // ----------------------------------------------------------------------
1958 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1959 myAddHypCmds.push_back( theCommand );
1961 const _pyID& hypID = theCommand->GetArg( 2 );
1962 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1963 if ( !hyp.IsNull() ) {
1964 myHypos.push_back( hyp );
1965 if ( hyp->GetMesh().IsEmpty() )
1966 hyp->SetMesh( this->GetID() );
1969 // ----------------------------------------------------------------------
1970 else if ( method == "CreateGroup" ||
1971 method == "CreateGroupFromGEOM" ||
1972 method == "CreateGroupFromFilter" ||
1973 method == "CreateDimGroup" )
1975 Handle(_pyGroup) group = new _pyGroup( theCommand );
1976 myGroups.push_back( group );
1977 theGen->AddObject( group );
1979 // ----------------------------------------------------------------------
1980 // update list of groups
1981 else if ( method == "GetGroups" )
1983 bool allGroupsRemoved = true;
1984 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1985 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1986 list< _pyID >::iterator grID = idList.begin();
1987 const size_t nbGroupsBefore = myGroups.size();
1988 Handle(_pyObject) obj;
1989 for ( ; grID != idList.end(); ++grID )
1991 obj = theGen->FindObject( *grID );
1994 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1995 theGen->AddObject( group );
1996 myGroups.push_back( group );
1999 if ( !obj->CanClear() )
2000 allGroupsRemoved = false;
2002 if ( nbGroupsBefore == myGroups.size() && !obj.IsNull() ) // no new _pyGroup created
2003 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
2005 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
2007 // check if the preceding command is Compute();
2008 // if GetGroups() is just after Compute(), this can mean that the groups
2009 // were created by some algorithm and hence Compute() should not be discarded
2010 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
2011 std::list< Handle(_pyCommand) >::reverse_iterator cmd = cmdList.rbegin();
2012 while ( (*cmd)->GetMethod() == "GetGroups" )
2014 if ( myLastComputeCmd == (*cmd))
2015 // protect last Compute() from clearing by the next Compute()
2016 myLastComputeCmd.Nullify();
2019 // ----------------------------------------------------------------------
2020 // notify a group about full removal
2021 else if ( method == "RemoveGroupWithContents" ||
2022 method == "RemoveGroup")
2024 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
2025 const _pyID groupID = theCommand->GetArg( 1 );
2026 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
2027 if ( !grp.IsNull() )
2029 if ( method == "RemoveGroupWithContents" )
2030 grp->RemovedWithContents();
2031 // to clear RemoveGroup() if the group creation is cleared
2032 grp->AddProcessedCmd( theCommand );
2036 // ----------------------------------------------------------------------
2037 else if ( theCommand->MethodStartsFrom( "Export" ))
2039 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
2040 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
2041 method == "ExportMED" )
2043 theCommand->SetMethod( "ExportMED" );
2044 // filter out deprecated version parameter
2045 vector< _AString > args;
2046 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2047 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2048 args.push_back( theCommand->GetArg( i ) );
2050 theCommand->RemoveArgs();
2051 for ( unsigned int i = 0; i < args.size(); i++ )
2052 theCommand->SetArg( i+1, args[i] );
2053 if ( theCommand->GetNbArgs() == 4 )
2055 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2056 _AString autoDimension = theCommand->GetArg( 4 );
2057 theCommand->SetArg( 4, "None" );
2058 theCommand->SetArg( 5, autoDimension );
2061 else if ( method == "ExportCGNS" )
2062 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2063 _pyID partID = theCommand->GetArg( 1 );
2064 int nbArgs = theCommand->GetNbArgs();
2065 for ( int i = 2; i <= nbArgs; ++i )
2066 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2067 theCommand->SetArg( nbArgs, partID );
2069 else if ( method == "ExportGMF" )
2070 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2071 _pyID partID = theCommand->GetArg( 1 );
2072 _AString file = theCommand->GetArg( 2 );
2073 theCommand->RemoveArgs();
2074 theCommand->SetArg( 1, file );
2075 theCommand->SetArg( 2, partID );
2077 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2078 { // ExportPartTo*(part, ...) -> Export*(..., part)
2080 // remove "PartTo" from the method
2081 TCollection_AsciiString newMethod = method;
2082 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2083 theCommand->SetMethod( newMethod );
2084 // replace version parameter by minor
2085 std::list< _AString > args;
2086 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2087 if ( _FilterArg( theCommand->GetArg( i )))
2088 args.push_back( "minor=0");
2090 args.push_back( theCommand->GetArg( i ));
2092 // check the 1st arg meshPart, it must be SMESH_IDSource
2093 _AString meshPart = args.front();
2094 if ( _pyCommand::IsStudyEntry( meshPart ) ||
2095 meshPart.Search( "Filter" ) > 0 ||
2096 meshPart.Search( "GetIDSource" ) > 0 ||
2097 meshPart.Search( "meshPart" ) > 0 )
2099 // set the 1st arg meshPart
2100 // - to 5th place for ExportMED command
2101 // - to last place for the rest commands
2102 std::list< _AString >::iterator newPos = args.end();
2103 if ( newMethod == "ExportMED" )
2104 std::advance( newPos = args.begin(), 5 );
2105 args.splice( newPos, args, args.begin() );
2107 std::list< _AString >::iterator a = args.begin();
2108 for ( unsigned int i = 1; a != args.end(); ++i, ++a )
2109 theCommand->SetArg( i, *a );
2111 // remember file name
2112 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2113 ExportedMeshData( this, myLastComputeCmd ));
2115 // ----------------------------------------------------------------------
2116 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2118 _pyID hypID = theCommand->GetArg( 2 );
2119 _pyID geomID = theCommand->GetArg( 1 );
2120 bool isLocal = ( geomID != GetGeom() );
2122 // check if this mesh still has corresponding addition command
2123 Handle(_pyCommand) addCmd;
2124 list< Handle(_pyCommand) >::iterator cmd;
2125 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2126 for ( int i = 0; i < 2; ++i )
2128 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2129 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2131 bool sameHyp = true;
2132 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2133 sameHyp = false; // other hyp
2134 if ( (*cmd)->GetNbArgs() == 2 &&
2135 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2136 sameHyp = false; // other geom
2137 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2138 sameHyp = false; // other geom
2142 cmd = addHypCmds.erase( cmd );
2143 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2145 theCommand->Clear();
2149 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2150 addCmd->RemoveArgs();
2151 addCmd->SetArg( 1, hypID );
2153 addCmd->SetArg( 2, geomID );
2162 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2163 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2164 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2165 _pyID geom = theCommand->GetArg( 1 );
2166 theCommand->RemoveArgs();
2167 theCommand->SetArg( 1, hypID );
2168 if ( geom != GetGeom() )
2169 theCommand->SetArg( 2, geom );
2171 // remove hyp from myHypos
2172 myHypos.remove( hyp );
2174 // check for SubMesh order commands
2175 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2177 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2178 // by GetMeshOrder() and SetMeshOrder(), since by default GetSubMesh()
2179 // commands are moved at the end of the script
2180 TCollection_AsciiString subIDs =
2181 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2182 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2183 list< _pyID >::iterator subID = idList.begin();
2184 for ( ; subID != idList.end(); ++subID )
2186 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2187 if ( !subMesh.IsNull() )
2188 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2191 // add accessor method if necessary
2194 if ( NeedMeshAccess( theCommand ))
2195 // apply theCommand to the mesh wrapped by smeshpy mesh
2196 AddMeshAccess( theCommand );
2200 //================================================================================
2202 * \brief Return True if addition of accesor method is needed
2204 //================================================================================
2206 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2208 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2209 // so no conversion is needed for them at all:
2210 static TStringSet sameMethods;
2211 if ( sameMethods.empty() ) {
2212 const char * names[] =
2213 { "ExportDAT","ExportUNV","ExportSTL", "RemoveGroup","RemoveGroupWithContents",
2214 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2215 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2216 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2217 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2218 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2219 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2220 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2221 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2222 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2223 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2224 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2225 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2226 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder",
2228 ,"" }; // <- mark of end
2229 sameMethods.Insert( names );
2232 return !sameMethods.Contains( theCommand->GetMethod() );
2235 //================================================================================
2237 * \brief Convert creation and addition of all algos and hypos
2239 //================================================================================
2241 void _pyMesh::Flush()
2244 // get the meshes this mesh depends on via hypotheses
2245 list< Handle(_pyMesh) > fatherMeshes;
2246 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2247 for ( ; hyp != myHypos.end(); ++hyp )
2248 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2249 myGeomNotInStudy = true;
2251 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2252 for ( ; m != fatherMeshes.end(); ++m )
2253 addFatherMesh( *m );
2254 // if ( removedGeom )
2255 // SetRemovedFromStudy(); // as referred geometry not in study
2257 if ( myGeomNotInStudy )
2260 list < Handle(_pyCommand) >::iterator cmd;
2262 // try to convert algo addition like this:
2263 // mesh.AddHypothesis( geom, ALGO ) --> ALGO = mesh.Algo()
2264 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2266 Handle(_pyCommand) addCmd = *cmd;
2268 _pyID algoID = addCmd->GetArg( 2 );
2269 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2270 if ( algo.IsNull() || !algo->IsAlgo() )
2273 // check and create new algorithm instance if it is already wrapped
2274 if ( algo->IsWrapped() ) {
2275 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2276 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2277 TCollection_AsciiString( " = " ) + theGen->GetID() +
2278 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2279 TCollection_AsciiString( "\" )" );
2281 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2282 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2283 if ( !newAlgo.IsNull() ) {
2284 newAlgo->Assign( algo, this->GetID() );
2285 newAlgo->SetCreationCmd( newCmd );
2287 // set algorithm creation
2288 theGen->SetCommandBefore( newCmd, addCmd );
2289 myHypos.push_back( newAlgo );
2290 if ( !myLastComputeCmd.IsNull() &&
2291 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2292 newAlgo->MeshComputed( myLastComputeCmd );
2297 _pyID geom = addCmd->GetArg( 1 );
2298 bool isLocalAlgo = ( geom != GetGeom() );
2301 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2303 // wrapped algo is created after mesh creation
2304 GetCreationCmd()->AddDependantCmd( addCmd );
2306 if ( isLocalAlgo ) {
2307 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2308 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2309 TCollection_AsciiString( "geom=" ) + geom );
2310 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2311 list < Handle(_pySubMesh) >::iterator smIt;
2312 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2313 Handle(_pySubMesh) subMesh = *smIt;
2314 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2315 if ( geom == subCmd->GetArg( 1 )) {
2316 subCmd->SetObject( algo->GetID() );
2317 subCmd->RemoveArgs();
2318 subMesh->SetCreator( algo );
2323 else // KO - ALGO was already created
2325 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2326 addCmd->RemoveArgs();
2327 addCmd->SetArg( 1, algoID );
2329 addCmd->SetArg( 2, geom );
2330 myNotConvertedAddHypCmds.push_back( addCmd );
2334 // try to convert hypo addition like this:
2335 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2336 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2338 Handle(_pyCommand) addCmd = *cmd;
2339 _pyID hypID = addCmd->GetArg( 2 );
2340 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2341 if ( hyp.IsNull() || hyp->IsAlgo() )
2343 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2345 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2346 _pyID geom = addCmd->GetArg( 1 );
2347 addCmd->RemoveArgs();
2348 addCmd->SetArg( 1, hypID );
2349 if ( geom != GetGeom() )
2350 addCmd->SetArg( 2, geom );
2351 myNotConvertedAddHypCmds.push_back( addCmd );
2355 myAddHypCmds.clear();
2356 mySubmeshes.clear();
2359 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2360 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2364 //================================================================================
2366 * \brief Sets myIsPublished of me and of all objects depending on me.
2368 //================================================================================
2370 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2372 _pyObject::SetRemovedFromStudy(isRemoved);
2374 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2375 for ( ; sm != mySubmeshes.end(); ++sm )
2376 (*sm)->SetRemovedFromStudy(isRemoved);
2378 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2379 for ( ; gr != myGroups.end(); ++gr )
2380 (*gr)->SetRemovedFromStudy(isRemoved);
2382 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2383 for ( ; m != myChildMeshes.end(); ++m )
2384 (*m)->SetRemovedFromStudy(isRemoved);
2386 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2387 for ( ; e != myEditors.end(); ++e )
2388 (*e)->SetRemovedFromStudy(isRemoved);
2391 //================================================================================
2393 * \brief Return true if none of myChildMeshes is in study
2395 //================================================================================
2397 bool _pyMesh::CanClear()
2402 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2403 for ( ; m != myChildMeshes.end(); ++m )
2404 if ( !(*m)->CanClear() )
2410 //================================================================================
2412 * \brief Clear my commands and commands of mesh editor
2414 //================================================================================
2416 void _pyMesh::ClearCommands()
2422 // mark all sub-objects as not removed, except child meshes
2423 list< Handle(_pyMesh) > children;
2424 children.swap( myChildMeshes );
2425 SetRemovedFromStudy( false );
2426 children.swap( myChildMeshes );
2430 _pyObject::ClearCommands();
2432 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2433 for ( ; sm != mySubmeshes.end(); ++sm )
2434 (*sm)->ClearCommands();
2436 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2437 for ( ; gr != myGroups.end(); ++gr )
2438 (*gr)->ClearCommands();
2440 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2441 for ( ; e != myEditors.end(); ++e )
2442 (*e)->ClearCommands();
2445 //================================================================================
2447 * \brief Add a father mesh by ID
2449 //================================================================================
2451 void _pyMesh::addFatherMesh( const _pyID& meshID )
2453 if ( !meshID.IsEmpty() && meshID != GetID() )
2454 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2457 //================================================================================
2459 * \brief Add a father mesh
2461 //================================================================================
2463 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2465 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2467 //myFatherMeshes.push_back( mesh );
2468 mesh->myChildMeshes.push_back( this );
2470 // protect last Compute() from clearing by the next Compute()
2471 mesh->myLastComputeCmd.Nullify();
2475 //================================================================================
2477 * \brief MeshEditor convert its commands to ones of mesh
2479 //================================================================================
2481 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2482 _pyObject( theCreationCmd )
2484 myMesh = theCreationCmd->GetObject();
2485 myCreationCmdStr = theCreationCmd->GetString();
2486 theCreationCmd->Clear();
2488 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2489 if ( !mesh.IsNull() )
2490 mesh->AddEditor( this );
2493 //================================================================================
2495 * \brief convert its commands to ones of mesh
2497 //================================================================================
2499 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2501 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2502 // commands calling these methods are converted to calls of Mesh methods without
2503 // additional modifs, only object is changed from MeshEditor to Mesh.
2504 static TStringSet sameMethods;
2505 if ( sameMethods.empty() ) {
2506 const char * names[] = {
2507 "RemoveElements","RemoveNodes","RemoveOrphanNodes","RemoveNodeWithReconnection",
2508 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2509 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces","AddNodeOnSegment",
2510 "MoveNode", "MoveClosestNodeToPoint","InverseDiag","DeleteDiag","AddNodeOnFace",
2511 "Reorient","ReorientObject","Reorient2DBy3D","Reorient2DByNeighbours",
2512 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2513 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2514 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2515 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2516 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2517 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2518 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2519 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2520 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject","Offset",
2521 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2522 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2523 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2524 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2525 "GetLastCreatedElems", "FaceGroupsSeparatedByEdges",
2526 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2527 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2528 "MakeBoundaryElements", "MakeBoundaryOfEachElement", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2529 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2530 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup","AffectedElemGroupsInRegion",
2531 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2532 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2533 ,"" }; // <- mark of the end
2534 sameMethods.Insert( names );
2537 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2538 TStringMap diffMethods;
2539 if ( diffMethods.empty() ) {
2540 const char * orig2newName[] = {
2541 // original name --------------> new name
2542 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2543 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2544 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2545 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2546 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2547 ""};// <- mark of the end
2548 diffMethods.Insert( orig2newName );
2551 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2552 // only by last two arguments
2553 static TStringSet diffLastTwoArgsMethods;
2554 if (diffLastTwoArgsMethods.empty() ) {
2555 const char * names[] = {
2556 "MirrorMakeGroups","MirrorObjectMakeGroups",
2557 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2558 "RotateMakeGroups","RotateObjectMakeGroups",
2559 ""};// <- mark of the end
2560 diffLastTwoArgsMethods.Insert( names );
2563 // only a method name is to change?
2564 const TCollection_AsciiString & method = theCommand->GetMethod();
2565 bool isPyMeshMethod = sameMethods.Contains( method );
2566 if ( !isPyMeshMethod )
2568 TCollection_AsciiString newMethod = diffMethods.Value( method );
2569 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2570 theCommand->SetMethod( newMethod );
2572 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2573 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2575 isPyMeshMethod = true;
2576 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2577 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2580 if ( !isPyMeshMethod )
2582 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2583 // functions with the flag "theMakeGroups = True" like:
2584 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2585 int pos = method.Search("MakeGroups");
2588 isPyMeshMethod = true;
2589 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2590 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2592 // 1. Remove "MakeGroups" from the Command
2593 TCollection_AsciiString aMethod = theCommand->GetMethod();
2594 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2597 pos = pos-2; //Remove "0D" from the Command too
2598 aMethod.Trunc(pos-1);
2599 theCommand->SetMethod(aMethod);
2601 // 2. And add last "True" argument(s)
2602 while(nbArgsToAdd--)
2603 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2604 if( is0DmethId || is0DmethObj )
2605 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2609 // ExtrusionSweep0D() -> ExtrusionSweep()
2610 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2611 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2612 method == "ExtrusionSweepObject0D" ))
2614 isPyMeshMethod = true;
2615 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2616 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2617 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2620 // DoubleNode...New(...) -> DoubleNode...(...,True)
2621 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2622 method == "DoubleNodeElemGroupsNew" ||
2623 method == "DoubleNodeGroupNew" ||
2624 method == "DoubleNodeGroupsNew" ||
2625 method == "DoubleNodeElemGroup2New" ||
2626 method == "DoubleNodeElemGroups2New"))
2628 isPyMeshMethod = true;
2629 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2630 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2631 if ( excessLen == 3 )
2633 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2635 else if ( theCommand->GetArg(4) == "0" ||
2636 theCommand->GetArg(5) == "0" )
2638 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2639 // Group = DoubleNodeGroup2New(,,,False, True)
2640 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2641 theCommand->SetResultValue( groupID );
2644 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2645 // FindElementsByPoint(x, y, z, elementType, meshPart)
2646 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2648 isPyMeshMethod = true;
2649 theCommand->SetMethod( "FindElementsByPoint" );
2650 // make the 1st arg be the last one
2651 _pyID partID = theCommand->GetArg( 1 );
2652 int nbArgs = theCommand->GetNbArgs();
2653 for ( int i = 2; i <= nbArgs; ++i )
2654 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2655 theCommand->SetArg( nbArgs, partID );
2657 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2658 if ( !isPyMeshMethod && method == "Reorient2D" )
2660 isPyMeshMethod = true;
2661 _AString mesh = theCommand->GetArg( 1 );
2662 _AString dir = theCommand->GetArg( 2 );
2663 _AString face = theCommand->GetArg( 3 );
2664 _AString point = theCommand->GetArg( 4 );
2665 theCommand->RemoveArgs();
2666 theCommand->SetArg( 1, mesh );
2667 theCommand->SetArg( 2, dir );
2668 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2669 theCommand->SetArg( 3, point );
2671 theCommand->SetArg( 3, face );
2674 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2676 isPyMeshMethod = true;
2677 int crit_arg = theCommand->GetNbArgs();
2678 const _AString& crit = theCommand->GetArg(crit_arg);
2679 if (crit.Search("MaxElementLength2D") != -1)
2680 theCommand->SetArg(crit_arg, "");
2683 if ( isPyMeshMethod )
2685 theCommand->SetObject( myMesh );
2689 // editor creation command is needed only if any editor function is called
2690 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2691 if ( !myCreationCmdStr.IsEmpty() ) {
2692 GetCreationCmd()->GetString() = myCreationCmdStr;
2693 myCreationCmdStr.Clear();
2698 //================================================================================
2700 * \brief Return true if my mesh can be removed
2702 //================================================================================
2704 bool _pyMeshEditor::CanClear()
2706 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2707 return mesh.IsNull() ? true : mesh->CanClear();
2710 //================================================================================
2712 * \brief _pyHypothesis constructor
2713 * \param theCreationCmd -
2715 //================================================================================
2717 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2718 _pyObject( theCreationCmd ), myCurCrMethod(0)
2720 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2723 //================================================================================
2725 * \brief Creates algorithm or hypothesis
2726 * \param theCreationCmd - The engine command creating a hypothesis
2727 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2729 //================================================================================
2731 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2733 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2734 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2736 Handle(_pyHypothesis) hyp, algo;
2739 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2740 if ( hypTypeQuoted.IsEmpty() )
2743 TCollection_AsciiString hypType =
2744 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2746 algo = new _pyAlgorithm( theCreationCmd );
2747 hyp = new _pyHypothesis( theCreationCmd );
2749 if ( hypType == "NumberOfSegments" ) {
2750 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2751 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2752 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2753 hyp->AddArgMethod( "SetNumberOfSegments" );
2754 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2755 hyp->AddArgMethod( "SetScaleFactor" );
2756 hyp->AddArgMethod( "SetReversedEdges" );
2757 // same for ""CompositeSegment_1D:
2758 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2759 hyp->AddArgMethod( "SetNumberOfSegments" );
2760 hyp->AddArgMethod( "SetScaleFactor" );
2761 hyp->AddArgMethod( "SetReversedEdges" );
2763 else if ( hypType == "SegmentLengthAroundVertex" ) {
2764 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2765 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2766 hyp->AddArgMethod( "SetLength" );
2767 // same for ""CompositeSegment_1D:
2768 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2769 hyp->AddArgMethod( "SetLength" );
2771 else if ( hypType == "LayerDistribution2D" ) {
2772 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2773 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2775 else if ( hypType == "LayerDistribution" ) {
2776 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2777 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2779 else if ( hypType == "CartesianParameters3D" ) {
2780 hyp = new _pyComplexParamHypo( theCreationCmd );
2781 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2782 for ( int iArg = 0; iArg < 4; ++iArg )
2783 hyp->setCreationArg( iArg+1, "[]");
2784 hyp->AddAccumulativeMethod( "SetGrid" );
2785 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2789 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2792 return algo->IsValid() ? algo : hyp;
2795 //================================================================================
2797 * \brief Returns true if addition of this hypothesis to a given mesh can be
2798 * wrapped into hypothesis creation
2800 //================================================================================
2802 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2804 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2806 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2807 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2813 //================================================================================
2815 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2816 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2817 * \param theAlgo - The algo that can create this hypo
2818 * \retval bool - false if the command can't be converted
2820 //================================================================================
2822 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2823 const _pyID& theMesh)
2825 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2827 if ( !IsWrappable( theMesh ))
2830 myGeom = theCmd->GetArg( 1 );
2832 Handle(_pyHypothesis) algo;
2834 // find algo created on myGeom in theMesh
2835 algo = theGen->FindAlgo( myGeom, theMesh, this );
2836 if ( algo.IsNull() )
2838 // attach hypothesis creation command to be after algo creation command
2839 // because it can be new created instance of algorithm
2840 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2844 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2845 theCmd->SetResultValue( GetID() );
2846 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2847 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2848 // set args (geom will be set by _pyMesh calling this method)
2849 theCmd->RemoveArgs();
2850 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2851 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2852 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2854 theCmd->SetArg( i+1, "[]");
2856 // set a new creation command
2857 GetCreationCmd()->Clear();
2858 // replace creation command by wrapped instance
2859 // please note, that hypothesis attaches to algo creation command (see upper)
2860 SetCreationCmd( theCmd );
2863 // clear commands setting arg values
2864 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2865 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2868 // set unknown arg commands after hypo creation
2869 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2870 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2871 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2872 afterCmd->AddDependantCmd( *cmd );
2878 //================================================================================
2880 * \brief Remember hypothesis parameter values
2881 * \param theCommand - The called hypothesis method
2883 //================================================================================
2885 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2887 ASSERT( !myIsAlgo );
2888 if ( !theGen->IsToKeepAllCommands() )
2889 rememberCmdOfParameter( theCommand );
2891 bool usedCommand = false;
2892 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2893 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2895 CreationMethod& crMethod = type2meth->second;
2896 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2897 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2899 myArgCommands.push_back( theCommand );
2901 while ( crMethod.myArgs.size() < i+1 )
2902 crMethod.myArgs.push_back( "None" );
2903 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2908 myUnusedCommands.push_back( theCommand );
2911 //================================================================================
2913 * \brief Finish conversion
2915 //================================================================================
2917 void _pyHypothesis::Flush()
2921 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2922 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2923 // Add access to a wrapped mesh
2924 theGen->AddMeshAccessorMethod( *cmd );
2925 // Add access to a wrapped algorithm
2926 theGen->AddAlgoAccessorMethod( *cmd );
2928 cmd = myUnusedCommands.begin();
2929 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2930 // Add access to a wrapped mesh
2931 theGen->AddMeshAccessorMethod( *cmd );
2932 // Add access to a wrapped algorithm
2933 theGen->AddAlgoAccessorMethod( *cmd );
2936 // forget previous hypothesis modifications
2937 myArgCommands.clear();
2938 myUnusedCommands.clear();
2941 //================================================================================
2943 * \brief clear creation, arg and unknown commands
2945 //================================================================================
2947 void _pyHypothesis::ClearAllCommands()
2949 GetCreationCmd()->Clear();
2950 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2951 for ( ; cmd != myArgCommands.end(); ++cmd )
2953 cmd = myUnusedCommands.begin();
2954 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2959 //================================================================================
2961 * \brief Assign fields of theOther to me except myIsWrapped
2963 //================================================================================
2965 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2966 const _pyID& theMesh )
2968 // myCreationCmd = theOther->myCreationCmd;
2969 myIsAlgo = theOther->myIsAlgo;
2970 myIsWrapped = false;
2971 myGeom = theOther->myGeom;
2973 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2974 myAccumulativeMethods = theOther->myAccumulativeMethods;
2975 //myUnusedCommands = theOther->myUnusedCommands;
2976 // init myCurCrMethod
2977 GetCreationMethod( theOther->GetAlgoType() );
2980 //================================================================================
2982 * \brief Analyze my erasability depending on myReferredObjs
2984 //================================================================================
2986 bool _pyHypothesis::CanClear()
2990 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2991 for ( ; obj != myReferredObjs.end(); ++obj )
2992 if ( (*obj)->CanClear() )
2999 //================================================================================
3001 * \brief Clear my commands depending on usage by meshes
3003 //================================================================================
3005 void _pyHypothesis::ClearCommands()
3007 // if ( !theGen->IsToKeepAllCommands() )
3009 // bool isUsed = false;
3010 // int lastComputeOrder = 0;
3011 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
3012 // for ( ; cmd != myComputeCmds.end(); ++cmd )
3013 // if ( ! (*cmd)->IsEmpty() )
3016 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
3017 // lastComputeOrder = (*cmd)->GetOrderNb();
3021 // SetRemovedFromStudy( true );
3025 // // clear my commands invoked after lastComputeOrder
3026 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3027 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3029 // // list< Handle(_pyCommand)> & cmds = m2c->second;
3030 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
3031 // // cmds.back()->Clear();
3035 _pyObject::ClearCommands();
3038 //================================================================================
3040 * \brief Find arguments that are objects like mesh, group, geometry
3041 * \param meshes - referred meshes (directly or indirrectly)
3042 * \retval bool - false if a referred geometry is not in the study
3044 //================================================================================
3046 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
3048 if ( IsAlgo() ) return true;
3050 bool geomPublished = true;
3051 vector< _AString > args;
3052 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3053 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3055 CreationMethod& crMethod = type2meth->second;
3056 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
3058 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
3059 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
3060 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
3061 args.push_back( (*cmd)->GetArg( nb ));
3064 for ( size_t i = 0; i < args.size(); ++i )
3066 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3067 if ( idList.empty() && !args[ i ].IsEmpty() )
3068 idList.push_back( args[ i ]);
3069 list< _pyID >::iterator id = idList.begin();
3070 for ( ; id != idList.end(); ++id )
3072 Handle(_pyObject) obj = theGen->FindObject( *id );
3073 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3076 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3077 geomPublished = false;
3081 myReferredObjs.push_back( obj );
3082 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3083 if ( !mesh.IsNull() )
3084 meshes.push_back( mesh );
3085 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3086 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3087 obj->SetRemovedFromStudy( false );
3091 return geomPublished;
3094 //================================================================================
3096 * \brief Remember theCommand setting a parameter
3098 //================================================================================
3100 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3102 // parameters are discriminated by method name
3103 _AString method = theCommand->GetMethod();
3104 if ( myAccumulativeMethods.count( method ))
3105 return; // this method adds values and not override the previous value
3107 // discriminate commands setting different parameters via one method
3108 // by passing parameter names like e.g. SetOption("size", "0.2")
3109 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3110 theCommand->GetNbArgs() > 1 )
3112 // mangle method by appending a 1st textual arg
3113 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3115 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3116 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3117 if ( !isalpha( arg.Value(2))) continue;
3122 // parameters are discriminated by method name
3123 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3124 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3126 cmds.back()->Clear(); // previous parameter value has not been used
3127 cmds.back() = theCommand;
3131 cmds.push_back( theCommand );
3135 //================================================================================
3137 * \brief Return true if a setting parameter command ha been used to compute mesh
3139 //================================================================================
3141 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3142 _pyCommand::TAddr avoidComputeAddr ) const
3144 bool isUsed = false;
3145 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3146 myComputeAddr2Cmds.begin();
3147 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3149 if ( addr2cmds->first == avoidComputeAddr ) continue;
3150 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3151 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3156 //================================================================================
3158 * \brief Save commands setting parameters as they are used for a mesh computation
3160 //================================================================================
3162 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3164 myComputeCmds.push_back( theComputeCmd );
3165 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3167 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3168 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3169 savedCmds.push_back( m2c->second.back() );
3172 //================================================================================
3174 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3176 //================================================================================
3178 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3180 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3182 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3183 for ( ; cmd != savedCmds.end(); ++cmd )
3185 // check if a cmd has been used to compute another mesh
3186 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3188 // check if a cmd is a sole command setting its parameter;
3189 // don't use method name for search as it can change
3190 map<_AString, list<Handle(_pyCommand)> >::iterator m2cmds = myMeth2Commands.begin();
3191 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3193 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3194 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3195 if ( cmdIt != cmds.end() )
3197 if ( cmds.back() != *cmd )
3199 cmds.erase( cmdIt );
3206 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3209 //================================================================================
3211 * \brief Sets an argNb-th argument of current creation command
3212 * \param argNb - argument index countered from 1
3214 //================================================================================
3216 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3218 if ( myCurCrMethod )
3220 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3221 myCurCrMethod->myArgs.push_back( "None" );
3222 if ( arg.IsEmpty() )
3223 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3225 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3230 //================================================================================
3232 * \brief Remember hypothesis parameter values
3233 * \param theCommand - The called hypothesis method
3235 //================================================================================
3237 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3239 if ( GetAlgoType() == "Cartesian_3D" )
3241 // CartesianParameters3D hyp
3243 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3244 theCommand->GetMethod() == "SetToAddEdges" )
3246 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3247 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3248 myArgCommands.push_back( theCommand );
3251 if ( theCommand->GetMethod() == "SetGrid" ||
3252 theCommand->GetMethod() == "SetGridSpacing" )
3254 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3255 int iArg = axis.Value(1) - '0';
3256 if ( theCommand->GetMethod() == "SetGrid" )
3258 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3262 myCurCrMethod->myArgs[ iArg ] = "[ ";
3263 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3264 myCurCrMethod->myArgs[ iArg ] += ", ";
3265 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3266 myCurCrMethod->myArgs[ iArg ] += "]";
3268 myArgCommands.push_back( theCommand );
3269 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3270 // accumulative, else, if the creation
3271 // is not converted, commands for axes 1 and 2 are lost
3276 if( theCommand->GetMethod() == "SetLength" )
3278 // NOW it is OBSOLETE
3279 // ex: hyp.SetLength(start, 1)
3280 // hyp.SetLength(end, 0)
3281 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3282 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3283 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3284 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3286 CreationMethod& crMethod = type2meth->second;
3287 while ( (int) crMethod.myArgs.size() < i+1 )
3288 crMethod.myArgs.push_back( "[]" );
3289 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3291 myArgCommands.push_back( theCommand );
3295 _pyHypothesis::Process( theCommand );
3298 //================================================================================
3300 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3302 //================================================================================
3304 void _pyComplexParamHypo::Flush()
3306 list < Handle(_pyCommand) >::iterator cmd;
3309 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3310 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3314 // if ( GetAlgoType() == "Cartesian_3D" )
3316 // _pyID algo = myCreationCmd->GetObject();
3317 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3319 // if ( IsWrapped() )
3321 // StructToList( *cmd, /*checkMethod=*/false );
3322 // const _AString & method = (*cmd)->GetMethod();
3323 // if ( method == "SetFixedPoint" )
3324 // (*cmd)->SetObject( algo );
3330 //================================================================================
3332 * \brief Convert methods of 1D hypotheses to my own methods
3333 * \param theCommand - The called hypothesis method
3335 //================================================================================
3337 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3339 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3342 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3343 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3344 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3346 // TCollection_AsciiString cmd =
3347 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3348 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3349 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3352 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3354 // // 1D hypo is already set, so distribution changes and the old
3355 // // 1D hypo is thrown away
3356 // my1dHyp->ClearAllCommands();
3359 // //my1dHyp->SetRemovedFromStudy( false );
3361 // if ( !myArgCommands.empty() )
3362 // myArgCommands.back()->Clear();
3363 myCurCrMethod->myArgs.push_back( hyp1dID );
3364 myArgCommands.push_back( theCommand );
3367 //================================================================================
3370 * \param theAdditionCmd - command to be converted
3371 * \param theMesh - mesh instance
3372 * \retval bool - status
3374 //================================================================================
3376 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3377 const _pyID& theMesh)
3379 myIsWrapped = false;
3381 if ( my1dHyp.IsNull() )
3384 // set "SetLayerDistribution()" after addition cmd
3385 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3387 _pyID geom = theAdditionCmd->GetArg( 1 );
3389 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3390 if ( !algo.IsNull() )
3392 my1dHyp->SetMesh( theMesh );
3393 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3394 algo->GetAlgoType().ToCString());
3395 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3398 // clear "SetLayerDistribution()" cmd
3399 myArgCommands.back()->Clear();
3401 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3403 // find RadialPrism algo created on <geom> for theMesh
3404 GetCreationCmd()->SetObject( algo->GetID() );
3405 GetCreationCmd()->SetMethod( myAlgoMethod );
3406 GetCreationCmd()->RemoveArgs();
3407 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3413 //================================================================================
3417 //================================================================================
3419 void _pyLayerDistributionHypo::Flush()
3421 // as creation of 1D hyp was written later then it's edition,
3422 // we need to find all it's edition calls and process them
3423 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3425 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3427 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3428 if ( hyp1dID.IsEmpty() ) continue;
3430 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3432 // make a new name for 1D hyp = "HypType" + "_Distribution"
3434 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3436 if ( prevNewName.IsEmpty() ) continue;
3437 newName = prevNewName;
3441 if ( hyp1d->IsWrapped() ) {
3442 newName = hyp1d->GetCreationCmd()->GetMethod();
3445 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3446 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3448 newName += "_Distribution";
3449 prevNewName = newName;
3451 hyp1d->GetCreationCmd()->SetResultValue( newName );
3453 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3454 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3455 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3456 const _pyID& objID = (*cmdIt)->GetObject();
3457 if ( objID == hyp1dID ) {
3458 if ( !hyp1d.IsNull() )
3460 hyp1d->Process( *cmdIt );
3461 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3463 ( *cmdIt )->SetObject( newName );
3466 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3467 (*cmd)->SetArg( 1, newName );
3471 //================================================================================
3473 * \brief additionally to Addition2Creation, clears SetDistrType() command
3474 * \param theCmd - AddHypothesis() command
3475 * \param theMesh - mesh to which a hypothesis is added
3476 * \retval bool - conversion result
3478 //================================================================================
3480 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3481 const _pyID& theMesh)
3483 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3484 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3485 bool scaleDistrType = false;
3486 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3487 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3488 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3489 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3490 scaleDistrType = true;
3493 else if ( !scaleDistrType ) {
3494 // distribution type changed: remove scale factor from args
3495 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3496 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3498 CreationMethod& crMethod = type2meth->second;
3499 if ( crMethod.myArgs.size() == 2 )
3500 crMethod.myArgs.pop_back();
3507 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3510 //================================================================================
3512 * \brief remove repeated commands defining distribution
3514 //================================================================================
3516 void _pyNumberOfSegmentsHyp::Flush()
3518 // find number of the last SetDistrType() command
3519 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3520 int distrTypeNb = 0;
3521 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3522 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3523 if ( cmd != myUnusedCommands.rbegin() )
3524 distrTypeNb = (*cmd)->GetOrderNb();
3526 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3529 // clear commands before the last SetDistrType()
3530 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3531 set< int > treatedCmdNbs; // avoid treating same cmd twice
3532 for ( int i = 0; i < 2; ++i ) {
3533 set<TCollection_AsciiString> uniqueMethods;
3534 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3535 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3537 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3538 continue;// avoid treating same cmd twice
3539 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3540 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3541 if ( !clear || method == "SetNumberOfSegments" ) {
3542 bool isNewInSet = uniqueMethods.insert( method ).second;
3543 clear = !isNewInSet;
3552 //================================================================================
3554 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3555 * into regular1D.LengthNearVertex( length, vertex )
3556 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3557 * \param theMesh - The mesh needing this hypo
3558 * \retval bool - false if the command can't be converted
3560 //================================================================================
3562 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3563 const _pyID& theMeshID)
3565 if ( IsWrappable( theMeshID )) {
3567 _pyID vertex = theCmd->GetArg( 1 );
3569 // the problem here is that segment algo can be not found
3570 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3571 // geometry where segment algorithm is assigned
3572 _pyID geom = vertex;
3573 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3574 while ( algo.IsNull() && !geom.IsEmpty()) {
3575 // try to find geom as a father of <vertex>
3576 geom = FatherID( geom );
3577 algo = theGen->FindAlgo( geom, theMeshID, this );
3579 if ( algo.IsNull() || geom.IsEmpty() )
3580 return false; // also possible to find geom as brother of veretex...
3582 // set geom instead of vertex
3583 theCmd->SetArg( 1, geom );
3585 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3586 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3587 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3589 // set vertex as a second arg
3590 theCmd->SetArg( 2, vertex );
3598 //================================================================================
3600 * \brief _pyAlgorithm constructor
3601 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3603 //================================================================================
3605 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3606 : _pyHypothesis( theCreationCmd )
3611 //================================================================================
3613 * \brief Convert the command adding an algorithm to mesh
3614 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3615 * \param theMesh - The mesh needing this algo
3616 * \retval bool - false if the command can't be converted
3618 //================================================================================
3620 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3621 const _pyID& theMeshID)
3623 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3624 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3625 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3631 //================================================================================
3633 * \brief Return starting position of a part of python command
3634 * \param thePartIndex - The index of command part
3635 * \retval int - Part position
3637 //================================================================================
3639 int _pyCommand::GetBegPos( int thePartIndex ) const
3643 if ( myBegPos.Length() < thePartIndex )
3645 ASSERT( thePartIndex > 0 );
3646 return myBegPos( thePartIndex );
3649 //================================================================================
3651 * \brief Store starting position of a part of python command
3652 * \param thePartIndex - The index of command part
3653 * \param thePosition - Part position
3655 //================================================================================
3657 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3659 while ( myBegPos.Length() < thePartIndex )
3660 myBegPos.Append( UNKNOWN );
3661 ASSERT( thePartIndex > 0 );
3662 myBegPos( thePartIndex ) = thePosition;
3665 //================================================================================
3667 * \brief Returns whitespace symbols at the line beginning
3668 * \retval TCollection_AsciiString - result
3670 //================================================================================
3672 TCollection_AsciiString _pyCommand::GetIndentation()
3675 //while ( end <= Length() && isblank( myString.Value( end )))
3676 //ANA: isblank() function isn't provided in VC2010 compiler
3677 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3679 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3682 //================================================================================
3684 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3685 * \retval const TCollection_AsciiString & - ResultValue substring
3687 //================================================================================
3689 const TCollection_AsciiString & _pyCommand::GetResultValue()
3691 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3693 SetBegPos( RESULT_IND, EMPTY );
3694 int begPos, endPos = myString.Location( "=", 1, Length() );
3698 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3699 if ( begPos < endPos )
3701 SetBegPos( RESULT_IND, begPos );
3703 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3704 myRes = myString.SubString( begPos, endPos );
3711 //================================================================================
3713 * \brief Return number of python command result value ResultValue = Obj.Meth()
3715 //================================================================================
3717 int _pyCommand::GetNbResultValues()
3720 return myResults.Length();
3724 //================================================================================
3726 * \brief Return substring of python command looking like
3727 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3728 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3730 //================================================================================
3731 const _AString& _pyCommand::GetResultValue(int res)
3733 if ( GetResultValue().IsEmpty() )
3734 return theEmptyString;
3736 if ( myResults.IsEmpty() )
3739 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3740 ++begPos; // skip [, else the whole list is returned
3741 while ( begPos < myRes.Length() ) {
3742 _AString result = GetWord( myRes, begPos, true );
3743 begPos += result.Length();
3745 // result.RemoveAll('[');
3746 // result.RemoveAll(']');
3751 myResults.Append( result );
3754 if ( res > 0 && res <= myResults.Length() )
3755 return myResults( res );
3756 return theEmptyString;
3759 //================================================================================
3761 * \brief Return substring of python command looking like ResVal = Object.Meth()
3762 * \retval const TCollection_AsciiString & - Object substring
3764 //================================================================================
3766 const TCollection_AsciiString & _pyCommand::GetObject()
3768 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3771 int begPos = GetBegPos( RESULT_IND );
3773 begPos = myString.Location( "=", 1, Length() ) + 1;
3774 // is '=' in the string argument (for example, name) or not
3775 int nb[4] = { 0, 0, 0, 0 }; // number of '"() character at the left of =
3776 for ( int i = 1; i < begPos-1; i++ )
3777 switch ( myString.Value( i )) {
3778 case '\'': nb[0]++; break;
3779 case '"' : nb[1]++; break;
3780 case '(' : nb[2]++; break;
3781 case ')' : nb[3]++; break;
3783 // if = is inside a string or a list
3784 // then get an object at the start of the command
3785 if ( nb[0] % 2 != 0 || nb[1] % 2 != 0 || nb[2] != nb[3])
3789 begPos += myRes.Length();
3791 myObj = GetWord( myString, begPos, true );
3792 if ( begPos != EMPTY )
3794 // check if object is complex,
3795 // so far consider case like "smesh.Method()"
3796 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3797 //if ( bracketPos==0 ) bracketPos = Length();
3798 int dotPos = begPos+myObj.Length();
3799 while ( dotPos+1 < bracketPos ) {
3800 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3805 if ( dotPos > begPos+myObj.Length() )
3806 myObj = myString.SubString( begPos, dotPos-1 );
3809 // 1st word after '=' is an object
3810 // else // no method -> no object
3816 SetBegPos( OBJECT_IND, begPos );
3822 //================================================================================
3824 * \brief Return substring of python command looking like ResVal = Obj.Method()
3825 * \retval const TCollection_AsciiString & - Method substring
3827 //================================================================================
3829 const TCollection_AsciiString & _pyCommand::GetMethod()
3831 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3834 int begPos = GetBegPos( OBJECT_IND );
3835 bool forward = true;
3837 begPos = myString.Location( "(", 1, Length() ) - 1;
3841 begPos += myObj.Length();
3844 myMeth = GetWord( myString, begPos, forward );
3845 SetBegPos( METHOD_IND, begPos );
3851 //================================================================================
3853 * \brief Returns true if there are brackets after the method
3855 //================================================================================
3857 bool _pyCommand::IsMethodCall()
3859 if ( GetMethod().IsEmpty() )
3861 if ( myString.StartsWith("#") )
3863 if ( myString.StartsWith("SHAPERSTUDY") ) // skip shaperstudy specific dump string analysis
3865 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3866 return ( s[0] == '(' || s[1] == '(' );
3869 //================================================================================
3871 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3872 * \retval const TCollection_AsciiString & - Arg<index> substring
3874 //================================================================================
3876 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3878 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3882 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3884 pos = myString.Location( "(", 1, Length() );
3888 // we are at or before '(', skip it if present
3890 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3891 if ( pos > Length() )
3895 SetBegPos( ARG1_IND, 0 ); // even no '('
3896 return theEmptyString;
3900 list< TCollection_AsciiString > separatorStack( 1, ",)");
3901 bool ignoreNesting = false;
3903 while ( pos <= Length() )
3905 const char chr = myString.Value( pos );
3907 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3909 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3911 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3913 TCollection_AsciiString arg;
3914 if ( pos-1 >= prevPos ) {
3915 arg = myString.SubString( prevPos, pos-1 );
3916 arg.RightAdjust(); // remove spaces
3919 if ( !arg.IsEmpty() || chr == ',' )
3921 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3922 myArgs.Append( arg );
3928 else // end of nesting args found
3930 separatorStack.pop_back();
3931 ignoreNesting = false;
3934 else if ( !ignoreNesting )
3937 case '(' : separatorStack.push_back(")"); break;
3938 case '[' : separatorStack.push_back("]"); break;
3939 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3940 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3947 if ( myArgs.Length() < index )
3948 return theEmptyString;
3949 return myArgs( index );
3952 //================================================================================
3954 * \brief Return position where arguments begin
3956 //================================================================================
3958 int _pyCommand::GetArgBeginning() const
3960 int pos = GetBegPos( ARG1_IND );
3961 if ( pos == UNKNOWN )
3963 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3964 if ( pos < 1 && Length() >= 4 )
3965 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3970 //================================================================================
3972 * \brief Check if char is a word part
3973 * \param c - The character to check
3974 * \retval bool - The check result
3976 //================================================================================
3978 static inline bool isWord(const char c, const bool dotIsWord)
3981 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3984 //================================================================================
3986 * \brief Looks for a word in the string and returns word's beginning
3987 * \param theString - The input string
3988 * \param theStartPos - The position to start the search, returning word's beginning
3989 * \param theForward - The search direction
3990 * \retval TCollection_AsciiString - The found word
3992 //================================================================================
3994 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3996 const bool theForward,
3997 const bool dotIsWord )
3999 int beg = theStartPos, end = theStartPos;
4000 theStartPos = EMPTY;
4001 if ( beg < 1 || beg > theString.Length() )
4002 return theEmptyString;
4004 if ( theForward ) { // search forward
4006 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
4008 if ( beg > theString.Length() )
4009 return theEmptyString; // no word found
4012 char begChar = theString.Value( beg );
4013 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
4014 char endChar = ( begChar == '[' ) ? ']' : begChar;
4015 // end is at the corresponding quoting mark or bracket
4016 while ( end < theString.Length() &&
4017 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
4021 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
4026 else { // search backward
4028 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
4031 return theEmptyString; // no word found
4033 char endChar = theString.Value( end );
4034 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
4035 char begChar = ( endChar == ']' ) ? '[' : endChar;
4036 // beg is at the corresponding quoting mark
4038 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
4042 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
4048 //cout << theString << " ---- " << beg << " - " << end << endl;
4049 if ( end > theString.Length() )
4051 theStartPos = EMPTY;
4052 return theEmptyString;
4054 return theString.SubString( beg, end );
4057 //================================================================================
4059 * \brief Returns true if the string looks like a study entry
4061 //================================================================================
4063 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
4065 if ( str.Length() < 5 ) return false;
4067 int nbColons = 0, isColon;
4068 for ( int i = 1; i <= str.Length(); ++i )
4070 char c = str.Value(i);
4071 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4073 nbColons += isColon;
4075 return nbColons > 2 && str.Length()-nbColons > 2;
4078 //================================================================================
4080 * \brief Returns true if the string looks like an object ID but not like a list,
4081 * string, command etc.
4083 //================================================================================
4085 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4087 if ( str.Length() < 1 ) return false;
4089 const char* s = str.ToCString();
4091 for ( int i = 0; i < str.Length(); ++i )
4092 if ( !IsIDChar( s[i] ))
4098 //================================================================================
4100 * \brief Finds entries in a string
4102 //================================================================================
4104 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4106 std::list< _pyID > resList;
4108 while ( ++pos <= str.Length() )
4110 if ( !isdigit( str.Value( pos ))) continue;
4111 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4114 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4115 _pyID entry = str.SubString( pos, end-1 );
4117 if ( IsStudyEntry( entry ))
4118 resList.push_back( entry );
4123 //================================================================================
4125 * \brief Look for position where not space char is
4126 * \param theString - The string
4127 * \param thePos - The position to search from and which returns result
4128 * \retval bool - false if there are only space after thePos in theString
4130 //================================================================================
4132 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4134 if ( thePos < 1 || thePos > theString.Length() )
4137 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4140 return thePos <= theString.Length();
4143 //================================================================================
4145 * \brief Modify a part of the command
4146 * \param thePartIndex - The index of the part
4147 * \param thePart - The new part string
4148 * \param theOldPart - The old part
4150 //================================================================================
4152 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4153 TCollection_AsciiString& theOldPart)
4155 int pos = GetBegPos( thePartIndex );
4156 if ( pos <= Length() && theOldPart != thePart)
4158 TCollection_AsciiString seperator;
4160 pos = GetBegPos( thePartIndex + 1 );
4161 if ( pos < 1 ) return;
4162 switch ( thePartIndex ) {
4163 case RESULT_IND: seperator = " = "; break;
4164 case OBJECT_IND: seperator = "."; break;
4165 case METHOD_IND: seperator = "()"; break;
4169 myString.Remove( pos, theOldPart.Length() );
4170 if ( !seperator.IsEmpty() )
4171 myString.Insert( pos , seperator );
4172 myString.Insert( pos, thePart );
4173 // update starting positions of the following parts
4174 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4175 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4176 if ( myBegPos( i ) > 0 )
4177 myBegPos( i ) += posDelta;
4179 theOldPart = thePart;
4183 //================================================================================
4185 * \brief Set argument
4186 * \param index - The argument index, it counts from 1
4187 * \param theArg - The argument string
4189 //================================================================================
4191 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4194 int argInd = ARG1_IND + index - 1;
4195 int pos = GetBegPos( argInd );
4196 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4198 // find a closing parenthesis
4199 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4200 int lastArgInd = GetNbArgs();
4201 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4202 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4207 while ( pos > 0 && myString.Value( pos ) != ')' )
4210 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4214 while ( myArgs.Length() < index ) {
4215 if ( myArgs.Length() )
4216 myString.Insert( pos++, "," );
4217 myArgs.Append("None");
4218 myString.Insert( pos, myArgs.Last() );
4219 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4220 pos += myArgs.Last().Length();
4223 SetPart( argInd, theArg, myArgs( index ));
4226 //================================================================================
4228 * \brief Empty arg list
4230 //================================================================================
4232 void _pyCommand::RemoveArgs()
4234 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4235 myString.Trunc( pos );
4238 if ( myBegPos.Length() >= ARG1_IND )
4239 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4242 //================================================================================
4244 * \brief Comment a python command
4246 //================================================================================
4248 void _pyCommand::Comment()
4250 if ( IsEmpty() ) return;
4253 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4254 if ( i <= Length() )
4256 myString.Insert( i, "#" );
4257 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4259 int begPos = GetBegPos( iPart );
4260 if ( begPos != UNKNOWN && begPos != EMPTY )
4261 SetBegPos( iPart, begPos + 1 );
4266 //================================================================================
4268 * \brief Set dependent commands after this one
4270 //================================================================================
4272 bool _pyCommand::SetDependentCmdsAfter() const
4274 bool orderChanged = false;
4275 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4276 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4277 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4278 orderChanged = true;
4279 theGen->SetCommandAfter( *cmd, this );
4280 (*cmd)->SetDependentCmdsAfter();
4283 return orderChanged;
4285 //================================================================================
4287 * \brief Insert accessor method after theObjectID
4288 * \param theObjectID - id of the accessed object
4289 * \param theAcsMethod - name of the method giving access to the object
4290 * \retval bool - false if theObjectID is not found in the command string
4292 //================================================================================
4294 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4296 if ( !theAcsMethod )
4298 // start object search from the object, i.e. ignore result
4300 int beg = GetBegPos( OBJECT_IND );
4301 if ( beg < 1 || beg > Length() )
4304 while (( beg = myString.Location( theObjectID, beg, Length() )))
4306 // check that theObjectID is not just a part of a longer ID
4307 int afterEnd = beg + theObjectID.Length();
4308 Standard_Character c = myString.Value( afterEnd );
4309 if ( !IsIDChar( c ))
4311 // check if accessor method already present
4313 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4315 int oldLen = Length();
4316 myString.Insert( afterEnd, (char*) theAcsMethod );
4317 myString.Insert( afterEnd, "." );
4318 // update starting positions of the parts following the modified one
4319 int posDelta = Length() - oldLen;
4320 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4321 if ( myBegPos( i ) > afterEnd )
4322 myBegPos( i ) += posDelta;
4327 beg = afterEnd; // is a part -> next search
4332 //================================================================================
4334 * \brief Creates pyObject
4336 //================================================================================
4338 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4339 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4344 //================================================================================
4346 * \brief Set up myID and myIsPublished
4348 //================================================================================
4350 void _pyObject::setID(const _pyID& theID)
4353 myIsPublished = !theGen->IsNotPublished( GetID() );
4356 //================================================================================
4358 * \brief Clear myCreationCmd and myProcessedCmds
4360 //================================================================================
4362 void _pyObject::ClearCommands()
4367 if ( !myCreationCmd.IsNull() )
4368 myCreationCmd->Clear();
4370 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4371 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4375 //================================================================================
4377 * \brief Return method name giving access to an interaface object wrapped by python class
4378 * \retval const char* - method name
4380 //================================================================================
4382 const char* _pyObject::AccessorMethod() const
4386 //================================================================================
4388 * \brief Return ID of a father
4390 //================================================================================
4392 _pyID _pyObject::FatherID(const _pyID & childID)
4394 int colPos = childID.SearchFromEnd(':');
4396 return childID.SubString( 1, colPos-1 );
4400 //================================================================================
4402 * \brief SelfEraser erases creation command if none of it's commands invoked
4403 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4405 //================================================================================
4407 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4408 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4410 myIsPublished = true; // prevent clearing as a not published
4411 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4414 //================================================================================
4416 * \brief SelfEraser erases creation command if none of it's commands invoked
4417 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4419 //================================================================================
4421 bool _pySelfEraser::CanClear()
4423 bool toErase = false;
4424 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4427 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4428 for ( ; cmd != myArgCmds.end(); ++cmd )
4429 nbArgUses += IsAliveCmd( *cmd );
4431 toErase = ( nbArgUses < 1 );
4436 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4437 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4438 for ( ; cmd != cmds.end(); )
4439 // check of cmd emptiness is not enough as object can change
4440 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4443 cmd = cmds.erase( cmd ); // save the cmd from clearing
4445 toErase = ( nbCalls < 1 );
4450 //================================================================================
4452 * \brief Check if a command is or can be cleared
4454 //================================================================================
4456 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4458 if ( theCmd->IsEmpty() )
4461 if ( !theGen->IsToKeepAllCommands() )
4463 const _pyID& objID = theCmd->GetObject();
4464 Handle( _pyObject ) obj = theGen->FindObject( objID );
4465 if ( !obj.IsNull() )
4466 return !obj->CanClear();
4471 //================================================================================
4473 * \brief SelfEraser erases creation command if none of it's commands invoked
4474 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4476 //================================================================================
4478 void _pySelfEraser::Flush()
4482 myIsPublished = false;
4483 _pyObject::ClearCommands();
4487 //================================================================================
4489 * \brief _pySubMesh constructor
4491 //================================================================================
4493 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4494 _pyObject(theCreationCmd)
4496 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4497 if ( toKeepAgrCmds )
4498 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4501 //================================================================================
4503 * \brief Return true if a sub-mesh can be used as argument of the given method
4505 //================================================================================
4507 bool _pySubMesh::CanBeArgOfMethod(const _AString& /*theMethodName*/)
4510 // names of all methods where a sub-mesh can be used as argument
4511 // static TStringSet methods;
4512 // if ( methods.empty() ) {
4513 // const char * names[] = {
4514 // // methods of SMESH_Gen
4516 // // methods of SMESH_Group
4518 // // methods of SMESH_Measurements
4520 // // methods of SMESH_Mesh
4521 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4523 // // methods of SMESH_MeshEditor
4524 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4525 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4526 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4527 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4528 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4529 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4530 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4531 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4532 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4533 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4534 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4535 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4536 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4537 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4538 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4539 // "" }; // <- mark of end
4540 // methods.Insert( names );
4542 // return methods.Contains( theMethodName );
4545 //================================================================================
4547 * \brief count invoked commands
4549 //================================================================================
4551 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4553 _pyObject::Process(theCommand); // count calls of Process()
4556 //================================================================================
4558 * \brief Move creation command depending on invoked commands
4560 //================================================================================
4562 void _pySubMesh::Flush()
4564 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4565 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4566 else if ( !myCreator.IsNull() )
4567 // move to be just after creator
4568 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4570 // move sub-mesh usage after creation cmd
4571 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4572 for ( ; cmd != myArgCmds.end(); ++cmd )
4573 if ( !(*cmd)->IsEmpty() )
4574 GetCreationCmd()->AddDependantCmd( *cmd );
4577 //================================================================================
4579 * \brief Creates _pyGroup
4581 //================================================================================
4583 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4584 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4586 if ( !id.IsEmpty() )
4589 myCanClearCreationCmd = true;
4591 const _AString& method = theCreationCmd->GetMethod();
4592 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4594 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4596 // ----------------------------------------------------------------------
4597 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4599 _pyID geom = theCreationCmd->GetArg( 3 );
4600 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4601 // next if(){...} section is commented
4602 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4603 // theCreationCmd->SetMethod( "Group" );
4604 // theCreationCmd->RemoveArgs();
4605 // theCreationCmd->SetArg( 1, geom );
4608 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4609 _pyID type = theCreationCmd->GetArg( 1 );
4610 _pyID name = theCreationCmd->GetArg( 2 );
4611 theCreationCmd->SetMethod( "GroupOnGeom" );
4612 theCreationCmd->RemoveArgs();
4613 theCreationCmd->SetArg( 1, geom );
4614 theCreationCmd->SetArg( 2, name );
4615 theCreationCmd->SetArg( 3, type );
4618 else if ( method == "CreateGroupFromFilter" )
4620 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4621 theCreationCmd->SetMethod( "GroupOnFilter" );
4623 _pyID filterID = theCreationCmd->GetArg(3);
4624 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4625 if ( !filter.IsNull())
4627 if ( !filter->GetNewID().IsEmpty() )
4628 theCreationCmd->SetArg( 3, filter->GetNewID() );
4629 //filter->AddUser( this );
4633 else if ( method == "GetGroups" )
4635 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4639 // theCreationCmd does something else apart from creation of this group
4640 // and thus it can't be cleared if this group is removed
4641 myCanClearCreationCmd = false;
4645 //================================================================================
4647 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4650 //================================================================================
4652 bool _pyGroup::CanClear()
4657 if ( !myCanClearCreationCmd &&
4658 !myCreationCmd.IsNull() &&
4659 myCreationCmd->GetMethod() == "GetGroups" )
4661 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4662 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4663 list< _pyID >::iterator grID = idList.begin();
4664 if ( GetID() == *grID )
4666 myCanClearCreationCmd = true;
4667 list< Handle(_pyGroup ) > groups;
4668 for ( ; grID != idList.end(); ++grID )
4670 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4671 if ( group.IsNull() ) continue;
4672 groups.push_back( group );
4673 if ( group->IsInStudy() )
4674 myCanClearCreationCmd = false;
4676 // set myCanClearCreationCmd == true to all groups
4677 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4678 for ( ; group != groups.end(); ++group )
4679 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4683 return myCanClearCreationCmd;
4686 //================================================================================
4688 * \brief set myCanClearCreationCmd = true if the main action of the creation
4689 * command is discarded
4691 //================================================================================
4693 void _pyGroup::RemovedWithContents()
4695 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4696 // via a created group
4697 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4698 // myCanClearCreationCmd = true;
4701 //================================================================================
4703 * \brief To convert creation of a group by filter
4705 //================================================================================
4707 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4709 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4710 // group = mesh.CreateEmptyGroup( elemType, groupName )
4711 // aFilter.SetMesh(mesh)
4712 // nbAdd = group.AddFrom( aFilter )
4713 Handle(_pyFilter) filter;
4714 if ( theCommand->GetMethod() == "AddFrom" )
4716 _pyID idSource = theCommand->GetArg(1);
4717 // check if idSource is a filter
4718 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4719 if ( !filter.IsNull() )
4721 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4722 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4723 while ( *cmdIt != theCommand ) ++cmdIt;
4724 while ( (*cmdIt)->GetOrderNb() != 1 )
4726 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4727 if ((setMeshCmd->GetObject() == idSource ||
4728 setMeshCmd->GetObject() == filter->GetNewID() )
4730 setMeshCmd->GetMethod() == "SetMesh")
4732 setMeshCmd->Clear();
4736 // replace 3 commands by one
4737 theCommand->Clear();
4738 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4739 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4740 if ( !filter->GetNewID().IsEmpty() )
4741 idSource = filter->GetNewID();
4742 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4743 makeGroupCmd->SetArg( 1, name );
4744 makeGroupCmd->SetArg( 2, idSource );
4745 filter->AddArgCmd( makeGroupCmd );
4748 else if ( theCommand->GetMethod() == "SetFilter" )
4750 // set new name of a filter or clear the command if the same filter is set
4751 _pyID filterID = theCommand->GetArg(1);
4752 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4753 if ( !myFilter.IsNull() && filter == myFilter )
4754 theCommand->Clear();
4755 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4756 theCommand->SetArg( 1, filter->GetNewID() );
4759 else if ( theCommand->GetMethod() == "GetFilter" )
4761 // GetFilter() returns a filter with other ID, make myFilter process
4762 // calls of the returned filter
4763 if ( !myFilter.IsNull() )
4765 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4766 theCommand->Clear();
4770 // if ( !filter.IsNull() )
4771 // filter->AddUser( this );
4773 theGen->AddMeshAccessorMethod( theCommand );
4776 //================================================================================
4778 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4780 //================================================================================
4782 void _pyGroup::Flush()
4784 if ( !theGen->IsToKeepAllCommands() &&
4785 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4787 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4791 //================================================================================
4793 * \brief Constructor of _pyFilter
4795 //================================================================================
4797 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4798 :_pyObject(theCreationCmd), myNewID( newID )
4800 //myIsPublished = true; // prevent clearing as a not published
4801 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4804 //================================================================================
4806 * \brief To convert creation of a filter by criteria and
4807 * to replace an old name by a new one
4809 //================================================================================
4811 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4813 if ( theCommand->GetObject() == GetID() )
4814 _pyObject::Process(theCommand); // count commands
4816 if ( !myNewID.IsEmpty() )
4817 theCommand->SetObject( myNewID );
4819 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4820 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4821 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4822 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4823 theCommand->GetMethod() == "SetCriteria")
4825 // aFilter.SetCriteria(aCriteria) ->
4826 // aFilter = smesh.GetFilterFromCriteria(criteria)
4827 if ( myNewID.IsEmpty() )
4828 theCommand->SetResultValue( GetID() );
4830 theCommand->SetResultValue( myNewID );
4831 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4832 theCommand->SetMethod( "GetFilterFromCriteria" );
4834 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4835 GetCreationCmd()->Clear();
4836 GetCreationCmd()->GetString() = theCommand->GetString();
4837 theCommand->Clear();
4838 theCommand->AddDependantCmd( GetCreationCmd() );
4839 // why swap? -- it's needed
4840 //GetCreationCmd()->Clear();
4842 else if ( theCommand->GetMethod() == "SetMesh" )
4844 if ( myMesh == theCommand->GetArg( 1 ))
4845 theCommand->Clear();
4847 myMesh = theCommand->GetArg( 1 );
4848 theGen->AddMeshAccessorMethod( theCommand );
4852 //================================================================================
4854 * \brief Set new filter name to the creation command and to myArgCmds
4856 //================================================================================
4858 void _pyFilter::Flush()
4860 if ( myNewID.IsEmpty() ) return;
4862 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4863 for ( ; cmd != myArgCmds.end(); ++cmd )
4864 if ( !(*cmd)->IsEmpty() )
4866 _AString cmdStr = (*cmd)->GetString();
4867 _AString id = GetID();
4868 int pos = cmdStr.Search( id );
4871 cmdStr.Remove( pos, id.Length() );
4872 cmdStr.Insert( pos, myNewID );
4875 (*cmd)->GetString() = cmdStr;
4878 if ( !GetCreationCmd()->IsEmpty() )
4879 GetCreationCmd()->SetResultValue( myNewID );
4882 //================================================================================
4884 * \brief Return true if all my users can be cleared
4886 //================================================================================
4888 bool _pyObject::CanClear()
4890 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4891 for ( ; cmd != myArgCmds.end(); ++cmd )
4892 if ( !(*cmd)->IsEmpty() )
4894 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4895 if ( !obj.IsNull() && !obj->CanClear() )
4898 return ( !myIsPublished );
4901 //================================================================================
4903 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4905 //================================================================================
4907 _pyHypothesisReader::_pyHypothesisReader()
4910 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4911 LDOMParser xmlParser;
4912 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4914 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4918 INFOS( xmlParser.GetError(data) );
4921 // <algorithm type="Regular_1D"
4922 // label-id="Wire discretisation"
4925 // <algo>Regular_1D=Segment()</algo>
4926 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4928 LDOM_Document xmlDoc = xmlParser.getDocument();
4929 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4930 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4932 LDOM_Node algoNode = algoNodeList.item( i );
4933 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4934 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4935 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4937 _AString text, algoType, method, arg;
4938 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4940 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4941 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4942 text = textNode.getNodeValue();
4943 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4944 algoType = algoCmd->GetResultValue();
4945 method = algoCmd->GetMethod();
4946 arg = algoCmd->GetArg(1);
4947 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4949 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4950 algo->SetConvMethodAndType( method, algoType );
4951 if ( !arg.IsEmpty() )
4952 algo->setCreationArg( 1, arg );
4954 myType2Hyp[ algoType ] = algo;
4958 if ( algoType.IsEmpty() ) continue;
4960 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4962 Handle( _pyHypothesis ) hyp;
4963 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4965 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4966 LDOM_Node textNode = pyHypoNode.getFirstChild();
4967 text = textNode.getNodeValue();
4968 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4969 hypType = hypoCmd->GetResultValue();
4970 method = hypoCmd->GetMethod();
4971 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4973 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4974 if ( type2hyp == myType2Hyp.end() )
4975 hyp = new _pyHypothesis( hypoCmd );
4977 hyp = type2hyp->second;
4978 hyp->SetConvMethodAndType( method, algoType );
4979 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4981 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4982 _AString argMethod = argCmd.GetMethod();
4983 _AString argNbText = argCmd.GetArg( 1 );
4984 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4985 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4987 hyp->AddArgMethod( argMethod,
4988 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4990 myType2Hyp[ hypType ] = hyp;
4994 // <hypothesis type="BLSURF_Parameters"
4998 // <accumulative-methods>
4999 // SetEnforcedVertex,
5000 // SetEnforcedVertexNamed
5001 // </accumulative-methods>
5005 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
5006 for ( int i = 0; i < hypNodeList.getLength(); ++i )
5008 LDOM_Node hypNode = hypNodeList.item( i );
5009 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
5010 _AString hypType = hypElem.getAttribute("type");
5011 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
5012 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
5014 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5015 if ( type2hyp == myType2Hyp.end() ) continue;
5017 LDOM_Node methNode = methNodeList.item( 0 );
5018 LDOM_Node textNode = methNode.getFirstChild();
5019 _AString text = textNode.getNodeValue();
5023 method = _pyCommand::GetWord( text, pos, /*forward= */true );
5024 pos += method.Length();
5025 type2hyp->second->AddAccumulativeMethod( method );
5027 while ( !method.IsEmpty() );
5030 } // loop on xmlPaths
5033 //================================================================================
5035 * \brief Returns a new hypothesis initialized according to the read information
5037 //================================================================================
5039 Handle(_pyHypothesis)
5040 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
5041 const Handle(_pyCommand)& creationCmd) const
5043 Handle(_pyHypothesis) resHyp, sampleHyp;
5045 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
5046 if ( type2hyp != myType2Hyp.end() )
5047 sampleHyp = type2hyp->second;
5049 if ( sampleHyp.IsNull() )
5051 resHyp = new _pyHypothesis(creationCmd);
5055 if ( sampleHyp->IsAlgo() )
5056 resHyp = new _pyAlgorithm( creationCmd );
5058 resHyp = new _pyHypothesis(creationCmd);
5059 resHyp->Assign( sampleHyp, _pyID() );
5064 //================================================================================
5066 * \brief Adds an object ID to some family of IDs with a common prefix
5067 * \param [in] str - the object ID
5068 * \return bool - \c false if \a str does not have the same prefix as \a this family
5069 * (for internal usage)
5071 //================================================================================
5073 bool _pyStringFamily::Add( const char* str )
5075 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5076 return false; // expected prefix is missing
5078 str += _prefix.Length(); // skip _prefix
5080 // try to add to some of child falimies
5081 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5082 for ( ; itSub != _subFams.end(); ++itSub )
5083 if ( itSub->Add( str ))
5086 // no suitable family found - add str to _strings or create a new child family
5088 // look for a proper place within sorted _strings
5089 std::list< _AString >::iterator itStr = _strings.begin();
5090 while ( itStr != _strings.end() && itStr->IsLess( str ))
5092 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5093 return true; // same ID already kept
5095 const int minPrefixSize = 4;
5097 // count "smaller" strings with the same prefix
5099 std::list< _AString >::iterator itLess = itStr;
5100 while ( itLess != _strings.begin() )
5103 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5111 // itLess points to the 1st string with same prefix
5113 // count "greater" strings with the same prefix
5115 std::list< _AString >::iterator itMore = itStr;
5116 for ( ; itMore != _strings.end(); ++itMore )
5117 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5121 // itMore points to the 1st string with greater prefix
5123 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5125 int prefixSize = minPrefixSize;
5126 _AString newPrefix ( str, prefixSize );
5128 // look for a proper place within _subFams sorted by _prefix
5129 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5130 if ( !itSub->_prefix.IsLess( newPrefix ))
5133 // add the new _pyStringFamily
5134 itSub = _subFams.insert( itSub, _pyStringFamily());
5135 _pyStringFamily& newSubFam = *itSub;
5136 newSubFam._prefix = newPrefix;
5138 // pass this->_strings to newSubFam._strings
5139 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5140 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5141 newSubFam._strings.push_back( str + prefixSize );
5142 for ( ; nbMore > 0; --nbMore, ++itStr )
5143 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5145 _strings.erase( itLess, itMore );
5147 else // too few string to make a family for them
5149 _strings.insert( itStr, str );
5154 //================================================================================
5156 * \brief Finds an object ID in the command
5157 * \param [in] longStr - the command string
5158 * \param [out] subStr - the found object ID
5159 * \return bool - \c true if the object ID found
5161 //================================================================================
5163 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5165 const _AString& longStr = cmd->GetString();
5166 const char* s = longStr.ToCString();
5169 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5170 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5171 if ( argBeg < 4 || argBeg > longStr.Length() )
5173 for ( ; itSub != _subFams.end(); ++itSub )
5176 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5177 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5179 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5180 from = pos + len + itSub->_prefix.Length();
5185 from += itSub->_prefix.Length();
5188 // look among _strings
5189 std::list< _AString >::iterator itStr = _strings.begin();
5190 for ( ; itStr != _strings.end(); ++itStr )
5191 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5192 // check that object ID does not continue after len
5193 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5195 subStr.push_back( *itStr );
5201 //================================================================================
5203 * \brief Return remainder length of the object ID after my _prefix
5204 * \param [in] str - remainder of the command after my _prefix
5205 * \return int - length of the object ID or -1 if not found
5207 //================================================================================
5209 int _pyStringFamily::isIn( const char* str )
5211 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5213 for ( ; itSub != _subFams.end(); ++itSub )
5215 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5218 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5219 return itSub->_prefix.Length() + len;
5224 if ( !_strings.empty() )
5226 std::list< _AString >::iterator itStr = _strings.begin();
5227 bool firstEmpty = itStr->IsEmpty();
5230 for ( ; itStr != _strings.end(); ++itStr )
5232 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5235 len = itStr->Length();
5244 // check that object ID does not continue after len
5245 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5252 //================================================================================
5256 //================================================================================
5258 void _pyStringFamily::Print( int level )
5260 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5261 std::list< _AString >::iterator itStr = _strings.begin();
5262 for ( ; itStr != _strings.end(); ++itStr )
5263 cout << *itStr << " | ";
5265 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5266 for ( ; itSub != _subFams.end(); ++itSub )
5267 itSub->Print( level + 1 );
5269 cout << string( 70, '-' ) << endl;