1 // Copyright (C) 2007-2013 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.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // File : SMESH_2smeshpy.cxx
24 // Created : Fri Nov 18 13:20:10 2005
25 // Author : Edward AGAPOV (eap)
27 #include "SMESH_2smeshpy.hxx"
29 #include "SMESH_PythonDump.hxx"
30 #include "SMESH_NoteBook.hxx"
31 #include "SMESH_Filter_i.hxx"
33 #include <SALOMEDS_wrap.hxx>
34 #include <utilities.h>
36 #include <Resource_DataMapOfAsciiStringAsciiString.hxx>
37 #include <Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString.hxx>
39 #include "SMESH_Gen_i.hxx"
40 /* SALOME headers that include CORBA headers that include windows.h
41 * that defines GetObject symbol as GetObjectA should stand before SALOME headers
42 * that declare methods named GetObject - to apply the same rules of GetObject renaming
43 * and thus to avoid mess with GetObject symbol on Windows */
45 #include <LDOMParser.hxx>
54 IMPLEMENT_STANDARD_HANDLE (_pyObject ,Standard_Transient);
55 IMPLEMENT_STANDARD_HANDLE (_pyCommand ,Standard_Transient);
56 IMPLEMENT_STANDARD_HANDLE (_pyHypothesisReader,Standard_Transient);
57 IMPLEMENT_STANDARD_HANDLE (_pyGen ,_pyObject);
58 IMPLEMENT_STANDARD_HANDLE (_pyMesh ,_pyObject);
59 IMPLEMENT_STANDARD_HANDLE (_pySubMesh ,_pyObject);
60 IMPLEMENT_STANDARD_HANDLE (_pyMeshEditor ,_pyObject);
61 IMPLEMENT_STANDARD_HANDLE (_pyHypothesis ,_pyObject);
62 IMPLEMENT_STANDARD_HANDLE (_pySelfEraser ,_pyObject);
63 IMPLEMENT_STANDARD_HANDLE (_pyGroup ,_pyObject);
64 IMPLEMENT_STANDARD_HANDLE (_pyFilter ,_pyObject);
65 IMPLEMENT_STANDARD_HANDLE (_pyAlgorithm ,_pyHypothesis);
66 IMPLEMENT_STANDARD_HANDLE (_pyComplexParamHypo,_pyHypothesis);
67 IMPLEMENT_STANDARD_HANDLE (_pyNumberOfSegmentsHyp,_pyHypothesis);
69 IMPLEMENT_STANDARD_RTTIEXT(_pyObject ,Standard_Transient);
70 IMPLEMENT_STANDARD_RTTIEXT(_pyCommand ,Standard_Transient);
71 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesisReader,Standard_Transient);
72 IMPLEMENT_STANDARD_RTTIEXT(_pyGen ,_pyObject);
73 IMPLEMENT_STANDARD_RTTIEXT(_pyMesh ,_pyObject);
74 IMPLEMENT_STANDARD_RTTIEXT(_pySubMesh ,_pyObject);
75 IMPLEMENT_STANDARD_RTTIEXT(_pyMeshEditor ,_pyObject);
76 IMPLEMENT_STANDARD_RTTIEXT(_pyHypothesis ,_pyObject);
77 IMPLEMENT_STANDARD_RTTIEXT(_pySelfEraser ,_pyObject);
78 IMPLEMENT_STANDARD_RTTIEXT(_pyGroup ,_pyObject);
79 IMPLEMENT_STANDARD_RTTIEXT(_pyFilter ,_pyObject);
80 IMPLEMENT_STANDARD_RTTIEXT(_pyAlgorithm ,_pyHypothesis);
81 IMPLEMENT_STANDARD_RTTIEXT(_pyComplexParamHypo,_pyHypothesis);
82 IMPLEMENT_STANDARD_RTTIEXT(_pyNumberOfSegmentsHyp,_pyHypothesis);
83 IMPLEMENT_STANDARD_RTTIEXT(_pyLayerDistributionHypo,_pyHypothesis);
84 IMPLEMENT_STANDARD_RTTIEXT(_pySegmentLengthAroundVertexHyp,_pyHypothesis);
87 using SMESH::TPythonDump;
90 * \brief Container of commands into which the initial script is split.
91 * It also contains data coresponding to SMESH_Gen contents
93 static Handle(_pyGen) theGen;
95 static TCollection_AsciiString theEmptyString;
97 //#define DUMP_CONVERSION
99 #if !defined(_DEBUG_) && defined(DUMP_CONVERSION)
100 #undef DUMP_CONVERSION
106 //================================================================================
108 * \brief Set of TCollection_AsciiString initialized by C array of C strings
110 //================================================================================
112 struct TStringSet: public set<TCollection_AsciiString>
115 * \brief Filling. The last string must be ""
117 void Insert(const char* names[]) {
118 for ( int i = 0; names[i][0] ; ++i )
119 insert( (char*) names[i] );
122 * \brief Check if a string is in
124 bool Contains(const TCollection_AsciiString& name ) {
125 return find( name ) != end();
129 //================================================================================
131 * \brief Map of TCollection_AsciiString initialized by C array of C strings.
132 * Odd items of the C array are map keys, and even items are values
134 //================================================================================
136 struct TStringMap: public map<TCollection_AsciiString,TCollection_AsciiString>
139 * \brief Filling. The last string must be ""
141 void Insert(const char* names_values[]) {
142 for ( int i = 0; names_values[i][0] ; i += 2 )
143 insert( make_pair( (char*) names_values[i], names_values[i+1] ));
146 * \brief Check if a string is in
148 TCollection_AsciiString Value(const TCollection_AsciiString& name ) {
149 map< _AString, _AString >::iterator it = find( name );
150 return it == end() ? "" : it->second;
154 //================================================================================
156 * \brief Returns a mesh by object
158 //================================================================================
160 Handle(_pyMesh) ObjectToMesh( const Handle( _pyObject )& obj )
164 if ( obj->IsKind( STANDARD_TYPE( _pyMesh )))
165 return Handle(_pyMesh)::DownCast( obj );
166 else if ( obj->IsKind( STANDARD_TYPE( _pySubMesh )))
167 return Handle(_pySubMesh)::DownCast( obj )->GetMesh();
168 else if ( obj->IsKind( STANDARD_TYPE( _pyGroup )))
169 return Handle(_pyGroup)::DownCast( obj )->GetMesh();
171 return Handle(_pyMesh)();
174 //================================================================================
176 * \brief Check if objects used as args have been created by previous commands
178 //================================================================================
180 void CheckObjectPresence( const Handle(_pyCommand)& cmd, set<_pyID> & presentObjects)
182 // either comment or erase a command including NotPublishedObjectName()
183 if ( cmd->GetString().Location( TPythonDump::NotPublishedObjectName(), 1, cmd->Length() ))
185 bool isResultPublished = false;
186 for ( int i = 0; i < cmd->GetNbResultValues(); i++ )
188 _pyID objID = cmd->GetResultValue( i+1 );
189 if ( cmd->IsStudyEntry( objID ))
190 isResultPublished = (! theGen->IsNotPublished( objID ));
191 theGen->ObjectCreationRemoved( objID ); // objID.SetName( name ) is not needed
193 if ( isResultPublished )
199 // check if an Object was created in the script
201 const _pyID& obj = cmd->GetObject();
202 if ( !obj.IsEmpty() && cmd->IsStudyEntry( obj ) && !presentObjects.count( obj ))
204 comment = "not created Object";
205 theGen->ObjectCreationRemoved( obj );
207 // check if a command has not created args
208 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
210 const _pyID& arg = cmd->GetArg( iArg );
211 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
213 list< _pyID > idList = cmd->GetStudyEntries( arg );
214 list< _pyID >::iterator id = idList.begin();
215 for ( ; id != idList.end(); ++id )
216 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
218 comment += *id + " has not been yet created";
222 // treat result objects
223 const _pyID& result = cmd->GetResultValue();
224 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
226 list< _pyID > idList = cmd->GetStudyEntries( result );
227 list< _pyID >::iterator id = idList.begin();
228 for ( ; id != idList.end(); ++id )
229 if ( comment.IsEmpty() )
230 presentObjects.insert( *id );
232 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
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
294 // It's necessary to continue recording this history and to fill
295 // undef2newItems (see below) accordingly.
297 typedef map< int, vector< int > > TUndef2newItems;
298 static TUndef2newItems undef2newItems;
299 if ( undef2newItems.empty() )
301 undef2newItems[ 26 ].push_back( 7 );
302 undef2newItems[ 27 ].push_back( 17 );
303 { int items[] = { 10, 11, 23, 24, 25 };
304 undef2newItems[ 32 ].assign( items, items+5 ); }
305 undef2newItems[ 33 ].push_back( 26 );
306 { int items[] = { 8, 9, 25, 26, 27, 28 };
307 undef2newItems[ 39 ].assign( items, items+6 ); }
308 { int items[] = { 14, 15, 16, 17 };
309 undef2newItems[ 43 ].assign( items, items+4 ); }
310 undef2newItems[ 44 ].push_back( 37 );
311 undef2newItems[ 45 ].push_back( 36 );
312 undef2newItems[ 46 ].push_back( 39 );
314 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
317 int iType = Type.IntegerValue();
318 int iCompare = Compare.IntegerValue();
319 int iUnaryOp = UnaryOp.IntegerValue();
320 int iBinaryOp = BinaryOp.IntegerValue();
322 // find out integer value of FT_Undefined at the moment of dump
323 int oldUndefined = iBinaryOp;
324 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
327 // apply history to args
328 TUndef2newItems::const_iterator undef_items =
329 undef2newItems.upper_bound( oldUndefined );
330 if ( undef_items != undef2newItems.end() )
332 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
333 for ( ; undef_items != undef2newItems.end(); ++undef_items )
335 const vector< int > & addedItems = undef_items->second;
336 for ( size_t i = 0; i < addedItems.size(); ++i )
337 for ( int iArg = 0; iArg < 4; ++iArg )
339 int& arg = *pArg[iArg];
340 if ( arg >= addedItems[i] )
344 Type = TCollection_AsciiString( iType );
345 Compare = TCollection_AsciiString( iCompare );
346 UnaryOp = TCollection_AsciiString( iUnaryOp );
347 BinaryOp = TCollection_AsciiString( iBinaryOp );
351 //================================================================================
353 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
354 * arguments of a given command by a list "[x,y,z]" if the list is accesible
357 //================================================================================
359 void StructToList( Handle( _pyCommand)& theCommand )
361 static TStringSet methodsAcceptingList;
362 if ( methodsAcceptingList.empty() ) {
363 const char * methodNames[] = {
364 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
365 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
366 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
367 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
368 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
369 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
370 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
371 "Translate","TranslateMakeGroups","TranslateMakeMesh",
372 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh"
373 ,"" }; // <- mark of the end
374 methodsAcceptingList.Insert( methodNames );
376 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
378 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
380 const _AString & arg = theCommand->GetArg( i );
381 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
382 arg.Search( "SMESH.DirStruct" ) == 1 )
384 Handle(_pyCommand) workCmd = new _pyCommand( arg );
385 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
387 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
389 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
391 _AString newArg = "[ ";
392 newArg += ( workCmd->GetArg( 1 ) + ", " +
393 workCmd->GetArg( 2 ) + ", " +
394 workCmd->GetArg( 3 ) + " ]");
395 theCommand->SetArg( i, newArg );
401 //================================================================================
403 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
404 * a list "[id1,id2]" if the list is an accesible type of argument.
406 //================================================================================
408 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
410 static TStringSet methodsAcceptingList;
411 if ( methodsAcceptingList.empty() ) {
412 const char * methodNames[] = {
413 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
414 "ExportCGNS","ExportGMF",
415 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
416 "ScaleMakeGroups","Scale","ScaleMakeMesh",
417 "FindCoincidentNodesOnPartBut","DoubleElements"
418 ,"" }; // <- mark of the end
419 methodsAcceptingList.Insert( methodNames );
421 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
423 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
425 _pyCommand argCmd( theCommand->GetArg( i ));
426 if ( argCmd.GetMethod() == "GetIDSource" &&
427 argCmd.GetNbArgs() == 2 )
429 theCommand->SetArg( i, argCmd.GetArg( 1 ));
436 //================================================================================
438 * \brief Convert a python script using commands of smeshBuilder.py
439 * \param theScript - Input script
440 * \param theEntry2AccessorMethod - returns method names to access to
441 * objects wrapped with python class
442 * \param theObjectNames - names of objects
443 * \param theRemovedObjIDs - entries of objects whose created commands were removed
444 * \param theHistoricalDump - true means to keep all commands, false means
445 * to exclude commands relating to objects removed from study
446 * \retval TCollection_AsciiString - Convertion result
448 //================================================================================
450 TCollection_AsciiString
451 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
452 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
453 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
454 std::set< TCollection_AsciiString >& theRemovedObjIDs,
455 SALOMEDS::Study_ptr& theStudy,
456 const bool theToKeepAllCommands)
458 theGen = new _pyGen( theEntry2AccessorMethod,
462 theToKeepAllCommands );
464 // split theScript into separate commands
466 SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
468 int from = 1, end = theScript.Length(), to;
469 while ( from < end && ( to = theScript.Location( "\n", from, end )))
472 // cut out and store a command
473 aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
477 aNoteBook->ReplaceVariables();
479 TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
483 // split theScript into separate commands
484 from = 1, end = aNoteScript.Length();
485 while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
488 // cut out and store a command
489 theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
495 #ifdef DUMP_CONVERSION
496 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
499 // clean commmands of removed objects depending on myIsPublished flag
500 theGen->ClearCommands();
502 // reorder commands after conversion
503 list< Handle(_pyCommand) >::iterator cmd;
506 orderChanges = false;
507 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
508 if ( (*cmd)->SetDependentCmdsAfter() )
510 } while ( orderChanges );
512 // concat commands back into a script
513 TCollection_AsciiString aScript, aPrevCmd;
514 set<_pyID> createdObjects;
515 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
517 #ifdef DUMP_CONVERSION
518 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
520 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
521 CheckObjectPresence( *cmd, createdObjects );
522 aPrevCmd = (*cmd)->GetString();
535 //================================================================================
537 * \brief _pyGen constructor
539 //================================================================================
541 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
542 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
543 std::set< TCollection_AsciiString >& theRemovedObjIDs,
544 SALOMEDS::Study_ptr& theStudy,
545 const bool theToKeepAllCommands)
546 : _pyObject( new _pyCommand( "", 0 )),
548 myID2AccessorMethod( theEntry2AccessorMethod ),
549 myObjectNames( theObjectNames ),
550 myRemovedObjIDs( theRemovedObjIDs ),
552 myToKeepAllCommands( theToKeepAllCommands ),
553 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
554 myGeomIDNb(0), myGeomIDIndex(-1)
556 // make that GetID() to return TPythonDump::SMESHGenName()
557 GetCreationCmd()->Clear();
558 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
559 GetCreationCmd()->GetString() += "=";
561 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
562 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
566 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
567 if ( geomComp->_is_nil() ) return;
568 CORBA::String_var entry = geomComp->GetID();
571 // find a SMESH entry
573 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
574 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
575 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
578 // find 1st difference between smeshID and geomID
579 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
580 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
581 if ( geomID.Value( i ) != smeshID.Value( i ))
583 myGeomIDNb = geomID.Value( i );
589 //================================================================================
591 * \brief name of SMESH_Gen in smeshBuilder.py
593 //================================================================================
595 const char* _pyGen::AccessorMethod() const
597 return SMESH_2smeshpy::GenName();
600 //================================================================================
602 * \brief Convert a command using a specific converter
603 * \param theCommand - the command to convert
605 //================================================================================
607 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
609 // store theCommand in the sequence
610 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
612 Handle(_pyCommand) aCommand = myCommands.back();
613 #ifdef DUMP_CONVERSION
614 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
617 const _pyID& objID = aCommand->GetObject();
619 if ( objID.IsEmpty() )
622 // Prevent moving a command creating a sub-mesh to the end of the script
623 // if the sub-mesh is used in theCommand as argument
624 if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
626 PlaceSubmeshAfterItsCreation( aCommand );
629 // Method( SMESH.PointStruct(x,y,z) -> Method( [x,y,z]
630 StructToList( aCommand );
632 // Find an object to process theCommand
635 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
637 this->Process( aCommand );
638 addFilterUser( aCommand, theGen ); // protect filters from clearing
642 // SMESH_Mesh method?
643 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
644 if ( id_mesh != myMeshes.end() )
646 //id_mesh->second->AddProcessedCmd( aCommand );
648 // check for mesh editor object
649 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
650 _pyID editorID = aCommand->GetResultValue();
651 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
652 myMeshEditors.insert( make_pair( editorID, editor ));
655 // check for SubMesh objects
656 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
657 _pyID subMeshID = aCommand->GetResultValue();
658 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
659 myObjects.insert( make_pair( subMeshID, subMesh ));
662 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
663 GetIDSourceToList( aCommand );
665 addFilterUser( aCommand, theGen ); // protect filters from clearing
667 id_mesh->second->Process( aCommand );
668 id_mesh->second->AddProcessedCmd( aCommand );
672 // SMESH_MeshEditor method?
673 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
674 if ( id_editor != myMeshEditors.end() )
676 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
677 GetIDSourceToList( aCommand );
679 addFilterUser( aCommand, theGen ); // protect filters from clearing
681 const TCollection_AsciiString& method = aCommand->GetMethod();
683 // some commands of SMESH_MeshEditor create meshes and groups
684 _pyID meshID, groups;
685 if ( method.Search("MakeMesh") != -1 )
686 meshID = aCommand->GetResultValue();
687 else if ( method == "MakeBoundaryMesh")
688 meshID = aCommand->GetResultValue(1);
689 else if ( method == "MakeBoundaryElements")
690 meshID = aCommand->GetResultValue(2);
692 if ( method.Search("MakeGroups") != -1 ||
693 method == "ExtrusionAlongPathX" ||
694 method == "ExtrusionAlongPathObjX" ||
695 method == "DoubleNodeGroupNew" ||
696 method == "DoubleNodeGroupsNew" ||
697 method == "DoubleNodeElemGroupNew" ||
698 method == "DoubleNodeElemGroupsNew"||
699 method == "DoubleNodeElemGroup2New"||
700 method == "DoubleNodeElemGroups2New"
702 groups = aCommand->GetResultValue();
703 else if ( method == "MakeBoundaryMesh" )
704 groups = aCommand->GetResultValue(2);
705 else if ( method == "MakeBoundaryElements")
706 groups = aCommand->GetResultValue(3);
707 else if ( method == "Create0DElementsOnAllNodes" &&
708 aCommand->GetArg(2).Length() > 2 ) // group name != ''
709 groups = aCommand->GetResultValue();
711 id_editor->second->Process( aCommand );
712 id_editor->second->AddProcessedCmd( aCommand );
715 if ( !meshID.IsEmpty() &&
716 !myMeshes.count( meshID ) &&
717 aCommand->IsStudyEntry( meshID ))
719 TCollection_AsciiString processedCommand = aCommand->GetString();
720 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
721 myMeshes.insert( make_pair( meshID, mesh ));
723 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
726 if ( !groups.IsEmpty() )
728 if ( !aCommand->IsStudyEntry( meshID ))
729 meshID = id_editor->second->GetMesh();
730 Handle(_pyMesh) mesh = myMeshes[ meshID ];
732 list< _pyID > idList = aCommand->GetStudyEntries( groups );
733 list< _pyID >::iterator grID = idList.begin();
734 for ( ; grID != idList.end(); ++grID )
735 if ( !myObjects.count( *grID ))
737 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
739 if ( !mesh.IsNull() ) mesh->AddGroup( group );
743 } // SMESH_MeshEditor methods
745 // SMESH_Hypothesis method?
746 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
747 for ( ; hyp != myHypos.end(); ++hyp )
748 if ( !(*hyp)->IsAlgo() && objID == (*hyp)->GetID() ) {
749 (*hyp)->Process( aCommand );
750 (*hyp)->AddProcessedCmd( aCommand );
754 // aFilterManager.CreateFilter() ?
755 if ( aCommand->GetMethod() == "CreateFilter" )
757 // Set a more human readable name to a filter
758 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
759 _pyID newID, filterID = aCommand->GetResultValue();
760 int pos = filterID.Search( "0x" );
762 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
764 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
768 // other object method?
769 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
770 if ( id_obj != myObjects.end() ) {
771 id_obj->second->Process( aCommand );
772 id_obj->second->AddProcessedCmd( aCommand );
776 // Add access to a wrapped mesh
777 AddMeshAccessorMethod( aCommand );
779 // Add access to a wrapped algorithm
780 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
782 // PAL12227. PythonDump was not updated at proper time; result is
783 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
784 // TypeError: __init__() takes exactly 11 arguments (10 given)
785 const char wrongCommand[] = "SMESH.Filter.Criterion(";
786 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
788 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
789 // there must be 10 arguments, 5-th arg ThresholdID is missing,
790 const int wrongNbArgs = 9, missingArg = 5;
791 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
793 for ( int i = wrongNbArgs; i > missingArg; --i )
794 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
795 tmpCmd.SetArg( missingArg, "''");
796 aCommand->GetString().Trunc( beg - 1 );
797 aCommand->GetString() += tmpCmd.GetString();
800 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
802 // instead of "SMESH.Filter.Criterion(
803 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
804 // 1 2 3 4 5 6 7 8 9 10
805 // in order to avoid the problem of type mismatch of long and FunctorType
806 const TCollection_AsciiString
807 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
808 TCollection_AsciiString
809 Type = aCommand->GetArg(1), // long
810 Compare = aCommand->GetArg(2), // long
811 Threshold = aCommand->GetArg(3), // double
812 ThresholdStr = aCommand->GetArg(4), // string
813 ThresholdID = aCommand->GetArg(5), // string
814 UnaryOp = aCommand->GetArg(6), // long
815 BinaryOp = aCommand->GetArg(7), // long
816 Tolerance = aCommand->GetArg(8), // double
817 TypeOfElement = aCommand->GetArg(9), // ElementType
818 Precision = aCommand->GetArg(10); // long
819 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
820 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
821 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
822 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
823 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
825 if ( Compare == "SMESH.FT_EqualTo" )
828 aCommand->RemoveArgs();
829 aCommand->SetObject( SMESH_2smeshpy::GenName() );
830 aCommand->SetMethod( "GetCriterion" );
832 aCommand->SetArg( 1, TypeOfElement );
833 aCommand->SetArg( 2, Type );
834 aCommand->SetArg( 3, Compare );
836 if ( Threshold.IsIntegerValue() )
838 int iGeom = Threshold.IntegerValue();
839 if ( Type == "SMESH.FT_ElemGeomType" )
841 // set SMESH.GeometryType instead of a numerical Threshold
842 const char* types[SMESH::Geom_BALL+1] = {
843 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
844 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
845 "Geom_POLYHEDRA", "Geom_BALL" };
846 if ( -1 < iGeom && iGeom < SMESH::Geom_POLYHEDRA+1 )
847 Threshold = SMESH + types[ iGeom ];
849 if (Type == "SMESH.FT_EntityType")
851 // set SMESH.EntityType instead of a numerical Threshold
852 const char* types[SMESH::Entity_Ball+1] = {
853 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
854 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
855 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
856 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
857 "Entity_Pyramid", "Entity_Quad_Pyramid",
858 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
859 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
860 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
861 if ( -1 < iGeom && iGeom < SMESH::Entity_Quad_Polyhedra+1 )
862 Threshold = SMESH + types[ iGeom ];
865 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
866 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
867 else if ( ThresholdStr.Length() != 2 )
868 aCommand->SetArg( 4, ThresholdStr );
869 else if ( ThresholdID.Length() != 2 )
870 aCommand->SetArg( 4, ThresholdID );
872 aCommand->SetArg( 4, Threshold );
873 // find the last not default arg
875 if ( Tolerance == dfltTol ) {
877 if ( BinaryOp == dfltFunctor ) {
879 if ( UnaryOp == dfltFunctor )
883 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
884 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
885 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
886 if ( Precision != dfltPreci )
888 TCollection_AsciiString crit = aCommand->GetResultValue();
889 aCommand->GetString() += "; ";
890 aCommand->GetString() += crit + ".Precision = " + Precision;
896 //================================================================================
898 * \brief Convert the command or remember it for later conversion
899 * \param theCommand - The python command calling a method of SMESH_Gen
901 //================================================================================
903 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
905 // there are methods to convert:
906 // CreateMesh( shape )
907 // Concatenate( [mesh1, ...], ... )
908 // CreateHypothesis( theHypType, theLibName )
909 // Compute( mesh, geom )
910 // Evaluate( mesh, geom )
912 TCollection_AsciiString method = theCommand->GetMethod();
914 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
916 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
917 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
920 if ( method == "CreateMeshesFromUNV" ||
921 method == "CreateMeshesFromSTL" ||
922 method == "CopyMesh" ) // command result is a mesh
924 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
925 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
928 if( method == "CreateMeshesFromMED" ||
929 method == "CreateMeshesFromSAUV"||
930 method == "CreateMeshesFromCGNS" ||
931 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
933 for ( int ind = 0; ind < theCommand->GetNbResultValues(); ind++ )
935 _pyID meshID = theCommand->GetResultValue(ind+1);
936 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
937 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
938 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
940 if ( method == "CreateMeshesFromGMF" )
942 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
943 // CreateMeshesFromGMF( theFileName )
944 _AString file = theCommand->GetArg(1);
945 theCommand->RemoveArgs();
946 theCommand->SetArg( 1, file );
950 // CreateHypothesis()
951 if ( method == "CreateHypothesis" )
953 // issue 199929, remove standard library name (default parameter)
954 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
955 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
956 // keep first argument
957 TCollection_AsciiString arg = theCommand->GetArg( 1 );
958 theCommand->RemoveArgs();
959 theCommand->SetArg( 1, arg );
962 myHypos.push_back( _pyHypothesis::NewHypothesis( theCommand ));
966 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
967 if ( method == "Compute" )
969 const _pyID& meshID = theCommand->GetArg( 1 );
970 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
971 if ( id_mesh != myMeshes.end() ) {
972 theCommand->SetObject( meshID );
973 theCommand->RemoveArgs();
974 id_mesh->second->Process( theCommand );
975 id_mesh->second->AddProcessedCmd( theCommand );
980 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
981 if ( method == "Evaluate" )
983 const _pyID& meshID = theCommand->GetArg( 1 );
984 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
985 if ( id_mesh != myMeshes.end() ) {
986 theCommand->SetObject( meshID );
987 _pyID geom = theCommand->GetArg( 2 );
988 theCommand->RemoveArgs();
989 theCommand->SetArg( 1, geom );
990 id_mesh->second->AddProcessedCmd( theCommand );
995 // objects erasing creation command if no more its commands invoked:
996 // SMESH_Pattern, FilterManager
997 if ( method == "GetPattern" ||
998 method == "CreateFilterManager" ||
999 method == "CreateMeasurements" ) {
1000 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1001 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
1002 theCommand->Clear(); // already created
1004 // Concatenate( [mesh1, ...], ... )
1005 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1007 if ( method == "ConcatenateWithGroups" ) {
1008 theCommand->SetMethod( "Concatenate" );
1009 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1011 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1012 myMeshes.insert( make_pair( mesh->GetID(), mesh ));
1013 AddMeshAccessorMethod( theCommand );
1015 else if ( method == "SetName" ) // SetName(obj,name)
1017 // store theCommand as one of object commands to erase it along with the object
1018 const _pyID& objID = theCommand->GetArg( 1 );
1019 Handle(_pyObject) obj = FindObject( objID );
1020 if ( !obj.IsNull() )
1021 obj->AddProcessedCmd( theCommand );
1024 // Replace name of SMESH_Gen
1026 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1027 static TStringSet smeshpyMethods;
1028 if ( smeshpyMethods.empty() ) {
1029 const char * names[] =
1030 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1031 "GetPattern","GetSubShapesId",
1032 "" }; // <- mark of array end
1033 smeshpyMethods.Insert( names );
1035 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1036 // smeshgen.Method() --> smesh.Method()
1037 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1039 // smeshgen.Method() --> smesh.Method()
1040 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1043 //================================================================================
1045 * \brief Convert the remembered commands
1047 //================================================================================
1049 void _pyGen::Flush()
1051 // create an empty command
1052 myLastCommand = new _pyCommand();
1054 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1055 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1056 list< Handle(_pyHypothesis) >::iterator hyp;
1058 if ( IsToKeepAllCommands() ) // historical dump
1060 // set myIsPublished = true to all objects
1061 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1062 id_mesh->second->SetRemovedFromStudy( false );
1063 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1064 (*hyp)->SetRemovedFromStudy( false );
1065 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1066 id_obj->second->SetRemovedFromStudy( false );
1070 // let hypotheses find referred objects in order to prevent clearing
1071 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1072 list< Handle(_pyMesh) > fatherMeshes;
1073 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1074 if ( !hyp->IsNull() )
1075 (*hyp)->GetReferredMeshesAndGeom( fatherMeshes );
1077 // set myIsPublished = false to all objects depending on
1078 // meshes built on a removed geometry
1079 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1080 if ( id_mesh->second->IsNotGeomPublished() )
1081 id_mesh->second->SetRemovedFromStudy( true );
1084 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1085 if ( ! id_mesh->second.IsNull() )
1086 id_mesh->second->Flush();
1089 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1090 if ( !hyp->IsNull() ) {
1092 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1093 if ( !(*hyp)->IsWrapped() )
1094 (*hyp)->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1097 // Flush other objects
1098 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1099 if ( ! id_obj->second.IsNull() )
1100 id_obj->second->Flush();
1102 myLastCommand->SetOrderNb( ++myNbCommands );
1103 myCommands.push_back( myLastCommand );
1106 //================================================================================
1108 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1109 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1111 //================================================================================
1113 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1115 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1116 for ( ; id_obj != myObjects.end(); ++id_obj )
1118 if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1119 for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1121 const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1122 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1124 list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1125 list< _pyID >::iterator id = idList.begin();
1126 for ( ; id != idList.end(); ++id )
1127 if ( id_obj->first == *id )
1128 // _pySubMesh::Process() does what we need
1129 Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1134 //================================================================================
1136 * \brief Clean commmands of removed objects depending on myIsPublished flag
1138 //================================================================================
1140 void _pyGen::ClearCommands()
1142 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1143 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1144 id_mesh->second->ClearCommands();
1146 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1147 for ( ; hyp != myHypos.end(); ++hyp )
1148 if ( !hyp->IsNull() )
1149 (*hyp)->ClearCommands();
1151 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1152 for ( ; id_obj != myObjects.end(); ++id_obj )
1153 id_obj->second->ClearCommands();
1156 //================================================================================
1158 * \brief Release mutual handles of objects
1160 //================================================================================
1164 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1165 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1166 id_mesh->second->Free();
1169 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1170 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1171 id_ed->second->Free();
1172 myMeshEditors.clear();
1174 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1175 for ( ; id_obj != myObjects.end(); ++id_obj )
1176 id_obj->second->Free();
1179 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1180 for ( ; hyp != myHypos.end(); ++hyp )
1181 if ( !hyp->IsNull() )
1185 myFile2ExportedMesh.clear();
1188 //================================================================================
1190 * \brief Add access method to mesh that is an argument
1191 * \param theCmd - command to add access method
1192 * \retval bool - true if added
1194 //================================================================================
1196 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1199 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1200 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1201 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1207 //================================================================================
1209 * \brief Add access method to algo that is an object or an argument
1210 * \param theCmd - command to add access method
1211 * \retval bool - true if added
1213 //================================================================================
1215 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1218 list< Handle(_pyHypothesis) >::const_iterator hyp = myHypos.begin();
1219 for ( ; hyp != myHypos.end(); ++hyp ) {
1220 if ( (*hyp)->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1221 theCmd->AddAccessorMethod( (*hyp)->GetID(), (*hyp)->AccessorMethod() ))
1227 //================================================================================
1229 * \brief Find hypothesis by ID (entry)
1230 * \param theHypID - The hypothesis ID
1231 * \retval Handle(_pyHypothesis) - The found hypothesis
1233 //================================================================================
1235 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1237 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1238 for ( ; hyp != myHypos.end(); ++hyp )
1239 if ( !hyp->IsNull() && theHypID == (*hyp)->GetID() )
1241 return Handle(_pyHypothesis)();
1244 //================================================================================
1246 * \brief Find algorithm the created algorithm
1247 * \param theGeom - The shape ID the algorithm was created on
1248 * \param theMesh - The mesh ID that created the algorithm
1249 * \param dim - The algo dimension
1250 * \retval Handle(_pyHypothesis) - The found algo
1252 //================================================================================
1254 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1255 const Handle(_pyHypothesis)& theHypothesis )
1257 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1258 for ( ; hyp != myHypos.end(); ++hyp )
1259 if ( !hyp->IsNull() &&
1261 theHypothesis->CanBeCreatedBy( (*hyp)->GetAlgoType() ) &&
1262 (*hyp)->GetGeom() == theGeom &&
1263 (*hyp)->GetMesh() == theMesh )
1268 //================================================================================
1270 * \brief Find subMesh by ID (entry)
1271 * \param theSubMeshID - The subMesh ID
1272 * \retval Handle(_pySubMesh) - The found subMesh
1274 //================================================================================
1276 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1278 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1279 if ( id_subMesh != myObjects.end() )
1280 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1281 return Handle(_pySubMesh)();
1285 //================================================================================
1287 * \brief Change order of commands in the script
1288 * \param theCmd1 - One command
1289 * \param theCmd2 - Another command
1291 //================================================================================
1293 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1295 list< Handle(_pyCommand) >::iterator pos1, pos2;
1296 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1297 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1298 myCommands.insert( pos1, theCmd2 );
1299 myCommands.insert( pos2, theCmd1 );
1300 myCommands.erase( pos1 );
1301 myCommands.erase( pos2 );
1303 int nb1 = theCmd1->GetOrderNb();
1304 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1305 theCmd2->SetOrderNb( nb1 );
1306 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1307 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1310 //================================================================================
1312 * \brief Set one command after the other
1313 * \param theCmd - Command to move
1314 * \param theAfterCmd - Command ater which to insert the first one
1316 //================================================================================
1318 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1320 setNeighbourCommand( theCmd, theAfterCmd, true );
1323 //================================================================================
1325 * \brief Set one command before the other
1326 * \param theCmd - Command to move
1327 * \param theBeforeCmd - Command before which to insert the first one
1329 //================================================================================
1331 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1333 setNeighbourCommand( theCmd, theBeforeCmd, false );
1336 //================================================================================
1338 * \brief Set one command before or after the other
1339 * \param theCmd - Command to move
1340 * \param theOtherCmd - Command ater or before which to insert the first one
1342 //================================================================================
1344 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1345 Handle(_pyCommand)& theOtherCmd,
1346 const bool theIsAfter )
1348 list< Handle(_pyCommand) >::iterator pos;
1349 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1350 myCommands.erase( pos );
1351 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1352 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1355 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1356 (*pos)->SetOrderNb( i++ );
1359 //================================================================================
1361 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1363 //================================================================================
1365 void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1367 const char filterPrefix[] = "aFilter0x";
1368 if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1371 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1373 const _AString & arg = theCommand->GetArg( i );
1374 // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1375 if ( arg.Search( filterPrefix ) != 1 )
1378 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1379 if ( !filter.IsNull() )
1381 filter->AddUser( user );
1382 if ( !filter->GetNewID().IsEmpty() )
1383 theCommand->SetArg( i, filter->GetNewID() );
1388 //================================================================================
1390 * \brief Set command be last in list of commands
1391 * \param theCmd - Command to be last
1393 //================================================================================
1395 Handle(_pyCommand)& _pyGen::GetLastCommand()
1397 return myLastCommand;
1400 //================================================================================
1402 * \brief Set method to access to object wrapped with python class
1403 * \param theID - The wrapped object entry
1404 * \param theMethod - The accessor method
1406 //================================================================================
1408 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1410 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1413 //================================================================================
1415 * \brief Generated new ID for object and assign with existing name
1416 * \param theID - ID of existing object
1418 //================================================================================
1420 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1425 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1427 while ( myObjectNames.IsBound( aNewID ) );
1429 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1430 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1431 : _pyID( "A" ) + aNewID );
1435 //================================================================================
1437 * \brief Stores theObj in myObjects
1439 //================================================================================
1441 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1443 if ( theObj.IsNull() ) return;
1445 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1446 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1448 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1449 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1452 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1455 //================================================================================
1457 * \brief Re-register an object with other ID to make it Process() commands of
1458 * other object having this ID
1460 //================================================================================
1462 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1464 if ( theObj.IsNull() ) return;
1466 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1467 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1469 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1470 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1473 myObjects.insert( make_pair( theID, theObj ));
1476 //================================================================================
1478 * \brief Finds a _pyObject by ID
1480 //================================================================================
1482 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1485 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1486 if ( id_obj != myObjects.end() )
1487 return id_obj->second;
1490 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1491 if ( id_obj != myMeshes.end() )
1492 return id_obj->second;
1495 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1496 // if ( id_obj != myMeshEditors.end() )
1497 // return id_obj->second;
1499 return Handle(_pyObject)();
1502 //================================================================================
1504 * \brief Check if a study entry is under GEOM component
1506 //================================================================================
1508 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1512 return ( myGeomIDIndex <= theObjID.Length() &&
1513 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1514 _pyCommand::IsStudyEntry( theObjID ));
1519 //================================================================================
1521 * \brief Returns true if an object is not present in a study
1523 //================================================================================
1525 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1527 if ( theObjID.IsEmpty() ) return false;
1529 if ( myObjectNames.IsBound( theObjID ))
1530 return false; // SMESH object is in study
1532 // either the SMESH object is not in study or it is a GEOM object
1533 if ( IsGeomObject( theObjID ))
1535 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1536 if ( so->_is_nil() ) return true;
1537 CORBA::Object_var obj = so->GetObject();
1538 return CORBA::is_nil( obj );
1540 return true; // SMESH object not in study
1543 //================================================================================
1545 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1546 * this object is not dumped
1547 * \param [in] theObjID - entry of the object whose creation command was eliminated
1549 //================================================================================
1551 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1553 myRemovedObjIDs.insert( theObjID );
1556 //================================================================================
1558 * \brief Return reader of hypotheses of plugins
1560 //================================================================================
1562 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1564 if (myHypReader.IsNull() )
1565 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1571 //================================================================================
1573 * \brief Mesh created by SMESH_Gen
1575 //================================================================================
1577 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1578 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1580 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1581 myGeomNotInStudy = true;
1583 // convert my creation command --> smeshpy.Mesh(...)
1584 Handle(_pyCommand) creationCmd = GetCreationCmd();
1585 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1586 creationCmd->SetMethod( "Mesh" );
1587 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1590 //================================================================================
1592 * \brief Mesh created by SMESH_MeshEditor
1594 //================================================================================
1596 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1597 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1599 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1601 // this mesh depends on the exported mesh
1602 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1603 if ( !file.IsEmpty() )
1605 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1606 addFatherMesh( exportData.myMesh );
1607 if ( !exportData.myLastComputeCmd.IsNull() )
1609 // restore cleared Compute() by which the exported mesh was generated
1610 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1611 // protect that Compute() cmd from clearing
1612 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1613 exportData.myMesh->myLastComputeCmd.Nullify();
1617 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1619 // this mesh depends on concatenated meshes
1620 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1621 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1622 list< _pyID >::iterator meshID = idList.begin();
1623 for ( ; meshID != idList.end(); ++meshID )
1624 addFatherMesh( *meshID );
1626 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1628 // this mesh depends on a copied IdSource
1629 const _pyID& objID = theCreationCmd->GetArg( 1 );
1630 addFatherMesh( objID );
1632 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1633 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1634 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1636 // this mesh depends on a source mesh
1637 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1638 const _pyID& meshID = theCreationCmd->GetObject();
1639 addFatherMesh( meshID );
1642 // convert my creation command
1643 Handle(_pyCommand) creationCmd = GetCreationCmd();
1644 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1645 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1648 //================================================================================
1650 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1651 * \param theCommand - Engine method called for this mesh
1653 //================================================================================
1655 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1657 // some methods of SMESH_Mesh interface needs special conversion
1658 // to methods of Mesh python class
1660 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1661 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1662 // 2. AddHypothesis(geom, hyp)
1663 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1664 // 3. CreateGroupFromGEOM(type, name, grp)
1665 // --> in Mesh.Group(grp, name="")
1666 // 4. ExportToMED(f, auto_groups, version)
1667 // --> in Mesh.ExportMED( f, auto_groups, version )
1670 const TCollection_AsciiString& method = theCommand->GetMethod();
1671 // ----------------------------------------------------------------------
1672 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1674 if ( !theGen->IsToKeepAllCommands() ) // !historical
1676 list< Handle(_pyHypothesis) >::iterator hyp;
1677 if ( !myLastComputeCmd.IsNull() )
1679 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1680 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1682 myLastComputeCmd->Clear();
1684 myLastComputeCmd = theCommand;
1686 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1687 (*hyp)->MeshComputed( myLastComputeCmd );
1691 // ----------------------------------------------------------------------
1692 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1694 if ( !theGen->IsToKeepAllCommands() ) // !historical
1697 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1698 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1699 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1701 if ( !myLastComputeCmd.IsNull() )
1703 list< Handle(_pyHypothesis) >::iterator hyp;
1704 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1705 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1707 myLastComputeCmd->Clear();
1710 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1711 for ( ; e != myEditors.end(); ++e )
1713 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1714 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1715 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1716 if ( !(*cmd)->IsEmpty() )
1718 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1722 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1725 // ----------------------------------------------------------------------
1726 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1727 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1728 if ( !subMesh.IsNull() ) {
1729 subMesh->SetCreator( this );
1730 mySubmeshes.push_back( subMesh );
1733 // ----------------------------------------------------------------------
1734 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1735 myAddHypCmds.push_back( theCommand );
1737 const _pyID& hypID = theCommand->GetArg( 2 );
1738 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1739 if ( !hyp.IsNull() ) {
1740 myHypos.push_back( hyp );
1741 if ( hyp->GetMesh().IsEmpty() )
1742 hyp->SetMesh( this->GetID() );
1745 // ----------------------------------------------------------------------
1746 else if ( method == "CreateGroup" ||
1747 method == "CreateGroupFromGEOM" ||
1748 method == "CreateGroupFromFilter" )
1750 Handle(_pyGroup) group = new _pyGroup( theCommand );
1751 myGroups.push_back( group );
1752 theGen->AddObject( group );
1754 // ----------------------------------------------------------------------
1755 // update list of groups
1756 else if ( method == "GetGroups" )
1758 bool allGroupsRemoved = true;
1759 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1760 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1761 list< _pyID >::iterator grID = idList.begin();
1762 const int nbGroupsBefore = myGroups.size();
1763 Handle(_pyObject) obj;
1764 for ( ; grID != idList.end(); ++grID )
1766 obj = theGen->FindObject( *grID );
1769 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1770 theGen->AddObject( group );
1771 myGroups.push_back( group );
1774 if ( !obj->CanClear() )
1775 allGroupsRemoved = false;
1777 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1778 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1780 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1782 // check if the preceding command is Compute();
1783 // if GetGroups() is just after Compute(), this can mean that the groups
1784 // were created by some algorithm and hence Compute() should not be discarded
1785 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1786 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1787 while ( (*cmd)->GetMethod() == "GetGroups" )
1789 if ( myLastComputeCmd == (*cmd))
1790 // protect last Compute() from clearing by the next Compute()
1791 myLastComputeCmd.Nullify();
1794 // ----------------------------------------------------------------------
1795 // notify a group about full removal
1796 else if ( method == "RemoveGroupWithContents" ||
1797 method == "RemoveGroup")
1799 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1800 const _pyID groupID = theCommand->GetArg( 1 );
1801 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1802 if ( !grp.IsNull() )
1804 if ( method == "RemoveGroupWithContents" )
1805 grp->RemovedWithContents();
1806 // to clear RemoveGroup() if the group creation is cleared
1807 grp->AddProcessedCmd( theCommand );
1811 // ----------------------------------------------------------------------
1812 else if ( theCommand->MethodStartsFrom( "Export" ))
1814 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1815 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1817 theCommand->SetMethod( "ExportMED" );
1818 if ( theCommand->GetNbArgs() == 5 )
1820 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1821 _AString autoDimension = theCommand->GetArg( 5 );
1822 theCommand->SetArg( 5, "None" );
1823 theCommand->SetArg( 6, autoDimension );
1826 else if ( method == "ExportCGNS" )
1827 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1828 _pyID partID = theCommand->GetArg( 1 );
1829 int nbArgs = theCommand->GetNbArgs();
1830 for ( int i = 2; i <= nbArgs; ++i )
1831 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1832 theCommand->SetArg( nbArgs, partID );
1834 else if ( method == "ExportGMF" )
1835 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1836 _pyID partID = theCommand->GetArg( 1 );
1837 _AString file = theCommand->GetArg( 2 );
1838 theCommand->RemoveArgs();
1839 theCommand->SetArg( 1, file );
1840 theCommand->SetArg( 2, partID );
1842 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1843 { // ExportPartTo*(part, ...) -> Export*(..., part)
1845 // remove "PartTo" from the method
1846 TCollection_AsciiString newMethod = method;
1847 newMethod.Remove( 7, 6 );
1848 theCommand->SetMethod( newMethod );
1849 // make the 1st arg be the last one (or last but one for ExportMED())
1850 _pyID partID = theCommand->GetArg( 1 );
1851 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1852 for ( int i = 2; i <= nbArgs; ++i )
1853 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1854 theCommand->SetArg( nbArgs, partID );
1856 // remember file name
1857 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1858 ExportedMeshData( this, myLastComputeCmd ));
1860 // ----------------------------------------------------------------------
1861 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1863 _pyID hypID = theCommand->GetArg( 2 );
1864 _pyID geomID = theCommand->GetArg( 1 );
1865 bool isLocal = ( geomID != GetGeom() );
1867 // check if this mesh still has corresponding addition command
1868 Handle(_pyCommand) addCmd;
1869 list< Handle(_pyCommand) >::iterator cmd;
1870 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1871 for ( int i = 0; i < 2; ++i )
1873 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1874 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1876 bool sameHyp = true;
1877 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1878 sameHyp = false; // other hyp
1879 if ( (*cmd)->GetNbArgs() == 2 &&
1880 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1881 sameHyp = false; // other geom
1882 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1883 sameHyp = false; // other geom
1887 cmd = addHypCmds.erase( cmd );
1888 if ( !theGen->IsToKeepAllCommands() ) {
1890 theCommand->Clear();
1899 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1900 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1901 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
1902 _pyID geom = theCommand->GetArg( 1 );
1903 theCommand->RemoveArgs();
1904 theCommand->SetArg( 1, hypID );
1905 if ( geom != GetGeom() )
1906 theCommand->SetArg( 2, geom );
1908 // remove hyp from myHypos
1909 myHypos.remove( hyp );
1911 // check for SubMesh order commands
1912 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
1914 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
1915 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
1916 // commands are moved at the end of the script
1917 TCollection_AsciiString subIDs =
1918 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
1919 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
1920 list< _pyID >::iterator subID = idList.begin();
1921 for ( ; subID != idList.end(); ++subID )
1923 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
1924 if ( !subMesh.IsNull() )
1925 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
1928 // add accessor method if necessary
1931 if ( NeedMeshAccess( theCommand ))
1932 // apply theCommand to the mesh wrapped by smeshpy mesh
1933 AddMeshAccess( theCommand );
1937 //================================================================================
1939 * \brief Return True if addition of accesor method is needed
1941 //================================================================================
1943 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
1945 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
1946 // so no conversion is needed for them at all:
1947 static TStringSet sameMethods;
1948 if ( sameMethods.empty() ) {
1949 const char * names[] =
1950 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
1951 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
1952 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
1953 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
1954 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
1955 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
1956 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
1957 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
1958 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
1959 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
1960 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
1961 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
1962 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
1963 ,"" }; // <- mark of end
1964 sameMethods.Insert( names );
1967 return !sameMethods.Contains( theCommand->GetMethod() );
1970 //================================================================================
1972 * \brief Convert creation and addition of all algos and hypos
1974 //================================================================================
1976 void _pyMesh::Flush()
1979 // get the meshes this mesh depends on via hypotheses
1980 list< Handle(_pyMesh) > fatherMeshes;
1981 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
1982 for ( ; hyp != myHypos.end(); ++hyp )
1983 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
1984 myGeomNotInStudy = true;
1986 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
1987 for ( ; m != fatherMeshes.end(); ++m )
1988 addFatherMesh( *m );
1989 // if ( removedGeom )
1990 // SetRemovedFromStudy(); // as reffered geometry not in study
1992 if ( myGeomNotInStudy )
1995 list < Handle(_pyCommand) >::iterator cmd;
1997 // try to convert algo addition like this:
1998 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
1999 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2001 Handle(_pyCommand) addCmd = *cmd;
2003 _pyID algoID = addCmd->GetArg( 2 );
2004 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2005 if ( algo.IsNull() || !algo->IsAlgo() )
2008 // check and create new algorithm instance if it is already wrapped
2009 if ( algo->IsWrapped() ) {
2010 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2011 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2012 TCollection_AsciiString( " = " ) + theGen->GetID() +
2013 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2014 TCollection_AsciiString( "\" )" );
2016 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2017 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2018 if ( !newAlgo.IsNull() ) {
2019 newAlgo->Assign( algo, this->GetID() );
2020 newAlgo->SetCreationCmd( newCmd );
2022 // set algorithm creation
2023 theGen->SetCommandBefore( newCmd, addCmd );
2024 myHypos.push_back( newAlgo );
2025 if ( !myLastComputeCmd.IsNull() &&
2026 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2027 newAlgo->MeshComputed( myLastComputeCmd );
2032 _pyID geom = addCmd->GetArg( 1 );
2033 bool isLocalAlgo = ( geom != GetGeom() );
2036 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2038 // wrapped algo is created after mesh creation
2039 GetCreationCmd()->AddDependantCmd( addCmd );
2041 if ( isLocalAlgo ) {
2042 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2043 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2044 TCollection_AsciiString( "geom=" ) + geom );
2045 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2046 list < Handle(_pySubMesh) >::iterator smIt;
2047 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2048 Handle(_pySubMesh) subMesh = *smIt;
2049 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2050 if ( geom == subCmd->GetArg( 1 )) {
2051 subCmd->SetObject( algo->GetID() );
2052 subCmd->RemoveArgs();
2053 subMesh->SetCreator( algo );
2058 else // KO - ALGO was already created
2060 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2061 addCmd->RemoveArgs();
2062 addCmd->SetArg( 1, algoID );
2064 addCmd->SetArg( 2, geom );
2065 myNotConvertedAddHypCmds.push_back( addCmd );
2069 // try to convert hypo addition like this:
2070 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2071 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2073 Handle(_pyCommand) addCmd = *cmd;
2074 _pyID hypID = addCmd->GetArg( 2 );
2075 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2076 if ( hyp.IsNull() || hyp->IsAlgo() )
2078 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2080 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2081 _pyID geom = addCmd->GetArg( 1 );
2082 addCmd->RemoveArgs();
2083 addCmd->SetArg( 1, hypID );
2084 if ( geom != GetGeom() )
2085 addCmd->SetArg( 2, geom );
2086 myNotConvertedAddHypCmds.push_back( addCmd );
2090 myAddHypCmds.clear();
2091 mySubmeshes.clear();
2094 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2095 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2099 //================================================================================
2101 * \brief Sets myIsPublished of me and of all objects depending on me.
2103 //================================================================================
2105 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2107 _pyObject::SetRemovedFromStudy(isRemoved);
2109 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2110 for ( ; sm != mySubmeshes.end(); ++sm )
2111 (*sm)->SetRemovedFromStudy(isRemoved);
2113 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2114 for ( ; gr != myGroups.end(); ++gr )
2115 (*gr)->SetRemovedFromStudy(isRemoved);
2117 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2118 for ( ; m != myChildMeshes.end(); ++m )
2119 (*m)->SetRemovedFromStudy(isRemoved);
2121 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2122 for ( ; e != myEditors.end(); ++e )
2123 (*e)->SetRemovedFromStudy(isRemoved);
2126 //================================================================================
2128 * \brief Return true if none of myChildMeshes is in study
2130 //================================================================================
2132 bool _pyMesh::CanClear()
2137 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2138 for ( ; m != myChildMeshes.end(); ++m )
2139 if ( !(*m)->CanClear() )
2145 //================================================================================
2147 * \brief Clear my commands and commands of mesh editor
2149 //================================================================================
2151 void _pyMesh::ClearCommands()
2157 // mark all sub-objects as not removed, except child meshes
2158 list< Handle(_pyMesh) > children;
2159 children.swap( myChildMeshes );
2160 SetRemovedFromStudy( false );
2161 children.swap( myChildMeshes );
2165 _pyObject::ClearCommands();
2167 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2168 for ( ; sm != mySubmeshes.end(); ++sm )
2169 (*sm)->ClearCommands();
2171 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2172 for ( ; gr != myGroups.end(); ++gr )
2173 (*gr)->ClearCommands();
2175 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2176 for ( ; e != myEditors.end(); ++e )
2177 (*e)->ClearCommands();
2180 //================================================================================
2182 * \brief Add a father mesh by ID
2184 //================================================================================
2186 void _pyMesh::addFatherMesh( const _pyID& meshID )
2188 if ( !meshID.IsEmpty() && meshID != GetID() )
2189 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2192 //================================================================================
2194 * \brief Add a father mesh
2196 //================================================================================
2198 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2200 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2202 //myFatherMeshes.push_back( mesh );
2203 mesh->myChildMeshes.push_back( this );
2205 // protect last Compute() from clearing by the next Compute()
2206 mesh->myLastComputeCmd.Nullify();
2210 //================================================================================
2212 * \brief MeshEditor convert its commands to ones of mesh
2214 //================================================================================
2216 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2217 _pyObject( theCreationCmd )
2219 myMesh = theCreationCmd->GetObject();
2220 myCreationCmdStr = theCreationCmd->GetString();
2221 theCreationCmd->Clear();
2223 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2224 if ( !mesh.IsNull() )
2225 mesh->AddEditor( this );
2228 //================================================================================
2230 * \brief convert its commands to ones of mesh
2232 //================================================================================
2234 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2236 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2237 // commands calling these methods are converted to calls of Mesh methods without
2238 // additional modifs, only object is changed from MeshEditor to Mesh.
2239 static TStringSet sameMethods;
2240 if ( sameMethods.empty() ) {
2241 const char * names[] = {
2242 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2243 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2244 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2245 "MoveNode", "MoveClosestNodeToPoint",
2246 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2247 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2248 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2249 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2250 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2251 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2252 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2253 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2254 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2255 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2256 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2257 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2258 "GetLastCreatedElems",
2259 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2260 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2261 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2262 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2263 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2264 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2265 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2266 ,"" }; // <- mark of the end
2267 sameMethods.Insert( names );
2270 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2271 TStringMap diffMethods;
2272 if ( diffMethods.empty() ) {
2273 const char * orig2newName[] = {
2274 // original name --------------> new name
2275 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2276 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2277 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2278 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2279 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2280 ""};// <- mark of the end
2281 diffMethods.Insert( orig2newName );
2284 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2285 // only by last two arguments
2286 static TStringSet diffLastTwoArgsMethods;
2287 if (diffLastTwoArgsMethods.empty() ) {
2288 const char * names[] = {
2289 "MirrorMakeGroups","MirrorObjectMakeGroups",
2290 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2291 "RotateMakeGroups","RotateObjectMakeGroups",
2292 ""};// <- mark of the end
2293 diffLastTwoArgsMethods.Insert( names );
2296 // only a method name is to change?
2297 const TCollection_AsciiString & method = theCommand->GetMethod();
2298 bool isPyMeshMethod = sameMethods.Contains( method );
2299 if ( !isPyMeshMethod )
2301 TCollection_AsciiString newMethod = diffMethods.Value( method );
2302 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2303 theCommand->SetMethod( newMethod );
2305 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2306 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2308 isPyMeshMethod = true;
2309 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2310 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2313 if ( !isPyMeshMethod )
2315 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2316 // functions with the flag "theMakeGroups = True" like:
2317 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2318 int pos = method.Search("MakeGroups");
2321 isPyMeshMethod = true;
2322 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2323 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2325 // 1. Remove "MakeGroups" from the Command
2326 TCollection_AsciiString aMethod = theCommand->GetMethod();
2327 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2330 pos = pos-2; //Remove "0D" from the Command too
2331 aMethod.Trunc(pos-1);
2332 theCommand->SetMethod(aMethod);
2334 // 2. And add last "True" argument(s)
2335 while(nbArgsToAdd--)
2336 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2337 if( is0DmethId || is0DmethObj )
2338 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2342 // ExtrusionSweep0D() -> ExtrusionSweep()
2343 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2344 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2345 method == "ExtrusionSweepObject0D" ))
2347 isPyMeshMethod = true;
2348 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2349 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2350 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2353 // DoubleNode...New(...) -> DoubleNode...(...,True)
2354 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2355 method == "DoubleNodeElemGroupsNew" ||
2356 method == "DoubleNodeGroupNew" ||
2357 method == "DoubleNodeGroupsNew" ||
2358 method == "DoubleNodeElemGroup2New" ||
2359 method == "DoubleNodeElemGroups2New"))
2361 isPyMeshMethod = true;
2362 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2363 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2364 if ( excessLen == 3 )
2366 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2368 else if ( theCommand->GetArg(4) == "0" ||
2369 theCommand->GetArg(5) == "0" )
2371 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2372 // Group = DoubleNodeGroup2New(,,,False, True)
2373 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2374 theCommand->SetResultValue( groupID );
2377 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2378 // FindElementsByPoint(x, y, z, elementType, meshPart)
2379 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2381 isPyMeshMethod = true;
2382 theCommand->SetMethod( "FindElementsByPoint" );
2383 // make the 1st arg be the last one
2384 _pyID partID = theCommand->GetArg( 1 );
2385 int nbArgs = theCommand->GetNbArgs();
2386 for ( int i = 2; i <= nbArgs; ++i )
2387 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2388 theCommand->SetArg( nbArgs, partID );
2390 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2391 if ( !isPyMeshMethod && method == "Reorient2D" )
2393 isPyMeshMethod = true;
2394 _AString mesh = theCommand->GetArg( 1 );
2395 _AString dir = theCommand->GetArg( 2 );
2396 _AString face = theCommand->GetArg( 3 );
2397 _AString point = theCommand->GetArg( 4 );
2398 theCommand->RemoveArgs();
2399 theCommand->SetArg( 1, mesh );
2400 theCommand->SetArg( 2, dir );
2401 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2402 theCommand->SetArg( 3, point );
2404 theCommand->SetArg( 3, face );
2407 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2409 isPyMeshMethod = true;
2410 int crit_arg = theCommand->GetNbArgs();
2411 const _AString& crit = theCommand->GetArg(crit_arg);
2412 if (crit.Search("MaxElementLength2D") != -1)
2413 theCommand->SetArg(crit_arg, "");
2416 if ( isPyMeshMethod )
2418 theCommand->SetObject( myMesh );
2422 // editor creation command is needed only if any editor function is called
2423 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2424 if ( !myCreationCmdStr.IsEmpty() ) {
2425 GetCreationCmd()->GetString() = myCreationCmdStr;
2426 myCreationCmdStr.Clear();
2431 //================================================================================
2433 * \brief Return true if my mesh can be removed
2435 //================================================================================
2437 bool _pyMeshEditor::CanClear()
2439 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2440 return mesh.IsNull() ? true : mesh->CanClear();
2443 //================================================================================
2445 * \brief _pyHypothesis constructor
2446 * \param theCreationCmd -
2448 //================================================================================
2450 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2451 _pyObject( theCreationCmd ), myCurCrMethod(0)
2453 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2456 //================================================================================
2458 * \brief Creates algorithm or hypothesis
2459 * \param theCreationCmd - The engine command creating a hypothesis
2460 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2462 //================================================================================
2464 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2466 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2467 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2469 Handle(_pyHypothesis) hyp, algo;
2472 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2473 if ( hypTypeQuoted.IsEmpty() )
2476 TCollection_AsciiString hypType =
2477 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2479 algo = new _pyAlgorithm( theCreationCmd );
2480 hyp = new _pyHypothesis( theCreationCmd );
2482 if ( hypType == "NumberOfSegments" ) {
2483 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2484 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2485 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2486 hyp->AddArgMethod( "SetNumberOfSegments" );
2487 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2488 hyp->AddArgMethod( "SetScaleFactor" );
2489 hyp->AddArgMethod( "SetReversedEdges" );
2490 // same for ""CompositeSegment_1D:
2491 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2492 hyp->AddArgMethod( "SetNumberOfSegments" );
2493 hyp->AddArgMethod( "SetScaleFactor" );
2494 hyp->AddArgMethod( "SetReversedEdges" );
2496 else if ( hypType == "SegmentLengthAroundVertex" ) {
2497 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2498 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2499 hyp->AddArgMethod( "SetLength" );
2500 // same for ""CompositeSegment_1D:
2501 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2502 hyp->AddArgMethod( "SetLength" );
2504 else if ( hypType == "LayerDistribution2D" ) {
2505 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2506 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2508 else if ( hypType == "LayerDistribution" ) {
2509 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2510 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2512 else if ( hypType == "CartesianParameters3D" ) {
2513 hyp = new _pyComplexParamHypo( theCreationCmd );
2514 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2515 for ( int iArg = 0; iArg < 4; ++iArg )
2516 hyp->setCreationArg( iArg+1, "[]");
2520 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2523 return algo->IsValid() ? algo : hyp;
2526 //================================================================================
2528 * \brief Returns true if addition of this hypothesis to a given mesh can be
2529 * wrapped into hypothesis creation
2531 //================================================================================
2533 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2535 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2537 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2538 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2544 //================================================================================
2546 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2547 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2548 * \param theAlgo - The algo that can create this hypo
2549 * \retval bool - false if the command cant be converted
2551 //================================================================================
2553 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2554 const _pyID& theMesh)
2556 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2558 if ( !IsWrappable( theMesh ))
2561 myGeom = theCmd->GetArg( 1 );
2563 Handle(_pyHypothesis) algo;
2565 // find algo created on myGeom in theMesh
2566 algo = theGen->FindAlgo( myGeom, theMesh, this );
2567 if ( algo.IsNull() )
2569 // attach hypothesis creation command to be after algo creation command
2570 // because it can be new created instance of algorithm
2571 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2575 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2576 theCmd->SetResultValue( GetID() );
2577 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2578 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2579 // set args (geom will be set by _pyMesh calling this method)
2580 theCmd->RemoveArgs();
2581 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2582 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2583 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2585 theCmd->SetArg( i+1, "[]");
2587 // set a new creation command
2588 GetCreationCmd()->Clear();
2589 // replace creation command by wrapped instance
2590 // please note, that hypothesis attaches to algo creation command (see upper)
2591 SetCreationCmd( theCmd );
2594 // clear commands setting arg values
2595 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2596 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2599 // set unknown arg commands after hypo creation
2600 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2601 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2602 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2603 afterCmd->AddDependantCmd( *cmd );
2609 //================================================================================
2611 * \brief Remember hypothesis parameter values
2612 * \param theCommand - The called hypothesis method
2614 //================================================================================
2616 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2618 ASSERT( !myIsAlgo );
2619 if ( !theGen->IsToKeepAllCommands() )
2620 rememberCmdOfParameter( theCommand );
2622 bool usedCommand = false;
2623 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2624 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2626 CreationMethod& crMethod = type2meth->second;
2627 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2628 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2630 myArgCommands.push_back( theCommand );
2632 while ( crMethod.myArgs.size() < i+1 )
2633 crMethod.myArgs.push_back( "[]" );
2634 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2639 myUnusedCommands.push_back( theCommand );
2642 //================================================================================
2644 * \brief Finish conversion
2646 //================================================================================
2648 void _pyHypothesis::Flush()
2652 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2653 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2654 // Add access to a wrapped mesh
2655 theGen->AddMeshAccessorMethod( *cmd );
2656 // Add access to a wrapped algorithm
2657 theGen->AddAlgoAccessorMethod( *cmd );
2659 cmd = myUnusedCommands.begin();
2660 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2661 // Add access to a wrapped mesh
2662 theGen->AddMeshAccessorMethod( *cmd );
2663 // Add access to a wrapped algorithm
2664 theGen->AddAlgoAccessorMethod( *cmd );
2667 // forget previous hypothesis modifications
2668 myArgCommands.clear();
2669 myUnusedCommands.clear();
2672 //================================================================================
2674 * \brief clear creation, arg and unkown commands
2676 //================================================================================
2678 void _pyHypothesis::ClearAllCommands()
2680 GetCreationCmd()->Clear();
2681 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2682 for ( ; cmd != myArgCommands.end(); ++cmd )
2684 cmd = myUnusedCommands.begin();
2685 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2690 //================================================================================
2692 * \brief Assign fields of theOther to me except myIsWrapped
2694 //================================================================================
2696 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2697 const _pyID& theMesh )
2699 // myCreationCmd = theOther->myCreationCmd;
2700 myIsAlgo = theOther->myIsAlgo;
2701 myIsWrapped = false;
2702 myGeom = theOther->myGeom;
2704 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2705 myAccumulativeMethods = theOther->myAccumulativeMethods;
2706 //myUnusedCommands = theOther->myUnusedCommands;
2707 // init myCurCrMethod
2708 GetCreationMethod( theOther->GetAlgoType() );
2711 //================================================================================
2713 * \brief Analyze my erasability depending on myReferredObjs
2715 //================================================================================
2717 bool _pyHypothesis::CanClear()
2721 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2722 for ( ; obj != myReferredObjs.end(); ++obj )
2723 if ( (*obj)->CanClear() )
2730 //================================================================================
2732 * \brief Clear my commands depending on usage by meshes
2734 //================================================================================
2736 void _pyHypothesis::ClearCommands()
2738 // if ( !theGen->IsToKeepAllCommands() )
2740 // bool isUsed = false;
2741 // int lastComputeOrder = 0;
2742 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2743 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2744 // if ( ! (*cmd)->IsEmpty() )
2747 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2748 // lastComputeOrder = (*cmd)->GetOrderNb();
2752 // SetRemovedFromStudy( true );
2756 // // clear my commands invoked after lastComputeOrder
2757 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2758 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2760 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2761 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2762 // // cmds.back()->Clear();
2766 _pyObject::ClearCommands();
2769 //================================================================================
2771 * \brief Find arguments that are objects like mesh, group, geometry
2772 * \param meshes - referred meshes (directly or indirrectly)
2773 * \retval bool - false if a referred geometry is not in the study
2775 //================================================================================
2777 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2779 if ( IsAlgo() ) return true;
2781 bool geomPublished = true;
2782 vector< _AString > args;
2783 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2784 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2786 CreationMethod& crMethod = type2meth->second;
2787 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2789 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2790 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2791 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2792 args.push_back( (*cmd)->GetArg( nb ));
2795 for ( size_t i = 0; i < args.size(); ++i )
2797 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2798 if ( idList.empty() && !args[ i ].IsEmpty() )
2799 idList.push_back( args[ i ]);
2800 list< _pyID >::iterator id = idList.begin();
2801 for ( ; id != idList.end(); ++id )
2803 Handle(_pyObject) obj = theGen->FindObject( *id );
2804 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2807 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2808 geomPublished = false;
2812 myReferredObjs.push_back( obj );
2813 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2814 if ( !mesh.IsNull() )
2815 meshes.push_back( mesh );
2816 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2817 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2818 obj->SetRemovedFromStudy( false );
2822 return geomPublished;
2825 //================================================================================
2827 * \brief Remember theCommand setting a parameter
2829 //================================================================================
2831 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2833 // parameters are discriminated by method name
2834 _AString method = theCommand->GetMethod();
2835 if ( myAccumulativeMethods.count( method ))
2836 return; // this method adds values and not override the previus value
2838 // discriminate commands setting different parameters via one method
2839 // by passing parameter names like e.g. SetOption("size", "0.2")
2840 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2841 theCommand->GetNbArgs() > 1 )
2843 // mangle method by appending a 1st textual arg
2844 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2846 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2847 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2848 if ( !isalpha( arg.Value(2))) continue;
2853 // parameters are discriminated by method name
2854 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2855 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2857 cmds.back()->Clear(); // previous parameter value has not been used
2858 cmds.back() = theCommand;
2862 cmds.push_back( theCommand );
2866 //================================================================================
2868 * \brief Return true if a setting parameter command ha been used to compute mesh
2870 //================================================================================
2872 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2873 _pyCommand::TAddr avoidComputeAddr ) const
2875 bool isUsed = false;
2876 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2877 myComputeAddr2Cmds.begin();
2878 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2880 if ( addr2cmds->first == avoidComputeAddr ) continue;
2881 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2882 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2887 //================================================================================
2889 * \brief Save commands setting parameters as they are used for a mesh computation
2891 //================================================================================
2893 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2895 myComputeCmds.push_back( theComputeCmd );
2896 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2898 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2899 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2900 savedCmds.push_back( m2c->second.back() );
2903 //================================================================================
2905 * \brief Clear commands setting parameters as a mesh computed using them is cleared
2907 //================================================================================
2909 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
2911 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2913 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
2914 for ( ; cmd != savedCmds.end(); ++cmd )
2916 // check if a cmd has been used to compute another mesh
2917 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
2919 // check if a cmd is a sole command setting its parameter;
2920 // don't use method name for search as it can change
2921 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
2922 m2cmds = myMeth2Commands.begin();
2923 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
2925 list< Handle(_pyCommand)>& cmds = m2cmds->second;
2926 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
2927 if ( cmdIt != cmds.end() )
2929 if ( cmds.back() != *cmd )
2931 cmds.erase( cmdIt );
2938 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
2941 //================================================================================
2943 * \brief Sets an argNb-th argument of current creation command
2944 * \param argNb - argument index countered from 1
2946 //================================================================================
2948 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
2950 if ( myCurCrMethod )
2952 while ( myCurCrMethod->myArgs.size() < argNb )
2953 myCurCrMethod->myArgs.push_back( "None" );
2954 if ( arg.IsEmpty() )
2955 myCurCrMethod->myArgs[ argNb-1 ] = "None";
2957 myCurCrMethod->myArgs[ argNb-1 ] = arg;
2962 //================================================================================
2964 * \brief Remember hypothesis parameter values
2965 * \param theCommand - The called hypothesis method
2967 //================================================================================
2969 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
2971 if ( GetAlgoType() == "Cartesian_3D" )
2973 // CartesianParameters3D hyp
2975 if ( theCommand->GetMethod() == "SetSizeThreshold" )
2977 setCreationArg( 4, theCommand->GetArg( 1 ));
2978 myArgCommands.push_back( theCommand );
2981 if ( theCommand->GetMethod() == "SetGrid" ||
2982 theCommand->GetMethod() == "SetGridSpacing" )
2984 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
2985 int iArg = axis.Value(1) - '0';
2986 if ( theCommand->GetMethod() == "SetGrid" )
2988 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
2992 myCurCrMethod->myArgs[ iArg ] = "[ ";
2993 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
2994 myCurCrMethod->myArgs[ iArg ] += ", ";
2995 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
2996 myCurCrMethod->myArgs[ iArg ] += "]";
2998 myArgCommands.push_back( theCommand );
2999 rememberCmdOfParameter( theCommand );
3004 if( theCommand->GetMethod() == "SetLength" )
3006 // NOW it is OBSOLETE
3007 // ex: hyp.SetLength(start, 1)
3008 // hyp.SetLength(end, 0)
3009 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3010 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3011 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3012 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3014 CreationMethod& crMethod = type2meth->second;
3015 while ( crMethod.myArgs.size() < i+1 )
3016 crMethod.myArgs.push_back( "[]" );
3017 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3019 myArgCommands.push_back( theCommand );
3023 _pyHypothesis::Process( theCommand );
3026 //================================================================================
3028 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3030 //================================================================================
3032 void _pyComplexParamHypo::Flush()
3036 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3037 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3038 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3043 //================================================================================
3045 * \brief Convert methods of 1D hypotheses to my own methods
3046 * \param theCommand - The called hypothesis method
3048 //================================================================================
3050 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3052 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3055 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3056 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3057 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3059 // TCollection_AsciiString cmd =
3060 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3061 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3062 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3065 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3067 // // 1D hypo is already set, so distribution changes and the old
3068 // // 1D hypo is thrown away
3069 // my1dHyp->ClearAllCommands();
3072 // //my1dHyp->SetRemovedFromStudy( false );
3074 // if ( !myArgCommands.empty() )
3075 // myArgCommands.back()->Clear();
3076 myCurCrMethod->myArgs.push_back( hyp1dID );
3077 myArgCommands.push_back( theCommand );
3080 //================================================================================
3083 * \param theAdditionCmd - command to be converted
3084 * \param theMesh - mesh instance
3085 * \retval bool - status
3087 //================================================================================
3089 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3090 const _pyID& theMesh)
3092 myIsWrapped = false;
3094 if ( my1dHyp.IsNull() )
3097 // set "SetLayerDistribution()" after addition cmd
3098 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3100 _pyID geom = theAdditionCmd->GetArg( 1 );
3102 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3103 if ( !algo.IsNull() )
3105 my1dHyp->SetMesh( theMesh );
3106 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3107 algo->GetAlgoType().ToCString());
3108 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3111 // clear "SetLayerDistribution()" cmd
3112 myArgCommands.back()->Clear();
3114 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3116 // find RadialPrism algo created on <geom> for theMesh
3117 GetCreationCmd()->SetObject( algo->GetID() );
3118 GetCreationCmd()->SetMethod( myAlgoMethod );
3119 GetCreationCmd()->RemoveArgs();
3120 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3126 //================================================================================
3130 //================================================================================
3132 void _pyLayerDistributionHypo::Flush()
3134 // as creation of 1D hyp was written later then it's edition,
3135 // we need to find all it's edition calls and process them
3136 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3138 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3140 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3141 if ( hyp1dID.IsEmpty() ) continue;
3143 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3145 // make a new name for 1D hyp = "HypType" + "_Distribution"
3147 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3149 if ( prevNewName.IsEmpty() ) continue;
3150 newName = prevNewName;
3154 if ( hyp1d->IsWrapped() ) {
3155 newName = hyp1d->GetCreationCmd()->GetMethod();
3158 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3159 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3161 newName += "_Distribution";
3162 prevNewName = newName;
3164 hyp1d->GetCreationCmd()->SetResultValue( newName );
3166 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3167 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3168 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3169 const _pyID& objID = (*cmdIt)->GetObject();
3170 if ( objID == hyp1dID ) {
3171 if ( !hyp1d.IsNull() )
3173 hyp1d->Process( *cmdIt );
3174 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3176 ( *cmdIt )->SetObject( newName );
3179 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3180 (*cmd)->SetArg( 1, newName );
3184 //================================================================================
3186 * \brief additionally to Addition2Creation, clears SetDistrType() command
3187 * \param theCmd - AddHypothesis() command
3188 * \param theMesh - mesh to which a hypothesis is added
3189 * \retval bool - convertion result
3191 //================================================================================
3193 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3194 const _pyID& theMesh)
3196 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3197 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3198 bool scaleDistrType = false;
3199 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3200 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3201 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3202 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3203 scaleDistrType = true;
3206 else if ( !scaleDistrType ) {
3207 // distribution type changed: remove scale factor from args
3208 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3209 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3211 CreationMethod& crMethod = type2meth->second;
3212 if ( crMethod.myArgs.size() == 2 )
3213 crMethod.myArgs.pop_back();
3220 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3223 //================================================================================
3225 * \brief remove repeated commands defining distribution
3227 //================================================================================
3229 void _pyNumberOfSegmentsHyp::Flush()
3231 // find number of the last SetDistrType() command
3232 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3233 int distrTypeNb = 0;
3234 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3235 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3236 if ( cmd != myUnusedCommands.rbegin() )
3237 distrTypeNb = (*cmd)->GetOrderNb();
3239 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3242 // clear commands before the last SetDistrType()
3243 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3244 set< int > treatedCmdNbs; // avoid treating same cmd twice
3245 for ( int i = 0; i < 2; ++i ) {
3246 set<TCollection_AsciiString> uniqueMethods;
3247 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3248 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3250 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3251 continue;// avoid treating same cmd twice
3252 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3253 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3254 if ( !clear || method == "SetNumberOfSegments" ) {
3255 bool isNewInSet = uniqueMethods.insert( method ).second;
3256 clear = !isNewInSet;
3265 //================================================================================
3267 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3268 * into regular1D.LengthNearVertex( length, vertex )
3269 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3270 * \param theMesh - The mesh needing this hypo
3271 * \retval bool - false if the command cant be converted
3273 //================================================================================
3275 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3276 const _pyID& theMeshID)
3278 if ( IsWrappable( theMeshID )) {
3280 _pyID vertex = theCmd->GetArg( 1 );
3282 // the problem here is that segment algo will not be found
3283 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3284 // geometry where segment algorithm is assigned
3285 Handle(_pyHypothesis) algo;
3286 _pyID geom = vertex;
3287 while ( algo.IsNull() && !geom.IsEmpty()) {
3288 // try to find geom as a father of <vertex>
3289 geom = FatherID( geom );
3290 algo = theGen->FindAlgo( geom, theMeshID, this );
3292 if ( algo.IsNull() )
3293 return false; // also possible to find geom as brother of veretex...
3294 // set geom instead of vertex
3295 theCmd->SetArg( 1, geom );
3297 // set vertex as a second arg
3298 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3299 setCreationArg( 2, vertex );
3301 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3302 // theMeshID.LengthNearVertex( length, vertex )
3303 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3308 //================================================================================
3310 * \brief _pyAlgorithm constructor
3311 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3313 //================================================================================
3315 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3316 : _pyHypothesis( theCreationCmd )
3321 //================================================================================
3323 * \brief Convert the command adding an algorithm to mesh
3324 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3325 * \param theMesh - The mesh needing this algo
3326 * \retval bool - false if the command cant be converted
3328 //================================================================================
3330 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3331 const _pyID& theMeshID)
3333 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3334 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3335 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3341 //================================================================================
3343 * \brief Return starting position of a part of python command
3344 * \param thePartIndex - The index of command part
3345 * \retval int - Part position
3347 //================================================================================
3349 int _pyCommand::GetBegPos( int thePartIndex )
3353 if ( myBegPos.Length() < thePartIndex )
3355 ASSERT( thePartIndex > 0 );
3356 return myBegPos( thePartIndex );
3359 //================================================================================
3361 * \brief Store starting position of a part of python command
3362 * \param thePartIndex - The index of command part
3363 * \param thePosition - Part position
3365 //================================================================================
3367 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3369 while ( myBegPos.Length() < thePartIndex )
3370 myBegPos.Append( UNKNOWN );
3371 ASSERT( thePartIndex > 0 );
3372 myBegPos( thePartIndex ) = thePosition;
3375 //================================================================================
3377 * \brief Returns whitespace symbols at the line beginning
3378 * \retval TCollection_AsciiString - result
3380 //================================================================================
3382 TCollection_AsciiString _pyCommand::GetIndentation()
3385 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3386 GetWord( myString, end, true );
3388 end = GetBegPos( RESULT_IND );
3389 return myString.SubString( 1, end - 1 );
3392 //================================================================================
3394 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3395 * \retval const TCollection_AsciiString & - ResultValue substring
3397 //================================================================================
3399 const TCollection_AsciiString & _pyCommand::GetResultValue()
3401 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3403 SetBegPos( RESULT_IND, EMPTY );
3404 int begPos, endPos = myString.Location( "=", 1, Length() );
3408 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3409 if ( begPos < endPos )
3411 SetBegPos( RESULT_IND, begPos );
3413 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3414 myRes = myString.SubString( begPos, endPos );
3421 //================================================================================
3423 * \brief Return number of python command result value ResultValue = Obj.Meth()
3425 //================================================================================
3427 int _pyCommand::GetNbResultValues()
3431 int endPos = myString.Location( "=", 1, Length() );
3432 while ( begPos < endPos )
3434 _AString str = GetWord( myString, begPos, true );
3435 begPos = begPos+ str.Length();
3442 //================================================================================
3444 * \brief Return substring of python command looking like
3445 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3446 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3448 //================================================================================
3449 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3452 if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3453 ++begPos; // skip [, else the whole list is returned
3454 int endPos = myString.Location( "=", 1, Length() );
3456 while ( begPos < endPos) {
3457 _AString result = GetWord( myString, begPos, true );
3458 begPos = begPos + result.Length();
3461 result.RemoveAll('[');
3462 result.RemoveAll(']');
3468 return theEmptyString;
3471 //================================================================================
3473 * \brief Return substring of python command looking like ResVal = Object.Meth()
3474 * \retval const TCollection_AsciiString & - Object substring
3476 //================================================================================
3478 const TCollection_AsciiString & _pyCommand::GetObject()
3480 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3483 int begPos = GetBegPos( RESULT_IND ) + myRes.Length();
3485 begPos = myString.Location( "=", 1, Length() ) + 1;
3486 // is '=' in the string argument (for example, name) or not
3487 int nb1 = 0; // number of ' character at the left of =
3488 int nb2 = 0; // number of " character at the left of =
3489 for ( int i = 1; i < begPos-1; i++ ) {
3490 if ( myString.Value( i )=='\'' )
3492 else if ( myString.Value( i )=='"' )
3495 // if number of ' or " is not divisible by 2,
3496 // then get an object at the start of the command
3497 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3500 myObj = GetWord( myString, begPos, true );
3501 if ( begPos != EMPTY )
3503 // check if object is complex,
3504 // so far consider case like "smesh.Method()"
3505 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3506 //if ( bracketPos==0 ) bracketPos = Length();
3507 int dotPos = begPos+myObj.Length();
3508 while ( dotPos+1 < bracketPos ) {
3509 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3514 if ( dotPos > begPos+myObj.Length() )
3515 myObj = myString.SubString( begPos, dotPos-1 );
3518 // 1st word after '=' is an object
3519 // else // no method -> no object
3525 SetBegPos( OBJECT_IND, begPos );
3531 //================================================================================
3533 * \brief Return substring of python command looking like ResVal = Obj.Method()
3534 * \retval const TCollection_AsciiString & - Method substring
3536 //================================================================================
3538 const TCollection_AsciiString & _pyCommand::GetMethod()
3540 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3543 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3544 bool forward = true;
3546 begPos = myString.Location( "(", 1, Length() ) - 1;
3550 myMeth = GetWord( myString, begPos, forward );
3551 SetBegPos( METHOD_IND, begPos );
3557 //================================================================================
3559 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3560 * \retval const TCollection_AsciiString & - Arg<index> substring
3562 //================================================================================
3564 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3566 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3570 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3572 pos = myString.Location( "(", 1, Length() );
3576 // we are at or before '(', skip it if present
3578 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3579 if ( pos > Length() )
3583 SetBegPos( ARG1_IND, 0 ); // even no '('
3584 return theEmptyString;
3588 list< TCollection_AsciiString > separatorStack( 1, ",)");
3589 bool ignoreNesting = false;
3591 while ( pos <= Length() )
3593 const char chr = myString.Value( pos );
3595 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3597 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3599 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3601 TCollection_AsciiString arg;
3602 if ( pos-1 >= prevPos ) {
3603 arg = myString.SubString( prevPos, pos-1 );
3604 arg.RightAdjust(); // remove spaces
3607 if ( !arg.IsEmpty() || chr == ',' )
3609 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3610 myArgs.Append( arg );
3616 else // end of nesting args found
3618 separatorStack.pop_back();
3619 ignoreNesting = false;
3622 else if ( !ignoreNesting )
3625 case '(' : separatorStack.push_back(")"); break;
3626 case '[' : separatorStack.push_back("]"); break;
3627 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3628 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3635 if ( myArgs.Length() < index )
3636 return theEmptyString;
3637 return myArgs( index );
3640 //================================================================================
3642 * \brief Check if char is a word part
3643 * \param c - The character to check
3644 * \retval bool - The check result
3646 //================================================================================
3648 static inline bool isWord(const char c, const bool dotIsWord)
3651 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3654 //================================================================================
3656 * \brief Looks for a word in the string and returns word's beginning
3657 * \param theString - The input string
3658 * \param theStartPos - The position to start the search, returning word's beginning
3659 * \param theForward - The search direction
3660 * \retval TCollection_AsciiString - The found word
3662 //================================================================================
3664 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3666 const bool theForward,
3667 const bool dotIsWord )
3669 int beg = theStartPos, end = theStartPos;
3670 theStartPos = EMPTY;
3671 if ( beg < 1 || beg > theString.Length() )
3672 return theEmptyString;
3674 if ( theForward ) { // search forward
3676 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3678 if ( beg > theString.Length() )
3679 return theEmptyString; // no word found
3682 char begChar = theString.Value( beg );
3683 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3684 char endChar = ( begChar == '[' ) ? ']' : begChar;
3685 // end is at the corresponding quoting mark or bracket
3686 while ( end < theString.Length() &&
3687 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3691 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3696 else { // search backward
3698 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3701 return theEmptyString; // no word found
3703 char endChar = theString.Value( end );
3704 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3705 char begChar = ( endChar == ']' ) ? '[' : endChar;
3706 // beg is at the corresponding quoting mark
3708 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3712 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3718 //cout << theString << " ---- " << beg << " - " << end << endl;
3719 return theString.SubString( beg, end );
3722 //================================================================================
3724 * \brief Returns true if the string looks like a study entry
3726 //================================================================================
3728 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3730 if ( str.Length() < 5 ) return false;
3732 int nbColons = 0, isColon;
3733 for ( int i = 1; i <= str.Length(); ++i )
3735 char c = str.Value(i);
3736 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3738 nbColons += isColon;
3740 return nbColons > 2 && str.Length()-nbColons > 2;
3743 //================================================================================
3745 * \brief Finds entries in a sting
3747 //================================================================================
3749 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3751 std::list< _pyID > resList;
3753 while ( ++pos <= str.Length() )
3755 if ( !isdigit( str.Value( pos ))) continue;
3756 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3759 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3760 _pyID entry = str.SubString( pos, end-1 );
3762 if ( IsStudyEntry( entry ))
3763 resList.push_back( entry );
3768 //================================================================================
3770 * \brief Look for position where not space char is
3771 * \param theString - The string
3772 * \param thePos - The position to search from and which returns result
3773 * \retval bool - false if there are only space after thePos in theString
3775 //================================================================================
3777 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3779 if ( thePos < 1 || thePos > theString.Length() )
3782 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3785 return thePos <= theString.Length();
3788 //================================================================================
3790 * \brief Modify a part of the command
3791 * \param thePartIndex - The index of the part
3792 * \param thePart - The new part string
3793 * \param theOldPart - The old part
3795 //================================================================================
3797 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3798 TCollection_AsciiString& theOldPart)
3800 int pos = GetBegPos( thePartIndex );
3801 if ( pos <= Length() && theOldPart != thePart)
3803 TCollection_AsciiString seperator;
3805 pos = GetBegPos( thePartIndex + 1 );
3806 if ( pos < 1 ) return;
3807 switch ( thePartIndex ) {
3808 case RESULT_IND: seperator = " = "; break;
3809 case OBJECT_IND: seperator = "."; break;
3810 case METHOD_IND: seperator = "()"; break;
3814 myString.Remove( pos, theOldPart.Length() );
3815 if ( !seperator.IsEmpty() )
3816 myString.Insert( pos , seperator );
3817 myString.Insert( pos, thePart );
3818 // update starting positions of the following parts
3819 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3820 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3821 if ( myBegPos( i ) > 0 )
3822 myBegPos( i ) += posDelta;
3824 theOldPart = thePart;
3828 //================================================================================
3830 * \brief Set agrument
3831 * \param index - The argument index, it counts from 1
3832 * \param theArg - The argument string
3834 //================================================================================
3836 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3839 int argInd = ARG1_IND + index - 1;
3840 int pos = GetBegPos( argInd );
3841 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3843 // find a closing parenthesis
3844 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3845 int lastArgInd = GetNbArgs();
3846 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3847 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3852 while ( pos > 0 && myString.Value( pos ) != ')' )
3855 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3859 while ( myArgs.Length() < index ) {
3860 if ( myArgs.Length() )
3861 myString.Insert( pos++, "," );
3862 myArgs.Append("None");
3863 myString.Insert( pos, myArgs.Last() );
3864 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
3865 pos += myArgs.Last().Length();
3868 SetPart( argInd, theArg, myArgs( index ));
3871 //================================================================================
3873 * \brief Empty arg list
3875 //================================================================================
3877 void _pyCommand::RemoveArgs()
3879 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
3880 myString.Trunc( pos );
3883 if ( myBegPos.Length() >= ARG1_IND )
3884 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
3887 //================================================================================
3889 * \brief Comment a python command
3891 //================================================================================
3893 void _pyCommand::Comment()
3895 if ( IsEmpty() ) return;
3898 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
3899 if ( i <= Length() )
3901 myString.Insert( i, "#" );
3902 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
3904 int begPos = GetBegPos( iPart + 1 );
3905 if ( begPos != UNKNOWN )
3906 SetBegPos( iPart + 1, begPos + 1 );
3911 //================================================================================
3913 * \brief Set dependent commands after this one
3915 //================================================================================
3917 bool _pyCommand::SetDependentCmdsAfter() const
3919 bool orderChanged = false;
3920 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
3921 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
3922 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
3923 orderChanged = true;
3924 theGen->SetCommandAfter( *cmd, this );
3925 (*cmd)->SetDependentCmdsAfter();
3928 return orderChanged;
3930 //================================================================================
3932 * \brief Insert accessor method after theObjectID
3933 * \param theObjectID - id of the accessed object
3934 * \param theAcsMethod - name of the method giving access to the object
3935 * \retval bool - false if theObjectID is not found in the command string
3937 //================================================================================
3939 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
3941 if ( !theAcsMethod )
3943 // start object search from the object, i.e. ignore result
3945 int beg = GetBegPos( OBJECT_IND );
3946 if ( beg < 1 || beg > Length() )
3949 while (( beg = myString.Location( theObjectID, beg, Length() )))
3951 // check that theObjectID is not just a part of a longer ID
3952 int afterEnd = beg + theObjectID.Length();
3953 Standard_Character c = myString.Value( afterEnd );
3954 if ( !isalnum( c ) && c != ':' ) {
3955 // check if accessor method already present
3957 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
3959 int oldLen = Length();
3960 myString.Insert( afterEnd, (char*) theAcsMethod );
3961 myString.Insert( afterEnd, "." );
3962 // update starting positions of the parts following the modified one
3963 int posDelta = Length() - oldLen;
3964 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
3965 if ( myBegPos( i ) > afterEnd )
3966 myBegPos( i ) += posDelta;
3971 beg = afterEnd; // is a part - next search
3976 //================================================================================
3978 * \brief Creates pyObject
3980 //================================================================================
3982 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
3983 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
3988 //================================================================================
3990 * \brief Set up myID and myIsPublished
3992 //================================================================================
3994 void _pyObject::setID(const _pyID& theID)
3997 myIsPublished = !theGen->IsNotPublished( GetID() );
4000 //================================================================================
4002 * \brief Clear myCreationCmd and myProcessedCmds
4004 //================================================================================
4006 void _pyObject::ClearCommands()
4011 if ( !myCreationCmd.IsNull() )
4012 myCreationCmd->Clear();
4014 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4015 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4019 //================================================================================
4021 * \brief Return method name giving access to an interaface object wrapped by python class
4022 * \retval const char* - method name
4024 //================================================================================
4026 const char* _pyObject::AccessorMethod() const
4030 //================================================================================
4032 * \brief Return ID of a father
4034 //================================================================================
4036 _pyID _pyObject::FatherID(const _pyID & childID)
4038 int colPos = childID.SearchFromEnd(':');
4040 return childID.SubString( 1, colPos-1 );
4044 //================================================================================
4046 * \brief SelfEraser erases creation command if no more it's commands invoked
4048 //================================================================================
4050 void _pySelfEraser::Flush()
4052 int nbCalls = GetNbCalls();
4055 // ignore cleared commands
4056 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4057 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4058 for ( ; cmd != cmds.end(); ++cmd )
4059 nbCalls -= (*cmd)->IsEmpty();
4062 GetCreationCmd()->Clear();
4065 //================================================================================
4067 * \brief _pySubMesh constructor
4069 //================================================================================
4071 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd):
4072 _pyObject(theCreationCmd)
4074 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4077 //================================================================================
4079 * \brief Return true if a sub-mesh can be used as argument of the given method
4081 //================================================================================
4083 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4085 // names of all methods where a sub-mesh can be used as argument
4086 static TStringSet methods;
4087 if ( methods.empty() ) {
4088 const char * names[] = {
4089 // methods of SMESH_Gen
4091 // methods of SMESH_Group
4093 // methods of SMESH_Measurements
4095 // methods of SMESH_Mesh
4096 "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4098 // methods of SMESH_MeshEditor
4099 "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4100 "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4101 "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4102 "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4103 "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4104 "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4105 "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4106 "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4107 "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4108 "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4109 "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4110 "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4111 "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4112 "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4113 "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4114 "" }; // <- mark of end
4115 methods.Insert( names );
4117 return methods.Contains( theMethodName );
4120 //================================================================================
4122 * \brief count invoked commands
4124 //================================================================================
4126 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4128 _pyObject::Process(theCommand); // count calls of Process()
4129 GetCreationCmd()->AddDependantCmd( theCommand );
4132 //================================================================================
4134 * \brief Move creation command depending on invoked commands
4136 //================================================================================
4138 void _pySubMesh::Flush()
4140 if ( GetNbCalls() == 0 ) // move to the end of all commands
4141 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4142 else if ( !myCreator.IsNull() )
4143 // move to be just after creator
4144 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4147 //================================================================================
4149 * \brief Creates _pyGroup
4151 //================================================================================
4153 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4154 :_pySubMesh(theCreationCmd)
4156 if ( !id.IsEmpty() )
4159 myCanClearCreationCmd = true;
4161 const _AString& method = theCreationCmd->GetMethod();
4162 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4164 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4166 // ----------------------------------------------------------------------
4167 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4169 _pyID geom = theCreationCmd->GetArg( 3 );
4170 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4171 // next if(){...} section is commented
4172 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4173 // theCreationCmd->SetMethod( "Group" );
4174 // theCreationCmd->RemoveArgs();
4175 // theCreationCmd->SetArg( 1, geom );
4178 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4179 _pyID type = theCreationCmd->GetArg( 1 );
4180 _pyID name = theCreationCmd->GetArg( 2 );
4181 theCreationCmd->SetMethod( "GroupOnGeom" );
4182 theCreationCmd->RemoveArgs();
4183 theCreationCmd->SetArg( 1, geom );
4184 theCreationCmd->SetArg( 2, name );
4185 theCreationCmd->SetArg( 3, type );
4188 else if ( method == "CreateGroupFromFilter" )
4190 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4191 theCreationCmd->SetMethod( "GroupOnFilter" );
4193 _pyID filterID = theCreationCmd->GetArg(3);
4194 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4195 if ( !filter.IsNull())
4197 if ( !filter->GetNewID().IsEmpty() )
4198 theCreationCmd->SetArg( 3, filter->GetNewID() );
4199 filter->AddUser( this );
4203 else if ( method == "GetGroups" )
4205 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4209 // theCreationCmd does something else apart from creation of this group
4210 // and thus it can't be cleared if this group is removed
4211 myCanClearCreationCmd = false;
4215 //================================================================================
4217 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4220 //================================================================================
4222 bool _pyGroup::CanClear()
4227 if ( !myCanClearCreationCmd && myCreationCmd->GetMethod() == "GetGroups" )
4229 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4230 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4231 list< _pyID >::iterator grID = idList.begin();
4232 if ( GetID() == *grID )
4234 myCanClearCreationCmd = true;
4235 list< Handle(_pyGroup ) > groups;
4236 for ( ; grID != idList.end(); ++grID )
4238 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4239 if ( group.IsNull() ) continue;
4240 groups.push_back( group );
4241 if ( group->IsInStudy() )
4242 myCanClearCreationCmd = false;
4244 // set myCanClearCreationCmd == true to all groups
4245 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4246 for ( ; group != groups.end(); ++group )
4247 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4251 return myCanClearCreationCmd;
4254 //================================================================================
4256 * \brief set myCanClearCreationCmd = true if the main action of the creation
4257 * command is discarded
4259 //================================================================================
4261 void _pyGroup::RemovedWithContents()
4263 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4264 // via a created group
4265 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4266 // myCanClearCreationCmd = true;
4269 //================================================================================
4271 * \brief To convert creation of a group by filter
4273 //================================================================================
4275 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4277 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4278 // group = mesh.CreateEmptyGroup( elemType, groupName )
4279 // aFilter.SetMesh(mesh)
4280 // nbAdd = group.AddFrom( aFilter )
4281 Handle(_pyFilter) filter;
4282 if ( theCommand->GetMethod() == "AddFrom" )
4284 _pyID idSource = theCommand->GetArg(1);
4285 // check if idSource is a filter
4286 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4287 if ( !filter.IsNull() )
4289 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4290 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4291 while ( *cmdIt != theCommand ) ++cmdIt;
4292 while ( (*cmdIt)->GetOrderNb() != 1 )
4294 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4295 if ((setMeshCmd->GetObject() == idSource ||
4296 setMeshCmd->GetObject() == filter->GetNewID() )
4298 setMeshCmd->GetMethod() == "SetMesh")
4300 setMeshCmd->Clear();
4304 // replace 3 commands by one
4305 theCommand->Clear();
4306 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4307 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4308 if ( !filter->GetNewID().IsEmpty() )
4309 idSource = filter->GetNewID();
4310 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4311 makeGroupCmd->SetArg( 1, name );
4312 makeGroupCmd->SetArg( 2, idSource );
4315 else if ( theCommand->GetMethod() == "SetFilter" )
4317 // set new name of a filter or clear the command if the same filter is set
4318 _pyID filterID = theCommand->GetArg(1);
4319 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4320 if ( !myFilter.IsNull() && filter == myFilter )
4321 theCommand->Clear();
4322 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4323 theCommand->SetArg( 1, filter->GetNewID() );
4326 else if ( theCommand->GetMethod() == "GetFilter" )
4328 // GetFilter() returns a filter with other ID, make myFilter process
4329 // calls of the returned filter
4330 if ( !myFilter.IsNull() )
4332 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4333 theCommand->Clear();
4337 if ( !filter.IsNull() )
4338 filter->AddUser( this );
4340 theGen->AddMeshAccessorMethod( theCommand );
4343 //================================================================================
4345 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4347 //================================================================================
4349 void _pyGroup::Flush()
4351 if ( !theGen->IsToKeepAllCommands() &&
4352 myCreationCmd && !myCanClearCreationCmd )
4354 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4358 //================================================================================
4360 * \brief Constructor of _pyFilter
4362 //================================================================================
4364 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4365 :_pyObject(theCreationCmd), myNewID( newID )
4369 //================================================================================
4371 * \brief To convert creation of a filter by criteria and
4372 * to replace an old name by a new one
4374 //================================================================================
4376 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4378 if ( theCommand->GetObject() == GetID() )
4379 _pyObject::Process(theCommand); // count commands
4381 if ( !myNewID.IsEmpty() )
4382 theCommand->SetObject( myNewID );
4384 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4385 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4386 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4387 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4388 theCommand->GetMethod() == "SetCriteria")
4390 // aFilter.SetCriteria(aCriteria) ->
4391 // aFilter = smesh.GetFilterFromCriteria(criteria)
4392 if ( myNewID.IsEmpty() )
4393 theCommand->SetResultValue( GetID() );
4395 theCommand->SetResultValue( myNewID );
4396 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4397 theCommand->SetMethod( "GetFilterFromCriteria" );
4399 // Clear aFilterManager.CreateFilter()
4400 GetCreationCmd()->Clear();
4402 else if ( theCommand->GetMethod() == "SetMesh" )
4404 if ( myMesh == theCommand->GetArg( 1 ))
4405 theCommand->Clear();
4407 myMesh = theCommand->GetArg( 1 );
4408 theGen->AddMeshAccessorMethod( theCommand );
4412 //================================================================================
4414 * \brief Set new filter name to the creation command
4416 //================================================================================
4418 void _pyFilter::Flush()
4420 if ( !myNewID.IsEmpty() && !GetCreationCmd()->IsEmpty() )
4421 GetCreationCmd()->SetResultValue( myNewID );
4424 //================================================================================
4426 * \brief Return true if all my users can be cleared
4428 //================================================================================
4430 bool _pyFilter::CanClear()
4432 list< Handle(_pyObject) >::iterator obj = myUsers.begin();
4433 for ( ; obj != myUsers.end(); ++obj )
4434 if ( !(*obj)->CanClear() )
4440 //================================================================================
4442 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4444 //================================================================================
4446 _pyHypothesisReader::_pyHypothesisReader()
4449 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4450 LDOMParser xmlParser;
4451 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4453 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4457 INFOS( xmlParser.GetError(data) );
4460 // <algorithm type="Regular_1D"
4461 // label-id="Wire discretisation"
4464 // <algo>Regular_1D=Segment()</algo>
4465 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4467 LDOM_Document xmlDoc = xmlParser.getDocument();
4468 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4469 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4471 LDOM_Node algoNode = algoNodeList.item( i );
4472 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4473 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4474 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4476 _AString text, algoType, method, arg;
4477 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4479 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4480 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4481 text = textNode.getNodeValue();
4482 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4483 algoType = algoCmd->GetResultValue();
4484 method = algoCmd->GetMethod();
4485 arg = algoCmd->GetArg(1);
4486 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4488 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4489 algo->SetConvMethodAndType( method, algoType );
4490 if ( !arg.IsEmpty() )
4491 algo->setCreationArg( 1, arg );
4493 myType2Hyp[ algoType ] = algo;
4497 if ( algoType.IsEmpty() ) continue;
4499 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4501 Handle( _pyHypothesis ) hyp;
4502 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4504 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4505 LDOM_Node textNode = pyHypoNode.getFirstChild();
4506 text = textNode.getNodeValue();
4507 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4508 hypType = hypoCmd->GetResultValue();
4509 method = hypoCmd->GetMethod();
4510 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4512 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4513 if ( type2hyp == myType2Hyp.end() )
4514 hyp = new _pyHypothesis( hypoCmd );
4516 hyp = type2hyp->second;
4517 hyp->SetConvMethodAndType( method, algoType );
4518 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4520 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4521 _AString argMethod = argCmd.GetMethod();
4522 _AString argNbText = argCmd.GetArg( 1 );
4523 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4524 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4526 hyp->AddArgMethod( argMethod,
4527 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4529 myType2Hyp[ hypType ] = hyp;
4533 // <hypothesis type="BLSURF_Parameters"
4537 // <accumulative-methods>
4538 // SetEnforcedVertex,
4539 // SetEnforcedVertexNamed
4540 // </accumulative-methods>
4544 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4545 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4547 LDOM_Node hypNode = hypNodeList.item( i );
4548 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4549 _AString hypType = hypElem.getAttribute("type");
4550 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4551 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4553 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4554 if ( type2hyp == myType2Hyp.end() ) continue;
4556 LDOM_Node methNode = methNodeList.item( 0 );
4557 LDOM_Node textNode = methNode.getFirstChild();
4558 _AString text = textNode.getNodeValue();
4562 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4563 pos += method.Length();
4564 type2hyp->second->AddAccumulativeMethod( method );
4566 while ( !method.IsEmpty() );
4569 } // loop on xmlPaths
4572 //================================================================================
4574 * \brief Returns a new hypothesis initialized according to the read information
4576 //================================================================================
4578 Handle(_pyHypothesis)
4579 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4580 const Handle(_pyCommand)& creationCmd) const
4582 Handle(_pyHypothesis) resHyp, sampleHyp;
4584 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4585 if ( type2hyp != myType2Hyp.end() )
4586 sampleHyp = type2hyp->second;
4588 if ( sampleHyp.IsNull() )
4590 resHyp = new _pyHypothesis(creationCmd);
4594 if ( sampleHyp->IsAlgo() )
4595 resHyp = new _pyAlgorithm( creationCmd );
4597 resHyp = new _pyHypothesis(creationCmd);
4598 resHyp->Assign( sampleHyp, _pyID() );