1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
53 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
54 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
55 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
56 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
57 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
58 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
59 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
60 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
61 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
62 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
63 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
64 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
65 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
66 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
67 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
68 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
71 using SMESH::TPythonDump;
74 * \brief Container of commands into which the initial script is split.
75 * It also contains data corresponding to SMESH_Gen contents
77 static Handle(_pyGen) theGen;
79 static TCollection_AsciiString theEmptyString;
81 //#define DUMP_CONVERSION
83 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
84 #undef DUMP_CONVERSION
90 //================================================================================
92 * \brief Set of TCollection_AsciiString initialized by C array of C strings
94 //================================================================================
96 struct TStringSet: public set<TCollection_AsciiString>
99 * \brief Filling. The last string must be ""
101 void Insert(const char* names[]) {
102 for ( int i = 0; names[i][0] ; ++i )
103 insert( (char*) names[i] );
106 * \brief Check if a string is in
108 bool Contains(const TCollection_AsciiString& name ) {
109 return find( name ) != end();
113 //================================================================================
115 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
116 * Odd items of the C array are map keys, and even items are values
118 //================================================================================
120 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
123 * \brief Filling. The last string must be ""
125 void Insert(const char* names_values[]) {
126 for ( int i = 0; names_values[i][0] ; i += 2 )
127 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
130 * \brief Check if a string is in
132 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
133 map< _AString, _AString >::iterator it = find( name );
134 return it == end() ? "" : it->second;
138 //================================================================================
140 * \brief Returns a mesh by object
142 //================================================================================
144 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
148 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
149 return Handle(_pyMesh)::DownCast( obj );
150 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
151 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
152 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
153 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
155 return Handle(_pyMesh)();
158 //================================================================================
160 * \brief Check if objects used as args have been created by previous commands
162 //================================================================================
164 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
166 // either comment or erase a command including NotPublishedObjectName()
167 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
169 bool isResultPublished = false;
170 const int nbRes = cmd->GetNbResultValues();
171 for ( int i = 0; i < nbRes; i++ )
173 _pyID objID = cmd->GetResultValue( i+1 );
174 if ( cmd->IsStudyEntry( objID ))
175 isResultPublished = (! theGen->IsNotPublished( objID ));
176 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
178 if ( isResultPublished )
184 // check if an Object was created in the script
187 _pyID obj = cmd->GetObject();
188 if ( obj.Search( "print(" ) == 1 )
189 return; // print statement
191 if ( !obj.IsEmpty() && obj.Value( obj.Length() ) == ')' )
192 // remove an accessor method
193 obj = _pyCommand( obj ).GetObject();
195 const bool isMethodCall = cmd->IsMethodCall();
196 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
198 comment = "not created Object";
199 theGen->ObjectCreationRemoved( obj );
201 // check if a command has not created args
202 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
204 const _pyID& arg = cmd->GetArg( iArg );
205 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
207 list< _pyID > idList = cmd->GetStudyEntries( arg );
208 list< _pyID >::iterator id = idList.begin();
209 for ( ; id != idList.end(); ++id )
210 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
212 comment += *id + " has not been yet created";
215 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
216 // comment += arg + " has not been yet created";
218 // treat result objects
219 const _pyID& result = cmd->GetResultValue();
220 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
222 list< _pyID > idList = cmd->GetStudyEntries( result );
223 list< _pyID >::iterator id = idList.begin();
224 for ( ; id != idList.end(); ++id )
226 if ( comment.IsEmpty() )
227 presentObjects.insert( *id );
229 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
231 if ( idList.empty() && cmd->IsID( result ))
232 presentObjects.insert( result );
234 // comment the command
235 if ( !comment.IsEmpty() )
238 cmd->GetString() += " ### ";
239 cmd->GetString() += comment;
243 //================================================================================
245 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
247 //================================================================================
249 void fixFunctorType( TCollection_AsciiString& Type,
250 TCollection_AsciiString& Compare,
251 TCollection_AsciiString& UnaryOp,
252 TCollection_AsciiString& BinaryOp )
254 // The problem is that dumps of old studies created using filters becomes invalid
255 // when new items are inserted in the enum SMESH::FunctorType since values
256 // of this enum are dumped as integer values.
257 // This function corrects enum values of old studies given as args (Type,Compare,...)
258 // We can find out how to correct them by value of BinaryOp which can have only two
259 // values: FT_Undefined or FT_LogicalNOT.
260 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
261 // where PythonDump appeared
262 // v 3.0.0: FT_Undefined == 25
263 // v 3.1.0: FT_Undefined == 26, new items:
265 // v 4.1.2: FT_Undefined == 27, new items:
266 // - FT_BelongToGenSurface = 17
267 // v 5.1.1: FT_Undefined == 32, new items:
268 // - FT_FreeNodes = 10
269 // - FT_FreeFaces = 11
270 // - FT_LinearOrQuadratic = 23
271 // - FT_GroupColor = 24
272 // - FT_ElemGeomType = 25
273 // v 5.1.5: FT_Undefined == 33, new items:
274 // - FT_CoplanarFaces = 26
275 // v 6.2.0: FT_Undefined == 39, new items:
276 // - FT_MaxElementLength2D = 8
277 // - FT_MaxElementLength3D = 9
278 // - FT_BareBorderVolume = 25
279 // - FT_BareBorderFace = 26
280 // - FT_OverConstrainedVolume = 27
281 // - FT_OverConstrainedFace = 28
282 // v 6.5.0: FT_Undefined == 43, new items:
283 // - FT_EqualNodes = 14
284 // - FT_EqualEdges = 15
285 // - FT_EqualFaces = 16
286 // - FT_EqualVolumes = 17
287 // v 6.6.0: FT_Undefined == 44, new items:
288 // - FT_BallDiameter = 37
289 // v 6.7.1: FT_Undefined == 45, new items:
290 // - FT_EntityType = 36
291 // v 7.3.0: FT_Undefined == 46, new items:
292 // - FT_ConnectedElements = 39
293 // v 7.6.0: FT_Undefined == 47, new items:
294 // - FT_BelongToMeshGroup = 22
295 // v 8.1.0: FT_Undefined == 48, new items:
296 // - FT_NodeConnectivityNumber= 22
297 // v 8.5.0: FT_Undefined == 49, new items:
298 // - FT_Deflection2D = 22
300 // It's necessary to continue recording this history and to fill
301 // undef2newItems (see below) accordingly.
303 typedef map< int, vector< int > > TUndef2newItems;
304 static TUndef2newItems undef2newItems;
305 if ( undef2newItems.empty() )
307 undef2newItems[ 26 ].push_back( 7 );
308 undef2newItems[ 27 ].push_back( 17 );
309 { int items[] = { 10, 11, 23, 24, 25 };
310 undef2newItems[ 32 ].assign( items, items+5 ); }
311 undef2newItems[ 33 ].push_back( 26 );
312 { int items[] = { 8, 9, 25, 26, 27, 28 };
313 undef2newItems[ 39 ].assign( items, items+6 ); }
314 { int items[] = { 14, 15, 16, 17 };
315 undef2newItems[ 43 ].assign( items, items+4 ); }
316 undef2newItems[ 44 ].push_back( 37 );
317 undef2newItems[ 45 ].push_back( 36 );
318 undef2newItems[ 46 ].push_back( 39 );
319 undef2newItems[ 47 ].push_back( 22 );
320 undef2newItems[ 48 ].push_back( 22 );
321 undef2newItems[ 49 ].push_back( 22 );
323 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
326 int iType = Type.IntegerValue();
327 int iCompare = Compare.IntegerValue();
328 int iUnaryOp = UnaryOp.IntegerValue();
329 int iBinaryOp = BinaryOp.IntegerValue();
331 // find out integer value of FT_Undefined at the moment of dump
332 int oldUndefined = iBinaryOp;
333 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
336 // apply history to args
337 TUndef2newItems::const_iterator undef_items =
338 undef2newItems.upper_bound( oldUndefined );
339 if ( undef_items != undef2newItems.end() )
341 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
342 for ( ; undef_items != undef2newItems.end(); ++undef_items )
344 const vector< int > & addedItems = undef_items->second;
345 for ( size_t i = 0; i < addedItems.size(); ++i )
346 for ( int iArg = 0; iArg < 4; ++iArg )
348 int& arg = *pArg[iArg];
349 if ( arg >= addedItems[i] )
353 Type = TCollection_AsciiString( iType );
354 Compare = TCollection_AsciiString( iCompare );
355 UnaryOp = TCollection_AsciiString( iUnaryOp );
356 BinaryOp = TCollection_AsciiString( iBinaryOp );
360 //================================================================================
362 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
363 * arguments of a given command by a list "[x,y,z]" if the list is accesible
366 //================================================================================
368 void StructToList( Handle( _pyCommand)& theCommand, const bool checkMethod=true )
370 static TStringSet methodsAcceptingList;
371 if ( methodsAcceptingList.empty() ) {
372 const char * methodNames[] = {
373 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
374 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
375 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
376 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
377 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
378 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
379 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
380 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
381 "Translate","TranslateMakeGroups","TranslateMakeMesh",
382 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
383 "ExtrusionAlongPathX","ExtrusionAlongPathObjX","SplitHexahedraIntoPrisms"
384 ,"" }; // <- mark of the end
385 methodsAcceptingList.Insert( methodNames );
387 if ( !checkMethod || methodsAcceptingList.Contains( theCommand->GetMethod() ))
389 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
391 const _AString & arg = theCommand->GetArg( i );
392 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
393 arg.Search( "SMESH.DirStruct" ) == 1 )
395 Handle(_pyCommand) workCmd = new _pyCommand( arg );
396 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
398 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
400 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
402 _AString newArg = "[ ";
403 newArg += ( workCmd->GetArg( 1 ) + ", " +
404 workCmd->GetArg( 2 ) + ", " +
405 workCmd->GetArg( 3 ) + " ]");
406 theCommand->SetArg( i, newArg );
412 //================================================================================
414 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
415 * a list "[id1,id2]" if the list is an accesible type of argument.
417 //================================================================================
419 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
421 static TStringSet methodsAcceptingList;
422 if ( methodsAcceptingList.empty() ) {
423 const char * methodNames[] = {
424 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
425 "ExportCGNS","ExportGMF",
426 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
427 "ScaleMakeGroups","Scale","ScaleMakeMesh",
428 "FindCoincidentNodesOnPartBut","DoubleElements",
429 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects"
430 ,"" }; // <- mark of the end
431 methodsAcceptingList.Insert( methodNames );
433 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
435 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
437 _pyCommand argCmd( theCommand->GetArg( i ));
438 if ( argCmd.GetMethod() == "GetIDSource" &&
439 argCmd.GetNbArgs() == 2 )
441 theCommand->SetArg( i, argCmd.GetArg( 1 ));
447 bool _FilterArg( const _AString& theArg )
449 static std::list<_AString> filteredArgs;
450 static bool initialized = false;
451 if ( !initialized ) {
453 filteredArgs.push_back( "SMESH.MED_V2_1" );
454 filteredArgs.push_back( "SMESH.MED_V2_2" );
456 return std::find( filteredArgs.begin(), filteredArgs.end(), theArg ) != filteredArgs.end();
460 //================================================================================
462 * \brief Convert a python script using commands of smeshBuilder.py
463 * \param theScriptLines - Lines of the input script
464 * \param theEntry2AccessorMethod - returns method names to access to
465 * objects wrapped with python class
466 * \param theObjectNames - names of objects
467 * \param theRemovedObjIDs - entries of objects whose created commands were removed
468 * \param theHistoricalDump - true means to keep all commands, false means
469 * to exclude commands relating to objects removed from study
470 * \retval TCollection_AsciiString - Conversion result
472 //================================================================================
475 SMESH_2smeshpy::ConvertScript(std::list< TCollection_AsciiString >& theScriptLines,
476 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
477 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
478 std::set< TCollection_AsciiString >& theRemovedObjIDs,
479 const bool theToKeepAllCommands)
481 std::list< TCollection_AsciiString >::iterator lineIt;
482 // process notebook variables
484 SMESH_NoteBook aNoteBook;
486 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
487 aNoteBook.AddCommand( *lineIt );
489 theScriptLines.clear();
491 aNoteBook.ReplaceVariables();
493 aNoteBook.GetResultLines( theScriptLines );
496 // convert to smeshBuilder.py API
498 theGen = new _pyGen( theEntry2AccessorMethod,
501 theToKeepAllCommands );
503 for ( lineIt = theScriptLines.begin(); lineIt != theScriptLines.end(); ++lineIt )
504 theGen->AddCommand( *lineIt );
506 theScriptLines.clear();
510 #ifdef DUMP_CONVERSION
511 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
514 // clean 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 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
534 #ifdef DUMP_CONVERSION
535 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
537 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
538 CheckObjectPresence( *cmd, createdObjects );
539 if ( !(*cmd)->IsEmpty() ) {
540 aPrevCmd = (*cmd)->GetString();
541 theScriptLines.push_back( aPrevCmd );
550 //================================================================================
552 * \brief _pyGen constructor
554 //================================================================================
556 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
557 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
558 std::set< TCollection_AsciiString >& theRemovedObjIDs,
559 const bool theToKeepAllCommands)
560 : _pyObject( new _pyCommand( "", 0 )),
562 myID2AccessorMethod( theEntry2AccessorMethod ),
563 myObjectNames( theObjectNames ),
564 myRemovedObjIDs( theRemovedObjIDs ),
566 myToKeepAllCommands( theToKeepAllCommands ),
567 myGeomIDNb(0), myGeomIDIndex(-1)
569 // make that GetID() to return TPythonDump::SMESHGenName()
570 GetCreationCmd()->Clear();
571 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
572 GetCreationCmd()->GetString() += "=";
574 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
575 if ( !theObjectNames.IsEmpty() )
579 SALOMEDS::SComponent_wrap geomComp = SMESH_Gen_i::getStudyServant()->FindComponent("GEOM");
580 if ( geomComp->_is_nil() ) return;
581 CORBA::String_var entry = geomComp->GetID();
584 // find a SMESH entry
586 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
587 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
588 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
591 // find 1st difference between smeshID and geomID
592 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
593 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
594 if ( geomID.Value( i ) != smeshID.Value( i ))
596 myGeomIDNb = geomID.Value( i );
602 //================================================================================
604 * \brief name of SMESH_Gen in smeshBuilder.py
606 //================================================================================
608 const char* _pyGen::AccessorMethod() const
610 return SMESH_2smeshpy::GenName();
613 //================================================================================
615 * \brief Convert a command using a specific converter
616 * \param theCommand - the command to convert
618 //================================================================================
620 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
622 // store theCommand in the sequence
623 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
625 Handle(_pyCommand) aCommand = myCommands.back();
626 #ifdef DUMP_CONVERSION
627 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
630 const _pyID& objID = aCommand->GetObject();
632 if ( objID.IsEmpty() )
635 // Prevent moving a command creating a sub-mesh to the end of the script
636 // if the sub-mesh is used in theCommand as argument
637 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
639 // PlaceSubmeshAfterItsCreation( aCommand );
642 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
643 StructToList( aCommand );
645 const TCollection_AsciiString& method = aCommand->GetMethod();
647 // not to erase _pySelfEraser's etc. used as args in some commands
649 #ifdef USE_STRING_FAMILY
650 std::list<_pyID> objIDs;
651 if ( myKeepAgrCmdsIDs.IsInArgs( aCommand, objIDs ))
653 std::list<_pyID>::iterator objID = objIDs.begin();
654 for ( ; objID != objIDs.end(); ++objID )
656 Handle(_pyObject) obj = FindObject( *objID );
659 obj->AddArgCmd( aCommand );
660 //cout << objID << " found in " << theCommand << endl;
665 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
666 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
667 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
669 Handle(_pyObject) obj = FindObject( *id );
671 obj->AddArgCmd( aCommand );
676 // Find an object to process theCommand
679 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
681 this->Process( aCommand );
682 //addFilterUser( aCommand, theGen ); // protect filters from clearing
686 // SMESH_Mesh method?
687 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
688 if ( id_mesh != myMeshes.end() )
690 //id_mesh->second->AddProcessedCmd( aCommand );
692 // Wrap Export*() into try-except
693 if ( aCommand->MethodStartsFrom("Export"))
696 _AString indent = aCommand->GetIndentation();
697 _AString tryStr = indent + "try:";
698 _AString newCmd = indent + tab + ( aCommand->GetString().ToCString() + indent.Length() );
699 _AString pasCmd = indent + tab + "pass"; // to keep valid if newCmd is erased
700 _AString excStr = indent + "except:";
701 _AString msgStr = indent + "\tprint('"; msgStr += method + "() failed. Invalid file name?')";
703 myCommands.insert( --myCommands.end(), new _pyCommand( tryStr, myNbCommands ));
705 aCommand->GetString() = newCmd;
706 aCommand->SetOrderNb( ++myNbCommands );
707 myCommands.push_back( new _pyCommand( pasCmd, ++myNbCommands ));
708 myCommands.push_back( new _pyCommand( excStr, ++myNbCommands ));
709 myCommands.push_back( new _pyCommand( msgStr, ++myNbCommands ));
711 // check for mesh editor object
712 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
713 _pyID editorID = aCommand->GetResultValue();
714 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
715 myMeshEditors.insert( make_pair( editorID, editor ));
718 // check for SubMesh objects
719 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
720 _pyID subMeshID = aCommand->GetResultValue();
721 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
722 AddObject( subMesh );
725 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
726 GetIDSourceToList( aCommand );
728 //addFilterUser( aCommand, theGen ); // protect filters from clearing
730 id_mesh->second->Process( aCommand );
731 id_mesh->second->AddProcessedCmd( aCommand );
735 // SMESH_MeshEditor method?
736 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
737 if ( id_editor != myMeshEditors.end() )
739 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
740 GetIDSourceToList( aCommand );
742 //addFilterUser( aCommand, theGen ); // protect filters from clearing
744 // some commands of SMESH_MeshEditor create meshes and groups
745 _pyID meshID, groups;
746 if ( method.Search("MakeMesh") != -1 )
747 meshID = aCommand->GetResultValue();
748 else if ( method == "MakeBoundaryMesh")
749 meshID = aCommand->GetResultValue(1);
750 else if ( method == "MakeBoundaryElements")
751 meshID = aCommand->GetResultValue(2);
753 if ( method.Search("MakeGroups") != -1 ||
754 method == "ExtrusionAlongPathX" ||
755 method == "ExtrusionAlongPathObjX" ||
756 method == "DoubleNodeGroupNew" ||
757 method == "DoubleNodeGroupsNew" ||
758 method == "DoubleNodeElemGroupNew" ||
759 method == "DoubleNodeElemGroupsNew"||
760 method == "DoubleNodeElemGroup2New"||
761 method == "DoubleNodeElemGroups2New"
763 groups = aCommand->GetResultValue();
764 else if ( method == "MakeBoundaryMesh" )
765 groups = aCommand->GetResultValue(2);
766 else if ( method == "MakeBoundaryElements")
767 groups = aCommand->GetResultValue(3);
768 else if ( method == "Create0DElementsOnAllNodes" &&
769 aCommand->GetArg(2).Length() > 2 ) // group name != ''
770 groups = aCommand->GetResultValue();
772 id_editor->second->Process( aCommand );
773 id_editor->second->AddProcessedCmd( aCommand );
776 if ( !meshID.IsEmpty() &&
777 !myMeshes.count( meshID ) &&
778 aCommand->IsStudyEntry( meshID ))
780 _AString processedCommand = aCommand->GetString();
781 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
782 CheckObjectIsReCreated( mesh );
783 myMeshes.insert( make_pair( meshID, mesh ));
785 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
788 if ( !groups.IsEmpty() )
790 if ( !aCommand->IsStudyEntry( meshID ))
791 meshID = id_editor->second->GetMesh();
792 Handle(_pyMesh) mesh = myMeshes[ meshID ];
794 list< _pyID > idList = aCommand->GetStudyEntries( groups );
795 list< _pyID >::iterator grID = idList.begin();
796 for ( ; grID != idList.end(); ++grID )
797 if ( !myObjects.count( *grID ))
799 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
801 if ( !mesh.IsNull() ) mesh->AddGroup( group );
805 } // SMESH_MeshEditor methods
807 // SMESH_Hypothesis method?
808 Handle(_pyHypothesis) hyp = FindHyp( objID );
809 if ( !hyp.IsNull() && !hyp->IsAlgo() )
811 hyp->Process( aCommand );
812 hyp->AddProcessedCmd( aCommand );
816 // aFilterManager.CreateFilter() ?
817 if ( aCommand->GetMethod() == "CreateFilter" )
819 // Set a more human readable name to a filter
820 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
821 _pyID newID, filterID = aCommand->GetResultValue();
822 int pos = filterID.Search( "0x" );
824 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
826 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
829 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
830 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
832 // create _pySelfEraser for functors
833 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
834 functor->IgnoreOwnCalls(); // to erase if not used as an argument
835 AddObject( functor );
838 // other object method?
839 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
840 if ( id_obj != myObjects.end() ) {
841 id_obj->second->Process( aCommand );
842 id_obj->second->AddProcessedCmd( aCommand );
846 // Add access to a wrapped mesh
847 AddMeshAccessorMethod( aCommand );
849 // Add access to a wrapped algorithm
850 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
852 // PAL12227. PythonDump was not updated at proper time; result is
853 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
854 // TypeError: __init__() takes exactly 11 arguments (10 given)
855 const char wrongCommand[] = "SMESH.Filter.Criterion(";
856 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
858 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
859 // there must be 10 arguments, 5-th arg ThresholdID is missing,
860 const int wrongNbArgs = 9, missingArg = 5;
861 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
863 for ( int i = wrongNbArgs; i > missingArg; --i )
864 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
865 tmpCmd.SetArg( missingArg, "''");
866 aCommand->GetString().Trunc( beg - 1 );
867 aCommand->GetString() += tmpCmd.GetString();
870 // set GetCriterion(elementType,CritType,Compare,Threshold,UnaryOp,BinaryOp,Tolerance)
872 // instead of "SMESH.Filter.Criterion(
873 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
874 // 1 2 3 4 5 6 7 8 9 10
875 // in order to avoid the problem of type mismatch of long and FunctorType
876 const TCollection_AsciiString
877 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
878 TCollection_AsciiString
879 Type = aCommand->GetArg(1), // long
880 Compare = aCommand->GetArg(2), // long
881 Threshold = aCommand->GetArg(3), // double
882 ThresholdStr = aCommand->GetArg(4), // string
883 ThresholdID = aCommand->GetArg(5), // string
884 UnaryOp = aCommand->GetArg(6), // long
885 BinaryOp = aCommand->GetArg(7), // long
886 Tolerance = aCommand->GetArg(8), // double
887 TypeOfElement = aCommand->GetArg(9), // ElementType
888 Precision = aCommand->GetArg(10); // long
889 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
890 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
891 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
892 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
893 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
895 if ( Compare == "SMESH.FT_EqualTo" )
898 aCommand->RemoveArgs();
899 aCommand->SetObject( SMESH_2smeshpy::GenName() );
900 aCommand->SetMethod( "GetCriterion" );
902 aCommand->SetArg( 1, TypeOfElement );
903 aCommand->SetArg( 2, Type );
904 aCommand->SetArg( 3, Compare );
906 if ( Threshold.IsIntegerValue() )
908 int iGeom = Threshold.IntegerValue();
909 if ( Type == "SMESH.FT_ElemGeomType" )
911 // set SMESH.GeometryType instead of a numerical Threshold
912 const int nbTypes = SMESH::Geom_LAST;
913 const char* types[] = {
914 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
915 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
916 "Geom_POLYHEDRA", "Geom_BALL" };
917 if ( -1 < iGeom && iGeom < nbTypes )
918 Threshold = SMESH + types[ iGeom ];
920 // is types complete? (compilation failure mains that enum GeometryType changed)
921 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
924 if (Type == "SMESH.FT_EntityType")
926 // set SMESH.EntityType instead of a numerical Threshold
927 const int nbTypes = SMESH::Entity_Last;
928 const char* types[] = {
929 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
930 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
931 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
932 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
933 "Entity_Pyramid", "Entity_Quad_Pyramid",
934 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
935 "Entity_Penta", "Entity_Quad_Penta", "Entity_BiQuad_Penta", "Entity_Hexagonal_Prism",
936 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
937 if ( -1 < iGeom && iGeom < nbTypes )
938 Threshold = SMESH + types[ iGeom ];
940 // is 'types' complete? (compilation failure mains that enum EntityType changed)
941 int _asrt[( sizeof(types) / sizeof(const char*) == nbTypes ) ? 2 : -1 ]; _asrt[0]=_asrt[1];
945 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
946 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
947 else if ( ThresholdStr.Length() != 2 )
948 aCommand->SetArg( 4, ThresholdStr );
949 else if ( ThresholdID.Length() != 2 )
950 aCommand->SetArg( 4, ThresholdID );
952 aCommand->SetArg( 4, Threshold );
953 // find the last not default arg
955 if ( Tolerance == dfltTol ) {
957 if ( BinaryOp == dfltFunctor ) {
959 if ( UnaryOp == dfltFunctor )
963 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
964 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
965 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
966 if ( Precision != dfltPreci )
968 TCollection_AsciiString crit = aCommand->GetResultValue();
969 aCommand->GetString() += "; ";
970 aCommand->GetString() += crit + ".Precision = " + Precision;
976 //================================================================================
978 * \brief Convert the command or remember it for later conversion
979 * \param theCommand - The python command calling a method of SMESH_Gen
981 //================================================================================
983 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
985 // there are methods to convert:
986 // CreateMesh( shape )
987 // Concatenate( [mesh1, ...], ... )
988 // CreateHypothesis( theHypType, theLibName )
989 // Compute( mesh, geom )
990 // Evaluate( mesh, geom )
992 TCollection_AsciiString method = theCommand->GetMethod();
994 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
996 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
1000 if ( method == "CreateMeshesFromUNV" ||
1001 method == "CreateMeshesFromSTL" ||
1002 method == "CopyMesh" ) // command result is a mesh
1004 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1008 if( method == "CreateMeshesFromMED" ||
1009 method == "CreateMeshesFromSAUV"||
1010 method == "CreateMeshesFromCGNS" ||
1011 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
1013 std::list< _pyID > meshIDs = theCommand->GetStudyEntries( theCommand->GetResultValue() );
1014 std::list< _pyID >::iterator meshID = meshIDs.begin();
1015 for ( ; meshID != meshIDs.end(); ++meshID )
1017 Handle(_pyMesh) mesh = new _pyMesh( theCommand, *meshID );
1020 if ( method == "CreateMeshesFromGMF" )
1022 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
1023 // CreateMeshesFromGMF( theFileName )
1024 _AString file = theCommand->GetArg(1);
1025 theCommand->RemoveArgs();
1026 theCommand->SetArg( 1, file );
1030 // CreateHypothesis()
1031 if ( method == "CreateHypothesis" )
1033 // issue 199929, remove standard library name (default parameter)
1034 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1035 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1036 // keep the first argument
1037 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1038 theCommand->RemoveArgs();
1039 theCommand->SetArg( 1, arg );
1042 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1043 CheckObjectIsReCreated( hyp );
1044 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1049 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1050 if ( method == "Compute" )
1052 const _pyID& meshID = theCommand->GetArg( 1 );
1053 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1054 if ( id_mesh != myMeshes.end() ) {
1055 theCommand->SetObject( meshID );
1056 theCommand->RemoveArgs();
1057 id_mesh->second->Process( theCommand );
1058 id_mesh->second->AddProcessedCmd( theCommand );
1063 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1064 if ( method == "Evaluate" )
1066 const _pyID& meshID = theCommand->GetArg( 1 );
1067 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1068 if ( id_mesh != myMeshes.end() ) {
1069 theCommand->SetObject( meshID );
1070 _pyID geom = theCommand->GetArg( 2 );
1071 theCommand->RemoveArgs();
1072 theCommand->SetArg( 1, geom );
1073 id_mesh->second->AddProcessedCmd( theCommand );
1078 // objects erasing creation command if no more its commands invoked:
1079 // SMESH_Pattern, FilterManager
1080 if ( method == "GetPattern" ||
1081 method == "CreateFilterManager" ||
1082 method == "CreateMeasurements" )
1084 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1085 if ( !AddObject( obj ) )
1086 theCommand->Clear(); // already created
1088 // Concatenate( [mesh1, ...], ... )
1089 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1091 if ( method == "ConcatenateWithGroups" ) {
1092 theCommand->SetMethod( "Concatenate" );
1093 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1095 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1097 AddMeshAccessorMethod( theCommand );
1099 else if ( method == "SetName" ) // SetName(obj,name)
1101 // store theCommand as one of object commands to erase it along with the object
1102 const _pyID& objID = theCommand->GetArg( 1 );
1103 Handle(_pyObject) obj = FindObject( objID );
1104 if ( !obj.IsNull() )
1105 obj->AddProcessedCmd( theCommand );
1108 // Replace name of SMESH_Gen
1110 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1111 static TStringSet smeshpyMethods;
1112 if ( smeshpyMethods.empty() ) {
1113 const char * names[] =
1114 { "SetEmbeddedMode","IsEmbeddedMode","UpdateStudy","GetStudy",
1115 "GetPattern","GetSubShapesId",
1116 "" }; // <- mark of array end
1117 smeshpyMethods.Insert( names );
1119 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1120 // smeshgen.Method() --> smesh.Method()
1121 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1123 // smeshgen.Method() --> smesh.Method()
1124 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1127 //================================================================================
1129 * \brief Convert the remembered commands
1131 //================================================================================
1133 void _pyGen::Flush()
1135 // create an empty command
1136 myLastCommand = new _pyCommand();
1138 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1139 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1140 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1142 if ( IsToKeepAllCommands() ) // historical dump
1144 // set myIsPublished = true to all objects
1145 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1146 id_mesh->second->SetRemovedFromStudy( false );
1147 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1148 id_hyp->second->SetRemovedFromStudy( false );
1149 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1150 id_obj->second->SetRemovedFromStudy( false );
1154 // let hypotheses find referred objects in order to prevent clearing
1155 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1156 list< Handle(_pyMesh) > fatherMeshes;
1157 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1158 if ( !id_hyp->second.IsNull() )
1159 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1161 // set myIsPublished = false to all objects depending on
1162 // meshes built on a removed geometry
1163 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1164 if ( id_mesh->second->IsNotGeomPublished() )
1165 id_mesh->second->SetRemovedFromStudy( true );
1168 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1169 if ( ! id_mesh->second.IsNull() )
1170 id_mesh->second->Flush();
1173 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1174 if ( !id_hyp->second.IsNull() ) {
1175 id_hyp->second->Flush();
1176 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1177 if ( !id_hyp->second->IsWrapped() )
1178 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1181 // Flush other objects. 2 times, for objects depending on Flush() of later created objects
1182 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1183 for ( ; robj != myOrderedObjects.rend(); ++robj )
1184 if ( ! robj->IsNull() )
1186 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1187 for ( ; obj != myOrderedObjects.end(); ++obj )
1188 if ( ! obj->IsNull() )
1191 myLastCommand->SetOrderNb( ++myNbCommands );
1192 myCommands.push_back( myLastCommand );
1195 //================================================================================
1197 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1198 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1200 //================================================================================
1202 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1204 // map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1205 // for ( ; id_obj != myObjects.end(); ++id_obj )
1207 // if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1208 // for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1210 // const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1211 // if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1213 // list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1214 // list< _pyID >::iterator id = idList.begin();
1215 // for ( ; id != idList.end(); ++id )
1216 // if ( id_obj->first == *id )
1217 // // _pySubMesh::Process() does what we need
1218 // Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1223 //================================================================================
1225 * \brief Clean commmands of removed objects depending on myIsPublished flag
1227 //================================================================================
1229 void _pyGen::ClearCommands()
1231 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1232 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1233 id_mesh->second->ClearCommands();
1235 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1236 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1237 if ( !id_hyp->second.IsNull() )
1238 id_hyp->second->ClearCommands();
1240 // Other objects. 2 times, for objects depending on ClearCommands() of later created objects
1241 std::list< Handle(_pyObject) >::reverse_iterator robj = myOrderedObjects.rbegin();
1242 for ( ; robj != myOrderedObjects.rend(); ++robj )
1243 if ( ! robj->IsNull() )
1244 (*robj)->ClearCommands();
1245 std::list< Handle(_pyObject) >::iterator obj = myOrderedObjects.begin();
1246 for ( ; obj != myOrderedObjects.end(); ++obj )
1247 if ( ! obj->IsNull() )
1248 (*obj)->ClearCommands();
1251 //================================================================================
1253 * \brief Release mutual handles of objects
1255 //================================================================================
1259 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1260 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1261 id_mesh->second->Free();
1264 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1265 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1266 id_ed->second->Free();
1267 myMeshEditors.clear();
1269 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1270 for ( ; id_obj != myObjects.end(); ++id_obj )
1271 id_obj->second->Free();
1274 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1275 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1276 if ( !id_hyp->second.IsNull() )
1277 id_hyp->second->Free();
1280 myFile2ExportedMesh.clear();
1282 //myKeepAgrCmdsIDs.Print();
1285 //================================================================================
1287 * \brief Add access method to mesh that is an argument
1288 * \param theCmd - command to add access method
1289 * \retval bool - true if added
1291 //================================================================================
1293 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1296 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1297 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1298 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1304 //================================================================================
1306 * \brief Add access method to algo that is an object or an argument
1307 * \param theCmd - command to add access method
1308 * \retval bool - true if added
1310 //================================================================================
1312 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1315 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1316 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1317 if ( !id_hyp->second.IsNull() &&
1318 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1319 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1320 id_hyp->second->AccessorMethod() ))
1326 //================================================================================
1328 * \brief Find hypothesis by ID (entry)
1329 * \param theHypID - The hypothesis ID
1330 * \retval Handle(_pyHypothesis) - The found hypothesis
1332 //================================================================================
1334 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1336 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1337 if ( id_hyp != myHypos.end() &&
1338 !id_hyp->second.IsNull() &&
1339 theHypID == id_hyp->second->GetID() )
1340 return id_hyp->second;
1341 return Handle(_pyHypothesis)();
1344 //================================================================================
1346 * \brief Find algorithm able to create a hypothesis
1347 * \param theGeom - The shape ID the algorithm was created on
1348 * \param theMesh - The mesh ID that created the algorithm
1349 * \param theHypothesis - The hypothesis the algorithm should be able to create
1350 * \retval Handle(_pyHypothesis) - The found algo
1352 //================================================================================
1354 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1355 const Handle(_pyHypothesis)& theHypothesis )
1357 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1358 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1359 if ( !id_hyp->second.IsNull() &&
1360 id_hyp->second->IsAlgo() &&
1361 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1362 id_hyp->second->GetGeom() == theGeom &&
1363 id_hyp->second->GetMesh() == theMesh )
1364 return id_hyp->second;
1365 return Handle(_pyHypothesis)();
1368 //================================================================================
1370 * \brief Find subMesh by ID (entry)
1371 * \param theSubMeshID - The subMesh ID
1372 * \retval Handle(_pySubMesh) - The found subMesh
1374 //================================================================================
1376 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1378 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1379 if ( id_subMesh != myObjects.end() )
1380 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1381 return Handle(_pySubMesh)();
1385 //================================================================================
1387 * \brief Change order of commands in the script
1388 * \param theCmd1 - One command
1389 * \param theCmd2 - Another command
1391 //================================================================================
1393 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1395 list< Handle(_pyCommand) >::iterator pos1, pos2;
1396 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1397 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1398 myCommands.insert( pos1, theCmd2 );
1399 myCommands.insert( pos2, theCmd1 );
1400 myCommands.erase( pos1 );
1401 myCommands.erase( pos2 );
1403 int nb1 = theCmd1->GetOrderNb();
1404 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1405 theCmd2->SetOrderNb( nb1 );
1406 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1407 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1410 //================================================================================
1412 * \brief Set one command after the other
1413 * \param theCmd - Command to move
1414 * \param theAfterCmd - Command ater which to insert the first one
1416 //================================================================================
1418 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1420 setNeighbourCommand( theCmd, theAfterCmd, true );
1423 //================================================================================
1425 * \brief Set one command before the other
1426 * \param theCmd - Command to move
1427 * \param theBeforeCmd - Command before which to insert the first one
1429 //================================================================================
1431 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1433 setNeighbourCommand( theCmd, theBeforeCmd, false );
1436 //================================================================================
1438 * \brief Set one command before or after the other
1439 * \param theCmd - Command to move
1440 * \param theOtherCmd - Command ater or before which to insert the first one
1442 //================================================================================
1444 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1445 Handle(_pyCommand)& theOtherCmd,
1446 const bool theIsAfter )
1448 list< Handle(_pyCommand) >::iterator pos;
1449 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1450 myCommands.erase( pos );
1451 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1452 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1455 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1456 (*pos)->SetOrderNb( i++ );
1459 //================================================================================
1461 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1463 //================================================================================
1465 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1467 // No more needed after adding _pyObject::myArgCommands
1469 // const char filterPrefix[] = "aFilter0x";
1470 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1473 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1475 // const _AString & arg = theCommand->GetArg( i );
1476 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1477 // if ( arg.Search( filterPrefix ) != 1 )
1480 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1481 // if ( !filter.IsNull() )
1483 // filter->AddUser( user );
1484 // if ( !filter->GetNewID().IsEmpty() )
1485 // theCommand->SetArg( i, filter->GetNewID() );
1490 //================================================================================
1492 * \brief Set command be last in list of commands
1493 * \param theCmd - Command to be last
1495 //================================================================================
1497 Handle(_pyCommand)& _pyGen::GetLastCommand()
1499 return myLastCommand;
1502 //================================================================================
1504 * \brief Set method to access to object wrapped with python class
1505 * \param theID - The wrapped object entry
1506 * \param theMethod - The accessor method
1508 //================================================================================
1510 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1512 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1515 //================================================================================
1517 * \brief Generated new ID for object and assign with existing name
1518 * \param theID - ID of existing object
1520 //================================================================================
1522 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1527 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1529 while ( myObjectNames.IsBound( aNewID ) );
1531 if ( myObjectNames.IsBound( theID ) )
1532 myObjectNames.Bind( aNewID, ( myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ) ) );
1534 myObjectNames.Bind( aNewID, ( _pyID( "A" ) + aNewID ) );
1538 //================================================================================
1540 * \brief Stores theObj in myObjects
1542 //================================================================================
1544 bool _pyGen::AddObject( Handle(_pyObject)& theObj )
1546 if ( theObj.IsNull() ) return false;
1548 CheckObjectIsReCreated( theObj );
1552 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh ))) {
1553 add = myMeshes.insert( make_pair( theObj->GetID(),
1554 Handle(_pyMesh)::DownCast( theObj ))).second;
1556 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor ))) {
1557 add = myMeshEditors.insert( make_pair( theObj->GetID(),
1558 Handle(_pyMeshEditor)::DownCast( theObj ))).second;
1561 add = myObjects.insert( make_pair( theObj->GetID(), theObj )).second;
1562 if ( add ) myOrderedObjects.push_back( theObj );
1567 //================================================================================
1569 * \brief Erases an existing object with the same ID. This method should be called
1570 * before storing theObj in _pyGen
1572 //================================================================================
1574 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1576 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1579 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1580 Handle(_pyObject) existing;
1582 existing = FindHyp( theObj->GetID() );
1584 existing = FindObject( theObj->GetID() );
1585 if ( !existing.IsNull() && existing != theObj )
1587 existing->SetRemovedFromStudy( true );
1588 existing->ClearCommands();
1591 if ( myHypos.count( theObj->GetID() ))
1592 myHypos.erase( theObj->GetID() );
1594 else if ( myMeshes.count( theObj->GetID() ))
1596 myMeshes.erase( theObj->GetID() );
1598 else if ( myObjects.count( theObj->GetID() ))
1600 myObjects.erase( theObj->GetID() );
1605 //================================================================================
1607 * \brief Re-register an object with other ID to make it Process() commands of
1608 * other object having this ID
1610 //================================================================================
1612 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1614 if ( theObj.IsNull() ) return;
1616 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1617 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1619 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1620 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1623 myObjects.insert( make_pair( theID, theObj ));
1626 //================================================================================
1628 * \brief Finds a _pyObject by ID
1630 //================================================================================
1632 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1635 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1636 if ( id_obj != myObjects.end() )
1637 return id_obj->second;
1640 _pyGen* me = const_cast< _pyGen* >( this );
1641 map< _pyID, Handle(_pyMesh) >::iterator id_obj = me->myMeshes.find( theObjID );
1642 if ( id_obj != myMeshes.end() )
1643 return id_obj->second;
1646 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1647 // if ( id_obj != myMeshEditors.end() )
1648 // return id_obj->second;
1650 return Handle(_pyObject)();
1653 //================================================================================
1655 * \brief Check if a study entry is under GEOM component
1657 //================================================================================
1659 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1663 return ( myGeomIDIndex <= theObjID.Length() &&
1664 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1665 _pyCommand::IsStudyEntry( theObjID ));
1670 //================================================================================
1672 * \brief Returns true if an object is not present in a study
1674 //================================================================================
1676 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1678 if ( theObjID.IsEmpty() ) return false;
1680 if ( myObjectNames.IsBound( theObjID ))
1681 return false; // SMESH object is in study
1683 // either the SMESH object is not in study or it is a GEOM object
1684 if ( IsGeomObject( theObjID ))
1686 SALOMEDS::SObject_wrap so = SMESH_Gen_i::getStudyServant()->FindObjectID( theObjID.ToCString() );
1687 if ( so->_is_nil() ) return true;
1688 CORBA::Object_var obj = so->GetObject();
1689 return CORBA::is_nil( obj );
1691 return true; // SMESH object not in study
1694 //================================================================================
1696 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1697 * this object is not dumped
1698 * \param [in] theObjID - entry of the object whose creation command was eliminated
1700 //================================================================================
1702 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1704 myRemovedObjIDs.insert( theObjID );
1707 //================================================================================
1709 * \brief Return reader of hypotheses of plugins
1711 //================================================================================
1713 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1715 if (myHypReader.IsNull() )
1716 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1722 //================================================================================
1724 * \brief Mesh created by SMESH_Gen
1726 //================================================================================
1728 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1729 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1731 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1732 myGeomNotInStudy = true;
1734 // convert my creation command --> smeshpy.Mesh(...)
1735 Handle(_pyCommand) creationCmd = GetCreationCmd();
1736 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1737 creationCmd->SetMethod( "Mesh" );
1738 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1741 //================================================================================
1743 * \brief Mesh created by SMESH_MeshEditor
1745 //================================================================================
1747 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1748 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1750 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1752 // this mesh depends on the exported mesh
1753 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1754 if ( !file.IsEmpty() )
1756 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1757 addFatherMesh( exportData.myMesh );
1758 if ( !exportData.myLastComputeCmd.IsNull() )
1760 // restore cleared Compute() by which the exported mesh was generated
1761 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1762 // protect that Compute() cmd from clearing
1763 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1764 exportData.myMesh->myLastComputeCmd.Nullify();
1768 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1770 // this mesh depends on concatenated meshes
1771 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1772 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1773 list< _pyID >::iterator meshID = idList.begin();
1774 for ( ; meshID != idList.end(); ++meshID )
1775 addFatherMesh( *meshID );
1777 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1779 // this mesh depends on a copied IdSource
1780 const _pyID& objID = theCreationCmd->GetArg( 1 );
1781 addFatherMesh( objID );
1783 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1784 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1785 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1787 // this mesh depends on a source mesh
1788 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1789 const _pyID& meshID = theCreationCmd->GetObject();
1790 addFatherMesh( meshID );
1793 // convert my creation command
1794 Handle(_pyCommand) creationCmd = GetCreationCmd();
1795 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1796 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1799 //================================================================================
1801 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1802 * \param theCommand - Engine method called for this mesh
1804 //================================================================================
1806 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1808 // some methods of SMESH_Mesh interface needs special conversion
1809 // to methods of Mesh python class
1811 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1812 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1813 // 2. AddHypothesis(geom, hyp)
1814 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1815 // 3. CreateGroupFromGEOM(type, name, grp)
1816 // --> in Mesh.Group(grp, name="")
1817 // 4. ExportToMED(f, auto_groups, version)
1818 // --> in Mesh.ExportMED( f, auto_groups, version )
1821 const TCollection_AsciiString& method = theCommand->GetMethod();
1822 // ----------------------------------------------------------------------
1823 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1825 if ( !theGen->IsToKeepAllCommands() ) // !historical
1827 list< Handle(_pyHypothesis) >::iterator hyp;
1828 if ( !myLastComputeCmd.IsNull() )
1830 // check if the previously computed mesh has been edited,
1831 // if so then we do not clear the previous Compute()
1832 bool toClear = true;
1833 if ( myLastComputeCmd->GetMethod() == "Compute" )
1835 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1836 for ( ; e != myEditors.end() && toClear; ++e )
1838 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1839 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1840 if ( cmd != cmds.rend() &&
1841 (*cmd)->GetOrderNb() > myLastComputeCmd->GetOrderNb() )
1847 // clear hyp commands called before myLastComputeCmd
1848 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1849 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1851 myLastComputeCmd->Clear();
1854 myLastComputeCmd = theCommand;
1856 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1857 (*hyp)->MeshComputed( myLastComputeCmd );
1861 // ----------------------------------------------------------------------
1862 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1864 if ( !theGen->IsToKeepAllCommands() ) // !historical
1867 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1868 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1869 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1871 if ( !myLastComputeCmd.IsNull() )
1873 list< Handle(_pyHypothesis) >::iterator hyp;
1874 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1875 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1877 myLastComputeCmd->Clear();
1880 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1881 for ( ; e != myEditors.end(); ++e )
1883 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1884 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1885 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1886 if ( !(*cmd)->IsEmpty() )
1888 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1892 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1895 // ----------------------------------------------------------------------
1896 else if ( method == "GetSubMesh" ) { // collect sub-meshes of the mesh
1897 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1898 if ( !subMesh.IsNull() ) {
1899 subMesh->SetCreator( this );
1900 mySubmeshes.push_back( subMesh );
1903 // ----------------------------------------------------------------------
1904 else if ( method == "GetSubMeshes" ) { // clear as the command does nothing (0023156)
1905 theCommand->Clear();
1907 // ----------------------------------------------------------------------
1908 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1909 myAddHypCmds.push_back( theCommand );
1911 const _pyID& hypID = theCommand->GetArg( 2 );
1912 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1913 if ( !hyp.IsNull() ) {
1914 myHypos.push_back( hyp );
1915 if ( hyp->GetMesh().IsEmpty() )
1916 hyp->SetMesh( this->GetID() );
1919 // ----------------------------------------------------------------------
1920 else if ( method == "CreateGroup" ||
1921 method == "CreateGroupFromGEOM" ||
1922 method == "CreateGroupFromFilter" ||
1923 method == "CreateDimGroup" )
1925 Handle(_pyGroup) group = new _pyGroup( theCommand );
1926 myGroups.push_back( group );
1927 theGen->AddObject( group );
1929 // ----------------------------------------------------------------------
1930 // update list of groups
1931 else if ( method == "GetGroups" )
1933 bool allGroupsRemoved = true;
1934 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1935 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1936 list< _pyID >::iterator grID = idList.begin();
1937 const size_t nbGroupsBefore = myGroups.size();
1938 Handle(_pyObject) obj;
1939 for ( ; grID != idList.end(); ++grID )
1941 obj = theGen->FindObject( *grID );
1944 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1945 theGen->AddObject( group );
1946 myGroups.push_back( group );
1949 if ( !obj->CanClear() )
1950 allGroupsRemoved = false;
1952 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1953 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1955 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1957 // check if the preceding command is Compute();
1958 // if GetGroups() is just after Compute(), this can mean that the groups
1959 // were created by some algorithm and hence Compute() should not be discarded
1960 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1961 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1962 while ( (*cmd)->GetMethod() == "GetGroups" )
1964 if ( myLastComputeCmd == (*cmd))
1965 // protect last Compute() from clearing by the next Compute()
1966 myLastComputeCmd.Nullify();
1969 // ----------------------------------------------------------------------
1970 // notify a group about full removal
1971 else if ( method == "RemoveGroupWithContents" ||
1972 method == "RemoveGroup")
1974 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1975 const _pyID groupID = theCommand->GetArg( 1 );
1976 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1977 if ( !grp.IsNull() )
1979 if ( method == "RemoveGroupWithContents" )
1980 grp->RemovedWithContents();
1981 // to clear RemoveGroup() if the group creation is cleared
1982 grp->AddProcessedCmd( theCommand );
1986 // ----------------------------------------------------------------------
1987 else if ( theCommand->MethodStartsFrom( "Export" ))
1989 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1990 method == "ExportToMEDX" || // ExportToMEDX() --> ExportMED()
1991 method == "ExportMED" )
1993 theCommand->SetMethod( "ExportMED" );
1994 // filter out deprecated version parameter
1995 vector< _AString > args;
1996 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
1997 if ( !_FilterArg( theCommand->GetArg( i ) ) )
1998 args.push_back( theCommand->GetArg( i ) );
2000 theCommand->RemoveArgs();
2001 for ( uint i = 0; i < args.size(); i++ )
2002 theCommand->SetArg( i+1, args[i] );
2003 if ( theCommand->GetNbArgs() == 4 )
2005 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
2006 _AString autoDimension = theCommand->GetArg( 4 );
2007 theCommand->SetArg( 4, "None" );
2008 theCommand->SetArg( 5, autoDimension );
2011 else if ( method == "ExportCGNS" )
2012 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
2013 _pyID partID = theCommand->GetArg( 1 );
2014 int nbArgs = theCommand->GetNbArgs();
2015 for ( int i = 2; i <= nbArgs; ++i )
2016 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2017 theCommand->SetArg( nbArgs, partID );
2019 else if ( method == "ExportGMF" )
2020 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
2021 _pyID partID = theCommand->GetArg( 1 );
2022 _AString file = theCommand->GetArg( 2 );
2023 theCommand->RemoveArgs();
2024 theCommand->SetArg( 1, file );
2025 theCommand->SetArg( 2, partID );
2027 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
2028 { // ExportPartTo*(part, ...) -> Export*(..., part)
2030 // remove "PartTo" from the method
2031 TCollection_AsciiString newMethod = method;
2032 newMethod.Remove( /*where=*/7, /*howmany=*/6 );
2033 theCommand->SetMethod( newMethod );
2034 // filter out deprecated version parameter
2035 vector< _AString > args;
2036 for ( int i = 1; i <= theCommand->GetNbArgs(); i++ ) {
2037 if ( !_FilterArg( theCommand->GetArg( i ) ) )
2038 args.push_back( theCommand->GetArg( i ) );
2040 theCommand->RemoveArgs();
2041 for ( uint i = 0; i < args.size(); i++ )
2042 theCommand->SetArg( i+1, args[i] );
2043 // make the 1st arg be the last one (or last but three for ExportMED())
2044 _pyID partID = theCommand->GetArg( 1 );
2045 int nbArgs = theCommand->GetNbArgs() - 3 * (newMethod == "ExportMED");
2046 for ( int i = 2; i <= nbArgs; ++i )
2047 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2048 theCommand->SetArg( nbArgs, partID );
2050 // remember file name
2051 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
2052 ExportedMeshData( this, myLastComputeCmd ));
2054 // ----------------------------------------------------------------------
2055 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
2057 _pyID hypID = theCommand->GetArg( 2 );
2058 _pyID geomID = theCommand->GetArg( 1 );
2059 bool isLocal = ( geomID != GetGeom() );
2061 // check if this mesh still has corresponding addition command
2062 Handle(_pyCommand) addCmd;
2063 list< Handle(_pyCommand) >::iterator cmd;
2064 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
2065 for ( int i = 0; i < 2; ++i )
2067 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
2068 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
2070 bool sameHyp = true;
2071 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
2072 sameHyp = false; // other hyp
2073 if ( (*cmd)->GetNbArgs() == 2 &&
2074 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
2075 sameHyp = false; // other geom
2076 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
2077 sameHyp = false; // other geom
2081 cmd = addHypCmds.erase( cmd );
2082 if ( !theGen->IsToKeepAllCommands() /*&& CanClear()*/ ) {
2084 theCommand->Clear();
2088 // mesh.AddHypothesis(geom, hyp) --> mesh.AddHypothesis(hyp, geom=0)
2089 addCmd->RemoveArgs();
2090 addCmd->SetArg( 1, hypID );
2092 addCmd->SetArg( 2, geomID );
2101 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2102 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
2103 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2104 _pyID geom = theCommand->GetArg( 1 );
2105 theCommand->RemoveArgs();
2106 theCommand->SetArg( 1, hypID );
2107 if ( geom != GetGeom() )
2108 theCommand->SetArg( 2, geom );
2110 // remove hyp from myHypos
2111 myHypos.remove( hyp );
2113 // check for SubMesh order commands
2114 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2116 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2117 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2118 // commands are moved at the end of the script
2119 TCollection_AsciiString subIDs =
2120 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2121 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2122 list< _pyID >::iterator subID = idList.begin();
2123 for ( ; subID != idList.end(); ++subID )
2125 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2126 if ( !subMesh.IsNull() )
2127 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2130 // add accessor method if necessary
2133 if ( NeedMeshAccess( theCommand ))
2134 // apply theCommand to the mesh wrapped by smeshpy mesh
2135 AddMeshAccess( theCommand );
2139 //================================================================================
2141 * \brief Return True if addition of accesor method is needed
2143 //================================================================================
2145 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2147 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2148 // so no conversion is needed for them at all:
2149 static TStringSet sameMethods;
2150 if ( sameMethods.empty() ) {
2151 const char * names[] =
2152 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2153 "GetGroups","UnionGroups","IntersectGroups","CutGroups","CreateDimGroup","GetLog","GetId",
2154 "ClearLog","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2155 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2156 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2157 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2158 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2159 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2160 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2161 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2162 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2163 "GetElemFaceNodes", "GetFaceNormal", "FindElementByNodes",
2164 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2165 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2166 ,"" }; // <- mark of end
2167 sameMethods.Insert( names );
2170 return !sameMethods.Contains( theCommand->GetMethod() );
2173 //================================================================================
2175 * \brief Convert creation and addition of all algos and hypos
2177 //================================================================================
2179 void _pyMesh::Flush()
2182 // get the meshes this mesh depends on via hypotheses
2183 list< Handle(_pyMesh) > fatherMeshes;
2184 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2185 for ( ; hyp != myHypos.end(); ++hyp )
2186 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2187 myGeomNotInStudy = true;
2189 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2190 for ( ; m != fatherMeshes.end(); ++m )
2191 addFatherMesh( *m );
2192 // if ( removedGeom )
2193 // SetRemovedFromStudy(); // as referred geometry not in study
2195 if ( myGeomNotInStudy )
2198 list < Handle(_pyCommand) >::iterator cmd;
2200 // try to convert algo addition like this:
2201 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2202 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2204 Handle(_pyCommand) addCmd = *cmd;
2206 _pyID algoID = addCmd->GetArg( 2 );
2207 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2208 if ( algo.IsNull() || !algo->IsAlgo() )
2211 // check and create new algorithm instance if it is already wrapped
2212 if ( algo->IsWrapped() ) {
2213 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2214 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2215 TCollection_AsciiString( " = " ) + theGen->GetID() +
2216 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2217 TCollection_AsciiString( "\" )" );
2219 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2220 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2221 if ( !newAlgo.IsNull() ) {
2222 newAlgo->Assign( algo, this->GetID() );
2223 newAlgo->SetCreationCmd( newCmd );
2225 // set algorithm creation
2226 theGen->SetCommandBefore( newCmd, addCmd );
2227 myHypos.push_back( newAlgo );
2228 if ( !myLastComputeCmd.IsNull() &&
2229 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2230 newAlgo->MeshComputed( myLastComputeCmd );
2235 _pyID geom = addCmd->GetArg( 1 );
2236 bool isLocalAlgo = ( geom != GetGeom() );
2239 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2241 // wrapped algo is created after mesh creation
2242 GetCreationCmd()->AddDependantCmd( addCmd );
2244 if ( isLocalAlgo ) {
2245 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2246 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2247 TCollection_AsciiString( "geom=" ) + geom );
2248 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2249 list < Handle(_pySubMesh) >::iterator smIt;
2250 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2251 Handle(_pySubMesh) subMesh = *smIt;
2252 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2253 if ( geom == subCmd->GetArg( 1 )) {
2254 subCmd->SetObject( algo->GetID() );
2255 subCmd->RemoveArgs();
2256 subMesh->SetCreator( algo );
2261 else // KO - ALGO was already created
2263 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2264 addCmd->RemoveArgs();
2265 addCmd->SetArg( 1, algoID );
2267 addCmd->SetArg( 2, geom );
2268 myNotConvertedAddHypCmds.push_back( addCmd );
2272 // try to convert hypo addition like this:
2273 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2274 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2276 Handle(_pyCommand) addCmd = *cmd;
2277 _pyID hypID = addCmd->GetArg( 2 );
2278 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2279 if ( hyp.IsNull() || hyp->IsAlgo() )
2281 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2283 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2284 _pyID geom = addCmd->GetArg( 1 );
2285 addCmd->RemoveArgs();
2286 addCmd->SetArg( 1, hypID );
2287 if ( geom != GetGeom() )
2288 addCmd->SetArg( 2, geom );
2289 myNotConvertedAddHypCmds.push_back( addCmd );
2293 myAddHypCmds.clear();
2294 mySubmeshes.clear();
2297 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2298 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2302 //================================================================================
2304 * \brief Sets myIsPublished of me and of all objects depending on me.
2306 //================================================================================
2308 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2310 _pyObject::SetRemovedFromStudy(isRemoved);
2312 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2313 for ( ; sm != mySubmeshes.end(); ++sm )
2314 (*sm)->SetRemovedFromStudy(isRemoved);
2316 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2317 for ( ; gr != myGroups.end(); ++gr )
2318 (*gr)->SetRemovedFromStudy(isRemoved);
2320 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2321 for ( ; m != myChildMeshes.end(); ++m )
2322 (*m)->SetRemovedFromStudy(isRemoved);
2324 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2325 for ( ; e != myEditors.end(); ++e )
2326 (*e)->SetRemovedFromStudy(isRemoved);
2329 //================================================================================
2331 * \brief Return true if none of myChildMeshes is in study
2333 //================================================================================
2335 bool _pyMesh::CanClear()
2340 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2341 for ( ; m != myChildMeshes.end(); ++m )
2342 if ( !(*m)->CanClear() )
2348 //================================================================================
2350 * \brief Clear my commands and commands of mesh editor
2352 //================================================================================
2354 void _pyMesh::ClearCommands()
2360 // mark all sub-objects as not removed, except child meshes
2361 list< Handle(_pyMesh) > children;
2362 children.swap( myChildMeshes );
2363 SetRemovedFromStudy( false );
2364 children.swap( myChildMeshes );
2368 _pyObject::ClearCommands();
2370 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2371 for ( ; sm != mySubmeshes.end(); ++sm )
2372 (*sm)->ClearCommands();
2374 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2375 for ( ; gr != myGroups.end(); ++gr )
2376 (*gr)->ClearCommands();
2378 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2379 for ( ; e != myEditors.end(); ++e )
2380 (*e)->ClearCommands();
2383 //================================================================================
2385 * \brief Add a father mesh by ID
2387 //================================================================================
2389 void _pyMesh::addFatherMesh( const _pyID& meshID )
2391 if ( !meshID.IsEmpty() && meshID != GetID() )
2392 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2395 //================================================================================
2397 * \brief Add a father mesh
2399 //================================================================================
2401 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2403 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2405 //myFatherMeshes.push_back( mesh );
2406 mesh->myChildMeshes.push_back( this );
2408 // protect last Compute() from clearing by the next Compute()
2409 mesh->myLastComputeCmd.Nullify();
2413 //================================================================================
2415 * \brief MeshEditor convert its commands to ones of mesh
2417 //================================================================================
2419 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2420 _pyObject( theCreationCmd )
2422 myMesh = theCreationCmd->GetObject();
2423 myCreationCmdStr = theCreationCmd->GetString();
2424 theCreationCmd->Clear();
2426 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2427 if ( !mesh.IsNull() )
2428 mesh->AddEditor( this );
2431 //================================================================================
2433 * \brief convert its commands to ones of mesh
2435 //================================================================================
2437 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2439 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2440 // commands calling these methods are converted to calls of Mesh methods without
2441 // additional modifs, only object is changed from MeshEditor to Mesh.
2442 static TStringSet sameMethods;
2443 if ( sameMethods.empty() ) {
2444 const char * names[] = {
2445 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2446 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2447 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2448 "MoveNode", "MoveClosestNodeToPoint",
2449 "InverseDiag","DeleteDiag","Reorient","ReorientObject","Reorient2DBy3D",
2450 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2451 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2452 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2453 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2454 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2455 "ExtrusionByNormal", "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2456 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2457 "ExtrusionSweepObjects","RotationSweepObjects","ExtrusionAlongPathObjects",
2458 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2459 "FindCoincidentNodes","MergeNodes","FindEqualElements","FillHole",
2460 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2461 "FindCoincidentFreeBorders", "SewCoincidentFreeBorders",
2462 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2463 "GetLastCreatedElems",
2464 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2465 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2466 "MakeBoundaryElements", "SplitVolumesIntoTetra","SplitHexahedraIntoPrisms",
2467 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2468 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2469 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2470 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2471 ,"" }; // <- mark of the end
2472 sameMethods.Insert( names );
2475 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2476 TStringMap diffMethods;
2477 if ( diffMethods.empty() ) {
2478 const char * orig2newName[] = {
2479 // original name --------------> new name
2480 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2481 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2482 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2483 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2484 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2485 ""};// <- mark of the end
2486 diffMethods.Insert( orig2newName );
2489 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2490 // only by last two arguments
2491 static TStringSet diffLastTwoArgsMethods;
2492 if (diffLastTwoArgsMethods.empty() ) {
2493 const char * names[] = {
2494 "MirrorMakeGroups","MirrorObjectMakeGroups",
2495 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2496 "RotateMakeGroups","RotateObjectMakeGroups",
2497 ""};// <- mark of the end
2498 diffLastTwoArgsMethods.Insert( names );
2501 // only a method name is to change?
2502 const TCollection_AsciiString & method = theCommand->GetMethod();
2503 bool isPyMeshMethod = sameMethods.Contains( method );
2504 if ( !isPyMeshMethod )
2506 TCollection_AsciiString newMethod = diffMethods.Value( method );
2507 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2508 theCommand->SetMethod( newMethod );
2510 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2511 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2513 isPyMeshMethod = true;
2514 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2515 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2518 if ( !isPyMeshMethod )
2520 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2521 // functions with the flag "theMakeGroups = True" like:
2522 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2523 int pos = method.Search("MakeGroups");
2526 isPyMeshMethod = true;
2527 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2528 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2530 // 1. Remove "MakeGroups" from the Command
2531 TCollection_AsciiString aMethod = theCommand->GetMethod();
2532 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2535 pos = pos-2; //Remove "0D" from the Command too
2536 aMethod.Trunc(pos-1);
2537 theCommand->SetMethod(aMethod);
2539 // 2. And add last "True" argument(s)
2540 while(nbArgsToAdd--)
2541 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2542 if( is0DmethId || is0DmethObj )
2543 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2547 // ExtrusionSweep0D() -> ExtrusionSweep()
2548 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2549 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2550 method == "ExtrusionSweepObject0D" ))
2552 isPyMeshMethod = true;
2553 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2554 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2555 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2558 // DoubleNode...New(...) -> DoubleNode...(...,True)
2559 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2560 method == "DoubleNodeElemGroupsNew" ||
2561 method == "DoubleNodeGroupNew" ||
2562 method == "DoubleNodeGroupsNew" ||
2563 method == "DoubleNodeElemGroup2New" ||
2564 method == "DoubleNodeElemGroups2New"))
2566 isPyMeshMethod = true;
2567 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2568 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2569 if ( excessLen == 3 )
2571 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2573 else if ( theCommand->GetArg(4) == "0" ||
2574 theCommand->GetArg(5) == "0" )
2576 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2577 // Group = DoubleNodeGroup2New(,,,False, True)
2578 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2579 theCommand->SetResultValue( groupID );
2582 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2583 // FindElementsByPoint(x, y, z, elementType, meshPart)
2584 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2586 isPyMeshMethod = true;
2587 theCommand->SetMethod( "FindElementsByPoint" );
2588 // make the 1st arg be the last one
2589 _pyID partID = theCommand->GetArg( 1 );
2590 int nbArgs = theCommand->GetNbArgs();
2591 for ( int i = 2; i <= nbArgs; ++i )
2592 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2593 theCommand->SetArg( nbArgs, partID );
2595 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2596 if ( !isPyMeshMethod && method == "Reorient2D" )
2598 isPyMeshMethod = true;
2599 _AString mesh = theCommand->GetArg( 1 );
2600 _AString dir = theCommand->GetArg( 2 );
2601 _AString face = theCommand->GetArg( 3 );
2602 _AString point = theCommand->GetArg( 4 );
2603 theCommand->RemoveArgs();
2604 theCommand->SetArg( 1, mesh );
2605 theCommand->SetArg( 2, dir );
2606 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2607 theCommand->SetArg( 3, point );
2609 theCommand->SetArg( 3, face );
2612 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2614 isPyMeshMethod = true;
2615 int crit_arg = theCommand->GetNbArgs();
2616 const _AString& crit = theCommand->GetArg(crit_arg);
2617 if (crit.Search("MaxElementLength2D") != -1)
2618 theCommand->SetArg(crit_arg, "");
2621 if ( isPyMeshMethod )
2623 theCommand->SetObject( myMesh );
2627 // editor creation command is needed only if any editor function is called
2628 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2629 if ( !myCreationCmdStr.IsEmpty() ) {
2630 GetCreationCmd()->GetString() = myCreationCmdStr;
2631 myCreationCmdStr.Clear();
2636 //================================================================================
2638 * \brief Return true if my mesh can be removed
2640 //================================================================================
2642 bool _pyMeshEditor::CanClear()
2644 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2645 return mesh.IsNull() ? true : mesh->CanClear();
2648 //================================================================================
2650 * \brief _pyHypothesis constructor
2651 * \param theCreationCmd -
2653 //================================================================================
2655 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2656 _pyObject( theCreationCmd ), myCurCrMethod(0)
2658 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2661 //================================================================================
2663 * \brief Creates algorithm or hypothesis
2664 * \param theCreationCmd - The engine command creating a hypothesis
2665 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2667 //================================================================================
2669 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2671 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2672 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2674 Handle(_pyHypothesis) hyp, algo;
2677 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2678 if ( hypTypeQuoted.IsEmpty() )
2681 TCollection_AsciiString hypType =
2682 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2684 algo = new _pyAlgorithm( theCreationCmd );
2685 hyp = new _pyHypothesis( theCreationCmd );
2687 if ( hypType == "NumberOfSegments" ) {
2688 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2689 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2690 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2691 hyp->AddArgMethod( "SetNumberOfSegments" );
2692 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2693 hyp->AddArgMethod( "SetScaleFactor" );
2694 hyp->AddArgMethod( "SetReversedEdges" );
2695 // same for ""CompositeSegment_1D:
2696 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2697 hyp->AddArgMethod( "SetNumberOfSegments" );
2698 hyp->AddArgMethod( "SetScaleFactor" );
2699 hyp->AddArgMethod( "SetReversedEdges" );
2701 else if ( hypType == "SegmentLengthAroundVertex" ) {
2702 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2703 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2704 hyp->AddArgMethod( "SetLength" );
2705 // same for ""CompositeSegment_1D:
2706 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2707 hyp->AddArgMethod( "SetLength" );
2709 else if ( hypType == "LayerDistribution2D" ) {
2710 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2711 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2713 else if ( hypType == "LayerDistribution" ) {
2714 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2715 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2717 else if ( hypType == "CartesianParameters3D" ) {
2718 hyp = new _pyComplexParamHypo( theCreationCmd );
2719 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2720 for ( int iArg = 0; iArg < 4; ++iArg )
2721 hyp->setCreationArg( iArg+1, "[]");
2722 hyp->AddAccumulativeMethod( "SetGrid" );
2723 hyp->AddAccumulativeMethod( "SetGridSpacing" );
2727 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2730 return algo->IsValid() ? algo : hyp;
2733 //================================================================================
2735 * \brief Returns true if addition of this hypothesis to a given mesh can be
2736 * wrapped into hypothesis creation
2738 //================================================================================
2740 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2742 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2744 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2745 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2751 //================================================================================
2753 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2754 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2755 * \param theAlgo - The algo that can create this hypo
2756 * \retval bool - false if the command can't be converted
2758 //================================================================================
2760 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2761 const _pyID& theMesh)
2763 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2765 if ( !IsWrappable( theMesh ))
2768 myGeom = theCmd->GetArg( 1 );
2770 Handle(_pyHypothesis) algo;
2772 // find algo created on myGeom in theMesh
2773 algo = theGen->FindAlgo( myGeom, theMesh, this );
2774 if ( algo.IsNull() )
2776 // attach hypothesis creation command to be after algo creation command
2777 // because it can be new created instance of algorithm
2778 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2782 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2783 theCmd->SetResultValue( GetID() );
2784 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2785 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2786 // set args (geom will be set by _pyMesh calling this method)
2787 theCmd->RemoveArgs();
2788 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2789 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2790 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2792 theCmd->SetArg( i+1, "[]");
2794 // set a new creation command
2795 GetCreationCmd()->Clear();
2796 // replace creation command by wrapped instance
2797 // please note, that hypothesis attaches to algo creation command (see upper)
2798 SetCreationCmd( theCmd );
2801 // clear commands setting arg values
2802 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2803 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2806 // set unknown arg commands after hypo creation
2807 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2808 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2809 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2810 afterCmd->AddDependantCmd( *cmd );
2816 //================================================================================
2818 * \brief Remember hypothesis parameter values
2819 * \param theCommand - The called hypothesis method
2821 //================================================================================
2823 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2825 ASSERT( !myIsAlgo );
2826 if ( !theGen->IsToKeepAllCommands() )
2827 rememberCmdOfParameter( theCommand );
2829 bool usedCommand = false;
2830 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2831 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2833 CreationMethod& crMethod = type2meth->second;
2834 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2835 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2837 myArgCommands.push_back( theCommand );
2839 while ( crMethod.myArgs.size() < i+1 )
2840 crMethod.myArgs.push_back( "None" );
2841 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2846 myUnusedCommands.push_back( theCommand );
2849 //================================================================================
2851 * \brief Finish conversion
2853 //================================================================================
2855 void _pyHypothesis::Flush()
2859 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2860 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2861 // Add access to a wrapped mesh
2862 theGen->AddMeshAccessorMethod( *cmd );
2863 // Add access to a wrapped algorithm
2864 theGen->AddAlgoAccessorMethod( *cmd );
2866 cmd = myUnusedCommands.begin();
2867 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2868 // Add access to a wrapped mesh
2869 theGen->AddMeshAccessorMethod( *cmd );
2870 // Add access to a wrapped algorithm
2871 theGen->AddAlgoAccessorMethod( *cmd );
2874 // forget previous hypothesis modifications
2875 myArgCommands.clear();
2876 myUnusedCommands.clear();
2879 //================================================================================
2881 * \brief clear creation, arg and unknown commands
2883 //================================================================================
2885 void _pyHypothesis::ClearAllCommands()
2887 GetCreationCmd()->Clear();
2888 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2889 for ( ; cmd != myArgCommands.end(); ++cmd )
2891 cmd = myUnusedCommands.begin();
2892 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2897 //================================================================================
2899 * \brief Assign fields of theOther to me except myIsWrapped
2901 //================================================================================
2903 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2904 const _pyID& theMesh )
2906 // myCreationCmd = theOther->myCreationCmd;
2907 myIsAlgo = theOther->myIsAlgo;
2908 myIsWrapped = false;
2909 myGeom = theOther->myGeom;
2911 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2912 myAccumulativeMethods = theOther->myAccumulativeMethods;
2913 //myUnusedCommands = theOther->myUnusedCommands;
2914 // init myCurCrMethod
2915 GetCreationMethod( theOther->GetAlgoType() );
2918 //================================================================================
2920 * \brief Analyze my erasability depending on myReferredObjs
2922 //================================================================================
2924 bool _pyHypothesis::CanClear()
2928 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2929 for ( ; obj != myReferredObjs.end(); ++obj )
2930 if ( (*obj)->CanClear() )
2937 //================================================================================
2939 * \brief Clear my commands depending on usage by meshes
2941 //================================================================================
2943 void _pyHypothesis::ClearCommands()
2945 // if ( !theGen->IsToKeepAllCommands() )
2947 // bool isUsed = false;
2948 // int lastComputeOrder = 0;
2949 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2950 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2951 // if ( ! (*cmd)->IsEmpty() )
2954 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2955 // lastComputeOrder = (*cmd)->GetOrderNb();
2959 // SetRemovedFromStudy( true );
2963 // // clear my commands invoked after lastComputeOrder
2964 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2965 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2967 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2968 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2969 // // cmds.back()->Clear();
2973 _pyObject::ClearCommands();
2976 //================================================================================
2978 * \brief Find arguments that are objects like mesh, group, geometry
2979 * \param meshes - referred meshes (directly or indirrectly)
2980 * \retval bool - false if a referred geometry is not in the study
2982 //================================================================================
2984 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2986 if ( IsAlgo() ) return true;
2988 bool geomPublished = true;
2989 vector< _AString > args;
2990 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2991 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2993 CreationMethod& crMethod = type2meth->second;
2994 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2996 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2997 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2998 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2999 args.push_back( (*cmd)->GetArg( nb ));
3002 for ( size_t i = 0; i < args.size(); ++i )
3004 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
3005 if ( idList.empty() && !args[ i ].IsEmpty() )
3006 idList.push_back( args[ i ]);
3007 list< _pyID >::iterator id = idList.begin();
3008 for ( ; id != idList.end(); ++id )
3010 Handle(_pyObject) obj = theGen->FindObject( *id );
3011 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
3014 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
3015 geomPublished = false;
3019 myReferredObjs.push_back( obj );
3020 Handle(_pyMesh) mesh = ObjectToMesh( obj );
3021 if ( !mesh.IsNull() )
3022 meshes.push_back( mesh );
3023 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
3024 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
3025 obj->SetRemovedFromStudy( false );
3029 return geomPublished;
3032 //================================================================================
3034 * \brief Remember theCommand setting a parameter
3036 //================================================================================
3038 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
3040 // parameters are discriminated by method name
3041 _AString method = theCommand->GetMethod();
3042 if ( myAccumulativeMethods.count( method ))
3043 return; // this method adds values and not override the previus value
3045 // discriminate commands setting different parameters via one method
3046 // by passing parameter names like e.g. SetOption("size", "0.2")
3047 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
3048 theCommand->GetNbArgs() > 1 )
3050 // mangle method by appending a 1st textual arg
3051 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
3053 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
3054 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
3055 if ( !isalpha( arg.Value(2))) continue;
3060 // parameters are discriminated by method name
3061 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
3062 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
3064 cmds.back()->Clear(); // previous parameter value has not been used
3065 cmds.back() = theCommand;
3069 cmds.push_back( theCommand );
3073 //================================================================================
3075 * \brief Return true if a setting parameter command ha been used to compute mesh
3077 //================================================================================
3079 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
3080 _pyCommand::TAddr avoidComputeAddr ) const
3082 bool isUsed = false;
3083 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
3084 myComputeAddr2Cmds.begin();
3085 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
3087 if ( addr2cmds->first == avoidComputeAddr ) continue;
3088 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
3089 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
3094 //================================================================================
3096 * \brief Save commands setting parameters as they are used for a mesh computation
3098 //================================================================================
3100 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
3102 myComputeCmds.push_back( theComputeCmd );
3103 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3105 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
3106 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
3107 savedCmds.push_back( m2c->second.back() );
3110 //================================================================================
3112 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3114 //================================================================================
3116 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3118 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3120 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3121 for ( ; cmd != savedCmds.end(); ++cmd )
3123 // check if a cmd has been used to compute another mesh
3124 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3126 // check if a cmd is a sole command setting its parameter;
3127 // don't use method name for search as it can change
3128 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3129 m2cmds = myMeth2Commands.begin();
3130 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3132 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3133 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3134 if ( cmdIt != cmds.end() )
3136 if ( cmds.back() != *cmd )
3138 cmds.erase( cmdIt );
3145 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3148 //================================================================================
3150 * \brief Sets an argNb-th argument of current creation command
3151 * \param argNb - argument index countered from 1
3153 //================================================================================
3155 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3157 if ( myCurCrMethod )
3159 while ( (int) myCurCrMethod->myArgs.size() < argNb )
3160 myCurCrMethod->myArgs.push_back( "None" );
3161 if ( arg.IsEmpty() )
3162 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3164 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3169 //================================================================================
3171 * \brief Remember hypothesis parameter values
3172 * \param theCommand - The called hypothesis method
3174 //================================================================================
3176 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3178 if ( GetAlgoType() == "Cartesian_3D" )
3180 // CartesianParameters3D hyp
3182 if ( theCommand->GetMethod() == "SetSizeThreshold" ||
3183 theCommand->GetMethod() == "SetToAddEdges" )
3185 int iEdges = ( theCommand->GetMethod().Value( 4 ) == 'T' );
3186 setCreationArg( 4+iEdges, theCommand->GetArg( 1 ));
3187 myArgCommands.push_back( theCommand );
3190 if ( theCommand->GetMethod() == "SetGrid" ||
3191 theCommand->GetMethod() == "SetGridSpacing" )
3193 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3194 int iArg = axis.Value(1) - '0';
3195 if ( theCommand->GetMethod() == "SetGrid" )
3197 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3201 myCurCrMethod->myArgs[ iArg ] = "[ ";
3202 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3203 myCurCrMethod->myArgs[ iArg ] += ", ";
3204 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3205 myCurCrMethod->myArgs[ iArg ] += "]";
3207 myArgCommands.push_back( theCommand );
3208 //rememberCmdOfParameter( theCommand ); -- these commands are marked as
3209 // accumulative, else, if the creation
3210 // is not converted, commands for axes 1 and 2 are lost
3215 if( theCommand->GetMethod() == "SetLength" )
3217 // NOW it is OBSOLETE
3218 // ex: hyp.SetLength(start, 1)
3219 // hyp.SetLength(end, 0)
3220 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3221 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3222 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3223 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3225 CreationMethod& crMethod = type2meth->second;
3226 while ( (int) crMethod.myArgs.size() < i+1 )
3227 crMethod.myArgs.push_back( "[]" );
3228 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3230 myArgCommands.push_back( theCommand );
3234 _pyHypothesis::Process( theCommand );
3237 //================================================================================
3239 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3241 //================================================================================
3243 void _pyComplexParamHypo::Flush()
3245 list < Handle(_pyCommand) >::iterator cmd;
3248 for ( cmd = myUnusedCommands.begin(); cmd != myUnusedCommands.end(); ++cmd )
3249 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3253 // if ( GetAlgoType() == "Cartesian_3D" )
3255 // _pyID algo = myCreationCmd->GetObject();
3256 // for ( cmd = myProcessedCmds.begin(); cmd != myProcessedCmds.end(); ++cmd )
3258 // if ( IsWrapped() )
3260 // StructToList( *cmd, /*checkMethod=*/false );
3261 // const _AString & method = (*cmd)->GetMethod();
3262 // if ( method == "SetFixedPoint" )
3263 // (*cmd)->SetObject( algo );
3269 //================================================================================
3271 * \brief Convert methods of 1D hypotheses to my own methods
3272 * \param theCommand - The called hypothesis method
3274 //================================================================================
3276 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3278 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3281 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3282 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3283 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3285 // TCollection_AsciiString cmd =
3286 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3287 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3288 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3291 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3293 // // 1D hypo is already set, so distribution changes and the old
3294 // // 1D hypo is thrown away
3295 // my1dHyp->ClearAllCommands();
3298 // //my1dHyp->SetRemovedFromStudy( false );
3300 // if ( !myArgCommands.empty() )
3301 // myArgCommands.back()->Clear();
3302 myCurCrMethod->myArgs.push_back( hyp1dID );
3303 myArgCommands.push_back( theCommand );
3306 //================================================================================
3309 * \param theAdditionCmd - command to be converted
3310 * \param theMesh - mesh instance
3311 * \retval bool - status
3313 //================================================================================
3315 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3316 const _pyID& theMesh)
3318 myIsWrapped = false;
3320 if ( my1dHyp.IsNull() )
3323 // set "SetLayerDistribution()" after addition cmd
3324 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3326 _pyID geom = theAdditionCmd->GetArg( 1 );
3328 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3329 if ( !algo.IsNull() )
3331 my1dHyp->SetMesh( theMesh );
3332 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3333 algo->GetAlgoType().ToCString());
3334 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3337 // clear "SetLayerDistribution()" cmd
3338 myArgCommands.back()->Clear();
3340 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3342 // find RadialPrism algo created on <geom> for theMesh
3343 GetCreationCmd()->SetObject( algo->GetID() );
3344 GetCreationCmd()->SetMethod( myAlgoMethod );
3345 GetCreationCmd()->RemoveArgs();
3346 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3352 //================================================================================
3356 //================================================================================
3358 void _pyLayerDistributionHypo::Flush()
3360 // as creation of 1D hyp was written later then it's edition,
3361 // we need to find all it's edition calls and process them
3362 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3364 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3366 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3367 if ( hyp1dID.IsEmpty() ) continue;
3369 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3371 // make a new name for 1D hyp = "HypType" + "_Distribution"
3373 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3375 if ( prevNewName.IsEmpty() ) continue;
3376 newName = prevNewName;
3380 if ( hyp1d->IsWrapped() ) {
3381 newName = hyp1d->GetCreationCmd()->GetMethod();
3384 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3385 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3387 newName += "_Distribution";
3388 prevNewName = newName;
3390 hyp1d->GetCreationCmd()->SetResultValue( newName );
3392 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3393 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3394 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3395 const _pyID& objID = (*cmdIt)->GetObject();
3396 if ( objID == hyp1dID ) {
3397 if ( !hyp1d.IsNull() )
3399 hyp1d->Process( *cmdIt );
3400 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3402 ( *cmdIt )->SetObject( newName );
3405 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3406 (*cmd)->SetArg( 1, newName );
3410 //================================================================================
3412 * \brief additionally to Addition2Creation, clears SetDistrType() command
3413 * \param theCmd - AddHypothesis() command
3414 * \param theMesh - mesh to which a hypothesis is added
3415 * \retval bool - conversion result
3417 //================================================================================
3419 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3420 const _pyID& theMesh)
3422 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3423 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3424 bool scaleDistrType = false;
3425 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3426 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3427 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3428 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3429 scaleDistrType = true;
3432 else if ( !scaleDistrType ) {
3433 // distribution type changed: remove scale factor from args
3434 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3435 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3437 CreationMethod& crMethod = type2meth->second;
3438 if ( crMethod.myArgs.size() == 2 )
3439 crMethod.myArgs.pop_back();
3446 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3449 //================================================================================
3451 * \brief remove repeated commands defining distribution
3453 //================================================================================
3455 void _pyNumberOfSegmentsHyp::Flush()
3457 // find number of the last SetDistrType() command
3458 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3459 int distrTypeNb = 0;
3460 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3461 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3462 if ( cmd != myUnusedCommands.rbegin() )
3463 distrTypeNb = (*cmd)->GetOrderNb();
3465 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3468 // clear commands before the last SetDistrType()
3469 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3470 set< int > treatedCmdNbs; // avoid treating same cmd twice
3471 for ( int i = 0; i < 2; ++i ) {
3472 set<TCollection_AsciiString> uniqueMethods;
3473 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3474 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3476 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3477 continue;// avoid treating same cmd twice
3478 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3479 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3480 if ( !clear || method == "SetNumberOfSegments" ) {
3481 bool isNewInSet = uniqueMethods.insert( method ).second;
3482 clear = !isNewInSet;
3491 //================================================================================
3493 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3494 * into regular1D.LengthNearVertex( length, vertex )
3495 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3496 * \param theMesh - The mesh needing this hypo
3497 * \retval bool - false if the command can't be converted
3499 //================================================================================
3501 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3502 const _pyID& theMeshID)
3504 if ( IsWrappable( theMeshID )) {
3506 _pyID vertex = theCmd->GetArg( 1 );
3508 // the problem here is that segment algo can be not found
3509 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3510 // geometry where segment algorithm is assigned
3511 _pyID geom = vertex;
3512 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMeshID, this );
3513 while ( algo.IsNull() && !geom.IsEmpty()) {
3514 // try to find geom as a father of <vertex>
3515 geom = FatherID( geom );
3516 algo = theGen->FindAlgo( geom, theMeshID, this );
3518 if ( algo.IsNull() || geom.IsEmpty() )
3519 return false; // also possible to find geom as brother of veretex...
3521 // set geom instead of vertex
3522 theCmd->SetArg( 1, geom );
3524 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3525 // SegmentLengthAroundVertex = Regular_1D.LengthNearVertex( length )
3526 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID ))
3528 // set vertex as a second arg
3529 theCmd->SetArg( 2, vertex );
3537 //================================================================================
3539 * \brief _pyAlgorithm constructor
3540 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3542 //================================================================================
3544 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3545 : _pyHypothesis( theCreationCmd )
3550 //================================================================================
3552 * \brief Convert the command adding an algorithm to mesh
3553 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3554 * \param theMesh - The mesh needing this algo
3555 * \retval bool - false if the command can't be converted
3557 //================================================================================
3559 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3560 const _pyID& theMeshID)
3562 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3563 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3564 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3570 //================================================================================
3572 * \brief Return starting position of a part of python command
3573 * \param thePartIndex - The index of command part
3574 * \retval int - Part position
3576 //================================================================================
3578 int _pyCommand::GetBegPos( int thePartIndex ) const
3582 if ( myBegPos.Length() < thePartIndex )
3584 ASSERT( thePartIndex > 0 );
3585 return myBegPos( thePartIndex );
3588 //================================================================================
3590 * \brief Store starting position of a part of python command
3591 * \param thePartIndex - The index of command part
3592 * \param thePosition - Part position
3594 //================================================================================
3596 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3598 while ( myBegPos.Length() < thePartIndex )
3599 myBegPos.Append( UNKNOWN );
3600 ASSERT( thePartIndex > 0 );
3601 myBegPos( thePartIndex ) = thePosition;
3604 //================================================================================
3606 * \brief Returns whitespace symbols at the line beginning
3607 * \retval TCollection_AsciiString - result
3609 //================================================================================
3611 TCollection_AsciiString _pyCommand::GetIndentation()
3614 //while ( end <= Length() && isblank( myString.Value( end )))
3615 //ANA: isblank() function isn't provided in VC2010 compiler
3616 while ( end <= Length() && ( myString.Value( end ) == ' ' || myString.Value( end ) == '\t') )
3618 return ( end == 1 ) ? _AString("") : myString.SubString( 1, end - 1 );
3621 //================================================================================
3623 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3624 * \retval const TCollection_AsciiString & - ResultValue substring
3626 //================================================================================
3628 const TCollection_AsciiString & _pyCommand::GetResultValue()
3630 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3632 SetBegPos( RESULT_IND, EMPTY );
3633 int begPos, endPos = myString.Location( "=", 1, Length() );
3637 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3638 if ( begPos < endPos )
3640 SetBegPos( RESULT_IND, begPos );
3642 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3643 myRes = myString.SubString( begPos, endPos );
3650 //================================================================================
3652 * \brief Return number of python command result value ResultValue = Obj.Meth()
3654 //================================================================================
3656 int _pyCommand::GetNbResultValues()
3659 return myResults.Length();
3663 //================================================================================
3665 * \brief Return substring of python command looking like
3666 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3667 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3669 //================================================================================
3670 const _AString& _pyCommand::GetResultValue(int res)
3672 if ( GetResultValue().IsEmpty() )
3673 return theEmptyString;
3675 if ( myResults.IsEmpty() )
3678 if ( SkipSpaces( myRes, begPos ) && myRes.Value( begPos ) == '[' )
3679 ++begPos; // skip [, else the whole list is returned
3680 while ( begPos < myRes.Length() ) {
3681 _AString result = GetWord( myRes, begPos, true );
3682 begPos += result.Length();
3684 // result.RemoveAll('[');
3685 // result.RemoveAll(']');
3690 myResults.Append( result );
3693 if ( res > 0 && res <= myResults.Length() )
3694 return myResults( res );
3695 return theEmptyString;
3698 //================================================================================
3700 * \brief Return substring of python command looking like ResVal = Object.Meth()
3701 * \retval const TCollection_AsciiString & - Object substring
3703 //================================================================================
3705 const TCollection_AsciiString & _pyCommand::GetObject()
3707 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3710 int begPos = GetBegPos( RESULT_IND );
3712 begPos = myString.Location( "=", 1, Length() ) + 1;
3713 // is '=' in the string argument (for example, name) or not
3714 int nb1 = 0; // number of ' character at the left of =
3715 int nb2 = 0; // number of " character at the left of =
3716 for ( int i = 1; i < begPos-1; i++ ) {
3717 if ( myString.Value( i )=='\'' )
3719 else if ( myString.Value( i )=='"' )
3722 // if number of ' or " is not divisible by 2,
3723 // then get an object at the start of the command
3724 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3728 begPos += myRes.Length();
3730 myObj = GetWord( myString, begPos, true );
3731 if ( begPos != EMPTY )
3733 // check if object is complex,
3734 // so far consider case like "smesh.Method()"
3735 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3736 //if ( bracketPos==0 ) bracketPos = Length();
3737 int dotPos = begPos+myObj.Length();
3738 while ( dotPos+1 < bracketPos ) {
3739 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3744 if ( dotPos > begPos+myObj.Length() )
3745 myObj = myString.SubString( begPos, dotPos-1 );
3748 // 1st word after '=' is an object
3749 // else // no method -> no object
3755 SetBegPos( OBJECT_IND, begPos );
3761 //================================================================================
3763 * \brief Return substring of python command looking like ResVal = Obj.Method()
3764 * \retval const TCollection_AsciiString & - Method substring
3766 //================================================================================
3768 const TCollection_AsciiString & _pyCommand::GetMethod()
3770 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3773 int begPos = GetBegPos( OBJECT_IND );
3774 bool forward = true;
3776 begPos = myString.Location( "(", 1, Length() ) - 1;
3780 begPos += myObj.Length();
3783 myMeth = GetWord( myString, begPos, forward );
3784 SetBegPos( METHOD_IND, begPos );
3790 //================================================================================
3792 * \brief Returns true if there are brackets after the method
3794 //================================================================================
3796 bool _pyCommand::IsMethodCall()
3798 if ( GetMethod().IsEmpty() )
3800 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3801 return ( s[0] == '(' || s[1] == '(' );
3804 //================================================================================
3806 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3807 * \retval const TCollection_AsciiString & - Arg<index> substring
3809 //================================================================================
3811 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3813 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3817 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3819 pos = myString.Location( "(", 1, Length() );
3823 // we are at or before '(', skip it if present
3825 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3826 if ( pos > Length() )
3830 SetBegPos( ARG1_IND, 0 ); // even no '('
3831 return theEmptyString;
3835 list< TCollection_AsciiString > separatorStack( 1, ",)");
3836 bool ignoreNesting = false;
3838 while ( pos <= Length() )
3840 const char chr = myString.Value( pos );
3842 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3844 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3846 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3848 TCollection_AsciiString arg;
3849 if ( pos-1 >= prevPos ) {
3850 arg = myString.SubString( prevPos, pos-1 );
3851 arg.RightAdjust(); // remove spaces
3854 if ( !arg.IsEmpty() || chr == ',' )
3856 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3857 myArgs.Append( arg );
3863 else // end of nesting args found
3865 separatorStack.pop_back();
3866 ignoreNesting = false;
3869 else if ( !ignoreNesting )
3872 case '(' : separatorStack.push_back(")"); break;
3873 case '[' : separatorStack.push_back("]"); break;
3874 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3875 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3882 if ( myArgs.Length() < index )
3883 return theEmptyString;
3884 return myArgs( index );
3887 //================================================================================
3889 * \brief Return position where arguments begin
3891 //================================================================================
3893 int _pyCommand::GetArgBeginning() const
3895 int pos = GetBegPos( ARG1_IND );
3896 if ( pos == UNKNOWN )
3898 pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3900 pos = myString.Location( "(", 4, Length() ); // 4 = strlen("b.c(")
3905 //================================================================================
3907 * \brief Check if char is a word part
3908 * \param c - The character to check
3909 * \retval bool - The check result
3911 //================================================================================
3913 static inline bool isWord(const char c, const bool dotIsWord)
3916 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3919 //================================================================================
3921 * \brief Looks for a word in the string and returns word's beginning
3922 * \param theString - The input string
3923 * \param theStartPos - The position to start the search, returning word's beginning
3924 * \param theForward - The search direction
3925 * \retval TCollection_AsciiString - The found word
3927 //================================================================================
3929 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3931 const bool theForward,
3932 const bool dotIsWord )
3934 int beg = theStartPos, end = theStartPos;
3935 theStartPos = EMPTY;
3936 if ( beg < 1 || beg > theString.Length() )
3937 return theEmptyString;
3939 if ( theForward ) { // search forward
3941 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3943 if ( beg > theString.Length() )
3944 return theEmptyString; // no word found
3947 char begChar = theString.Value( beg );
3948 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3949 char endChar = ( begChar == '[' ) ? ']' : begChar;
3950 // end is at the corresponding quoting mark or bracket
3951 while ( end < theString.Length() &&
3952 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3956 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3961 else { // search backward
3963 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3966 return theEmptyString; // no word found
3968 char endChar = theString.Value( end );
3969 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3970 char begChar = ( endChar == ']' ) ? '[' : endChar;
3971 // beg is at the corresponding quoting mark
3973 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3977 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3983 //cout << theString << " ---- " << beg << " - " << end << endl;
3984 return theString.SubString( beg, end );
3987 //================================================================================
3989 * \brief Returns true if the string looks like a study entry
3991 //================================================================================
3993 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3995 if ( str.Length() < 5 ) return false;
3997 int nbColons = 0, isColon;
3998 for ( int i = 1; i <= str.Length(); ++i )
4000 char c = str.Value(i);
4001 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
4003 nbColons += isColon;
4005 return nbColons > 2 && str.Length()-nbColons > 2;
4008 //================================================================================
4010 * \brief Returns true if the string looks like an object ID but not like a list,
4011 * string, command etc.
4013 //================================================================================
4015 bool _pyCommand::IsID( const TCollection_AsciiString& str )
4017 if ( str.Length() < 1 ) return false;
4019 const char* s = str.ToCString();
4021 for ( int i = 0; i < str.Length(); ++i )
4022 if ( !IsIDChar( s[i] ))
4028 //================================================================================
4030 * \brief Finds entries in a sting
4032 //================================================================================
4034 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
4036 std::list< _pyID > resList;
4038 while ( ++pos <= str.Length() )
4040 if ( !isdigit( str.Value( pos ))) continue;
4041 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
4044 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
4045 _pyID entry = str.SubString( pos, end-1 );
4047 if ( IsStudyEntry( entry ))
4048 resList.push_back( entry );
4053 //================================================================================
4055 * \brief Look for position where not space char is
4056 * \param theString - The string
4057 * \param thePos - The position to search from and which returns result
4058 * \retval bool - false if there are only space after thePos in theString
4060 //================================================================================
4062 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
4064 if ( thePos < 1 || thePos > theString.Length() )
4067 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
4070 return thePos <= theString.Length();
4073 //================================================================================
4075 * \brief Modify a part of the command
4076 * \param thePartIndex - The index of the part
4077 * \param thePart - The new part string
4078 * \param theOldPart - The old part
4080 //================================================================================
4082 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
4083 TCollection_AsciiString& theOldPart)
4085 int pos = GetBegPos( thePartIndex );
4086 if ( pos <= Length() && theOldPart != thePart)
4088 TCollection_AsciiString seperator;
4090 pos = GetBegPos( thePartIndex + 1 );
4091 if ( pos < 1 ) return;
4092 switch ( thePartIndex ) {
4093 case RESULT_IND: seperator = " = "; break;
4094 case OBJECT_IND: seperator = "."; break;
4095 case METHOD_IND: seperator = "()"; break;
4099 myString.Remove( pos, theOldPart.Length() );
4100 if ( !seperator.IsEmpty() )
4101 myString.Insert( pos , seperator );
4102 myString.Insert( pos, thePart );
4103 // update starting positions of the following parts
4104 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
4105 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
4106 if ( myBegPos( i ) > 0 )
4107 myBegPos( i ) += posDelta;
4109 theOldPart = thePart;
4113 //================================================================================
4115 * \brief Set agrument
4116 * \param index - The argument index, it counts from 1
4117 * \param theArg - The argument string
4119 //================================================================================
4121 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
4124 int argInd = ARG1_IND + index - 1;
4125 int pos = GetBegPos( argInd );
4126 if ( pos < 1 ) // no index-th arg exist, append inexistent args
4128 // find a closing parenthesis
4129 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
4130 int lastArgInd = GetNbArgs();
4131 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
4132 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
4137 while ( pos > 0 && myString.Value( pos ) != ')' )
4140 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
4144 while ( myArgs.Length() < index ) {
4145 if ( myArgs.Length() )
4146 myString.Insert( pos++, "," );
4147 myArgs.Append("None");
4148 myString.Insert( pos, myArgs.Last() );
4149 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4150 pos += myArgs.Last().Length();
4153 SetPart( argInd, theArg, myArgs( index ));
4156 //================================================================================
4158 * \brief Empty arg list
4160 //================================================================================
4162 void _pyCommand::RemoveArgs()
4164 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4165 myString.Trunc( pos );
4168 if ( myBegPos.Length() >= ARG1_IND )
4169 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4172 //================================================================================
4174 * \brief Comment a python command
4176 //================================================================================
4178 void _pyCommand::Comment()
4180 if ( IsEmpty() ) return;
4183 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4184 if ( i <= Length() )
4186 myString.Insert( i, "#" );
4187 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4189 int begPos = GetBegPos( iPart );
4190 if ( begPos != UNKNOWN && begPos != EMPTY )
4191 SetBegPos( iPart, begPos + 1 );
4196 //================================================================================
4198 * \brief Set dependent commands after this one
4200 //================================================================================
4202 bool _pyCommand::SetDependentCmdsAfter() const
4204 bool orderChanged = false;
4205 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4206 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4207 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4208 orderChanged = true;
4209 theGen->SetCommandAfter( *cmd, this );
4210 (*cmd)->SetDependentCmdsAfter();
4213 return orderChanged;
4215 //================================================================================
4217 * \brief Insert accessor method after theObjectID
4218 * \param theObjectID - id of the accessed object
4219 * \param theAcsMethod - name of the method giving access to the object
4220 * \retval bool - false if theObjectID is not found in the command string
4222 //================================================================================
4224 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4226 if ( !theAcsMethod )
4228 // start object search from the object, i.e. ignore result
4230 int beg = GetBegPos( OBJECT_IND );
4231 if ( beg < 1 || beg > Length() )
4234 while (( beg = myString.Location( theObjectID, beg, Length() )))
4236 // check that theObjectID is not just a part of a longer ID
4237 int afterEnd = beg + theObjectID.Length();
4238 Standard_Character c = myString.Value( afterEnd );
4239 if ( !IsIDChar( c ))
4241 // check if accessor method already present
4243 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4245 int oldLen = Length();
4246 myString.Insert( afterEnd, (char*) theAcsMethod );
4247 myString.Insert( afterEnd, "." );
4248 // update starting positions of the parts following the modified one
4249 int posDelta = Length() - oldLen;
4250 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4251 if ( myBegPos( i ) > afterEnd )
4252 myBegPos( i ) += posDelta;
4257 beg = afterEnd; // is a part -> next search
4262 //================================================================================
4264 * \brief Creates pyObject
4266 //================================================================================
4268 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4269 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4274 //================================================================================
4276 * \brief Set up myID and myIsPublished
4278 //================================================================================
4280 void _pyObject::setID(const _pyID& theID)
4283 myIsPublished = !theGen->IsNotPublished( GetID() );
4286 //================================================================================
4288 * \brief Clear myCreationCmd and myProcessedCmds
4290 //================================================================================
4292 void _pyObject::ClearCommands()
4297 if ( !myCreationCmd.IsNull() )
4298 myCreationCmd->Clear();
4300 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4301 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4305 //================================================================================
4307 * \brief Return method name giving access to an interaface object wrapped by python class
4308 * \retval const char* - method name
4310 //================================================================================
4312 const char* _pyObject::AccessorMethod() const
4316 //================================================================================
4318 * \brief Return ID of a father
4320 //================================================================================
4322 _pyID _pyObject::FatherID(const _pyID & childID)
4324 int colPos = childID.SearchFromEnd(':');
4326 return childID.SubString( 1, colPos-1 );
4330 //================================================================================
4332 * \brief SelfEraser erases creation command if none of it's commands invoked
4333 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4335 //================================================================================
4337 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4338 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4340 myIsPublished = true; // prevent clearing as a not published
4341 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4344 //================================================================================
4346 * \brief SelfEraser erases creation command if none of it's commands invoked
4347 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4349 //================================================================================
4351 bool _pySelfEraser::CanClear()
4353 bool toErase = false;
4354 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4357 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4358 for ( ; cmd != myArgCmds.end(); ++cmd )
4359 nbArgUses += IsAliveCmd( *cmd );
4361 toErase = ( nbArgUses < 1 );
4366 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4367 std::list< Handle(_pyCommand) >::iterator cmd = cmds.begin();
4368 for ( ; cmd != cmds.end(); )
4369 // check of cmd emptiness is not enough as object can change
4370 if (( *cmd )->GetString().Search( GetID() ) > 0 )
4373 cmd = cmds.erase( cmd ); // save the cmd from clearing
4375 toErase = ( nbCalls < 1 );
4380 //================================================================================
4382 * \brief Check if a command is or can be cleared
4384 //================================================================================
4386 bool _pySelfEraser::IsAliveCmd( const Handle(_pyCommand)& theCmd )
4388 if ( theCmd->IsEmpty() )
4391 if ( !theGen->IsToKeepAllCommands() )
4393 const _pyID& objID = theCmd->GetObject();
4394 Handle( _pyObject ) obj = theGen->FindObject( objID );
4395 if ( !obj.IsNull() )
4396 return !obj->CanClear();
4401 //================================================================================
4403 * \brief SelfEraser erases creation command if none of it's commands invoked
4404 * (e.g. filterManager) or it's not used as a command argument (e.g. a filter)
4406 //================================================================================
4408 void _pySelfEraser::Flush()
4412 myIsPublished = false;
4413 _pyObject::ClearCommands();
4417 //================================================================================
4419 * \brief _pySubMesh constructor
4421 //================================================================================
4423 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4424 _pyObject(theCreationCmd)
4426 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4427 if ( toKeepAgrCmds )
4428 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4431 //================================================================================
4433 * \brief Return true if a sub-mesh can be used as argument of the given method
4435 //================================================================================
4437 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4440 // names of all methods where a sub-mesh can be used as argument
4441 // static TStringSet methods;
4442 // if ( methods.empty() ) {
4443 // const char * names[] = {
4444 // // methods of SMESH_Gen
4446 // // methods of SMESH_Group
4448 // // methods of SMESH_Measurements
4450 // // methods of SMESH_Mesh
4451 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4453 // // methods of SMESH_MeshEditor
4454 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4455 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4456 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4457 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4458 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4459 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4460 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4461 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4462 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4463 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4464 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4465 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4466 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4467 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4468 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4469 // "" }; // <- mark of end
4470 // methods.Insert( names );
4472 // return methods.Contains( theMethodName );
4475 //================================================================================
4477 * \brief count invoked commands
4479 //================================================================================
4481 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4483 _pyObject::Process(theCommand); // count calls of Process()
4486 //================================================================================
4488 * \brief Move creation command depending on invoked commands
4490 //================================================================================
4492 void _pySubMesh::Flush()
4494 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4495 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4496 else if ( !myCreator.IsNull() )
4497 // move to be just after creator
4498 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4500 // move sub-mesh usage after creation cmd
4501 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4502 for ( ; cmd != myArgCmds.end(); ++cmd )
4503 if ( !(*cmd)->IsEmpty() )
4504 GetCreationCmd()->AddDependantCmd( *cmd );
4507 //================================================================================
4509 * \brief Creates _pyGroup
4511 //================================================================================
4513 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4514 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4516 if ( !id.IsEmpty() )
4519 myCanClearCreationCmd = true;
4521 const _AString& method = theCreationCmd->GetMethod();
4522 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4524 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4526 // ----------------------------------------------------------------------
4527 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4529 _pyID geom = theCreationCmd->GetArg( 3 );
4530 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4531 // next if(){...} section is commented
4532 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4533 // theCreationCmd->SetMethod( "Group" );
4534 // theCreationCmd->RemoveArgs();
4535 // theCreationCmd->SetArg( 1, geom );
4538 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4539 _pyID type = theCreationCmd->GetArg( 1 );
4540 _pyID name = theCreationCmd->GetArg( 2 );
4541 theCreationCmd->SetMethod( "GroupOnGeom" );
4542 theCreationCmd->RemoveArgs();
4543 theCreationCmd->SetArg( 1, geom );
4544 theCreationCmd->SetArg( 2, name );
4545 theCreationCmd->SetArg( 3, type );
4548 else if ( method == "CreateGroupFromFilter" )
4550 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4551 theCreationCmd->SetMethod( "GroupOnFilter" );
4553 _pyID filterID = theCreationCmd->GetArg(3);
4554 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4555 if ( !filter.IsNull())
4557 if ( !filter->GetNewID().IsEmpty() )
4558 theCreationCmd->SetArg( 3, filter->GetNewID() );
4559 //filter->AddUser( this );
4563 else if ( method == "GetGroups" )
4565 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4569 // theCreationCmd does something else apart from creation of this group
4570 // and thus it can't be cleared if this group is removed
4571 myCanClearCreationCmd = false;
4575 //================================================================================
4577 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4580 //================================================================================
4582 bool _pyGroup::CanClear()
4587 if ( !myCanClearCreationCmd &&
4588 !myCreationCmd.IsNull() &&
4589 myCreationCmd->GetMethod() == "GetGroups" )
4591 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4592 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4593 list< _pyID >::iterator grID = idList.begin();
4594 if ( GetID() == *grID )
4596 myCanClearCreationCmd = true;
4597 list< Handle(_pyGroup ) > groups;
4598 for ( ; grID != idList.end(); ++grID )
4600 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4601 if ( group.IsNull() ) continue;
4602 groups.push_back( group );
4603 if ( group->IsInStudy() )
4604 myCanClearCreationCmd = false;
4606 // set myCanClearCreationCmd == true to all groups
4607 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4608 for ( ; group != groups.end(); ++group )
4609 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4613 return myCanClearCreationCmd;
4616 //================================================================================
4618 * \brief set myCanClearCreationCmd = true if the main action of the creation
4619 * command is discarded
4621 //================================================================================
4623 void _pyGroup::RemovedWithContents()
4625 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4626 // via a created group
4627 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4628 // myCanClearCreationCmd = true;
4631 //================================================================================
4633 * \brief To convert creation of a group by filter
4635 //================================================================================
4637 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4639 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4640 // group = mesh.CreateEmptyGroup( elemType, groupName )
4641 // aFilter.SetMesh(mesh)
4642 // nbAdd = group.AddFrom( aFilter )
4643 Handle(_pyFilter) filter;
4644 if ( theCommand->GetMethod() == "AddFrom" )
4646 _pyID idSource = theCommand->GetArg(1);
4647 // check if idSource is a filter
4648 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4649 if ( !filter.IsNull() )
4651 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4652 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4653 while ( *cmdIt != theCommand ) ++cmdIt;
4654 while ( (*cmdIt)->GetOrderNb() != 1 )
4656 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4657 if ((setMeshCmd->GetObject() == idSource ||
4658 setMeshCmd->GetObject() == filter->GetNewID() )
4660 setMeshCmd->GetMethod() == "SetMesh")
4662 setMeshCmd->Clear();
4666 // replace 3 commands by one
4667 theCommand->Clear();
4668 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4669 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4670 if ( !filter->GetNewID().IsEmpty() )
4671 idSource = filter->GetNewID();
4672 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4673 makeGroupCmd->SetArg( 1, name );
4674 makeGroupCmd->SetArg( 2, idSource );
4675 filter->AddArgCmd( makeGroupCmd );
4678 else if ( theCommand->GetMethod() == "SetFilter" )
4680 // set new name of a filter or clear the command if the same filter is set
4681 _pyID filterID = theCommand->GetArg(1);
4682 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4683 if ( !myFilter.IsNull() && filter == myFilter )
4684 theCommand->Clear();
4685 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4686 theCommand->SetArg( 1, filter->GetNewID() );
4689 else if ( theCommand->GetMethod() == "GetFilter" )
4691 // GetFilter() returns a filter with other ID, make myFilter process
4692 // calls of the returned filter
4693 if ( !myFilter.IsNull() )
4695 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4696 theCommand->Clear();
4700 // if ( !filter.IsNull() )
4701 // filter->AddUser( this );
4703 theGen->AddMeshAccessorMethod( theCommand );
4706 //================================================================================
4708 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4710 //================================================================================
4712 void _pyGroup::Flush()
4714 if ( !theGen->IsToKeepAllCommands() &&
4715 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4717 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4721 //================================================================================
4723 * \brief Constructor of _pyFilter
4725 //================================================================================
4727 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4728 :_pyObject(theCreationCmd), myNewID( newID )
4730 //myIsPublished = true; // prevent clearing as a not published
4731 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4734 //================================================================================
4736 * \brief To convert creation of a filter by criteria and
4737 * to replace an old name by a new one
4739 //================================================================================
4741 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4743 if ( theCommand->GetObject() == GetID() )
4744 _pyObject::Process(theCommand); // count commands
4746 if ( !myNewID.IsEmpty() )
4747 theCommand->SetObject( myNewID );
4749 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4750 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4751 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4752 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4753 theCommand->GetMethod() == "SetCriteria")
4755 // aFilter.SetCriteria(aCriteria) ->
4756 // aFilter = smesh.GetFilterFromCriteria(criteria)
4757 if ( myNewID.IsEmpty() )
4758 theCommand->SetResultValue( GetID() );
4760 theCommand->SetResultValue( myNewID );
4761 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4762 theCommand->SetMethod( "GetFilterFromCriteria" );
4764 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4765 GetCreationCmd()->Clear();
4766 GetCreationCmd()->GetString() = theCommand->GetString();
4767 theCommand->Clear();
4768 theCommand->AddDependantCmd( GetCreationCmd() );
4769 // why swap? -- it's needed
4770 //GetCreationCmd()->Clear();
4772 else if ( theCommand->GetMethod() == "SetMesh" )
4774 if ( myMesh == theCommand->GetArg( 1 ))
4775 theCommand->Clear();
4777 myMesh = theCommand->GetArg( 1 );
4778 theGen->AddMeshAccessorMethod( theCommand );
4782 //================================================================================
4784 * \brief Set new filter name to the creation command and to myArgCmds
4786 //================================================================================
4788 void _pyFilter::Flush()
4790 if ( myNewID.IsEmpty() ) return;
4792 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4793 for ( ; cmd != myArgCmds.end(); ++cmd )
4794 if ( !(*cmd)->IsEmpty() )
4796 _AString cmdStr = (*cmd)->GetString();
4797 _AString id = GetID();
4798 int pos = cmdStr.Search( id );
4801 cmdStr.Remove( pos, id.Length() );
4802 cmdStr.Insert( pos, myNewID );
4805 (*cmd)->GetString() = cmdStr;
4808 if ( !GetCreationCmd()->IsEmpty() )
4809 GetCreationCmd()->SetResultValue( myNewID );
4812 //================================================================================
4814 * \brief Return true if all my users can be cleared
4816 //================================================================================
4818 bool _pyObject::CanClear()
4820 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4821 for ( ; cmd != myArgCmds.end(); ++cmd )
4822 if ( !(*cmd)->IsEmpty() )
4824 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4825 if ( !obj.IsNull() && !obj->CanClear() )
4828 return ( !myIsPublished );
4831 //================================================================================
4833 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4835 //================================================================================
4837 _pyHypothesisReader::_pyHypothesisReader()
4840 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4841 LDOMParser xmlParser;
4842 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4844 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4848 INFOS( xmlParser.GetError(data) );
4851 // <algorithm type="Regular_1D"
4852 // label-id="Wire discretisation"
4855 // <algo>Regular_1D=Segment()</algo>
4856 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4858 LDOM_Document xmlDoc = xmlParser.getDocument();
4859 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4860 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4862 LDOM_Node algoNode = algoNodeList.item( i );
4863 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4864 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4865 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4867 _AString text, algoType, method, arg;
4868 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4870 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4871 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4872 text = textNode.getNodeValue();
4873 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4874 algoType = algoCmd->GetResultValue();
4875 method = algoCmd->GetMethod();
4876 arg = algoCmd->GetArg(1);
4877 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4879 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4880 algo->SetConvMethodAndType( method, algoType );
4881 if ( !arg.IsEmpty() )
4882 algo->setCreationArg( 1, arg );
4884 myType2Hyp[ algoType ] = algo;
4888 if ( algoType.IsEmpty() ) continue;
4890 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4892 Handle( _pyHypothesis ) hyp;
4893 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4895 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4896 LDOM_Node textNode = pyHypoNode.getFirstChild();
4897 text = textNode.getNodeValue();
4898 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4899 hypType = hypoCmd->GetResultValue();
4900 method = hypoCmd->GetMethod();
4901 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4903 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4904 if ( type2hyp == myType2Hyp.end() )
4905 hyp = new _pyHypothesis( hypoCmd );
4907 hyp = type2hyp->second;
4908 hyp->SetConvMethodAndType( method, algoType );
4909 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4911 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4912 _AString argMethod = argCmd.GetMethod();
4913 _AString argNbText = argCmd.GetArg( 1 );
4914 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4915 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4917 hyp->AddArgMethod( argMethod,
4918 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4920 myType2Hyp[ hypType ] = hyp;
4924 // <hypothesis type="BLSURF_Parameters"
4928 // <accumulative-methods>
4929 // SetEnforcedVertex,
4930 // SetEnforcedVertexNamed
4931 // </accumulative-methods>
4935 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4936 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4938 LDOM_Node hypNode = hypNodeList.item( i );
4939 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4940 _AString hypType = hypElem.getAttribute("type");
4941 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4942 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4944 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4945 if ( type2hyp == myType2Hyp.end() ) continue;
4947 LDOM_Node methNode = methNodeList.item( 0 );
4948 LDOM_Node textNode = methNode.getFirstChild();
4949 _AString text = textNode.getNodeValue();
4953 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4954 pos += method.Length();
4955 type2hyp->second->AddAccumulativeMethod( method );
4957 while ( !method.IsEmpty() );
4960 } // loop on xmlPaths
4963 //================================================================================
4965 * \brief Returns a new hypothesis initialized according to the read information
4967 //================================================================================
4969 Handle(_pyHypothesis)
4970 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4971 const Handle(_pyCommand)& creationCmd) const
4973 Handle(_pyHypothesis) resHyp, sampleHyp;
4975 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4976 if ( type2hyp != myType2Hyp.end() )
4977 sampleHyp = type2hyp->second;
4979 if ( sampleHyp.IsNull() )
4981 resHyp = new _pyHypothesis(creationCmd);
4985 if ( sampleHyp->IsAlgo() )
4986 resHyp = new _pyAlgorithm( creationCmd );
4988 resHyp = new _pyHypothesis(creationCmd);
4989 resHyp->Assign( sampleHyp, _pyID() );
4994 //================================================================================
4996 * \brief Adds an object ID to some family of IDs with a common prefix
4997 * \param [in] str - the object ID
4998 * \return bool - \c false if \a str does not have the same prefix as \a this family
4999 * (for internal usage)
5001 //================================================================================
5003 bool _pyStringFamily::Add( const char* str )
5005 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
5006 return false; // expected prefix is missing
5008 str += _prefix.Length(); // skip _prefix
5010 // try to add to some of child falimies
5011 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5012 for ( ; itSub != _subFams.end(); ++itSub )
5013 if ( itSub->Add( str ))
5016 // no suitable family found - add str to _strings or create a new child family
5018 // look for a proper place within sorted _strings
5019 std::list< _AString >::iterator itStr = _strings.begin();
5020 while ( itStr != _strings.end() && itStr->IsLess( str ))
5022 if ( itStr != _strings.end() && itStr->IsEqual( str ))
5023 return true; // same ID already kept
5025 const int minPrefixSize = 4;
5027 // count "smaller" strings with the same prefix
5028 std::list< _AString >::iterator itLess = itStr; --itLess;
5030 for ( ; itLess != _strings.end(); --itLess )
5031 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
5036 // count "greater" strings with the same prefix
5037 std::list< _AString >::iterator itMore = itStr;
5039 for ( ; itMore != _strings.end(); ++itMore )
5040 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
5045 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
5047 // look for a maximal prefix length
5048 // int lessPrefSize = 3, morePrefSize = 3;
5049 // if ( nbLess > 0 )
5050 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
5052 // if ( nbMore > 0 )
5053 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
5055 // int prefixSize = 3;
5056 // if ( nbLess == 0 )
5057 // prefixSize = morePrefSize;
5058 // else if ( nbMore == 0 )
5059 // prefixSize = lessPrefSize;
5061 // prefixSize = Min( lessPrefSize, morePrefSize );
5062 int prefixSize = minPrefixSize;
5063 _AString newPrefix ( str, prefixSize );
5065 // look for a proper place within _subFams sorted by _prefix
5066 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
5067 if ( !itSub->_prefix.IsLess( newPrefix ))
5070 // add the new _pyStringFamily
5071 itSub = _subFams.insert( itSub, _pyStringFamily());
5072 _pyStringFamily& newSubFam = *itSub;
5073 newSubFam._prefix = newPrefix;
5075 // pass this->_strings to newSubFam._strings
5076 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
5077 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5078 newSubFam._strings.push_back( str + prefixSize );
5079 for ( ; nbMore > 0; --nbMore, ++itStr )
5080 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
5082 _strings.erase( itLess, ++itMore );
5084 else // to few string to make a family fot them
5086 _strings.insert( itStr, str );
5091 //================================================================================
5093 * \brief Finds an object ID in the command
5094 * \param [in] longStr - the command string
5095 * \param [out] subStr - the found object ID
5096 * \return bool - \c true if the object ID found
5098 //================================================================================
5100 bool _pyStringFamily::IsInArgs( Handle( _pyCommand)& cmd, std::list<_AString>& subStr )
5102 const _AString& longStr = cmd->GetString();
5103 const char* s = longStr.ToCString();
5106 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5107 int nbFound = 0, pos, len, from, argBeg = cmd->GetArgBeginning();
5108 if ( argBeg < 4 || argBeg > longStr.Length() )
5110 for ( ; itSub != _subFams.end(); ++itSub )
5113 while (( pos = longStr.Location( itSub->_prefix, from, longStr.Length() )))
5114 if (( len = itSub->isIn( s + pos-1 + itSub->_prefix.Length() )) >= 0 )
5116 subStr.push_back( _AString( s + pos-1, len + itSub->_prefix.Length() ));
5117 from = pos + len + itSub->_prefix.Length();
5122 from += itSub->_prefix.Length();
5125 // look among _strings
5126 std::list< _AString >::iterator itStr = _strings.begin();
5127 for ( ; itStr != _strings.end(); ++itStr )
5128 if (( pos = longStr.Location( *itStr, argBeg, longStr.Length() )))
5129 // check that object ID does not continue after len
5130 if ( !cmd->IsIDChar( s[ pos + itStr->Length() - 1 ] ))
5132 subStr.push_back( *itStr );
5138 //================================================================================
5140 * \brief Return remainder length of the object ID after my _prefix
5141 * \param [in] str - remainder of the command after my _prefix
5142 * \return int - length of the object ID or -1 if not found
5144 //================================================================================
5146 int _pyStringFamily::isIn( const char* str )
5148 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5150 for ( ; itSub != _subFams.end(); ++itSub )
5152 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
5155 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
5156 return itSub->_prefix.Length() + len;
5161 if ( !_strings.empty() )
5163 std::list< _AString >::iterator itStr = _strings.begin();
5164 bool firstEmpty = itStr->IsEmpty();
5167 for ( ; itStr != _strings.end(); ++itStr )
5169 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
5172 len = itStr->Length();
5181 // check that object ID does not continue after len
5182 if ( len >= 0 && _pyCommand::IsIDChar( str[len] ))
5189 //================================================================================
5193 //================================================================================
5195 void _pyStringFamily::Print( int level )
5197 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
5198 std::list< _AString >::iterator itStr = _strings.begin();
5199 for ( ; itStr != _strings.end(); ++itStr )
5200 cout << *itStr << " | ";
5202 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
5203 for ( ; itSub != _subFams.end(); ++itSub )
5204 itSub->Print( level + 1 );
5206 cout << string( 70, '-' ) << endl;