1 // Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 const int nbRes = cmd->GetNbResultValues();
187 for ( int i = 0; i < nbRes; i++ )
189 _pyID objID = cmd->GetResultValue( i+1 );
190 if ( cmd->IsStudyEntry( objID ))
191 isResultPublished = (! theGen->IsNotPublished( objID ));
192 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
194 if ( isResultPublished )
200 // check if an Object was created in the script
203 _pyID obj = cmd->GetObject();
204 if ( obj.Search( "print " ) == 1 )
205 return; // print statement
207 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
208 // remove an accessor method
209 obj = _pyCommand( obj ).GetObject();
211 const bool isMethodCall = cmd->IsMethodCall();
212 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
214 comment = "not created Object";
215 theGen->ObjectCreationRemoved( obj );
217 // check if a command has not created args
218 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
220 const _pyID& arg = cmd->GetArg( iArg );
221 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
223 list< _pyID > idList = cmd->GetStudyEntries( arg );
224 list< _pyID >::iterator id = idList.begin();
225 for ( ; id != idList.end(); ++id )
226 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
228 comment += *id + " has not been yet created";
231 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
232 // comment += arg + " has not been yet created";
234 // treat result objects
235 const _pyID& result = cmd->GetResultValue();
236 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
238 list< _pyID > idList = cmd->GetStudyEntries( result );
239 list< _pyID >::iterator id = idList.begin();
240 for ( ; id != idList.end(); ++id )
242 if ( comment.IsEmpty() )
243 presentObjects.insert( *id );
245 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
247 if ( idList.empty() && cmd->IsID( result ))
248 presentObjects.insert( result );
250 // comment the command
251 if ( !comment.IsEmpty() )
254 cmd->GetString() += " ### ";
255 cmd->GetString() += comment;
259 //================================================================================
261 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
263 //================================================================================
265 void fixFunctorType( TCollection_AsciiString& Type,
266 TCollection_AsciiString& Compare,
267 TCollection_AsciiString& UnaryOp,
268 TCollection_AsciiString& BinaryOp )
270 // The problem is that dumps of old studies created using filters becomes invalid
271 // when new items are inserted in the enum SMESH::FunctorType since values
272 // of this enum are dumped as integer values.
273 // This function corrects enum values of old studies given as args (Type,Compare,...)
274 // We can find out how to correct them by value of BinaryOp which can have only two
275 // values: FT_Undefined or FT_LogicalNOT.
276 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
277 // where PythonDump appeared
278 // v 3.0.0: FT_Undefined == 25
279 // v 3.1.0: FT_Undefined == 26, new items:
281 // v 4.1.2: FT_Undefined == 27, new items:
282 // - FT_BelongToGenSurface = 17
283 // v 5.1.1: FT_Undefined == 32, new items:
284 // - FT_FreeNodes = 10
285 // - FT_FreeFaces = 11
286 // - FT_LinearOrQuadratic = 23
287 // - FT_GroupColor = 24
288 // - FT_ElemGeomType = 25
289 // v 5.1.5: FT_Undefined == 33, new items:
290 // - FT_CoplanarFaces = 26
291 // v 6.2.0: FT_Undefined == 39, new items:
292 // - FT_MaxElementLength2D = 8
293 // - FT_MaxElementLength3D = 9
294 // - FT_BareBorderVolume = 25
295 // - FT_BareBorderFace = 26
296 // - FT_OverConstrainedVolume = 27
297 // - FT_OverConstrainedFace = 28
298 // v 6.5.0: FT_Undefined == 43, new items:
299 // - FT_EqualNodes = 14
300 // - FT_EqualEdges = 15
301 // - FT_EqualFaces = 16
302 // - FT_EqualVolumes = 17
303 // v 6.6.0: FT_Undefined == 44, new items:
304 // - FT_BallDiameter = 37
305 // v 6.7.1: FT_Undefined == 45, new items:
306 // - FT_EntityType = 36
307 // v 7.3.0: FT_Undefined == 46, new items:
308 // - FT_ConnectedElements = 39
309 // v 7.6.0: FT_Undefined == 47, new items:
310 // - FT_BelongToMeshGroup = 22
312 // It's necessary to continue recording this history and to fill
313 // undef2newItems (see below) accordingly.
315 typedef map< int, vector< int > > TUndef2newItems;
316 static TUndef2newItems undef2newItems;
317 if ( undef2newItems.empty() )
319 undef2newItems[ 26 ].push_back( 7 );
320 undef2newItems[ 27 ].push_back( 17 );
321 { int items[] = { 10, 11, 23, 24, 25 };
322 undef2newItems[ 32 ].assign( items, items+5 ); }
323 undef2newItems[ 33 ].push_back( 26 );
324 { int items[] = { 8, 9, 25, 26, 27, 28 };
325 undef2newItems[ 39 ].assign( items, items+6 ); }
326 { int items[] = { 14, 15, 16, 17 };
327 undef2newItems[ 43 ].assign( items, items+4 ); }
328 undef2newItems[ 44 ].push_back( 37 );
329 undef2newItems[ 45 ].push_back( 36 );
330 undef2newItems[ 46 ].push_back( 39 );
331 undef2newItems[ 47 ].push_back( 22 );
333 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
336 int iType = Type.IntegerValue();
337 int iCompare = Compare.IntegerValue();
338 int iUnaryOp = UnaryOp.IntegerValue();
339 int iBinaryOp = BinaryOp.IntegerValue();
341 // find out integer value of FT_Undefined at the moment of dump
342 int oldUndefined = iBinaryOp;
343 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
346 // apply history to args
347 TUndef2newItems::const_iterator undef_items =
348 undef2newItems.upper_bound( oldUndefined );
349 if ( undef_items != undef2newItems.end() )
351 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
352 for ( ; undef_items != undef2newItems.end(); ++undef_items )
354 const vector< int > & addedItems = undef_items->second;
355 for ( size_t i = 0; i < addedItems.size(); ++i )
356 for ( int iArg = 0; iArg < 4; ++iArg )
358 int& arg = *pArg[iArg];
359 if ( arg >= addedItems[i] )
363 Type = TCollection_AsciiString( iType );
364 Compare = TCollection_AsciiString( iCompare );
365 UnaryOp = TCollection_AsciiString( iUnaryOp );
366 BinaryOp = TCollection_AsciiString( iBinaryOp );
370 //================================================================================
372 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
373 * arguments of a given command by a list "[x,y,z]" if the list is accesible
376 //================================================================================
378 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
380 static TStringSet methodsAcceptingList;
381 if ( methodsAcceptingList.empty() ) {
382 const char * methodNames[] = {
383 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
384 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
385 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
386 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
387 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
388 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
389 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
390 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
391 "Translate","TranslateMakeGroups","TranslateMakeMesh",
392 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
393 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
394 ,"" }; // <- mark of the end
395 methodsAcceptingList.Insert( methodNames );
397 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
399 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
401 const _AString & arg = theCommand->GetArg( i );
402 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
403 arg.Search( "SMESH.DirStruct" ) == 1 )
405 Handle(_pyCommand) workCmd = new _pyCommand( arg );
406 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
408 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
410 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
412 _AString newArg = "[ ";
413 newArg += ( workCmd->GetArg( 1 ) + ", " +
414 workCmd->GetArg( 2 ) + ", " +
415 workCmd->GetArg( 3 ) + " ]");
416 theCommand->SetArg( i, newArg );
422 //================================================================================
424 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
425 * a list "[id1,id2]" if the list is an accesible type of argument.
427 //================================================================================
429 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
431 static TStringSet methodsAcceptingList;
432 if ( methodsAcceptingList.empty() ) {
433 const char * methodNames[] = {
434 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
435 "ExportCGNS","ExportGMF",
436 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
437 "ScaleMakeGroups","Scale","ScaleMakeMesh",
438 "FindCoincidentNodesOnPartBut","DoubleElements",
439 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
440 ,"" }; // <- mark of the end
441 methodsAcceptingList.Insert( methodNames );
443 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
445 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
447 _pyCommand argCmd( theCommand->GetArg( i ));
448 if ( argCmd.GetMethod() == "GetIDSource" &&
449 argCmd.GetNbArgs() == 2 )
451 theCommand->SetArg( i, argCmd.GetArg( 1 ));
458 //================================================================================
460 * \brief Convert a python script using commands of smeshBuilder.py
461 * \param theScriptLines - Lines of the input script
462 * \param theEntry2AccessorMethod - returns method names to access to
463 * objects wrapped with python class
464 * \param theObjectNames - names of objects
465 * \param theRemovedObjIDs - entries of objects whose created commands were removed
466 * \param theHistoricalDump - true means to keep all commands, false means
467 * to exclude commands relating to objects removed from study
468 * \retval TCollection_AsciiString - Convertion result
470 //================================================================================
473 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
474 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
475 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
476 std::set< TCollection_AsciiString >& theRemovedObjIDs,
477 SALOMEDS::Study_ptr& theStudy,
478 const bool theToKeepAllCommands)
480 std::list< TCollection_AsciiString >::iterator lineIt;
481 // process notebook variables
483 SMESH_NoteBook aNoteBook;
485 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
486 aNoteBook.AddCommand( *lineIt );
488 theScriptLines.clear();
490 aNoteBook.ReplaceVariables();
492 aNoteBook.GetResultLines( theScriptLines );
495 // convert to smeshBuilder.py API
497 theGen = new _pyGen( theEntry2AccessorMethod,
501 theToKeepAllCommands );
503 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504 theGen->AddCommand( *lineIt );
506 theScriptLines.clear();
510 #ifdef DUMP_CONVERSION
511 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
514 // clean commmands of removed objects depending on myIsPublished flag
515 theGen->ClearCommands();
517 // reorder commands after conversion
518 list< Handle(_pyCommand) >::iterator cmd;
521 orderChanges = false;
522 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
523 if ( (*cmd)->SetDependentCmdsAfter() )
525 } while ( orderChanges );
527 // concat commands back into a script
528 TCollection_AsciiString aPrevCmd;
529 set<_pyID> createdObjects;
530 createdObjects.insert( "smeshBuilder" );
531 createdObjects.insert( "smesh" );
532 createdObjects.insert( "theStudy" );
533 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
535 #ifdef DUMP_CONVERSION
536 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
538 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
539 CheckObjectPresence( *cmd, createdObjects );
540 if ( !(*cmd)->IsEmpty() ) {
541 aPrevCmd = (*cmd)->GetString();
542 theScriptLines.push_back( aPrevCmd );
551 //================================================================================
553 * \brief _pyGen constructor
555 //================================================================================
557 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
558 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
559 std::set< TCollection_AsciiString >& theRemovedObjIDs,
560 SALOMEDS::Study_ptr& theStudy,
561 const bool theToKeepAllCommands)
562 : _pyObject( new _pyCommand( "", 0 )),
564 myID2AccessorMethod( theEntry2AccessorMethod ),
565 myObjectNames( theObjectNames ),
566 myRemovedObjIDs( theRemovedObjIDs ),
568 myToKeepAllCommands( theToKeepAllCommands ),
569 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
570 myGeomIDNb(0), myGeomIDIndex(-1)
572 // make that GetID() to return TPythonDump::SMESHGenName()
573 GetCreationCmd()->Clear();
574 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
575 GetCreationCmd()->GetString() += "=";
577 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
578 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
582 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
583 if ( geomComp->_is_nil() ) return;
584 CORBA::String_var entry = geomComp->GetID();
587 // find a SMESH entry
589 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
590 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
591 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
594 // find 1st difference between smeshID and geomID
595 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
596 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
597 if ( geomID.Value( i ) != smeshID.Value( i ))
599 myGeomIDNb = geomID.Value( i );
605 //================================================================================
607 * \brief name of SMESH_Gen in smeshBuilder.py
609 //================================================================================
611 const char* _pyGen::AccessorMethod() const
613 return SMESH_2smeshpy::GenName();
616 //================================================================================
618 * \brief Convert a command using a specific converter
619 * \param theCommand - the command to convert
621 //================================================================================
623 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
625 // store theCommand in the sequence
626 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
628 Handle(_pyCommand) aCommand = myCommands.back();
629 #ifdef DUMP_CONVERSION
630 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
633 const _pyID& objID = aCommand->GetObject();
635 if ( objID.IsEmpty() )
638 // Prevent moving a command creating a sub-mesh to the end of the script
639 // if the sub-mesh is used in theCommand as argument
640 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
642 // PlaceSubmeshAfterItsCreation( aCommand );
645 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
646 StructToList( aCommand );
648 const TCollection_AsciiString& method = aCommand->GetMethod();
650 // not to erase _pySelfEraser's etc. used as args in some commands
652 #ifdef USE_STRING_FAMILY
653 std::list<_pyID> objIDs;
654 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
656 std::list<_pyID>::iterator objID = objIDs.begin();
657 for ( ; objID != objIDs.end(); ++objID )
659 Handle(_pyObject) obj = FindObject( *objID );
662 obj->AddArgCmd( aCommand );
663 //cout << objID << " found in " << theCommand << endl;
668 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
669 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
670 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
672 Handle(_pyObject) obj = FindObject( *id );
674 obj->AddArgCmd( aCommand );
679 // Find an object to process theCommand
682 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
684 this->Process( aCommand );
685 //addFilterUser( aCommand, theGen ); // protect filters from clearing
689 // SMESH_Mesh method?
690 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
691 if ( id_mesh != myMeshes.end() )
693 //id_mesh->second->AddProcessedCmd( aCommand );
695 // check for mesh editor object
696 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
697 _pyID editorID = aCommand->GetResultValue();
698 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
699 myMeshEditors.insert( make_pair( editorID, editor ));
702 // check for SubMesh objects
703 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
704 _pyID subMeshID = aCommand->GetResultValue();
705 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
706 AddObject( subMesh );
709 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
710 GetIDSourceToList( aCommand );
712 //addFilterUser( aCommand, theGen ); // protect filters from clearing
714 id_mesh->second->Process( aCommand );
715 id_mesh->second->AddProcessedCmd( aCommand );
719 // SMESH_MeshEditor method?
720 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
721 if ( id_editor != myMeshEditors.end() )
723 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
724 GetIDSourceToList( aCommand );
726 //addFilterUser( aCommand, theGen ); // protect filters from clearing
728 // some commands of SMESH_MeshEditor create meshes and groups
729 _pyID meshID, groups;
730 if ( method.Search("MakeMesh") != -1 )
731 meshID = aCommand->GetResultValue();
732 else if ( method == "MakeBoundaryMesh")
733 meshID = aCommand->GetResultValue(1);
734 else if ( method == "MakeBoundaryElements")
735 meshID = aCommand->GetResultValue(2);
737 if ( method.Search("MakeGroups") != -1 ||
738 method == "ExtrusionAlongPathX" ||
739 method == "ExtrusionAlongPathObjX" ||
740 method == "DoubleNodeGroupNew" ||
741 method == "DoubleNodeGroupsNew" ||
742 method == "DoubleNodeElemGroupNew" ||
743 method == "DoubleNodeElemGroupsNew"||
744 method == "DoubleNodeElemGroup2New"||
745 method == "DoubleNodeElemGroups2New"
747 groups = aCommand->GetResultValue();
748 else if ( method == "MakeBoundaryMesh" )
749 groups = aCommand->GetResultValue(2);
750 else if ( method == "MakeBoundaryElements")
751 groups = aCommand->GetResultValue(3);
752 else if ( method == "Create0DElementsOnAllNodes" &&
753 aCommand->GetArg(2).Length() > 2 ) // group name != ''
754 groups = aCommand->GetResultValue();
756 id_editor->second->Process( aCommand );
757 id_editor->second->AddProcessedCmd( aCommand );
760 if ( !meshID.IsEmpty() &&
761 !myMeshes.count( meshID ) &&
762 aCommand->IsStudyEntry( meshID ))
764 _AString processedCommand = aCommand->GetString();
765 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
766 CheckObjectIsReCreated( mesh );
767 myMeshes.insert( make_pair( meshID, mesh ));
769 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
772 if ( !groups.IsEmpty() )
774 if ( !aCommand->IsStudyEntry( meshID ))
775 meshID = id_editor->second->GetMesh();
776 Handle(_pyMesh) mesh = myMeshes[ meshID ];
778 list< _pyID > idList = aCommand->GetStudyEntries( groups );
779 list< _pyID >::iterator grID = idList.begin();
780 for ( ; grID != idList.end(); ++grID )
781 if ( !myObjects.count( *grID ))
783 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
785 if ( !mesh.IsNull() ) mesh->AddGroup( group );
789 } // SMESH_MeshEditor methods
791 // SMESH_Hypothesis method?
792 Handle(_pyHypothesis) hyp = FindHyp( objID );
793 if ( !hyp.IsNull() && !hyp->IsAlgo() )
795 hyp->Process( aCommand );
796 hyp->AddProcessedCmd( aCommand );
800 // aFilterManager.CreateFilter() ?
801 if ( aCommand->GetMethod() == "CreateFilter" )
803 // Set a more human readable name to a filter
804 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
805 _pyID newID, filterID = aCommand->GetResultValue();
806 int pos = filterID.Search( "0x" );
808 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
810 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
813 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
814 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
816 // create _pySelfEraser for functors
817 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
818 functor->IgnoreOwnCalls(); // to erase if not used as an argument
819 AddObject( functor );
822 // other object method?
823 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
824 if ( id_obj != myObjects.end() ) {
825 id_obj->second->Process( aCommand );
826 id_obj->second->AddProcessedCmd( aCommand );
830 // Add access to a wrapped mesh
831 AddMeshAccessorMethod( aCommand );
833 // Add access to a wrapped algorithm
834 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
836 // PAL12227. PythonDump was not updated at proper time; result is
837 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
838 // TypeError: __init__() takes exactly 11 arguments (10 given)
839 const char wrongCommand[] = "SMESH.Filter.Criterion(";
840 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
842 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
843 // there must be 10 arguments, 5-th arg ThresholdID is missing,
844 const int wrongNbArgs = 9, missingArg = 5;
845 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
847 for ( int i = wrongNbArgs; i > missingArg; --i )
848 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
849 tmpCmd.SetArg( missingArg, "''");
850 aCommand->GetString().Trunc( beg - 1 );
851 aCommand->GetString() += tmpCmd.GetString();
854 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
856 // instead of "SMESH.Filter.Criterion(
857 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
858 // 1 2 3 4 5 6 7 8 9 10
859 // in order to avoid the problem of type mismatch of long and FunctorType
860 const TCollection_AsciiString
861 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
862 TCollection_AsciiString
863 Type = aCommand->GetArg(1), // long
864 Compare = aCommand->GetArg(2), // long
865 Threshold = aCommand->GetArg(3), // double
866 ThresholdStr = aCommand->GetArg(4), // string
867 ThresholdID = aCommand->GetArg(5), // string
868 UnaryOp = aCommand->GetArg(6), // long
869 BinaryOp = aCommand->GetArg(7), // long
870 Tolerance = aCommand->GetArg(8), // double
871 TypeOfElement = aCommand->GetArg(9), // ElementType
872 Precision = aCommand->GetArg(10); // long
873 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
874 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
875 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
876 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
877 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
879 if ( Compare == "SMESH.FT_EqualTo" )
882 aCommand->RemoveArgs();
883 aCommand->SetObject( SMESH_2smeshpy::GenName() );
884 aCommand->SetMethod( "GetCriterion" );
886 aCommand->SetArg( 1, TypeOfElement );
887 aCommand->SetArg( 2, Type );
888 aCommand->SetArg( 3, Compare );
890 if ( Threshold.IsIntegerValue() )
892 int iGeom = Threshold.IntegerValue();
893 if ( Type == "SMESH.FT_ElemGeomType" )
895 // set SMESH.GeometryType instead of a numerical Threshold
896 const int nbTypes = SMESH::Geom_LAST;
897 const char* types[nbTypes] = {
898 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
899 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
900 "Geom_POLYHEDRA", "Geom_BALL" };
901 if ( -1 < iGeom && iGeom < nbTypes )
902 Threshold = SMESH + types[ iGeom ];
904 // is types complete? (compilation failure mains that enum GeometryType changed)
905 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
908 if (Type == "SMESH.FT_EntityType")
910 // set SMESH.EntityType instead of a numerical Threshold
911 const int nbTypes = SMESH::Entity_Last;
912 const char* types[nbTypes] = {
913 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
914 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
915 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
916 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
917 "Entity_Pyramid", "Entity_Quad_Pyramid",
918 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
919 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
920 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
921 if ( -1 < iGeom && iGeom < nbTypes )
922 Threshold = SMESH + types[ iGeom ];
924 // is types complete? (compilation failure mains that enum EntityType changed)
925 int _assert[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 1 : -1 ];
929 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
930 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
931 else if ( ThresholdStr.Length() != 2 )
932 aCommand->SetArg( 4, ThresholdStr );
933 else if ( ThresholdID.Length() != 2 )
934 aCommand->SetArg( 4, ThresholdID );
936 aCommand->SetArg( 4, Threshold );
937 // find the last not default arg
939 if ( Tolerance == dfltTol ) {
941 if ( BinaryOp == dfltFunctor ) {
943 if ( UnaryOp == dfltFunctor )
947 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
948 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
949 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
950 if ( Precision != dfltPreci )
952 TCollection_AsciiString crit = aCommand->GetResultValue();
953 aCommand->GetString() += "; ";
954 aCommand->GetString() += crit + ".Precision = " + Precision;
960 //================================================================================
962 * \brief Convert the command or remember it for later conversion
963 * \param theCommand - The python command calling a method of SMESH_Gen
965 //================================================================================
967 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
969 // there are methods to convert:
970 // CreateMesh( shape )
971 // Concatenate( [mesh1, ...], ... )
972 // CreateHypothesis( theHypType, theLibName )
973 // Compute( mesh, geom )
974 // Evaluate( mesh, geom )
976 TCollection_AsciiString method = theCommand->GetMethod();
978 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
980 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
984 if ( method == "CreateMeshesFromUNV" ||
985 method == "CreateMeshesFromSTL" ||
986 method == "CopyMesh" ) // command result is a mesh
988 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
992 if( method == "CreateMeshesFromMED" ||
993 method == "CreateMeshesFromSAUV"||
994 method == "CreateMeshesFromCGNS" ||
995 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
997 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
998 std::list< _pyID >::iterator meshID = meshIDs.begin();
999 for ( ; meshID != meshIDs.end(); ++meshID )
1001 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1004 if ( method == "CreateMeshesFromGMF" )
1006 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1007 // CreateMeshesFromGMF( theFileName )
1008 _AString file = theCommand->GetArg(1);
1009 theCommand->RemoveArgs();
1010 theCommand->SetArg( 1, file );
1014 // CreateHypothesis()
1015 if ( method == "CreateHypothesis" )
1017 // issue 199929, remove standard library name (default parameter)
1018 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1019 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1020 // keep the first argument
1021 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1022 theCommand->RemoveArgs();
1023 theCommand->SetArg( 1, arg );
1026 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1027 CheckObjectIsReCreated( hyp );
1028 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1033 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1034 if ( method == "Compute" )
1036 const _pyID& meshID = theCommand->GetArg( 1 );
1037 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1038 if ( id_mesh != myMeshes.end() ) {
1039 theCommand->SetObject( meshID );
1040 theCommand->RemoveArgs();
1041 id_mesh->second->Process( theCommand );
1042 id_mesh->second->AddProcessedCmd( theCommand );
1047 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1048 if ( method == "Evaluate" )
1050 const _pyID& meshID = theCommand->GetArg( 1 );
1051 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1052 if ( id_mesh != myMeshes.end() ) {
1053 theCommand->SetObject( meshID );
1054 _pyID geom = theCommand->GetArg( 2 );
1055 theCommand->RemoveArgs();
1056 theCommand->SetArg( 1, geom );
1057 id_mesh->second->AddProcessedCmd( theCommand );
1062 // objects erasing creation command if no more its commands invoked:
1063 // SMESH_Pattern, FilterManager
1064 if ( method == "GetPattern" ||
1065 method == "CreateFilterManager" ||
1066 method == "CreateMeasurements" )
1068 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1069 if ( !AddObject( obj ) )
1070 theCommand->Clear(); // already created
1072 // Concatenate( [mesh1, ...], ... )
1073 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1075 if ( method == "ConcatenateWithGroups" ) {
1076 theCommand->SetMethod( "Concatenate" );
1077 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1079 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1081 AddMeshAccessorMethod( theCommand );
1083 else if ( method == "SetName" ) // SetName(obj,name)
1085 // store theCommand as one of object commands to erase it along with the object
1086 const _pyID& objID = theCommand->GetArg( 1 );
1087 Handle(_pyObject) obj = FindObject( objID );
1088 if ( !obj.IsNull() )
1089 obj->AddProcessedCmd( theCommand );
1092 // Replace name of SMESH_Gen
1094 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1095 static TStringSet smeshpyMethods;
1096 if ( smeshpyMethods.empty() ) {
1097 const char * names[] =
1098 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1099 "GetPattern","GetSubShapesId",
1100 "" }; // <- mark of array end
1101 smeshpyMethods.Insert( names );
1103 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1104 // smeshgen.Method() --> smesh.Method()
1105 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1107 // smeshgen.Method() --> smesh.Method()
1108 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1111 //================================================================================
1113 * \brief Convert the remembered commands
1115 //================================================================================
1117 void _pyGen::Flush()
1119 // create an empty command
1120 myLastCommand = new _pyCommand();
1122 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1123 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1124 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1126 if ( IsToKeepAllCommands() ) // historical dump
1128 // set myIsPublished = true to all objects
1129 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1130 id_mesh->second->SetRemovedFromStudy( false );
1131 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1132 id_hyp->second->SetRemovedFromStudy( false );
1133 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1134 id_obj->second->SetRemovedFromStudy( false );
1138 // let hypotheses find referred objects in order to prevent clearing
1139 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1140 list< Handle(_pyMesh) > fatherMeshes;
1141 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1142 if ( !id_hyp->second.IsNull() )
1143 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1145 // set myIsPublished = false to all objects depending on
1146 // meshes built on a removed geometry
1147 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1148 if ( id_mesh->second->IsNotGeomPublished() )
1149 id_mesh->second->SetRemovedFromStudy( true );
1152 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1153 if ( ! id_mesh->second.IsNull() )
1154 id_mesh->second->Flush();
1157 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1158 if ( !id_hyp->second.IsNull() ) {
1159 id_hyp->second->Flush();
1160 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1161 if ( !id_hyp->second->IsWrapped() )
1162 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1165 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1166 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1167 for ( ; robj != myOrderedObjects.rend(); ++robj )
1168 if ( ! robj->IsNull() )
1170 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1171 for ( ; obj != myOrderedObjects.end(); ++obj )
1172 if ( ! obj->IsNull() )
1175 myLastCommand->SetOrderNb( ++myNbCommands );
1176 myCommands.push_back( myLastCommand );
1179 //================================================================================
1181 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1182 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1184 //================================================================================
1186 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1188 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1189 // for ( ; id_obj != myObjects.end(); ++id_obj )
1191 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1192 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1194 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1195 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1197 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1198 // list< _pyID >::iterator id = idList.begin();
1199 // for ( ; id != idList.end(); ++id )
1200 // if ( id_obj->first == *id )
1201 // // _pySubMesh::Process() does what we need
1202 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1207 //================================================================================
1209 * \brief Clean commmands of removed objects depending on myIsPublished flag
1211 //================================================================================
1213 void _pyGen::ClearCommands()
1215 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1216 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1217 id_mesh->second->ClearCommands();
1219 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1220 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1221 if ( !id_hyp->second.IsNull() )
1222 id_hyp->second->ClearCommands();
1224 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1225 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1226 for ( ; robj != myOrderedObjects.rend(); ++robj )
1227 if ( ! robj->IsNull() )
1228 (*robj)->ClearCommands();
1229 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1230 for ( ; obj != myOrderedObjects.end(); ++obj )
1231 if ( ! obj->IsNull() )
1232 (*obj)->ClearCommands();
1235 //================================================================================
1237 * \brief Release mutual handles of objects
1239 //================================================================================
1243 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1244 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1245 id_mesh->second->Free();
1248 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1249 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1250 id_ed->second->Free();
1251 myMeshEditors.clear();
1253 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1254 for ( ; id_obj != myObjects.end(); ++id_obj )
1255 id_obj->second->Free();
1258 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1259 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1260 if ( !id_hyp->second.IsNull() )
1261 id_hyp->second->Free();
1264 myFile2ExportedMesh.clear();
1266 //myKeepAgrCmdsIDs.Print();
1269 //================================================================================
1271 * \brief Add access method to mesh that is an argument
1272 * \param theCmd - command to add access method
1273 * \retval bool - true if added
1275 //================================================================================
1277 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1280 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1281 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1282 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1288 //================================================================================
1290 * \brief Add access method to algo that is an object or an argument
1291 * \param theCmd - command to add access method
1292 * \retval bool - true if added
1294 //================================================================================
1296 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1299 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1300 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1301 if ( !id_hyp->second.IsNull() &&
1302 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1303 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1304 id_hyp->second->AccessorMethod() ))
1310 //================================================================================
1312 * \brief Find hypothesis by ID (entry)
1313 * \param theHypID - The hypothesis ID
1314 * \retval Handle(_pyHypothesis) - The found hypothesis
1316 //================================================================================
1318 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1320 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1321 if ( id_hyp != myHypos.end() &&
1322 !id_hyp->second.IsNull() &&
1323 theHypID == id_hyp->second->GetID() )
1324 return id_hyp->second;
1325 return Handle(_pyHypothesis)();
1328 //================================================================================
1330 * \brief Find algorithm able to create a hypothesis
1331 * \param theGeom - The shape ID the algorithm was created on
1332 * \param theMesh - The mesh ID that created the algorithm
1333 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1334 * \retval Handle(_pyHypothesis) - The found algo
1336 //================================================================================
1338 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1339 const Handle(_pyHypothesis)& theHypothesis )
1341 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1342 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1343 if ( !id_hyp->second.IsNull() &&
1344 id_hyp->second->IsAlgo() &&
1345 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1346 id_hyp->second->GetGeom() == theGeom &&
1347 id_hyp->second->GetMesh() == theMesh )
1348 return id_hyp->second;
1349 return Handle(_pyHypothesis)();
1352 //================================================================================
1354 * \brief Find subMesh by ID (entry)
1355 * \param theSubMeshID - The subMesh ID
1356 * \retval Handle(_pySubMesh) - The found subMesh
1358 //================================================================================
1360 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1362 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1363 if ( id_subMesh != myObjects.end() )
1364 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1365 return Handle(_pySubMesh)();
1369 //================================================================================
1371 * \brief Change order of commands in the script
1372 * \param theCmd1 - One command
1373 * \param theCmd2 - Another command
1375 //================================================================================
1377 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1379 list< Handle(_pyCommand) >::iterator pos1, pos2;
1380 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1381 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1382 myCommands.insert( pos1, theCmd2 );
1383 myCommands.insert( pos2, theCmd1 );
1384 myCommands.erase( pos1 );
1385 myCommands.erase( pos2 );
1387 int nb1 = theCmd1->GetOrderNb();
1388 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1389 theCmd2->SetOrderNb( nb1 );
1390 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1391 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1394 //================================================================================
1396 * \brief Set one command after the other
1397 * \param theCmd - Command to move
1398 * \param theAfterCmd - Command ater which to insert the first one
1400 //================================================================================
1402 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1404 setNeighbourCommand( theCmd, theAfterCmd, true );
1407 //================================================================================
1409 * \brief Set one command before the other
1410 * \param theCmd - Command to move
1411 * \param theBeforeCmd - Command before which to insert the first one
1413 //================================================================================
1415 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1417 setNeighbourCommand( theCmd, theBeforeCmd, false );
1420 //================================================================================
1422 * \brief Set one command before or after the other
1423 * \param theCmd - Command to move
1424 * \param theOtherCmd - Command ater or before which to insert the first one
1426 //================================================================================
1428 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1429 Handle(_pyCommand)& theOtherCmd,
1430 const bool theIsAfter )
1432 list< Handle(_pyCommand) >::iterator pos;
1433 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1434 myCommands.erase( pos );
1435 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1436 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1439 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1440 (*pos)->SetOrderNb( i++ );
1443 //================================================================================
1445 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1447 //================================================================================
1449 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1451 // No more needed after adding _pyObject::myArgCommands
1453 // const char filterPrefix[] = "aFilter0x";
1454 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1457 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1459 // const _AString & arg = theCommand->GetArg( i );
1460 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1461 // if ( arg.Search( filterPrefix ) != 1 )
1464 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1465 // if ( !filter.IsNull() )
1467 // filter->AddUser( user );
1468 // if ( !filter->GetNewID().IsEmpty() )
1469 // theCommand->SetArg( i, filter->GetNewID() );
1474 //================================================================================
1476 * \brief Set command be last in list of commands
1477 * \param theCmd - Command to be last
1479 //================================================================================
1481 Handle(_pyCommand)& _pyGen::GetLastCommand()
1483 return myLastCommand;
1486 //================================================================================
1488 * \brief Set method to access to object wrapped with python class
1489 * \param theID - The wrapped object entry
1490 * \param theMethod - The accessor method
1492 //================================================================================
1494 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1496 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1499 //================================================================================
1501 * \brief Generated new ID for object and assign with existing name
1502 * \param theID - ID of existing object
1504 //================================================================================
1506 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1511 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1513 while ( myObjectNames.IsBound( aNewID ) );
1515 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1516 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1517 : _pyID( "A" ) + aNewID );
1521 //================================================================================
1523 * \brief Stores theObj in myObjects
1525 //================================================================================
1527 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1529 if ( theObj.IsNull() ) return false;
1531 CheckObjectIsReCreated( theObj );
1535 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1536 add = myMeshes.insert( make_pair( theObj->GetID(),
1537 Handle(_pyMesh)::DownCast( theObj ))).second;
1539 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1540 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1541 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1544 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1545 if ( add ) myOrderedObjects.push_back( theObj );
1550 //================================================================================
1552 * \brief Erases an existing object with the same ID. This method should be called
1553 * before storing theObj in _pyGen
1555 //================================================================================
1557 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1559 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1562 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1563 Handle(_pyObject) existing =
1564 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1565 if ( !existing.IsNull() && existing != theObj )
1567 existing->SetRemovedFromStudy( true );
1568 existing->ClearCommands();
1571 if ( myHypos.count( theObj->GetID() ))
1572 myHypos.erase( theObj->GetID() );
1574 else if ( myMeshes.count( theObj->GetID() ))
1576 myMeshes.erase( theObj->GetID() );
1578 else if ( myObjects.count( theObj->GetID() ))
1580 myObjects.erase( theObj->GetID() );
1585 //================================================================================
1587 * \brief Re-register an object with other ID to make it Process() commands of
1588 * other object having this ID
1590 //================================================================================
1592 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1594 if ( theObj.IsNull() ) return;
1596 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1597 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1599 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1600 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1603 myObjects.insert( make_pair( theID, theObj ));
1606 //================================================================================
1608 * \brief Finds a _pyObject by ID
1610 //================================================================================
1612 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1615 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1616 if ( id_obj != myObjects.end() )
1617 return id_obj->second;
1620 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1621 if ( id_obj != myMeshes.end() )
1622 return id_obj->second;
1625 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1626 // if ( id_obj != myMeshEditors.end() )
1627 // return id_obj->second;
1629 return Handle(_pyObject)();
1632 //================================================================================
1634 * \brief Check if a study entry is under GEOM component
1636 //================================================================================
1638 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1642 return ( myGeomIDIndex <= theObjID.Length() &&
1643 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1644 _pyCommand::IsStudyEntry( theObjID ));
1649 //================================================================================
1651 * \brief Returns true if an object is not present in a study
1653 //================================================================================
1655 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1657 if ( theObjID.IsEmpty() ) return false;
1659 if ( myObjectNames.IsBound( theObjID ))
1660 return false; // SMESH object is in study
1662 // either the SMESH object is not in study or it is a GEOM object
1663 if ( IsGeomObject( theObjID ))
1665 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1666 if ( so->_is_nil() ) return true;
1667 CORBA::Object_var obj = so->GetObject();
1668 return CORBA::is_nil( obj );
1670 return true; // SMESH object not in study
1673 //================================================================================
1675 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1676 * this object is not dumped
1677 * \param [in] theObjID - entry of the object whose creation command was eliminated
1679 //================================================================================
1681 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1683 myRemovedObjIDs.insert( theObjID );
1686 //================================================================================
1688 * \brief Return reader of hypotheses of plugins
1690 //================================================================================
1692 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1694 if (myHypReader.IsNull() )
1695 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1701 //================================================================================
1703 * \brief Mesh created by SMESH_Gen
1705 //================================================================================
1707 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1708 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1710 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1711 myGeomNotInStudy = true;
1713 // convert my creation command --> smeshpy.Mesh(...)
1714 Handle(_pyCommand) creationCmd = GetCreationCmd();
1715 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1716 creationCmd->SetMethod( "Mesh" );
1717 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1720 //================================================================================
1722 * \brief Mesh created by SMESH_MeshEditor
1724 //================================================================================
1726 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1727 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1729 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1731 // this mesh depends on the exported mesh
1732 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1733 if ( !file.IsEmpty() )
1735 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1736 addFatherMesh( exportData.myMesh );
1737 if ( !exportData.myLastComputeCmd.IsNull() )
1739 // restore cleared Compute() by which the exported mesh was generated
1740 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1741 // protect that Compute() cmd from clearing
1742 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1743 exportData.myMesh->myLastComputeCmd.Nullify();
1747 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1749 // this mesh depends on concatenated meshes
1750 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1751 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1752 list< _pyID >::iterator meshID = idList.begin();
1753 for ( ; meshID != idList.end(); ++meshID )
1754 addFatherMesh( *meshID );
1756 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1758 // this mesh depends on a copied IdSource
1759 const _pyID& objID = theCreationCmd->GetArg( 1 );
1760 addFatherMesh( objID );
1762 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1763 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1764 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1766 // this mesh depends on a source mesh
1767 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1768 const _pyID& meshID = theCreationCmd->GetObject();
1769 addFatherMesh( meshID );
1772 // convert my creation command
1773 Handle(_pyCommand) creationCmd = GetCreationCmd();
1774 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1775 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1778 //================================================================================
1780 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1781 * \param theCommand - Engine method called for this mesh
1783 //================================================================================
1785 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1787 // some methods of SMESH_Mesh interface needs special conversion
1788 // to methods of Mesh python class
1790 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1791 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1792 // 2. AddHypothesis(geom, hyp)
1793 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1794 // 3. CreateGroupFromGEOM(type, name, grp)
1795 // --> in Mesh.Group(grp, name="")
1796 // 4. ExportToMED(f, auto_groups, version)
1797 // --> in Mesh.ExportMED( f, auto_groups, version )
1800 const TCollection_AsciiString& method = theCommand->GetMethod();
1801 // ----------------------------------------------------------------------
1802 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1804 if ( !theGen->IsToKeepAllCommands() ) // !historical
1806 list< Handle(_pyHypothesis) >::iterator hyp;
1807 if ( !myLastComputeCmd.IsNull() )
1809 // check if the previously computed mesh has been edited,
1810 // if so then we do not clear the previous Compute()
1811 bool toClear = true;
1812 if ( myLastComputeCmd->GetMethod() == "Compute" )
1814 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1815 for ( ; e != myEditors.end() && toClear; ++e )
1817 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1818 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1819 if ( cmd != cmds.rend() &&
1820 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1826 // clear hyp commands called before myLastComputeCmd
1827 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1828 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1830 myLastComputeCmd->Clear();
1833 myLastComputeCmd = theCommand;
1835 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1836 (*hyp)->MeshComputed( myLastComputeCmd );
1840 // ----------------------------------------------------------------------
1841 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1843 if ( !theGen->IsToKeepAllCommands() ) // !historical
1846 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1847 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1848 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1850 if ( !myLastComputeCmd.IsNull() )
1852 list< Handle(_pyHypothesis) >::iterator hyp;
1853 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1854 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1856 myLastComputeCmd->Clear();
1859 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1860 for ( ; e != myEditors.end(); ++e )
1862 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1863 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1864 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1865 if ( !(*cmd)->IsEmpty() )
1867 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1871 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1874 // ----------------------------------------------------------------------
1875 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1876 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1877 if ( !subMesh.IsNull() ) {
1878 subMesh->SetCreator( this );
1879 mySubmeshes.push_back( subMesh );
1882 // ----------------------------------------------------------------------
1883 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1884 myAddHypCmds.push_back( theCommand );
1886 const _pyID& hypID = theCommand->GetArg( 2 );
1887 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1888 if ( !hyp.IsNull() ) {
1889 myHypos.push_back( hyp );
1890 if ( hyp->GetMesh().IsEmpty() )
1891 hyp->SetMesh( this->GetID() );
1894 // ----------------------------------------------------------------------
1895 else if ( method == "CreateGroup" ||
1896 method == "CreateGroupFromGEOM" ||
1897 method == "CreateGroupFromFilter" ||
1898 method == "CreateDimGroup" )
1900 Handle(_pyGroup) group = new _pyGroup( theCommand );
1901 myGroups.push_back( group );
1902 theGen->AddObject( group );
1904 // ----------------------------------------------------------------------
1905 // update list of groups
1906 else if ( method == "GetGroups" )
1908 bool allGroupsRemoved = true;
1909 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1910 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1911 list< _pyID >::iterator grID = idList.begin();
1912 const int nbGroupsBefore = myGroups.size();
1913 Handle(_pyObject) obj;
1914 for ( ; grID != idList.end(); ++grID )
1916 obj = theGen->FindObject( *grID );
1919 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1920 theGen->AddObject( group );
1921 myGroups.push_back( group );
1924 if ( !obj->CanClear() )
1925 allGroupsRemoved = false;
1927 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1928 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1930 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1932 // check if the preceding command is Compute();
1933 // if GetGroups() is just after Compute(), this can mean that the groups
1934 // were created by some algorithm and hence Compute() should not be discarded
1935 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1936 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1937 while ( (*cmd)->GetMethod() == "GetGroups" )
1939 if ( myLastComputeCmd == (*cmd))
1940 // protect last Compute() from clearing by the next Compute()
1941 myLastComputeCmd.Nullify();
1944 // ----------------------------------------------------------------------
1945 // notify a group about full removal
1946 else if ( method == "RemoveGroupWithContents" ||
1947 method == "RemoveGroup")
1949 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1950 const _pyID groupID = theCommand->GetArg( 1 );
1951 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1952 if ( !grp.IsNull() )
1954 if ( method == "RemoveGroupWithContents" )
1955 grp->RemovedWithContents();
1956 // to clear RemoveGroup() if the group creation is cleared
1957 grp->AddProcessedCmd( theCommand );
1961 // ----------------------------------------------------------------------
1962 else if ( theCommand->MethodStartsFrom( "Export" ))
1964 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1965 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1967 theCommand->SetMethod( "ExportMED" );
1968 if ( theCommand->GetNbArgs() == 5 )
1970 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1971 _AString autoDimension = theCommand->GetArg( 5 );
1972 theCommand->SetArg( 5, "None" );
1973 theCommand->SetArg( 6, autoDimension );
1976 else if ( method == "ExportCGNS" )
1977 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1978 _pyID partID = theCommand->GetArg( 1 );
1979 int nbArgs = theCommand->GetNbArgs();
1980 for ( int i = 2; i <= nbArgs; ++i )
1981 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1982 theCommand->SetArg( nbArgs, partID );
1984 else if ( method == "ExportGMF" )
1985 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1986 _pyID partID = theCommand->GetArg( 1 );
1987 _AString file = theCommand->GetArg( 2 );
1988 theCommand->RemoveArgs();
1989 theCommand->SetArg( 1, file );
1990 theCommand->SetArg( 2, partID );
1992 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1993 { // ExportPartTo*(part, ...) -> Export*(..., part)
1995 // remove "PartTo" from the method
1996 TCollection_AsciiString newMethod = method;
1997 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
1998 theCommand->SetMethod( newMethod );
1999 // make the 1st arg be the last one (or last but three for ExportMED())
2000 _pyID partID = theCommand->GetArg( 1 );
2001 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2002 for ( int i = 2; i <= nbArgs; ++i )
2003 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2004 theCommand->SetArg( nbArgs, partID );
2006 // remember file name
2007 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2008 ExportedMeshData( this, myLastComputeCmd ));
2010 // ----------------------------------------------------------------------
2011 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2013 _pyID hypID = theCommand->GetArg( 2 );
2014 _pyID geomID = theCommand->GetArg( 1 );
2015 bool isLocal = ( geomID != GetGeom() );
2017 // check if this mesh still has corresponding addition command
2018 Handle(_pyCommand) addCmd;
2019 list< Handle(_pyCommand) >::iterator cmd;
2020 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2021 for ( int i = 0; i < 2; ++i )
2023 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2024 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2026 bool sameHyp = true;
2027 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2028 sameHyp = false; // other hyp
2029 if ( (*cmd)->GetNbArgs() == 2 &&
2030 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2031 sameHyp = false; // other geom
2032 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2033 sameHyp = false; // other geom
2037 cmd = addHypCmds.erase( cmd );
2038 if ( !theGen->IsToKeepAllCommands() && CanClear() ) {
2040 theCommand->Clear();
2044 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2045 addCmd->RemoveArgs();
2046 addCmd->SetArg( 1, hypID );
2048 addCmd->SetArg( 2, geomID );
2057 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2058 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2059 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2060 _pyID geom = theCommand->GetArg( 1 );
2061 theCommand->RemoveArgs();
2062 theCommand->SetArg( 1, hypID );
2063 if ( geom != GetGeom() )
2064 theCommand->SetArg( 2, geom );
2066 // remove hyp from myHypos
2067 myHypos.remove( hyp );
2069 // check for SubMesh order commands
2070 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2072 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2073 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2074 // commands are moved at the end of the script
2075 TCollection_AsciiString subIDs =
2076 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2077 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2078 list< _pyID >::iterator subID = idList.begin();
2079 for ( ; subID != idList.end(); ++subID )
2081 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2082 if ( !subMesh.IsNull() )
2083 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2086 // add accessor method if necessary
2089 if ( NeedMeshAccess( theCommand ))
2090 // apply theCommand to the mesh wrapped by smeshpy mesh
2091 AddMeshAccess( theCommand );
2095 //================================================================================
2097 * \brief Return True if addition of accesor method is needed
2099 //================================================================================
2101 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2103 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2104 // so no conversion is needed for them at all:
2105 static TStringSet sameMethods;
2106 if ( sameMethods.empty() ) {
2107 const char * names[] =
2108 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2109 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2110 "ClearLog","GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2111 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2112 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2113 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2114 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2115 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2116 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2117 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2118 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2119 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2120 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2121 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2122 ,"" }; // <- mark of end
2123 sameMethods.Insert( names );
2126 return !sameMethods.Contains( theCommand->GetMethod() );
2129 //================================================================================
2131 * \brief Convert creation and addition of all algos and hypos
2133 //================================================================================
2135 void _pyMesh::Flush()
2138 // get the meshes this mesh depends on via hypotheses
2139 list< Handle(_pyMesh) > fatherMeshes;
2140 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2141 for ( ; hyp != myHypos.end(); ++hyp )
2142 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2143 myGeomNotInStudy = true;
2145 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2146 for ( ; m != fatherMeshes.end(); ++m )
2147 addFatherMesh( *m );
2148 // if ( removedGeom )
2149 // SetRemovedFromStudy(); // as reffered geometry not in study
2151 if ( myGeomNotInStudy )
2154 list < Handle(_pyCommand) >::iterator cmd;
2156 // try to convert algo addition like this:
2157 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2158 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2160 Handle(_pyCommand) addCmd = *cmd;
2162 _pyID algoID = addCmd->GetArg( 2 );
2163 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2164 if ( algo.IsNull() || !algo->IsAlgo() )
2167 // check and create new algorithm instance if it is already wrapped
2168 if ( algo->IsWrapped() ) {
2169 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2170 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2171 TCollection_AsciiString( " = " ) + theGen->GetID() +
2172 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2173 TCollection_AsciiString( "\" )" );
2175 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2176 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2177 if ( !newAlgo.IsNull() ) {
2178 newAlgo->Assign( algo, this->GetID() );
2179 newAlgo->SetCreationCmd( newCmd );
2181 // set algorithm creation
2182 theGen->SetCommandBefore( newCmd, addCmd );
2183 myHypos.push_back( newAlgo );
2184 if ( !myLastComputeCmd.IsNull() &&
2185 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2186 newAlgo->MeshComputed( myLastComputeCmd );
2191 _pyID geom = addCmd->GetArg( 1 );
2192 bool isLocalAlgo = ( geom != GetGeom() );
2195 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2197 // wrapped algo is created after mesh creation
2198 GetCreationCmd()->AddDependantCmd( addCmd );
2200 if ( isLocalAlgo ) {
2201 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2202 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2203 TCollection_AsciiString( "geom=" ) + geom );
2204 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2205 list < Handle(_pySubMesh) >::iterator smIt;
2206 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2207 Handle(_pySubMesh) subMesh = *smIt;
2208 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2209 if ( geom == subCmd->GetArg( 1 )) {
2210 subCmd->SetObject( algo->GetID() );
2211 subCmd->RemoveArgs();
2212 subMesh->SetCreator( algo );
2217 else // KO - ALGO was already created
2219 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2220 addCmd->RemoveArgs();
2221 addCmd->SetArg( 1, algoID );
2223 addCmd->SetArg( 2, geom );
2224 myNotConvertedAddHypCmds.push_back( addCmd );
2228 // try to convert hypo addition like this:
2229 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2230 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2232 Handle(_pyCommand) addCmd = *cmd;
2233 _pyID hypID = addCmd->GetArg( 2 );
2234 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2235 if ( hyp.IsNull() || hyp->IsAlgo() )
2237 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2239 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2240 _pyID geom = addCmd->GetArg( 1 );
2241 addCmd->RemoveArgs();
2242 addCmd->SetArg( 1, hypID );
2243 if ( geom != GetGeom() )
2244 addCmd->SetArg( 2, geom );
2245 myNotConvertedAddHypCmds.push_back( addCmd );
2249 myAddHypCmds.clear();
2250 mySubmeshes.clear();
2253 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2254 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2258 //================================================================================
2260 * \brief Sets myIsPublished of me and of all objects depending on me.
2262 //================================================================================
2264 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2266 _pyObject::SetRemovedFromStudy(isRemoved);
2268 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2269 for ( ; sm != mySubmeshes.end(); ++sm )
2270 (*sm)->SetRemovedFromStudy(isRemoved);
2272 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2273 for ( ; gr != myGroups.end(); ++gr )
2274 (*gr)->SetRemovedFromStudy(isRemoved);
2276 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2277 for ( ; m != myChildMeshes.end(); ++m )
2278 (*m)->SetRemovedFromStudy(isRemoved);
2280 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2281 for ( ; e != myEditors.end(); ++e )
2282 (*e)->SetRemovedFromStudy(isRemoved);
2285 //================================================================================
2287 * \brief Return true if none of myChildMeshes is in study
2289 //================================================================================
2291 bool _pyMesh::CanClear()
2296 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2297 for ( ; m != myChildMeshes.end(); ++m )
2298 if ( !(*m)->CanClear() )
2304 //================================================================================
2306 * \brief Clear my commands and commands of mesh editor
2308 //================================================================================
2310 void _pyMesh::ClearCommands()
2316 // mark all sub-objects as not removed, except child meshes
2317 list< Handle(_pyMesh) > children;
2318 children.swap( myChildMeshes );
2319 SetRemovedFromStudy( false );
2320 children.swap( myChildMeshes );
2324 _pyObject::ClearCommands();
2326 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2327 for ( ; sm != mySubmeshes.end(); ++sm )
2328 (*sm)->ClearCommands();
2330 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2331 for ( ; gr != myGroups.end(); ++gr )
2332 (*gr)->ClearCommands();
2334 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2335 for ( ; e != myEditors.end(); ++e )
2336 (*e)->ClearCommands();
2339 //================================================================================
2341 * \brief Add a father mesh by ID
2343 //================================================================================
2345 void _pyMesh::addFatherMesh( const _pyID& meshID )
2347 if ( !meshID.IsEmpty() && meshID != GetID() )
2348 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2351 //================================================================================
2353 * \brief Add a father mesh
2355 //================================================================================
2357 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2359 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2361 //myFatherMeshes.push_back( mesh );
2362 mesh->myChildMeshes.push_back( this );
2364 // protect last Compute() from clearing by the next Compute()
2365 mesh->myLastComputeCmd.Nullify();
2369 //================================================================================
2371 * \brief MeshEditor convert its commands to ones of mesh
2373 //================================================================================
2375 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2376 _pyObject( theCreationCmd )
2378 myMesh = theCreationCmd->GetObject();
2379 myCreationCmdStr = theCreationCmd->GetString();
2380 theCreationCmd->Clear();
2382 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2383 if ( !mesh.IsNull() )
2384 mesh->AddEditor( this );
2387 //================================================================================
2389 * \brief convert its commands to ones of mesh
2391 //================================================================================
2393 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2395 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2396 // commands calling these methods are converted to calls of Mesh methods without
2397 // additional modifs, only object is changed from MeshEditor to Mesh.
2398 static TStringSet sameMethods;
2399 if ( sameMethods.empty() ) {
2400 const char * names[] = {
2401 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2402 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2403 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2404 "MoveNode", "MoveClosestNodeToPoint",
2405 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2406 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2407 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2408 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2409 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2410 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2411 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2412 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2413 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2414 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2415 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2416 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2417 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2418 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2419 "GetLastCreatedElems",
2420 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2421 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2422 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2423 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2424 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2425 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2426 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2427 ,"" }; // <- mark of the end
2428 sameMethods.Insert( names );
2431 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2432 TStringMap diffMethods;
2433 if ( diffMethods.empty() ) {
2434 const char * orig2newName[] = {
2435 // original name --------------> new name
2436 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2437 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2438 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2439 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2440 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2441 ""};// <- mark of the end
2442 diffMethods.Insert( orig2newName );
2445 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2446 // only by last two arguments
2447 static TStringSet diffLastTwoArgsMethods;
2448 if (diffLastTwoArgsMethods.empty() ) {
2449 const char * names[] = {
2450 "MirrorMakeGroups","MirrorObjectMakeGroups",
2451 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2452 "RotateMakeGroups","RotateObjectMakeGroups",
2453 ""};// <- mark of the end
2454 diffLastTwoArgsMethods.Insert( names );
2457 // only a method name is to change?
2458 const TCollection_AsciiString & method = theCommand->GetMethod();
2459 bool isPyMeshMethod = sameMethods.Contains( method );
2460 if ( !isPyMeshMethod )
2462 TCollection_AsciiString newMethod = diffMethods.Value( method );
2463 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2464 theCommand->SetMethod( newMethod );
2466 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2467 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2469 isPyMeshMethod = true;
2470 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2471 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2474 if ( !isPyMeshMethod )
2476 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2477 // functions with the flag "theMakeGroups = True" like:
2478 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2479 int pos = method.Search("MakeGroups");
2482 isPyMeshMethod = true;
2483 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2484 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2486 // 1. Remove "MakeGroups" from the Command
2487 TCollection_AsciiString aMethod = theCommand->GetMethod();
2488 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2491 pos = pos-2; //Remove "0D" from the Command too
2492 aMethod.Trunc(pos-1);
2493 theCommand->SetMethod(aMethod);
2495 // 2. And add last "True" argument(s)
2496 while(nbArgsToAdd--)
2497 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2498 if( is0DmethId || is0DmethObj )
2499 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2503 // ExtrusionSweep0D() -> ExtrusionSweep()
2504 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2505 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2506 method == "ExtrusionSweepObject0D" ))
2508 isPyMeshMethod = true;
2509 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2510 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2511 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2514 // DoubleNode...New(...) -> DoubleNode...(...,True)
2515 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2516 method == "DoubleNodeElemGroupsNew" ||
2517 method == "DoubleNodeGroupNew" ||
2518 method == "DoubleNodeGroupsNew" ||
2519 method == "DoubleNodeElemGroup2New" ||
2520 method == "DoubleNodeElemGroups2New"))
2522 isPyMeshMethod = true;
2523 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2524 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2525 if ( excessLen == 3 )
2527 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2529 else if ( theCommand->GetArg(4) == "0" ||
2530 theCommand->GetArg(5) == "0" )
2532 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2533 // Group = DoubleNodeGroup2New(,,,False, True)
2534 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2535 theCommand->SetResultValue( groupID );
2538 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2539 // FindElementsByPoint(x, y, z, elementType, meshPart)
2540 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2542 isPyMeshMethod = true;
2543 theCommand->SetMethod( "FindElementsByPoint" );
2544 // make the 1st arg be the last one
2545 _pyID partID = theCommand->GetArg( 1 );
2546 int nbArgs = theCommand->GetNbArgs();
2547 for ( int i = 2; i <= nbArgs; ++i )
2548 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2549 theCommand->SetArg( nbArgs, partID );
2551 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2552 if ( !isPyMeshMethod && method == "Reorient2D" )
2554 isPyMeshMethod = true;
2555 _AString mesh = theCommand->GetArg( 1 );
2556 _AString dir = theCommand->GetArg( 2 );
2557 _AString face = theCommand->GetArg( 3 );
2558 _AString point = theCommand->GetArg( 4 );
2559 theCommand->RemoveArgs();
2560 theCommand->SetArg( 1, mesh );
2561 theCommand->SetArg( 2, dir );
2562 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2563 theCommand->SetArg( 3, point );
2565 theCommand->SetArg( 3, face );
2568 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2570 isPyMeshMethod = true;
2571 int crit_arg = theCommand->GetNbArgs();
2572 const _AString& crit = theCommand->GetArg(crit_arg);
2573 if (crit.Search("MaxElementLength2D") != -1)
2574 theCommand->SetArg(crit_arg, "");
2577 if ( isPyMeshMethod )
2579 theCommand->SetObject( myMesh );
2583 // editor creation command is needed only if any editor function is called
2584 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2585 if ( !myCreationCmdStr.IsEmpty() ) {
2586 GetCreationCmd()->GetString() = myCreationCmdStr;
2587 myCreationCmdStr.Clear();
2592 //================================================================================
2594 * \brief Return true if my mesh can be removed
2596 //================================================================================
2598 bool _pyMeshEditor::CanClear()
2600 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2601 return mesh.IsNull() ? true : mesh->CanClear();
2604 //================================================================================
2606 * \brief _pyHypothesis constructor
2607 * \param theCreationCmd -
2609 //================================================================================
2611 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2612 _pyObject( theCreationCmd ), myCurCrMethod(0)
2614 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2617 //================================================================================
2619 * \brief Creates algorithm or hypothesis
2620 * \param theCreationCmd - The engine command creating a hypothesis
2621 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2623 //================================================================================
2625 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2627 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2628 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2630 Handle(_pyHypothesis) hyp, algo;
2633 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2634 if ( hypTypeQuoted.IsEmpty() )
2637 TCollection_AsciiString hypType =
2638 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2640 algo = new _pyAlgorithm( theCreationCmd );
2641 hyp = new _pyHypothesis( theCreationCmd );
2643 if ( hypType == "NumberOfSegments" ) {
2644 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2645 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2646 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2647 hyp->AddArgMethod( "SetNumberOfSegments" );
2648 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2649 hyp->AddArgMethod( "SetScaleFactor" );
2650 hyp->AddArgMethod( "SetReversedEdges" );
2651 // same for ""CompositeSegment_1D:
2652 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2653 hyp->AddArgMethod( "SetNumberOfSegments" );
2654 hyp->AddArgMethod( "SetScaleFactor" );
2655 hyp->AddArgMethod( "SetReversedEdges" );
2657 else if ( hypType == "SegmentLengthAroundVertex" ) {
2658 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2659 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2660 hyp->AddArgMethod( "SetLength" );
2661 // same for ""CompositeSegment_1D:
2662 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2663 hyp->AddArgMethod( "SetLength" );
2665 else if ( hypType == "LayerDistribution2D" ) {
2666 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2667 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2669 else if ( hypType == "LayerDistribution" ) {
2670 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2671 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2673 else if ( hypType == "CartesianParameters3D" ) {
2674 hyp = new _pyComplexParamHypo( theCreationCmd );
2675 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2676 for ( int iArg = 0; iArg < 4; ++iArg )
2677 hyp->setCreationArg( iArg+1, "[]");
2678 hyp->AddAccumulativeMethod( "SetGrid" );
2679 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2683 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2686 return algo->IsValid() ? algo : hyp;
2689 //================================================================================
2691 * \brief Returns true if addition of this hypothesis to a given mesh can be
2692 * wrapped into hypothesis creation
2694 //================================================================================
2696 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2698 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2700 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2701 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2707 //================================================================================
2709 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2710 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2711 * \param theAlgo - The algo that can create this hypo
2712 * \retval bool - false if the command cant be converted
2714 //================================================================================
2716 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2717 const _pyID& theMesh)
2719 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2721 if ( !IsWrappable( theMesh ))
2724 myGeom = theCmd->GetArg( 1 );
2726 Handle(_pyHypothesis) algo;
2728 // find algo created on myGeom in theMesh
2729 algo = theGen->FindAlgo( myGeom, theMesh, this );
2730 if ( algo.IsNull() )
2732 // attach hypothesis creation command to be after algo creation command
2733 // because it can be new created instance of algorithm
2734 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2738 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2739 theCmd->SetResultValue( GetID() );
2740 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2741 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2742 // set args (geom will be set by _pyMesh calling this method)
2743 theCmd->RemoveArgs();
2744 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2745 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2746 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2748 theCmd->SetArg( i+1, "[]");
2750 // set a new creation command
2751 GetCreationCmd()->Clear();
2752 // replace creation command by wrapped instance
2753 // please note, that hypothesis attaches to algo creation command (see upper)
2754 SetCreationCmd( theCmd );
2757 // clear commands setting arg values
2758 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2759 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2762 // set unknown arg commands after hypo creation
2763 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2764 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2765 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2766 afterCmd->AddDependantCmd( *cmd );
2772 //================================================================================
2774 * \brief Remember hypothesis parameter values
2775 * \param theCommand - The called hypothesis method
2777 //================================================================================
2779 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2781 ASSERT( !myIsAlgo );
2782 if ( !theGen->IsToKeepAllCommands() )
2783 rememberCmdOfParameter( theCommand );
2785 bool usedCommand = false;
2786 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2787 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2789 CreationMethod& crMethod = type2meth->second;
2790 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2791 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2793 myArgCommands.push_back( theCommand );
2795 while ( crMethod.myArgs.size() < i+1 )
2796 crMethod.myArgs.push_back( "None" );
2797 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2802 myUnusedCommands.push_back( theCommand );
2805 //================================================================================
2807 * \brief Finish conversion
2809 //================================================================================
2811 void _pyHypothesis::Flush()
2815 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2816 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2817 // Add access to a wrapped mesh
2818 theGen->AddMeshAccessorMethod( *cmd );
2819 // Add access to a wrapped algorithm
2820 theGen->AddAlgoAccessorMethod( *cmd );
2822 cmd = myUnusedCommands.begin();
2823 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2824 // Add access to a wrapped mesh
2825 theGen->AddMeshAccessorMethod( *cmd );
2826 // Add access to a wrapped algorithm
2827 theGen->AddAlgoAccessorMethod( *cmd );
2830 // forget previous hypothesis modifications
2831 myArgCommands.clear();
2832 myUnusedCommands.clear();
2835 //================================================================================
2837 * \brief clear creation, arg and unkown commands
2839 //================================================================================
2841 void _pyHypothesis::ClearAllCommands()
2843 GetCreationCmd()->Clear();
2844 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2845 for ( ; cmd != myArgCommands.end(); ++cmd )
2847 cmd = myUnusedCommands.begin();
2848 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2853 //================================================================================
2855 * \brief Assign fields of theOther to me except myIsWrapped
2857 //================================================================================
2859 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2860 const _pyID& theMesh )
2862 // myCreationCmd = theOther->myCreationCmd;
2863 myIsAlgo = theOther->myIsAlgo;
2864 myIsWrapped = false;
2865 myGeom = theOther->myGeom;
2867 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2868 myAccumulativeMethods = theOther->myAccumulativeMethods;
2869 //myUnusedCommands = theOther->myUnusedCommands;
2870 // init myCurCrMethod
2871 GetCreationMethod( theOther->GetAlgoType() );
2874 //================================================================================
2876 * \brief Analyze my erasability depending on myReferredObjs
2878 //================================================================================
2880 bool _pyHypothesis::CanClear()
2884 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2885 for ( ; obj != myReferredObjs.end(); ++obj )
2886 if ( (*obj)->CanClear() )
2893 //================================================================================
2895 * \brief Clear my commands depending on usage by meshes
2897 //================================================================================
2899 void _pyHypothesis::ClearCommands()
2901 // if ( !theGen->IsToKeepAllCommands() )
2903 // bool isUsed = false;
2904 // int lastComputeOrder = 0;
2905 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2906 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2907 // if ( ! (*cmd)->IsEmpty() )
2910 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2911 // lastComputeOrder = (*cmd)->GetOrderNb();
2915 // SetRemovedFromStudy( true );
2919 // // clear my commands invoked after lastComputeOrder
2920 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2921 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2923 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2924 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2925 // // cmds.back()->Clear();
2929 _pyObject::ClearCommands();
2932 //================================================================================
2934 * \brief Find arguments that are objects like mesh, group, geometry
2935 * \param meshes - referred meshes (directly or indirrectly)
2936 * \retval bool - false if a referred geometry is not in the study
2938 //================================================================================
2940 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2942 if ( IsAlgo() ) return true;
2944 bool geomPublished = true;
2945 vector< _AString > args;
2946 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2947 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2949 CreationMethod& crMethod = type2meth->second;
2950 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2952 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2953 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2954 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2955 args.push_back( (*cmd)->GetArg( nb ));
2958 for ( size_t i = 0; i < args.size(); ++i )
2960 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2961 if ( idList.empty() && !args[ i ].IsEmpty() )
2962 idList.push_back( args[ i ]);
2963 list< _pyID >::iterator id = idList.begin();
2964 for ( ; id != idList.end(); ++id )
2966 Handle(_pyObject) obj = theGen->FindObject( *id );
2967 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2970 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2971 geomPublished = false;
2975 myReferredObjs.push_back( obj );
2976 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2977 if ( !mesh.IsNull() )
2978 meshes.push_back( mesh );
2979 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2980 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2981 obj->SetRemovedFromStudy( false );
2985 return geomPublished;
2988 //================================================================================
2990 * \brief Remember theCommand setting a parameter
2992 //================================================================================
2994 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2996 // parameters are discriminated by method name
2997 _AString method = theCommand->GetMethod();
2998 if ( myAccumulativeMethods.count( method ))
2999 return; // this method adds values and not override the previus value
3001 // discriminate commands setting different parameters via one method
3002 // by passing parameter names like e.g. SetOption("size", "0.2")
3003 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3004 theCommand->GetNbArgs() > 1 )
3006 // mangle method by appending a 1st textual arg
3007 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3009 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3010 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3011 if ( !isalpha( arg.Value(2))) continue;
3016 // parameters are discriminated by method name
3017 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3018 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3020 cmds.back()->Clear(); // previous parameter value has not been used
3021 cmds.back() = theCommand;
3025 cmds.push_back( theCommand );
3029 //================================================================================
3031 * \brief Return true if a setting parameter command ha been used to compute mesh
3033 //================================================================================
3035 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3036 _pyCommand::TAddr avoidComputeAddr ) const
3038 bool isUsed = false;
3039 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3040 myComputeAddr2Cmds.begin();
3041 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3043 if ( addr2cmds->first == avoidComputeAddr ) continue;
3044 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3045 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3050 //================================================================================
3052 * \brief Save commands setting parameters as they are used for a mesh computation
3054 //================================================================================
3056 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3058 myComputeCmds.push_back( theComputeCmd );
3059 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3061 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3062 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3063 savedCmds.push_back( m2c->second.back() );
3066 //================================================================================
3068 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3070 //================================================================================
3072 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3074 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3076 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3077 for ( ; cmd != savedCmds.end(); ++cmd )
3079 // check if a cmd has been used to compute another mesh
3080 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3082 // check if a cmd is a sole command setting its parameter;
3083 // don't use method name for search as it can change
3084 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3085 m2cmds = myMeth2Commands.begin();
3086 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3088 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3089 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3090 if ( cmdIt != cmds.end() )
3092 if ( cmds.back() != *cmd )
3094 cmds.erase( cmdIt );
3101 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3104 //================================================================================
3106 * \brief Sets an argNb-th argument of current creation command
3107 * \param argNb - argument index countered from 1
3109 //================================================================================
3111 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3113 if ( myCurCrMethod )
3115 while ( myCurCrMethod->myArgs.size() < argNb )
3116 myCurCrMethod->myArgs.push_back( "None" );
3117 if ( arg.IsEmpty() )
3118 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3120 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3125 //================================================================================
3127 * \brief Remember hypothesis parameter values
3128 * \param theCommand - The called hypothesis method
3130 //================================================================================
3132 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3134 if ( GetAlgoType() == "Cartesian_3D" )
3136 // CartesianParameters3D hyp
3138 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3139 theCommand->GetMethod() == "SetToAddEdges" )
3141 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3142 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3143 myArgCommands.push_back( theCommand );
3146 if ( theCommand->GetMethod() == "SetGrid" ||
3147 theCommand->GetMethod() == "SetGridSpacing" )
3149 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3150 int iArg = axis.Value(1) - '0';
3151 if ( theCommand->GetMethod() == "SetGrid" )
3153 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3157 myCurCrMethod->myArgs[ iArg ] = "[ ";
3158 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3159 myCurCrMethod->myArgs[ iArg ] += ", ";
3160 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3161 myCurCrMethod->myArgs[ iArg ] += "]";
3163 myArgCommands.push_back( theCommand );
3164 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3165 // accumulative, else, if the creation
3166 // is not converted, commands for axes 1 and 2 are lost
3171 if( theCommand->GetMethod() == "SetLength" )
3173 // NOW it is OBSOLETE
3174 // ex: hyp.SetLength(start, 1)
3175 // hyp.SetLength(end, 0)
3176 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3177 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3178 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3179 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3181 CreationMethod& crMethod = type2meth->second;
3182 while ( crMethod.myArgs.size() < i+1 )
3183 crMethod.myArgs.push_back( "[]" );
3184 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3186 myArgCommands.push_back( theCommand );
3190 _pyHypothesis::Process( theCommand );
3193 //================================================================================
3195 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3197 //================================================================================
3199 void _pyComplexParamHypo::Flush()
3201 list < Handle(_pyCommand) >::iterator cmd;
3204 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3205 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3209 // if ( GetAlgoType() == "Cartesian_3D" )
3211 // _pyID algo = myCreationCmd->GetObject();
3212 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3214 // if ( IsWrapped() )
3216 // StructToList( *cmd, /*checkMethod=*/false );
3217 // const _AString & method = (*cmd)->GetMethod();
3218 // if ( method == "SetFixedPoint" )
3219 // (*cmd)->SetObject( algo );
3225 //================================================================================
3227 * \brief Convert methods of 1D hypotheses to my own methods
3228 * \param theCommand - The called hypothesis method
3230 //================================================================================
3232 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3234 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3237 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3238 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3239 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3241 // TCollection_AsciiString cmd =
3242 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3243 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3244 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3247 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3249 // // 1D hypo is already set, so distribution changes and the old
3250 // // 1D hypo is thrown away
3251 // my1dHyp->ClearAllCommands();
3254 // //my1dHyp->SetRemovedFromStudy( false );
3256 // if ( !myArgCommands.empty() )
3257 // myArgCommands.back()->Clear();
3258 myCurCrMethod->myArgs.push_back( hyp1dID );
3259 myArgCommands.push_back( theCommand );
3262 //================================================================================
3265 * \param theAdditionCmd - command to be converted
3266 * \param theMesh - mesh instance
3267 * \retval bool - status
3269 //================================================================================
3271 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3272 const _pyID& theMesh)
3274 myIsWrapped = false;
3276 if ( my1dHyp.IsNull() )
3279 // set "SetLayerDistribution()" after addition cmd
3280 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3282 _pyID geom = theAdditionCmd->GetArg( 1 );
3284 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3285 if ( !algo.IsNull() )
3287 my1dHyp->SetMesh( theMesh );
3288 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3289 algo->GetAlgoType().ToCString());
3290 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3293 // clear "SetLayerDistribution()" cmd
3294 myArgCommands.back()->Clear();
3296 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3298 // find RadialPrism algo created on <geom> for theMesh
3299 GetCreationCmd()->SetObject( algo->GetID() );
3300 GetCreationCmd()->SetMethod( myAlgoMethod );
3301 GetCreationCmd()->RemoveArgs();
3302 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3308 //================================================================================
3312 //================================================================================
3314 void _pyLayerDistributionHypo::Flush()
3316 // as creation of 1D hyp was written later then it's edition,
3317 // we need to find all it's edition calls and process them
3318 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3320 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3322 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3323 if ( hyp1dID.IsEmpty() ) continue;
3325 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3327 // make a new name for 1D hyp = "HypType" + "_Distribution"
3329 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3331 if ( prevNewName.IsEmpty() ) continue;
3332 newName = prevNewName;
3336 if ( hyp1d->IsWrapped() ) {
3337 newName = hyp1d->GetCreationCmd()->GetMethod();
3340 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3341 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3343 newName += "_Distribution";
3344 prevNewName = newName;
3346 hyp1d->GetCreationCmd()->SetResultValue( newName );
3348 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3349 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3350 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3351 const _pyID& objID = (*cmdIt)->GetObject();
3352 if ( objID == hyp1dID ) {
3353 if ( !hyp1d.IsNull() )
3355 hyp1d->Process( *cmdIt );
3356 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3358 ( *cmdIt )->SetObject( newName );
3361 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3362 (*cmd)->SetArg( 1, newName );
3366 //================================================================================
3368 * \brief additionally to Addition2Creation, clears SetDistrType() command
3369 * \param theCmd - AddHypothesis() command
3370 * \param theMesh - mesh to which a hypothesis is added
3371 * \retval bool - convertion result
3373 //================================================================================
3375 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3376 const _pyID& theMesh)
3378 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3379 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3380 bool scaleDistrType = false;
3381 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3382 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3383 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3384 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3385 scaleDistrType = true;
3388 else if ( !scaleDistrType ) {
3389 // distribution type changed: remove scale factor from args
3390 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3391 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3393 CreationMethod& crMethod = type2meth->second;
3394 if ( crMethod.myArgs.size() == 2 )
3395 crMethod.myArgs.pop_back();
3402 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3405 //================================================================================
3407 * \brief remove repeated commands defining distribution
3409 //================================================================================
3411 void _pyNumberOfSegmentsHyp::Flush()
3413 // find number of the last SetDistrType() command
3414 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3415 int distrTypeNb = 0;
3416 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3417 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3418 if ( cmd != myUnusedCommands.rbegin() )
3419 distrTypeNb = (*cmd)->GetOrderNb();
3421 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3424 // clear commands before the last SetDistrType()
3425 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3426 set< int > treatedCmdNbs; // avoid treating same cmd twice
3427 for ( int i = 0; i < 2; ++i ) {
3428 set<TCollection_AsciiString> uniqueMethods;
3429 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3430 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3432 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3433 continue;// avoid treating same cmd twice
3434 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3435 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3436 if ( !clear || method == "SetNumberOfSegments" ) {
3437 bool isNewInSet = uniqueMethods.insert( method ).second;
3438 clear = !isNewInSet;
3447 //================================================================================
3449 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3450 * into regular1D.LengthNearVertex( length, vertex )
3451 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3452 * \param theMesh - The mesh needing this hypo
3453 * \retval bool - false if the command cant be converted
3455 //================================================================================
3457 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3458 const _pyID& theMeshID)
3460 if ( IsWrappable( theMeshID )) {
3462 _pyID vertex = theCmd->GetArg( 1 );
3464 // the problem here is that segment algo will not be found
3465 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3466 // geometry where segment algorithm is assigned
3467 Handle(_pyHypothesis) algo;
3468 _pyID geom = vertex;
3469 while ( algo.IsNull() && !geom.IsEmpty()) {
3470 // try to find geom as a father of <vertex>
3471 geom = FatherID( geom );
3472 algo = theGen->FindAlgo( geom, theMeshID, this );
3474 if ( algo.IsNull() )
3475 return false; // also possible to find geom as brother of veretex...
3476 // set geom instead of vertex
3477 theCmd->SetArg( 1, geom );
3479 // set vertex as a second arg
3480 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3481 setCreationArg( 2, vertex );
3483 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3484 // theMeshID.LengthNearVertex( length, vertex )
3485 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3490 //================================================================================
3492 * \brief _pyAlgorithm constructor
3493 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3495 //================================================================================
3497 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3498 : _pyHypothesis( theCreationCmd )
3503 //================================================================================
3505 * \brief Convert the command adding an algorithm to mesh
3506 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3507 * \param theMesh - The mesh needing this algo
3508 * \retval bool - false if the command cant be converted
3510 //================================================================================
3512 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3513 const _pyID& theMeshID)
3515 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3516 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3517 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3523 //================================================================================
3525 * \brief Return starting position of a part of python command
3526 * \param thePartIndex - The index of command part
3527 * \retval int - Part position
3529 //================================================================================
3531 int _pyCommand::GetBegPos( int thePartIndex ) const
3535 if ( myBegPos.Length() < thePartIndex )
3537 ASSERT( thePartIndex > 0 );
3538 return myBegPos( thePartIndex );
3541 //================================================================================
3543 * \brief Store starting position of a part of python command
3544 * \param thePartIndex - The index of command part
3545 * \param thePosition - Part position
3547 //================================================================================
3549 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3551 while ( myBegPos.Length() < thePartIndex )
3552 myBegPos.Append( UNKNOWN );
3553 ASSERT( thePartIndex > 0 );
3554 myBegPos( thePartIndex ) = thePosition;
3557 //================================================================================
3559 * \brief Returns whitespace symbols at the line beginning
3560 * \retval TCollection_AsciiString - result
3562 //================================================================================
3564 TCollection_AsciiString _pyCommand::GetIndentation()
3567 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3568 GetWord( myString, end, true );
3570 end = GetBegPos( RESULT_IND );
3571 return myString.SubString( 1, Max( end - 1, 1 ));
3574 //================================================================================
3576 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3577 * \retval const TCollection_AsciiString & - ResultValue substring
3579 //================================================================================
3581 const TCollection_AsciiString & _pyCommand::GetResultValue()
3583 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3585 SetBegPos( RESULT_IND, EMPTY );
3586 int begPos, endPos = myString.Location( "=", 1, Length() );
3590 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3591 if ( begPos < endPos )
3593 SetBegPos( RESULT_IND, begPos );
3595 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3596 myRes = myString.SubString( begPos, endPos );
3603 //================================================================================
3605 * \brief Return number of python command result value ResultValue = Obj.Meth()
3607 //================================================================================
3609 int _pyCommand::GetNbResultValues()
3612 return myResults.Length();
3616 //================================================================================
3618 * \brief Return substring of python command looking like
3619 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3620 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3622 //================================================================================
3623 const _AString& _pyCommand::GetResultValue(int res)
3625 if ( GetResultValue().IsEmpty() )
3626 return theEmptyString;
3628 if ( myResults.IsEmpty() )
3631 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3632 ++begPos; // skip [, else the whole list is returned
3633 while ( begPos < myRes.Length() ) {
3634 _AString result = GetWord( myRes, begPos, true );
3635 begPos += result.Length();
3637 // result.RemoveAll('[');
3638 // result.RemoveAll(']');
3643 myResults.Append( result );
3646 if ( res > 0 && res <= myResults.Length() )
3647 return myResults( res );
3648 return theEmptyString;
3651 //================================================================================
3653 * \brief Return substring of python command looking like ResVal = Object.Meth()
3654 * \retval const TCollection_AsciiString & - Object substring
3656 //================================================================================
3658 const TCollection_AsciiString & _pyCommand::GetObject()
3660 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3663 int begPos = GetBegPos( RESULT_IND );
3665 begPos = myString.Location( "=", 1, Length() ) + 1;
3666 // is '=' in the string argument (for example, name) or not
3667 int nb1 = 0; // number of ' character at the left of =
3668 int nb2 = 0; // number of " character at the left of =
3669 for ( int i = 1; i < begPos-1; i++ ) {
3670 if ( myString.Value( i )=='\'' )
3672 else if ( myString.Value( i )=='"' )
3675 // if number of ' or " is not divisible by 2,
3676 // then get an object at the start of the command
3677 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3681 begPos += myRes.Length();
3683 myObj = GetWord( myString, begPos, true );
3684 if ( begPos != EMPTY )
3686 // check if object is complex,
3687 // so far consider case like "smesh.Method()"
3688 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3689 //if ( bracketPos==0 ) bracketPos = Length();
3690 int dotPos = begPos+myObj.Length();
3691 while ( dotPos+1 < bracketPos ) {
3692 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3697 if ( dotPos > begPos+myObj.Length() )
3698 myObj = myString.SubString( begPos, dotPos-1 );
3701 // 1st word after '=' is an object
3702 // else // no method -> no object
3708 SetBegPos( OBJECT_IND, begPos );
3714 //================================================================================
3716 * \brief Return substring of python command looking like ResVal = Obj.Method()
3717 * \retval const TCollection_AsciiString & - Method substring
3719 //================================================================================
3721 const TCollection_AsciiString & _pyCommand::GetMethod()
3723 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3726 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3727 bool forward = true;
3729 begPos = myString.Location( "(", 1, Length() ) - 1;
3733 myMeth = GetWord( myString, begPos, forward );
3734 SetBegPos( METHOD_IND, begPos );
3740 //================================================================================
3742 * \brief Returns true if there are brackets after the method
3744 //================================================================================
3746 bool _pyCommand::IsMethodCall()
3748 if ( GetMethod().IsEmpty() )
3750 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3751 return ( s[0] == '(' || s[1] == '(' );
3754 //================================================================================
3756 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3757 * \retval const TCollection_AsciiString & - Arg<index> substring
3759 //================================================================================
3761 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3763 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3767 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3769 pos = myString.Location( "(", 1, Length() );
3773 // we are at or before '(', skip it if present
3775 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3776 if ( pos > Length() )
3780 SetBegPos( ARG1_IND, 0 ); // even no '('
3781 return theEmptyString;
3785 list< TCollection_AsciiString > separatorStack( 1, ",)");
3786 bool ignoreNesting = false;
3788 while ( pos <= Length() )
3790 const char chr = myString.Value( pos );
3792 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3794 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3796 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3798 TCollection_AsciiString arg;
3799 if ( pos-1 >= prevPos ) {
3800 arg = myString.SubString( prevPos, pos-1 );
3801 arg.RightAdjust(); // remove spaces
3804 if ( !arg.IsEmpty() || chr == ',' )
3806 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3807 myArgs.Append( arg );
3813 else // end of nesting args found
3815 separatorStack.pop_back();
3816 ignoreNesting = false;
3819 else if ( !ignoreNesting )
3822 case '(' : separatorStack.push_back(")"); break;
3823 case '[' : separatorStack.push_back("]"); break;
3824 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3825 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3832 if ( myArgs.Length() < index )
3833 return theEmptyString;
3834 return myArgs( index );
3837 //================================================================================
3839 * \brief Return position where arguments begin
3841 //================================================================================
3843 int _pyCommand::GetArgBeginning() const
3845 int pos = GetBegPos( ARG1_IND );
3846 if ( pos == UNKNOWN )
3848 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3850 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3855 //================================================================================
3857 * \brief Check if char is a word part
3858 * \param c - The character to check
3859 * \retval bool - The check result
3861 //================================================================================
3863 static inline bool isWord(const char c, const bool dotIsWord)
3866 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3869 //================================================================================
3871 * \brief Looks for a word in the string and returns word's beginning
3872 * \param theString - The input string
3873 * \param theStartPos - The position to start the search, returning word's beginning
3874 * \param theForward - The search direction
3875 * \retval TCollection_AsciiString - The found word
3877 //================================================================================
3879 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3881 const bool theForward,
3882 const bool dotIsWord )
3884 int beg = theStartPos, end = theStartPos;
3885 theStartPos = EMPTY;
3886 if ( beg < 1 || beg > theString.Length() )
3887 return theEmptyString;
3889 if ( theForward ) { // search forward
3891 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3893 if ( beg > theString.Length() )
3894 return theEmptyString; // no word found
3897 char begChar = theString.Value( beg );
3898 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3899 char endChar = ( begChar == '[' ) ? ']' : begChar;
3900 // end is at the corresponding quoting mark or bracket
3901 while ( end < theString.Length() &&
3902 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3906 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3911 else { // search backward
3913 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3916 return theEmptyString; // no word found
3918 char endChar = theString.Value( end );
3919 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3920 char begChar = ( endChar == ']' ) ? '[' : endChar;
3921 // beg is at the corresponding quoting mark
3923 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3927 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3933 //cout << theString << " ---- " << beg << " - " << end << endl;
3934 return theString.SubString( beg, end );
3937 //================================================================================
3939 * \brief Returns true if the string looks like a study entry
3941 //================================================================================
3943 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3945 if ( str.Length() < 5 ) return false;
3947 int nbColons = 0, isColon;
3948 for ( int i = 1; i <= str.Length(); ++i )
3950 char c = str.Value(i);
3951 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3953 nbColons += isColon;
3955 return nbColons > 2 && str.Length()-nbColons > 2;
3958 //================================================================================
3960 * \brief Returns true if the string looks like an object ID but not like a list,
3961 * string, command etc.
3963 //================================================================================
3965 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3967 if ( str.Length() < 1 ) return false;
3969 const char* s = str.ToCString();
3971 for ( int i = 0; i < str.Length(); ++i )
3972 if ( !IsIDChar( s[i] ))
3978 //================================================================================
3980 * \brief Finds entries in a sting
3982 //================================================================================
3984 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3986 std::list< _pyID > resList;
3988 while ( ++pos <= str.Length() )
3990 if ( !isdigit( str.Value( pos ))) continue;
3991 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3994 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3995 _pyID entry = str.SubString( pos, end-1 );
3997 if ( IsStudyEntry( entry ))
3998 resList.push_back( entry );
4003 //================================================================================
4005 * \brief Look for position where not space char is
4006 * \param theString - The string
4007 * \param thePos - The position to search from and which returns result
4008 * \retval bool - false if there are only space after thePos in theString
4010 //================================================================================
4012 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4014 if ( thePos < 1 || thePos > theString.Length() )
4017 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4020 return thePos <= theString.Length();
4023 //================================================================================
4025 * \brief Modify a part of the command
4026 * \param thePartIndex - The index of the part
4027 * \param thePart - The new part string
4028 * \param theOldPart - The old part
4030 //================================================================================
4032 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4033 TCollection_AsciiString& theOldPart)
4035 int pos = GetBegPos( thePartIndex );
4036 if ( pos <= Length() && theOldPart != thePart)
4038 TCollection_AsciiString seperator;
4040 pos = GetBegPos( thePartIndex + 1 );
4041 if ( pos < 1 ) return;
4042 switch ( thePartIndex ) {
4043 case RESULT_IND: seperator = " = "; break;
4044 case OBJECT_IND: seperator = "."; break;
4045 case METHOD_IND: seperator = "()"; break;
4049 myString.Remove( pos, theOldPart.Length() );
4050 if ( !seperator.IsEmpty() )
4051 myString.Insert( pos , seperator );
4052 myString.Insert( pos, thePart );
4053 // update starting positions of the following parts
4054 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4055 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4056 if ( myBegPos( i ) > 0 )
4057 myBegPos( i ) += posDelta;
4059 theOldPart = thePart;
4063 //================================================================================
4065 * \brief Set agrument
4066 * \param index - The argument index, it counts from 1
4067 * \param theArg - The argument string
4069 //================================================================================
4071 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4074 int argInd = ARG1_IND + index - 1;
4075 int pos = GetBegPos( argInd );
4076 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4078 // find a closing parenthesis
4079 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4080 int lastArgInd = GetNbArgs();
4081 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4082 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4087 while ( pos > 0 && myString.Value( pos ) != ')' )
4090 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4094 while ( myArgs.Length() < index ) {
4095 if ( myArgs.Length() )
4096 myString.Insert( pos++, "," );
4097 myArgs.Append("None");
4098 myString.Insert( pos, myArgs.Last() );
4099 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4100 pos += myArgs.Last().Length();
4103 SetPart( argInd, theArg, myArgs( index ));
4106 //================================================================================
4108 * \brief Empty arg list
4110 //================================================================================
4112 void _pyCommand::RemoveArgs()
4114 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4115 myString.Trunc( pos );
4118 if ( myBegPos.Length() >= ARG1_IND )
4119 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4122 //================================================================================
4124 * \brief Comment a python command
4126 //================================================================================
4128 void _pyCommand::Comment()
4130 if ( IsEmpty() ) return;
4133 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4134 if ( i <= Length() )
4136 myString.Insert( i, "#" );
4137 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4139 int begPos = GetBegPos( iPart );
4140 if ( begPos != UNKNOWN && begPos != EMPTY )
4141 SetBegPos( iPart, begPos + 1 );
4146 //================================================================================
4148 * \brief Set dependent commands after this one
4150 //================================================================================
4152 bool _pyCommand::SetDependentCmdsAfter() const
4154 bool orderChanged = false;
4155 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4156 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4157 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4158 orderChanged = true;
4159 theGen->SetCommandAfter( *cmd, this );
4160 (*cmd)->SetDependentCmdsAfter();
4163 return orderChanged;
4165 //================================================================================
4167 * \brief Insert accessor method after theObjectID
4168 * \param theObjectID - id of the accessed object
4169 * \param theAcsMethod - name of the method giving access to the object
4170 * \retval bool - false if theObjectID is not found in the command string
4172 //================================================================================
4174 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4176 if ( !theAcsMethod )
4178 // start object search from the object, i.e. ignore result
4180 int beg = GetBegPos( OBJECT_IND );
4181 if ( beg < 1 || beg > Length() )
4184 while (( beg = myString.Location( theObjectID, beg, Length() )))
4186 // check that theObjectID is not just a part of a longer ID
4187 int afterEnd = beg + theObjectID.Length();
4188 Standard_Character c = myString.Value( afterEnd );
4189 if ( !IsIDChar( c ))
4191 // check if accessor method already present
4193 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4195 int oldLen = Length();
4196 myString.Insert( afterEnd, (char*) theAcsMethod );
4197 myString.Insert( afterEnd, "." );
4198 // update starting positions of the parts following the modified one
4199 int posDelta = Length() - oldLen;
4200 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4201 if ( myBegPos( i ) > afterEnd )
4202 myBegPos( i ) += posDelta;
4207 beg = afterEnd; // is a part -> next search
4212 //================================================================================
4214 * \brief Creates pyObject
4216 //================================================================================
4218 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4219 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4224 //================================================================================
4226 * \brief Set up myID and myIsPublished
4228 //================================================================================
4230 void _pyObject::setID(const _pyID& theID)
4233 myIsPublished = !theGen->IsNotPublished( GetID() );
4236 //================================================================================
4238 * \brief Clear myCreationCmd and myProcessedCmds
4240 //================================================================================
4242 void _pyObject::ClearCommands()
4247 if ( !myCreationCmd.IsNull() )
4248 myCreationCmd->Clear();
4250 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4251 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4255 //================================================================================
4257 * \brief Return method name giving access to an interaface object wrapped by python class
4258 * \retval const char* - method name
4260 //================================================================================
4262 const char* _pyObject::AccessorMethod() const
4266 //================================================================================
4268 * \brief Return ID of a father
4270 //================================================================================
4272 _pyID _pyObject::FatherID(const _pyID & childID)
4274 int colPos = childID.SearchFromEnd(':');
4276 return childID.SubString( 1, colPos-1 );
4280 //================================================================================
4282 * \brief SelfEraser erases creation command if none of it's commands invoked
4283 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4285 //================================================================================
4287 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4288 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4290 myIsPublished = true; // prevent clearing as a not published
4291 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4294 //================================================================================
4296 * \brief SelfEraser erases creation command if none of it's commands invoked
4297 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4299 //================================================================================
4301 bool _pySelfEraser::CanClear()
4303 bool toErase = false;
4304 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4307 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4308 for ( ; cmd != myArgCmds.end(); ++cmd )
4309 nbArgUses += IsAliveCmd( *cmd );
4311 toErase = ( nbArgUses < 1 );
4316 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4317 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4318 for ( ; cmd != cmds.end(); )
4319 // check of cmd emptiness is not enough as object can change
4320 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4323 cmd = cmds.erase( cmd ); // save the cmd from clearing
4325 toErase = ( nbCalls < 1 );
4330 //================================================================================
4332 * \brief Check if a command is or can be cleared
4334 //================================================================================
4336 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4338 if ( theCmd->IsEmpty() )
4341 if ( !theGen->IsToKeepAllCommands() )
4343 const _pyID& objID = theCmd->GetObject();
4344 Handle( _pyObject ) obj = theGen->FindObject( objID );
4345 if ( !obj.IsNull() )
4346 return !obj->CanClear();
4351 //================================================================================
4353 * \brief SelfEraser erases creation command if none of it's commands invoked
4354 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4356 //================================================================================
4358 void _pySelfEraser::Flush()
4362 myIsPublished = false;
4363 _pyObject::ClearCommands();
4367 //================================================================================
4369 * \brief _pySubMesh constructor
4371 //================================================================================
4373 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4374 _pyObject(theCreationCmd)
4376 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4377 if ( toKeepAgrCmds )
4378 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4381 //================================================================================
4383 * \brief Return true if a sub-mesh can be used as argument of the given method
4385 //================================================================================
4387 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4390 // // names of all methods where a sub-mesh can be used as argument
4391 // static TStringSet methods;
4392 // if ( methods.empty() ) {
4393 // const char * names[] = {
4394 // // methods of SMESH_Gen
4396 // // methods of SMESH_Group
4398 // // methods of SMESH_Measurements
4400 // // methods of SMESH_Mesh
4401 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4403 // // methods of SMESH_MeshEditor
4404 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4405 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4406 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4407 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4408 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4409 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4410 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4411 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4412 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4413 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4414 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4415 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4416 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4417 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4418 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4419 // "" }; // <- mark of end
4420 // methods.Insert( names );
4422 // return methods.Contains( theMethodName );
4425 //================================================================================
4427 * \brief count invoked commands
4429 //================================================================================
4431 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4433 _pyObject::Process(theCommand); // count calls of Process()
4436 //================================================================================
4438 * \brief Move creation command depending on invoked commands
4440 //================================================================================
4442 void _pySubMesh::Flush()
4444 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4445 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4446 else if ( !myCreator.IsNull() )
4447 // move to be just after creator
4448 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4450 // move sub-mesh usage after creation cmd
4451 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4452 for ( ; cmd != myArgCmds.end(); ++cmd )
4453 if ( !(*cmd)->IsEmpty() )
4454 GetCreationCmd()->AddDependantCmd( *cmd );
4457 //================================================================================
4459 * \brief Creates _pyGroup
4461 //================================================================================
4463 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4464 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4466 if ( !id.IsEmpty() )
4469 myCanClearCreationCmd = true;
4471 const _AString& method = theCreationCmd->GetMethod();
4472 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4474 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4476 // ----------------------------------------------------------------------
4477 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4479 _pyID geom = theCreationCmd->GetArg( 3 );
4480 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4481 // next if(){...} section is commented
4482 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4483 // theCreationCmd->SetMethod( "Group" );
4484 // theCreationCmd->RemoveArgs();
4485 // theCreationCmd->SetArg( 1, geom );
4488 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4489 _pyID type = theCreationCmd->GetArg( 1 );
4490 _pyID name = theCreationCmd->GetArg( 2 );
4491 theCreationCmd->SetMethod( "GroupOnGeom" );
4492 theCreationCmd->RemoveArgs();
4493 theCreationCmd->SetArg( 1, geom );
4494 theCreationCmd->SetArg( 2, name );
4495 theCreationCmd->SetArg( 3, type );
4498 else if ( method == "CreateGroupFromFilter" )
4500 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4501 theCreationCmd->SetMethod( "GroupOnFilter" );
4503 _pyID filterID = theCreationCmd->GetArg(3);
4504 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4505 if ( !filter.IsNull())
4507 if ( !filter->GetNewID().IsEmpty() )
4508 theCreationCmd->SetArg( 3, filter->GetNewID() );
4509 //filter->AddUser( this );
4513 else if ( method == "GetGroups" )
4515 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4519 // theCreationCmd does something else apart from creation of this group
4520 // and thus it can't be cleared if this group is removed
4521 myCanClearCreationCmd = false;
4525 //================================================================================
4527 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4530 //================================================================================
4532 bool _pyGroup::CanClear()
4537 if ( !myCanClearCreationCmd &&
4538 !myCreationCmd.IsNull() &&
4539 myCreationCmd->GetMethod() == "GetGroups" )
4541 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4542 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4543 list< _pyID >::iterator grID = idList.begin();
4544 if ( GetID() == *grID )
4546 myCanClearCreationCmd = true;
4547 list< Handle(_pyGroup ) > groups;
4548 for ( ; grID != idList.end(); ++grID )
4550 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4551 if ( group.IsNull() ) continue;
4552 groups.push_back( group );
4553 if ( group->IsInStudy() )
4554 myCanClearCreationCmd = false;
4556 // set myCanClearCreationCmd == true to all groups
4557 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4558 for ( ; group != groups.end(); ++group )
4559 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4563 return myCanClearCreationCmd;
4566 //================================================================================
4568 * \brief set myCanClearCreationCmd = true if the main action of the creation
4569 * command is discarded
4571 //================================================================================
4573 void _pyGroup::RemovedWithContents()
4575 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4576 // via a created group
4577 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4578 // myCanClearCreationCmd = true;
4581 //================================================================================
4583 * \brief To convert creation of a group by filter
4585 //================================================================================
4587 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4589 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4590 // group = mesh.CreateEmptyGroup( elemType, groupName )
4591 // aFilter.SetMesh(mesh)
4592 // nbAdd = group.AddFrom( aFilter )
4593 Handle(_pyFilter) filter;
4594 if ( theCommand->GetMethod() == "AddFrom" )
4596 _pyID idSource = theCommand->GetArg(1);
4597 // check if idSource is a filter
4598 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4599 if ( !filter.IsNull() )
4601 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4602 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4603 while ( *cmdIt != theCommand ) ++cmdIt;
4604 while ( (*cmdIt)->GetOrderNb() != 1 )
4606 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4607 if ((setMeshCmd->GetObject() == idSource ||
4608 setMeshCmd->GetObject() == filter->GetNewID() )
4610 setMeshCmd->GetMethod() == "SetMesh")
4612 setMeshCmd->Clear();
4616 // replace 3 commands by one
4617 theCommand->Clear();
4618 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4619 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4620 if ( !filter->GetNewID().IsEmpty() )
4621 idSource = filter->GetNewID();
4622 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4623 makeGroupCmd->SetArg( 1, name );
4624 makeGroupCmd->SetArg( 2, idSource );
4625 filter->AddArgCmd( makeGroupCmd );
4628 else if ( theCommand->GetMethod() == "SetFilter" )
4630 // set new name of a filter or clear the command if the same filter is set
4631 _pyID filterID = theCommand->GetArg(1);
4632 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4633 if ( !myFilter.IsNull() && filter == myFilter )
4634 theCommand->Clear();
4635 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4636 theCommand->SetArg( 1, filter->GetNewID() );
4639 else if ( theCommand->GetMethod() == "GetFilter" )
4641 // GetFilter() returns a filter with other ID, make myFilter process
4642 // calls of the returned filter
4643 if ( !myFilter.IsNull() )
4645 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4646 theCommand->Clear();
4650 // if ( !filter.IsNull() )
4651 // filter->AddUser( this );
4653 theGen->AddMeshAccessorMethod( theCommand );
4656 //================================================================================
4658 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4660 //================================================================================
4662 void _pyGroup::Flush()
4664 if ( !theGen->IsToKeepAllCommands() &&
4665 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4667 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4671 //================================================================================
4673 * \brief Constructor of _pyFilter
4675 //================================================================================
4677 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4678 :_pyObject(theCreationCmd), myNewID( newID )
4680 //myIsPublished = true; // prevent clearing as a not published
4681 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4684 //================================================================================
4686 * \brief To convert creation of a filter by criteria and
4687 * to replace an old name by a new one
4689 //================================================================================
4691 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4693 if ( theCommand->GetObject() == GetID() )
4694 _pyObject::Process(theCommand); // count commands
4696 if ( !myNewID.IsEmpty() )
4697 theCommand->SetObject( myNewID );
4699 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4700 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4701 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4702 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4703 theCommand->GetMethod() == "SetCriteria")
4705 // aFilter.SetCriteria(aCriteria) ->
4706 // aFilter = smesh.GetFilterFromCriteria(criteria)
4707 if ( myNewID.IsEmpty() )
4708 theCommand->SetResultValue( GetID() );
4710 theCommand->SetResultValue( myNewID );
4711 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4712 theCommand->SetMethod( "GetFilterFromCriteria" );
4714 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4715 GetCreationCmd()->Clear();
4716 GetCreationCmd()->GetString() = theCommand->GetString();
4717 theCommand->Clear();
4718 theCommand->AddDependantCmd( GetCreationCmd() );
4719 // why swap? -- it's needed
4720 //GetCreationCmd()->Clear();
4722 else if ( theCommand->GetMethod() == "SetMesh" )
4724 if ( myMesh == theCommand->GetArg( 1 ))
4725 theCommand->Clear();
4727 myMesh = theCommand->GetArg( 1 );
4728 theGen->AddMeshAccessorMethod( theCommand );
4732 //================================================================================
4734 * \brief Set new filter name to the creation command and to myArgCmds
4736 //================================================================================
4738 void _pyFilter::Flush()
4740 if ( myNewID.IsEmpty() ) return;
4742 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4743 for ( ; cmd != myArgCmds.end(); ++cmd )
4744 if ( !(*cmd)->IsEmpty() )
4746 _AString cmdStr = (*cmd)->GetString();
4747 _AString id = GetID();
4748 int pos = cmdStr.Search( id );
4751 cmdStr.Remove( pos, id.Length() );
4752 cmdStr.Insert( pos, myNewID );
4755 (*cmd)->GetString() = cmdStr;
4758 if ( !GetCreationCmd()->IsEmpty() )
4759 GetCreationCmd()->SetResultValue( myNewID );
4762 //================================================================================
4764 * \brief Return true if all my users can be cleared
4766 //================================================================================
4768 bool _pyObject::CanClear()
4770 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4771 for ( ; cmd != myArgCmds.end(); ++cmd )
4772 if ( !(*cmd)->IsEmpty() )
4774 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4775 if ( !obj.IsNull() && !obj->CanClear() )
4778 return ( !myIsPublished );
4781 //================================================================================
4783 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4785 //================================================================================
4787 _pyHypothesisReader::_pyHypothesisReader()
4790 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4791 LDOMParser xmlParser;
4792 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4794 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4798 INFOS( xmlParser.GetError(data) );
4801 // <algorithm type="Regular_1D"
4802 // label-id="Wire discretisation"
4805 // <algo>Regular_1D=Segment()</algo>
4806 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4808 LDOM_Document xmlDoc = xmlParser.getDocument();
4809 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4810 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4812 LDOM_Node algoNode = algoNodeList.item( i );
4813 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4814 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4815 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4817 _AString text, algoType, method, arg;
4818 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4820 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4821 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4822 text = textNode.getNodeValue();
4823 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4824 algoType = algoCmd->GetResultValue();
4825 method = algoCmd->GetMethod();
4826 arg = algoCmd->GetArg(1);
4827 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4829 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4830 algo->SetConvMethodAndType( method, algoType );
4831 if ( !arg.IsEmpty() )
4832 algo->setCreationArg( 1, arg );
4834 myType2Hyp[ algoType ] = algo;
4838 if ( algoType.IsEmpty() ) continue;
4840 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4842 Handle( _pyHypothesis ) hyp;
4843 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4845 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4846 LDOM_Node textNode = pyHypoNode.getFirstChild();
4847 text = textNode.getNodeValue();
4848 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4849 hypType = hypoCmd->GetResultValue();
4850 method = hypoCmd->GetMethod();
4851 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4853 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4854 if ( type2hyp == myType2Hyp.end() )
4855 hyp = new _pyHypothesis( hypoCmd );
4857 hyp = type2hyp->second;
4858 hyp->SetConvMethodAndType( method, algoType );
4859 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4861 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4862 _AString argMethod = argCmd.GetMethod();
4863 _AString argNbText = argCmd.GetArg( 1 );
4864 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4865 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4867 hyp->AddArgMethod( argMethod,
4868 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4870 myType2Hyp[ hypType ] = hyp;
4874 // <hypothesis type="BLSURF_Parameters"
4878 // <accumulative-methods>
4879 // SetEnforcedVertex,
4880 // SetEnforcedVertexNamed
4881 // </accumulative-methods>
4885 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4886 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4888 LDOM_Node hypNode = hypNodeList.item( i );
4889 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4890 _AString hypType = hypElem.getAttribute("type");
4891 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4892 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4894 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4895 if ( type2hyp == myType2Hyp.end() ) continue;
4897 LDOM_Node methNode = methNodeList.item( 0 );
4898 LDOM_Node textNode = methNode.getFirstChild();
4899 _AString text = textNode.getNodeValue();
4903 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4904 pos += method.Length();
4905 type2hyp->second->AddAccumulativeMethod( method );
4907 while ( !method.IsEmpty() );
4910 } // loop on xmlPaths
4913 //================================================================================
4915 * \brief Returns a new hypothesis initialized according to the read information
4917 //================================================================================
4919 Handle(_pyHypothesis)
4920 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4921 const Handle(_pyCommand)& creationCmd) const
4923 Handle(_pyHypothesis) resHyp, sampleHyp;
4925 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4926 if ( type2hyp != myType2Hyp.end() )
4927 sampleHyp = type2hyp->second;
4929 if ( sampleHyp.IsNull() )
4931 resHyp = new _pyHypothesis(creationCmd);
4935 if ( sampleHyp->IsAlgo() )
4936 resHyp = new _pyAlgorithm( creationCmd );
4938 resHyp = new _pyHypothesis(creationCmd);
4939 resHyp->Assign( sampleHyp, _pyID() );
4944 //================================================================================
4946 * \brief Adds an object ID to some family of IDs with a common prefix
4947 * \param [in] str - the object ID
4948 * \return bool - \c false if \a str does not have the same prefix as \a this family
4949 * (for internal usage)
4951 //================================================================================
4953 bool _pyStringFamily::Add( const char* str )
4955 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4956 return false; // expected prefix is missing
4958 str += _prefix.Length(); // skip _prefix
4960 // try to add to some of child falimies
4961 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4962 for ( ; itSub != _subFams.end(); ++itSub )
4963 if ( itSub->Add( str ))
4966 // no suitable family found - add str to _strings or create a new child family
4968 // look for a proper place within sorted _strings
4969 std::list< _AString >::iterator itStr = _strings.begin();
4970 while ( itStr != _strings.end() && itStr->IsLess( str ))
4972 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4973 return true; // same ID already kept
4975 const int minPrefixSize = 4;
4977 // count "smaller" strings with the same prefix
4978 std::list< _AString >::iterator itLess = itStr; --itLess;
4980 for ( ; itLess != _strings.end(); --itLess )
4981 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4986 // count "greater" strings with the same prefix
4987 std::list< _AString >::iterator itMore = itStr;
4989 for ( ; itMore != _strings.end(); ++itMore )
4990 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4995 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4997 // look for a maximal prefix length
4998 // int lessPrefSize = 3, morePrefSize = 3;
4999 // if ( nbLess > 0 )
5000 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5002 // if ( nbMore > 0 )
5003 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5005 // int prefixSize = 3;
5006 // if ( nbLess == 0 )
5007 // prefixSize = morePrefSize;
5008 // else if ( nbMore == 0 )
5009 // prefixSize = lessPrefSize;
5011 // prefixSize = Min( lessPrefSize, morePrefSize );
5012 int prefixSize = minPrefixSize;
5013 _AString newPrefix ( str, prefixSize );
5015 // look for a proper place within _subFams sorted by _prefix
5016 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5017 if ( !itSub->_prefix.IsLess( newPrefix ))
5020 // add the new _pyStringFamily
5021 itSub = _subFams.insert( itSub, _pyStringFamily());
5022 _pyStringFamily& newSubFam = *itSub;
5023 newSubFam._prefix = newPrefix;
5025 // pass this->_strings to newSubFam._strings
5026 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5027 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5028 newSubFam._strings.push_back( str + prefixSize );
5029 for ( ; nbMore > 0; --nbMore, ++itStr )
5030 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5032 _strings.erase( itLess, ++itMore );
5034 else // to few string to make a family fot them
5036 _strings.insert( itStr, str );
5041 //================================================================================
5043 * \brief Finds an object ID in the command
5044 * \param [in] longStr - the command string
5045 * \param [out] subStr - the found object ID
5046 * \return bool - \c true if the object ID found
5048 //================================================================================
5050 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5052 const _AString& longStr = cmd->GetString();
5053 const char* s = longStr.ToCString();
5056 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5057 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5058 if ( argBeg < 4 || argBeg > longStr.Length() )
5060 for ( ; itSub != _subFams.end(); ++itSub )
5063 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5064 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5066 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5067 from = pos + len + itSub->_prefix.Length();
5072 from += itSub->_prefix.Length();
5075 // look among _strings
5076 std::list< _AString >::iterator itStr = _strings.begin();
5077 for ( ; itStr != _strings.end(); ++itStr )
5078 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5079 // check that object ID does not continue after len
5080 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5082 subStr.push_back( *itStr );
5088 //================================================================================
5090 * \brief Return remainder length of the object ID after my _prefix
5091 * \param [in] str - remainder of the command after my _prefix
5092 * \return int - length of the object ID or -1 if not found
5094 //================================================================================
5096 int _pyStringFamily::isIn( const char* str )
5098 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5100 for ( ; itSub != _subFams.end(); ++itSub )
5102 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5105 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5106 return itSub->_prefix.Length() + len;
5111 if ( !_strings.empty() )
5113 std::list< _AString >::iterator itStr = _strings.begin();
5114 bool firstEmpty = itStr->IsEmpty();
5117 for ( ; itStr != _strings.end(); ++itStr )
5119 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5122 len = itStr->Length();
5131 // check that object ID does not continue after len
5132 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5139 //================================================================================
5143 //================================================================================
5145 void _pyStringFamily::Print( int level )
5147 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5148 std::list< _AString >::iterator itStr = _strings.begin();
5149 for ( ; itStr != _strings.end(); ++itStr )
5150 cout << *itStr << " | ";
5152 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5153 for ( ; itSub != _subFams.end(); ++itSub )
5154 itSub->Print( level + 1 );
5156 cout << string( 70, '-' ) << endl;