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 const bool isMethodCall = cmd->IsMethodCall();
203 if ( !obj.IsEmpty() && isMethodCall && !presentObjects.count( obj ) )
205 comment = "not created Object";
206 theGen->ObjectCreationRemoved( obj );
208 // check if a command has not created args
209 for ( int iArg = cmd->GetNbArgs(); iArg && comment.IsEmpty(); --iArg )
211 const _pyID& arg = cmd->GetArg( iArg );
212 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
214 list< _pyID > idList = cmd->GetStudyEntries( arg );
215 list< _pyID >::iterator id = idList.begin();
216 for ( ; id != idList.end(); ++id )
217 if ( !theGen->IsGeomObject( *id ) && !presentObjects.count( *id ))
219 comment += *id + " has not been yet created";
222 // if ( idList.empty() && cmd->IsID( arg ) && !presentObjects.count( arg ))
223 // comment += arg + " has not been yet created";
225 // treat result objects
226 const _pyID& result = cmd->GetResultValue();
227 if ( !result.IsEmpty() && result.Value( 1 ) != '"' && result.Value( 1 ) != '\'' )
229 list< _pyID > idList = cmd->GetStudyEntries( result );
230 list< _pyID >::iterator id = idList.begin();
231 for ( ; id != idList.end(); ++id )
233 if ( comment.IsEmpty() )
234 presentObjects.insert( *id );
236 theGen->ObjectCreationRemoved( *id ); // objID.SetName( name ) is not needed
238 if ( idList.empty() && cmd->IsID( result ))
239 presentObjects.insert( result );
241 // comment the command
242 if ( !comment.IsEmpty() )
245 cmd->GetString() += " ### ";
246 cmd->GetString() += comment;
250 //================================================================================
252 * \brief Fix SMESH::FunctorType arguments of SMESH::Filter::Criterion()
254 //================================================================================
256 void fixFunctorType( TCollection_AsciiString& Type,
257 TCollection_AsciiString& Compare,
258 TCollection_AsciiString& UnaryOp,
259 TCollection_AsciiString& BinaryOp )
261 // The problem is that dumps of old studies created using filters becomes invalid
262 // when new items are inserted in the enum SMESH::FunctorType since values
263 // of this enum are dumped as integer values.
264 // This function corrects enum values of old studies given as args (Type,Compare,...)
265 // We can find out how to correct them by value of BinaryOp which can have only two
266 // values: FT_Undefined or FT_LogicalNOT.
267 // Hereafter is the history of the enum SMESH::FunctorType since v3.0.0
268 // where PythonDump appeared
269 // v 3.0.0: FT_Undefined == 25
270 // v 3.1.0: FT_Undefined == 26, new items:
272 // v 4.1.2: FT_Undefined == 27, new items:
273 // - FT_BelongToGenSurface = 17
274 // v 5.1.1: FT_Undefined == 32, new items:
275 // - FT_FreeNodes = 10
276 // - FT_FreeFaces = 11
277 // - FT_LinearOrQuadratic = 23
278 // - FT_GroupColor = 24
279 // - FT_ElemGeomType = 25
280 // v 5.1.5: FT_Undefined == 33, new items:
281 // - FT_CoplanarFaces = 26
282 // v 6.2.0: FT_Undefined == 39, new items:
283 // - FT_MaxElementLength2D = 8
284 // - FT_MaxElementLength3D = 9
285 // - FT_BareBorderVolume = 25
286 // - FT_BareBorderFace = 26
287 // - FT_OverConstrainedVolume = 27
288 // - FT_OverConstrainedFace = 28
289 // v 6.5.0: FT_Undefined == 43, new items:
290 // - FT_EqualNodes = 14
291 // - FT_EqualEdges = 15
292 // - FT_EqualFaces = 16
293 // - FT_EqualVolumes = 17
294 // v 6.6.0: FT_Undefined == 44, new items:
295 // - FT_BallDiameter = 37
296 // v 6.7.1: FT_Undefined == 45, new items:
297 // - FT_EntityType = 36
298 // v 7.3.0: FT_Undefined == 46, new items:
299 // - FT_ConnectedElements = 39
301 // It's necessary to continue recording this history and to fill
302 // undef2newItems (see below) accordingly.
304 typedef map< int, vector< int > > TUndef2newItems;
305 static TUndef2newItems undef2newItems;
306 if ( undef2newItems.empty() )
308 undef2newItems[ 26 ].push_back( 7 );
309 undef2newItems[ 27 ].push_back( 17 );
310 { int items[] = { 10, 11, 23, 24, 25 };
311 undef2newItems[ 32 ].assign( items, items+5 ); }
312 undef2newItems[ 33 ].push_back( 26 );
313 { int items[] = { 8, 9, 25, 26, 27, 28 };
314 undef2newItems[ 39 ].assign( items, items+6 ); }
315 { int items[] = { 14, 15, 16, 17 };
316 undef2newItems[ 43 ].assign( items, items+4 ); }
317 undef2newItems[ 44 ].push_back( 37 );
318 undef2newItems[ 45 ].push_back( 36 );
319 undef2newItems[ 46 ].push_back( 39 );
321 ASSERT( undef2newItems.rbegin()->first == SMESH::FT_Undefined );
324 int iType = Type.IntegerValue();
325 int iCompare = Compare.IntegerValue();
326 int iUnaryOp = UnaryOp.IntegerValue();
327 int iBinaryOp = BinaryOp.IntegerValue();
329 // find out integer value of FT_Undefined at the moment of dump
330 int oldUndefined = iBinaryOp;
331 if ( iBinaryOp < iUnaryOp ) // BinaryOp was FT_LogicalNOT
334 // apply history to args
335 TUndef2newItems::const_iterator undef_items =
336 undef2newItems.upper_bound( oldUndefined );
337 if ( undef_items != undef2newItems.end() )
339 int* pArg[4] = { &iType, &iCompare, &iUnaryOp, &iBinaryOp };
340 for ( ; undef_items != undef2newItems.end(); ++undef_items )
342 const vector< int > & addedItems = undef_items->second;
343 for ( size_t i = 0; i < addedItems.size(); ++i )
344 for ( int iArg = 0; iArg < 4; ++iArg )
346 int& arg = *pArg[iArg];
347 if ( arg >= addedItems[i] )
351 Type = TCollection_AsciiString( iType );
352 Compare = TCollection_AsciiString( iCompare );
353 UnaryOp = TCollection_AsciiString( iUnaryOp );
354 BinaryOp = TCollection_AsciiString( iBinaryOp );
358 //================================================================================
360 * \brief Replaces "SMESH.PointStruct(x,y,z)" and "SMESH.DirStruct( SMESH.PointStruct(x,y,z))"
361 * arguments of a given command by a list "[x,y,z]" if the list is accesible
364 //================================================================================
366 void StructToList( Handle( _pyCommand)& theCommand )
368 static TStringSet methodsAcceptingList;
369 if ( methodsAcceptingList.empty() ) {
370 const char * methodNames[] = {
371 "GetCriterion","Reorient2D","ExtrusionSweep","ExtrusionSweepMakeGroups0D",
372 "ExtrusionSweepMakeGroups","ExtrusionSweep0D",
373 "AdvancedExtrusion","AdvancedExtrusionMakeGroups",
374 "ExtrusionSweepObject","ExtrusionSweepObject0DMakeGroups",
375 "ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
376 "ExtrusionSweepObject1D","ExtrusionSweepObject1DMakeGroups",
377 "ExtrusionSweepObject2D","ExtrusionSweepObject2DMakeGroups",
378 "Translate","TranslateMakeGroups","TranslateMakeMesh",
379 "TranslateObject","TranslateObjectMakeGroups", "TranslateObjectMakeMesh",
380 "ExtrusionAlongPathX","ExtrusionAlongPathObjX"
381 ,"" }; // <- mark of the end
382 methodsAcceptingList.Insert( methodNames );
384 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
386 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
388 const _AString & arg = theCommand->GetArg( i );
389 if ( arg.Search( "SMESH.PointStruct" ) == 1 ||
390 arg.Search( "SMESH.DirStruct" ) == 1 )
392 Handle(_pyCommand) workCmd = new _pyCommand( arg );
393 if ( workCmd->GetNbArgs() == 1 ) // SMESH.DirStruct( SMESH.PointStruct(x,y,z))
395 workCmd = new _pyCommand( workCmd->GetArg( 1 ) );
397 if ( workCmd->GetNbArgs() == 3 ) // SMESH.PointStruct(x,y,z)
399 _AString newArg = "[ ";
400 newArg += ( workCmd->GetArg( 1 ) + ", " +
401 workCmd->GetArg( 2 ) + ", " +
402 workCmd->GetArg( 3 ) + " ]");
403 theCommand->SetArg( i, newArg );
409 //================================================================================
411 * \brief Replaces "mesh.GetIDSource([id1,id2])" argument of a given command by
412 * a list "[id1,id2]" if the list is an accesible type of argument.
414 //================================================================================
416 void GetIDSourceToList( Handle( _pyCommand)& theCommand )
418 static TStringSet methodsAcceptingList;
419 if ( methodsAcceptingList.empty() ) {
420 const char * methodNames[] = {
421 "ExportPartToMED","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
422 "ExportCGNS","ExportGMF",
423 "Create0DElementsOnAllNodes","Reorient2D","QuadTo4Tri",
424 "ScaleMakeGroups","Scale","ScaleMakeMesh",
425 "FindCoincidentNodesOnPartBut","DoubleElements"
426 ,"" }; // <- mark of the end
427 methodsAcceptingList.Insert( methodNames );
429 if ( methodsAcceptingList.Contains( theCommand->GetMethod() ))
431 for ( int i = theCommand->GetNbArgs(); i > 0; --i )
433 _pyCommand argCmd( theCommand->GetArg( i ));
434 if ( argCmd.GetMethod() == "GetIDSource" &&
435 argCmd.GetNbArgs() == 2 )
437 theCommand->SetArg( i, argCmd.GetArg( 1 ));
444 //================================================================================
446 * \brief Convert a python script using commands of smeshBuilder.py
447 * \param theScript - Input script
448 * \param theEntry2AccessorMethod - returns method names to access to
449 * objects wrapped with python class
450 * \param theObjectNames - names of objects
451 * \param theRemovedObjIDs - entries of objects whose created commands were removed
452 * \param theHistoricalDump - true means to keep all commands, false means
453 * to exclude commands relating to objects removed from study
454 * \retval TCollection_AsciiString - Convertion result
456 //================================================================================
458 TCollection_AsciiString
459 SMESH_2smeshpy::ConvertScript(const TCollection_AsciiString& theScript,
460 Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
461 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
462 std::set< TCollection_AsciiString >& theRemovedObjIDs,
463 SALOMEDS::Study_ptr& theStudy,
464 const bool theToKeepAllCommands)
466 theGen = new _pyGen( theEntry2AccessorMethod,
470 theToKeepAllCommands );
472 // split theScript into separate commands
474 SMESH_NoteBook * aNoteBook = new SMESH_NoteBook();
476 int from = 1, end = theScript.Length(), to;
477 while ( from < end && ( to = theScript.Location( "\n", from, end )))
480 // cut out and store a command
481 aNoteBook->AddCommand( theScript.SubString( from, to - 1 ));
485 aNoteBook->ReplaceVariables();
487 TCollection_AsciiString aNoteScript = aNoteBook->GetResultScript();
491 // split theScript into separate commands
492 from = 1, end = aNoteScript.Length();
493 while ( from < end && ( to = aNoteScript.Location( "\n", from, end )))
496 // cut out and store a command
497 theGen->AddCommand( aNoteScript.SubString( from, to - 1 ));
503 #ifdef DUMP_CONVERSION
504 MESSAGE_BEGIN ( std::endl << " ######## RESULT ######## " << std::endl<< std::endl );
507 // clean commmands of removed objects depending on myIsPublished flag
508 theGen->ClearCommands();
510 // reorder commands after conversion
511 list< Handle(_pyCommand) >::iterator cmd;
514 orderChanges = false;
515 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
516 if ( (*cmd)->SetDependentCmdsAfter() )
518 } while ( orderChanges );
520 // concat commands back into a script
521 TCollection_AsciiString aScript, aPrevCmd;
522 set<_pyID> createdObjects;
523 createdObjects.insert( "smeshBuilder" );
524 createdObjects.insert( "smesh" );
525 createdObjects.insert( "theStudy" );
526 for ( cmd = theGen->GetCommands().begin(); cmd != theGen->GetCommands().end(); ++cmd )
528 #ifdef DUMP_CONVERSION
529 MESSAGE_ADD ( "## COM " << (*cmd)->GetOrderNb() << ": "<< (*cmd)->GetString() << std::endl );
531 if ( !(*cmd)->IsEmpty() && aPrevCmd != (*cmd)->GetString()) {
532 CheckObjectPresence( *cmd, createdObjects );
533 if ( !(*cmd)->IsEmpty() ) {
534 aPrevCmd = (*cmd)->GetString();
548 //================================================================================
550 * \brief _pyGen constructor
552 //================================================================================
554 _pyGen::_pyGen(Resource_DataMapOfAsciiStringAsciiString& theEntry2AccessorMethod,
555 Resource_DataMapOfAsciiStringAsciiString& theObjectNames,
556 std::set< TCollection_AsciiString >& theRemovedObjIDs,
557 SALOMEDS::Study_ptr& theStudy,
558 const bool theToKeepAllCommands)
559 : _pyObject( new _pyCommand( "", 0 )),
561 myID2AccessorMethod( theEntry2AccessorMethod ),
562 myObjectNames( theObjectNames ),
563 myRemovedObjIDs( theRemovedObjIDs ),
565 myToKeepAllCommands( theToKeepAllCommands ),
566 myStudy( SALOMEDS::Study::_duplicate( theStudy )),
567 myGeomIDNb(0), myGeomIDIndex(-1)
569 // make that GetID() to return TPythonDump::SMESHGenName()
570 GetCreationCmd()->Clear();
571 GetCreationCmd()->GetString() = TPythonDump::SMESHGenName();
572 GetCreationCmd()->GetString() += "=";
574 // Find 1st digit of study entry by which a GEOM object differs from a SMESH object
575 if ( !theObjectNames.IsEmpty() && !CORBA::is_nil( theStudy ))
579 SALOMEDS::SComponent_wrap geomComp = theStudy->FindComponent("GEOM");
580 if ( geomComp->_is_nil() ) return;
581 CORBA::String_var entry = geomComp->GetID();
584 // find a SMESH entry
586 Resource_DataMapIteratorOfDataMapOfAsciiStringAsciiString e2n( theObjectNames );
587 for ( ; e2n.More() && smeshID.IsEmpty(); e2n.Next() )
588 if ( _pyCommand::IsStudyEntry( e2n.Key() ))
591 // find 1st difference between smeshID and geomID
592 if ( !geomID.IsEmpty() && !smeshID.IsEmpty() )
593 for ( int i = 1; i <= geomID.Length() && i <= smeshID.Length(); ++i )
594 if ( geomID.Value( i ) != smeshID.Value( i ))
596 myGeomIDNb = geomID.Value( i );
602 //================================================================================
604 * \brief name of SMESH_Gen in smeshBuilder.py
606 //================================================================================
608 const char* _pyGen::AccessorMethod() const
610 return SMESH_2smeshpy::GenName();
613 //================================================================================
615 * \brief Convert a command using a specific converter
616 * \param theCommand - the command to convert
618 //================================================================================
620 Handle(_pyCommand) _pyGen::AddCommand( const TCollection_AsciiString& theCommand)
622 // store theCommand in the sequence
623 myCommands.push_back( new _pyCommand( theCommand, ++myNbCommands ));
625 Handle(_pyCommand) aCommand = myCommands.back();
626 #ifdef DUMP_CONVERSION
627 MESSAGE ( "## COM " << myNbCommands << ": "<< aCommand->GetString() );
630 const _pyID& objID = aCommand->GetObject();
632 if ( objID.IsEmpty() )
635 // Prevent moving a command creating a sub-mesh to the end of the script
636 // if the sub-mesh is used in theCommand as argument
637 // if ( _pySubMesh::CanBeArgOfMethod( aCommand->GetMethod() ))
639 // PlaceSubmeshAfterItsCreation( aCommand );
642 // Method( SMESH.PointStruct(x,y,z)... -> Method( [x,y,z]...
643 StructToList( aCommand );
645 // not to erase _pySelfEraser's etc. used as args in some commands
647 #ifdef USE_STRING_FAMILY
649 if ( myKeepAgrCmdsIDs.IsIn( theCommand, objID ))
651 Handle(_pyObject) obj = FindObject( objID );
654 obj->AddArgCmd( aCommand );
655 //cout << objID << " found in " << theCommand << endl;
659 std::list< _pyID >::const_iterator id = myKeepAgrCmdsIDs.begin();
660 for ( ; id != myKeepAgrCmdsIDs.end(); ++id )
661 if ( *id != objID && theCommand.Search( *id ) > id->Length() )
663 Handle(_pyObject) obj = FindObject( *id );
665 obj->AddArgCmd( aCommand );
670 // Find an object to process theCommand
673 if ( objID == this->GetID() || objID == SMESH_2smeshpy::GenName())
675 this->Process( aCommand );
676 //addFilterUser( aCommand, theGen ); // protect filters from clearing
680 // SMESH_Mesh method?
681 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( objID );
682 if ( id_mesh != myMeshes.end() )
684 //id_mesh->second->AddProcessedCmd( aCommand );
686 // check for mesh editor object
687 if ( aCommand->GetMethod() == "GetMeshEditor" ) { // MeshEditor creation
688 _pyID editorID = aCommand->GetResultValue();
689 Handle(_pyMeshEditor) editor = new _pyMeshEditor( aCommand );
690 myMeshEditors.insert( make_pair( editorID, editor ));
693 // check for SubMesh objects
694 else if ( aCommand->GetMethod() == "GetSubMesh" ) { // SubMesh creation
695 _pyID subMeshID = aCommand->GetResultValue();
696 Handle(_pySubMesh) subMesh = new _pySubMesh( aCommand );
697 CheckObjectIsReCreated( subMesh );
698 myObjects.insert( make_pair( subMeshID, subMesh ));
701 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
702 GetIDSourceToList( aCommand );
704 //addFilterUser( aCommand, theGen ); // protect filters from clearing
706 id_mesh->second->Process( aCommand );
707 id_mesh->second->AddProcessedCmd( aCommand );
711 // SMESH_MeshEditor method?
712 map< _pyID, Handle(_pyMeshEditor) >::iterator id_editor = myMeshEditors.find( objID );
713 if ( id_editor != myMeshEditors.end() )
715 // Method( mesh.GetIDSource([id1,id2]) -> Method( [id1,id2]
716 GetIDSourceToList( aCommand );
718 //addFilterUser( aCommand, theGen ); // protect filters from clearing
720 const TCollection_AsciiString& method = aCommand->GetMethod();
722 // some commands of SMESH_MeshEditor create meshes and groups
723 _pyID meshID, groups;
724 if ( method.Search("MakeMesh") != -1 )
725 meshID = aCommand->GetResultValue();
726 else if ( method == "MakeBoundaryMesh")
727 meshID = aCommand->GetResultValue(1);
728 else if ( method == "MakeBoundaryElements")
729 meshID = aCommand->GetResultValue(2);
731 if ( method.Search("MakeGroups") != -1 ||
732 method == "ExtrusionAlongPathX" ||
733 method == "ExtrusionAlongPathObjX" ||
734 method == "DoubleNodeGroupNew" ||
735 method == "DoubleNodeGroupsNew" ||
736 method == "DoubleNodeElemGroupNew" ||
737 method == "DoubleNodeElemGroupsNew"||
738 method == "DoubleNodeElemGroup2New"||
739 method == "DoubleNodeElemGroups2New"
741 groups = aCommand->GetResultValue();
742 else if ( method == "MakeBoundaryMesh" )
743 groups = aCommand->GetResultValue(2);
744 else if ( method == "MakeBoundaryElements")
745 groups = aCommand->GetResultValue(3);
746 else if ( method == "Create0DElementsOnAllNodes" &&
747 aCommand->GetArg(2).Length() > 2 ) // group name != ''
748 groups = aCommand->GetResultValue();
750 id_editor->second->Process( aCommand );
751 id_editor->second->AddProcessedCmd( aCommand );
754 if ( !meshID.IsEmpty() &&
755 !myMeshes.count( meshID ) &&
756 aCommand->IsStudyEntry( meshID ))
758 _AString processedCommand = aCommand->GetString();
759 Handle(_pyMesh) mesh = new _pyMesh( aCommand, meshID );
760 CheckObjectIsReCreated( mesh );
761 myMeshes.insert( make_pair( meshID, mesh ));
763 aCommand->GetString() = processedCommand; // discard changes made by _pyMesh
766 if ( !groups.IsEmpty() )
768 if ( !aCommand->IsStudyEntry( meshID ))
769 meshID = id_editor->second->GetMesh();
770 Handle(_pyMesh) mesh = myMeshes[ meshID ];
772 list< _pyID > idList = aCommand->GetStudyEntries( groups );
773 list< _pyID >::iterator grID = idList.begin();
774 for ( ; grID != idList.end(); ++grID )
775 if ( !myObjects.count( *grID ))
777 Handle(_pyGroup) group = new _pyGroup( aCommand, *grID );
779 if ( !mesh.IsNull() ) mesh->AddGroup( group );
783 } // SMESH_MeshEditor methods
785 // SMESH_Hypothesis method?
786 Handle(_pyHypothesis) hyp = FindHyp( objID );
787 if ( !hyp.IsNull() && !hyp->IsAlgo() )
789 hyp->Process( aCommand );
790 hyp->AddProcessedCmd( aCommand );
794 // aFilterManager.CreateFilter() ?
795 if ( aCommand->GetMethod() == "CreateFilter" )
797 // Set a more human readable name to a filter
798 // aFilter0x7fbf6c71cfb0 -> aFilter_nb
799 _pyID newID, filterID = aCommand->GetResultValue();
800 int pos = filterID.Search( "0x" );
802 newID = (filterID.SubString(1,pos-1) + "_") + _pyID( ++myNbFilters );
804 Handle(_pyObject) filter( new _pyFilter( aCommand, newID ));
807 // aFreeNodes0x5011f80 = aFilterManager.CreateFreeNodes() ## issue 0020976
808 else if ( theCommand.Search( "aFilterManager.Create" ) > 0 )
810 // create _pySelfEraser for functors
811 Handle(_pySelfEraser) functor = new _pySelfEraser( aCommand );
812 functor->IgnoreOwnCalls(); // to erase if not used as an argument
813 AddObject( functor );
816 // other object method?
817 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.find( objID );
818 if ( id_obj != myObjects.end() ) {
819 id_obj->second->Process( aCommand );
820 id_obj->second->AddProcessedCmd( aCommand );
824 // Add access to a wrapped mesh
825 AddMeshAccessorMethod( aCommand );
827 // Add access to a wrapped algorithm
828 // AddAlgoAccessorMethod( aCommand ); // ??? what if algo won't be wrapped at all ???
830 // PAL12227. PythonDump was not updated at proper time; result is
831 // aCriteria.append(SMESH.Filter.Criterion(17,26,0,'L1',26,25,1e-07,SMESH.EDGE,-1))
832 // TypeError: __init__() takes exactly 11 arguments (10 given)
833 const char wrongCommand[] = "SMESH.Filter.Criterion(";
834 if ( int beg = theCommand.Location( wrongCommand, 1, theCommand.Length() ))
836 _pyCommand tmpCmd( theCommand.SubString( beg, theCommand.Length() ), -1);
837 // there must be 10 arguments, 5-th arg ThresholdID is missing,
838 const int wrongNbArgs = 9, missingArg = 5;
839 if ( tmpCmd.GetNbArgs() == wrongNbArgs )
841 for ( int i = wrongNbArgs; i > missingArg; --i )
842 tmpCmd.SetArg( i + 1, tmpCmd.GetArg( i ));
843 tmpCmd.SetArg( missingArg, "''");
844 aCommand->GetString().Trunc( beg - 1 );
845 aCommand->GetString() += tmpCmd.GetString();
848 // set GetCriterion(elementType,CritType,Compare,Treshold,UnaryOp,BinaryOp,Tolerance)
850 // instead of "SMESH.Filter.Criterion(
851 // Type,Compare,Threshold,ThresholdStr,ThresholdID,UnaryOp,BinaryOp,Tolerance,TypeOfElement,Precision)
852 // 1 2 3 4 5 6 7 8 9 10
853 // in order to avoid the problem of type mismatch of long and FunctorType
854 const TCollection_AsciiString
855 SMESH("SMESH."), dfltFunctor("SMESH.FT_Undefined"), dfltTol("1e-07"), dfltPreci("-1");
856 TCollection_AsciiString
857 Type = aCommand->GetArg(1), // long
858 Compare = aCommand->GetArg(2), // long
859 Threshold = aCommand->GetArg(3), // double
860 ThresholdStr = aCommand->GetArg(4), // string
861 ThresholdID = aCommand->GetArg(5), // string
862 UnaryOp = aCommand->GetArg(6), // long
863 BinaryOp = aCommand->GetArg(7), // long
864 Tolerance = aCommand->GetArg(8), // double
865 TypeOfElement = aCommand->GetArg(9), // ElementType
866 Precision = aCommand->GetArg(10); // long
867 fixFunctorType( Type, Compare, UnaryOp, BinaryOp );
868 Type = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Type.IntegerValue() ));
869 Compare = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( Compare.IntegerValue() ));
870 UnaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( UnaryOp.IntegerValue() ));
871 BinaryOp = SMESH + SMESH::FunctorTypeToString( SMESH::FunctorType( BinaryOp.IntegerValue() ));
873 if ( Compare == "SMESH.FT_EqualTo" )
876 aCommand->RemoveArgs();
877 aCommand->SetObject( SMESH_2smeshpy::GenName() );
878 aCommand->SetMethod( "GetCriterion" );
880 aCommand->SetArg( 1, TypeOfElement );
881 aCommand->SetArg( 2, Type );
882 aCommand->SetArg( 3, Compare );
884 if ( Threshold.IsIntegerValue() )
886 int iGeom = Threshold.IntegerValue();
887 if ( Type == "SMESH.FT_ElemGeomType" )
889 // set SMESH.GeometryType instead of a numerical Threshold
890 const int nbTypes = SMESH::Geom_BALL+1;
891 const char* types[nbTypes] = {
892 "Geom_POINT", "Geom_EDGE", "Geom_TRIANGLE", "Geom_QUADRANGLE", "Geom_POLYGON",
893 "Geom_TETRA", "Geom_PYRAMID", "Geom_HEXA", "Geom_PENTA", "Geom_HEXAGONAL_PRISM",
894 "Geom_POLYHEDRA", "Geom_BALL" };
895 if ( -1 < iGeom && iGeom < nbTypes )
896 Threshold = SMESH + types[ iGeom ];
898 if (Type == "SMESH.FT_EntityType")
900 // set SMESH.EntityType instead of a numerical Threshold
901 const int nbTypes = SMESH::Entity_Ball+1;
902 const char* types[nbTypes] = {
903 "Entity_Node", "Entity_0D", "Entity_Edge", "Entity_Quad_Edge",
904 "Entity_Triangle", "Entity_Quad_Triangle", "Entity_BiQuad_Triangle",
905 "Entity_Quadrangle", "Entity_Quad_Quadrangle", "Entity_BiQuad_Quadrangle",
906 "Entity_Polygon", "Entity_Quad_Polygon", "Entity_Tetra", "Entity_Quad_Tetra",
907 "Entity_Pyramid", "Entity_Quad_Pyramid",
908 "Entity_Hexa", "Entity_Quad_Hexa", "Entity_TriQuad_Hexa",
909 "Entity_Penta", "Entity_Quad_Penta", "Entity_Hexagonal_Prism",
910 "Entity_Polyhedra", "Entity_Quad_Polyhedra", "Entity_Ball" };
911 if ( -1 < iGeom && iGeom < nbTypes )
912 Threshold = SMESH + types[ iGeom ];
915 if ( ThresholdID.Length() != 2 ) // neither '' nor ""
916 aCommand->SetArg( 4, ThresholdID.SubString( 2, ThresholdID.Length()-1 )); // shape entry
917 else if ( ThresholdStr.Length() != 2 )
918 aCommand->SetArg( 4, ThresholdStr );
919 else if ( ThresholdID.Length() != 2 )
920 aCommand->SetArg( 4, ThresholdID );
922 aCommand->SetArg( 4, Threshold );
923 // find the last not default arg
925 if ( Tolerance == dfltTol ) {
927 if ( BinaryOp == dfltFunctor ) {
929 if ( UnaryOp == dfltFunctor )
933 if ( 5 < lastDefault ) aCommand->SetArg( 5, UnaryOp );
934 if ( 6 < lastDefault ) aCommand->SetArg( 6, BinaryOp );
935 if ( 7 < lastDefault ) aCommand->SetArg( 7, Tolerance );
936 if ( Precision != dfltPreci )
938 TCollection_AsciiString crit = aCommand->GetResultValue();
939 aCommand->GetString() += "; ";
940 aCommand->GetString() += crit + ".Precision = " + Precision;
946 //================================================================================
948 * \brief Convert the command or remember it for later conversion
949 * \param theCommand - The python command calling a method of SMESH_Gen
951 //================================================================================
953 void _pyGen::Process( const Handle(_pyCommand)& theCommand )
955 // there are methods to convert:
956 // CreateMesh( shape )
957 // Concatenate( [mesh1, ...], ... )
958 // CreateHypothesis( theHypType, theLibName )
959 // Compute( mesh, geom )
960 // Evaluate( mesh, geom )
962 TCollection_AsciiString method = theCommand->GetMethod();
964 if ( method == "CreateMesh" || method == "CreateEmptyMesh")
966 Handle(_pyMesh) mesh = new _pyMesh( theCommand );
970 if ( method == "CreateMeshesFromUNV" ||
971 method == "CreateMeshesFromSTL" ||
972 method == "CopyMesh" ) // command result is a mesh
974 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
978 if( method == "CreateMeshesFromMED" ||
979 method == "CreateMeshesFromSAUV"||
980 method == "CreateMeshesFromCGNS" ||
981 method == "CreateMeshesFromGMF" ) // command result is ( [mesh1,mesh2], status )
983 for ( int ind = 0; ind < theCommand->GetNbResultValues(); ind++ )
985 _pyID meshID = theCommand->GetResultValue(ind+1);
986 if ( !theCommand->IsStudyEntry( meshID ) ) continue;
987 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue(ind+1));
990 if ( method == "CreateMeshesFromGMF" )
992 // CreateMeshesFromGMF( theFileName, theMakeRequiredGroups ) ->
993 // CreateMeshesFromGMF( theFileName )
994 _AString file = theCommand->GetArg(1);
995 theCommand->RemoveArgs();
996 theCommand->SetArg( 1, file );
1000 // CreateHypothesis()
1001 if ( method == "CreateHypothesis" )
1003 // issue 199929, remove standard library name (default parameter)
1004 const TCollection_AsciiString & aLibName = theCommand->GetArg( 2 );
1005 if ( aLibName.Search( "StdMeshersEngine" ) != -1 ) {
1006 // keep the first argument
1007 TCollection_AsciiString arg = theCommand->GetArg( 1 );
1008 theCommand->RemoveArgs();
1009 theCommand->SetArg( 1, arg );
1012 Handle(_pyHypothesis) hyp = _pyHypothesis::NewHypothesis( theCommand );
1013 CheckObjectIsReCreated( hyp );
1014 myHypos.insert( make_pair( hyp->GetID(), hyp ));
1019 // smeshgen.Compute( mesh, geom ) --> mesh.Compute()
1020 if ( method == "Compute" )
1022 const _pyID& meshID = theCommand->GetArg( 1 );
1023 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1024 if ( id_mesh != myMeshes.end() ) {
1025 theCommand->SetObject( meshID );
1026 theCommand->RemoveArgs();
1027 id_mesh->second->Process( theCommand );
1028 id_mesh->second->AddProcessedCmd( theCommand );
1033 // smeshgen.Evaluate( mesh, geom ) --> mesh.Evaluate(geom)
1034 if ( method == "Evaluate" )
1036 const _pyID& meshID = theCommand->GetArg( 1 );
1037 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.find( meshID );
1038 if ( id_mesh != myMeshes.end() ) {
1039 theCommand->SetObject( meshID );
1040 _pyID geom = theCommand->GetArg( 2 );
1041 theCommand->RemoveArgs();
1042 theCommand->SetArg( 1, geom );
1043 id_mesh->second->AddProcessedCmd( theCommand );
1048 // objects erasing creation command if no more its commands invoked:
1049 // SMESH_Pattern, FilterManager
1050 if ( method == "GetPattern" ||
1051 method == "CreateFilterManager" ||
1052 method == "CreateMeasurements" )
1054 Handle(_pyObject) obj = new _pySelfEraser( theCommand );
1055 if ( !myObjects.insert( make_pair( obj->GetID(), obj )).second )
1056 theCommand->Clear(); // already created
1058 // Concatenate( [mesh1, ...], ... )
1059 else if ( method == "Concatenate" || method == "ConcatenateWithGroups")
1061 if ( method == "ConcatenateWithGroups" ) {
1062 theCommand->SetMethod( "Concatenate" );
1063 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
1065 Handle(_pyMesh) mesh = new _pyMesh( theCommand, theCommand->GetResultValue() );
1067 AddMeshAccessorMethod( theCommand );
1069 else if ( method == "SetName" ) // SetName(obj,name)
1071 // store theCommand as one of object commands to erase it along with the object
1072 const _pyID& objID = theCommand->GetArg( 1 );
1073 Handle(_pyObject) obj = FindObject( objID );
1074 if ( !obj.IsNull() )
1075 obj->AddProcessedCmd( theCommand );
1078 // Replace name of SMESH_Gen
1080 // names of SMESH_Gen methods fully equal to methods defined in smeshBuilder.py
1081 static TStringSet smeshpyMethods;
1082 if ( smeshpyMethods.empty() ) {
1083 const char * names[] =
1084 { "SetEmbeddedMode","IsEmbeddedMode","SetCurrentStudy","GetCurrentStudy",
1085 "GetPattern","GetSubShapesId",
1086 "" }; // <- mark of array end
1087 smeshpyMethods.Insert( names );
1089 if ( smeshpyMethods.Contains( theCommand->GetMethod() ))
1090 // smeshgen.Method() --> smesh.Method()
1091 theCommand->SetObject( SMESH_2smeshpy::SmeshpyName() );
1093 // smeshgen.Method() --> smesh.Method()
1094 theCommand->SetObject( SMESH_2smeshpy::GenName() );
1097 //================================================================================
1099 * \brief Convert the remembered commands
1101 //================================================================================
1103 void _pyGen::Flush()
1105 // create an empty command
1106 myLastCommand = new _pyCommand();
1108 map< _pyID, Handle(_pyMesh) >::iterator id_mesh;
1109 map< _pyID, Handle(_pyObject) >::iterator id_obj;
1110 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp;
1112 if ( IsToKeepAllCommands() ) // historical dump
1114 // set myIsPublished = true to all objects
1115 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1116 id_mesh->second->SetRemovedFromStudy( false );
1117 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1118 id_hyp->second->SetRemovedFromStudy( false );
1119 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1120 id_obj->second->SetRemovedFromStudy( false );
1124 // let hypotheses find referred objects in order to prevent clearing
1125 // not published referred hyps (it's needed for hyps like "LayerDistribution")
1126 list< Handle(_pyMesh) > fatherMeshes;
1127 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1128 if ( !id_hyp->second.IsNull() )
1129 id_hyp->second->GetReferredMeshesAndGeom( fatherMeshes );
1131 // set myIsPublished = false to all objects depending on
1132 // meshes built on a removed geometry
1133 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1134 if ( id_mesh->second->IsNotGeomPublished() )
1135 id_mesh->second->SetRemovedFromStudy( true );
1138 for ( id_mesh = myMeshes.begin(); id_mesh != myMeshes.end(); ++id_mesh )
1139 if ( ! id_mesh->second.IsNull() )
1140 id_mesh->second->Flush();
1143 for ( id_hyp = myHypos.begin(); id_hyp != myHypos.end(); ++id_hyp )
1144 if ( !id_hyp->second.IsNull() ) {
1145 id_hyp->second->Flush();
1146 // smeshgen.CreateHypothesis() --> smesh.CreateHypothesis()
1147 if ( !id_hyp->second->IsWrapped() )
1148 id_hyp->second->GetCreationCmd()->SetObject( SMESH_2smeshpy::GenName() );
1151 // Flush other objects
1152 for ( id_obj = myObjects.begin(); id_obj != myObjects.end(); ++id_obj )
1153 if ( ! id_obj->second.IsNull() )
1154 id_obj->second->Flush();
1156 myLastCommand->SetOrderNb( ++myNbCommands );
1157 myCommands.push_back( myLastCommand );
1160 //================================================================================
1162 * \brief Prevent moving a command creating a sub-mesh to the end of the script
1163 * if the sub-mesh is used in theCmdUsingSubmesh as argument
1165 //================================================================================
1167 void _pyGen::PlaceSubmeshAfterItsCreation( Handle(_pyCommand) theCmdUsingSubmesh ) const
1169 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.begin();
1170 for ( ; id_obj != myObjects.end(); ++id_obj )
1172 if ( !id_obj->second->IsKind( STANDARD_TYPE( _pySubMesh ))) continue;
1173 for ( int iArg = theCmdUsingSubmesh->GetNbArgs(); iArg; --iArg )
1175 const _pyID& arg = theCmdUsingSubmesh->GetArg( iArg );
1176 if ( arg.IsEmpty() || arg.Value( 1 ) == '"' || arg.Value( 1 ) == '\'' )
1178 list< _pyID > idList = theCmdUsingSubmesh->GetStudyEntries( arg );
1179 list< _pyID >::iterator id = idList.begin();
1180 for ( ; id != idList.end(); ++id )
1181 if ( id_obj->first == *id )
1182 // _pySubMesh::Process() does what we need
1183 Handle(_pySubMesh)::DownCast( id_obj->second )->Process( theCmdUsingSubmesh );
1188 //================================================================================
1190 * \brief Clean commmands of removed objects depending on myIsPublished flag
1192 //================================================================================
1194 void _pyGen::ClearCommands()
1196 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1197 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1198 id_mesh->second->ClearCommands();
1200 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1201 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1202 if ( !id_hyp->second.IsNull() )
1203 id_hyp->second->ClearCommands();
1205 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1206 for ( ; id_obj != myObjects.end(); ++id_obj )
1207 id_obj->second->ClearCommands();
1210 //================================================================================
1212 * \brief Release mutual handles of objects
1214 //================================================================================
1218 map< _pyID, Handle(_pyMesh) >::iterator id_mesh = myMeshes.begin();
1219 for ( ; id_mesh != myMeshes.end(); ++id_mesh )
1220 id_mesh->second->Free();
1223 map< _pyID, Handle(_pyMeshEditor) >::iterator id_ed = myMeshEditors.begin();
1224 for ( ; id_ed != myMeshEditors.end(); ++id_ed )
1225 id_ed->second->Free();
1226 myMeshEditors.clear();
1228 map< _pyID, Handle(_pyObject) >::iterator id_obj = myObjects.begin();
1229 for ( ; id_obj != myObjects.end(); ++id_obj )
1230 id_obj->second->Free();
1233 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1234 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1235 if ( !id_hyp->second.IsNull() )
1236 id_hyp->second->Free();
1239 myFile2ExportedMesh.clear();
1241 //myKeepAgrCmdsIDs.Print();
1244 //================================================================================
1246 * \brief Add access method to mesh that is an argument
1247 * \param theCmd - command to add access method
1248 * \retval bool - true if added
1250 //================================================================================
1252 bool _pyGen::AddMeshAccessorMethod( Handle(_pyCommand) theCmd ) const
1255 map< _pyID, Handle(_pyMesh) >::const_iterator id_mesh = myMeshes.begin();
1256 for ( ; id_mesh != myMeshes.end(); ++id_mesh ) {
1257 if ( theCmd->AddAccessorMethod( id_mesh->first, id_mesh->second->AccessorMethod() ))
1263 //================================================================================
1265 * \brief Add access method to algo that is an object or an argument
1266 * \param theCmd - command to add access method
1267 * \retval bool - true if added
1269 //================================================================================
1271 bool _pyGen::AddAlgoAccessorMethod( Handle(_pyCommand) theCmd ) const
1274 map< _pyID, Handle(_pyHypothesis) >::const_iterator id_hyp = myHypos.begin();
1275 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1276 if ( !id_hyp->second.IsNull() &&
1277 id_hyp->second->IsAlgo() && /*(*hyp)->IsWrapped() &&*/
1278 theCmd->AddAccessorMethod( id_hyp->second->GetID(),
1279 id_hyp->second->AccessorMethod() ))
1285 //================================================================================
1287 * \brief Find hypothesis by ID (entry)
1288 * \param theHypID - The hypothesis ID
1289 * \retval Handle(_pyHypothesis) - The found hypothesis
1291 //================================================================================
1293 Handle(_pyHypothesis) _pyGen::FindHyp( const _pyID& theHypID )
1295 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.find( theHypID );
1296 if ( id_hyp != myHypos.end() &&
1297 !id_hyp->second.IsNull() &&
1298 theHypID == id_hyp->second->GetID() )
1299 return id_hyp->second;
1300 return Handle(_pyHypothesis)();
1303 //================================================================================
1305 * \brief Find algorithm able to create a hypothesis
1306 * \param theGeom - The shape ID the algorithm was created on
1307 * \param theMesh - The mesh ID that created the algorithm
1308 * \param theHypothesis - The hypothesis the algorithm sould be able to create
1309 * \retval Handle(_pyHypothesis) - The found algo
1311 //================================================================================
1313 Handle(_pyHypothesis) _pyGen::FindAlgo( const _pyID& theGeom, const _pyID& theMesh,
1314 const Handle(_pyHypothesis)& theHypothesis )
1316 map< _pyID, Handle(_pyHypothesis) >::iterator id_hyp = myHypos.begin();
1317 for ( ; id_hyp != myHypos.end(); ++id_hyp )
1318 if ( !id_hyp->second.IsNull() &&
1319 id_hyp->second->IsAlgo() &&
1320 theHypothesis->CanBeCreatedBy( id_hyp->second->GetAlgoType() ) &&
1321 id_hyp->second->GetGeom() == theGeom &&
1322 id_hyp->second->GetMesh() == theMesh )
1323 return id_hyp->second;
1324 return Handle(_pyHypothesis)();
1327 //================================================================================
1329 * \brief Find subMesh by ID (entry)
1330 * \param theSubMeshID - The subMesh ID
1331 * \retval Handle(_pySubMesh) - The found subMesh
1333 //================================================================================
1335 Handle(_pySubMesh) _pyGen::FindSubMesh( const _pyID& theSubMeshID )
1337 map< _pyID, Handle(_pyObject) >::iterator id_subMesh = myObjects.find(theSubMeshID);
1338 if ( id_subMesh != myObjects.end() )
1339 return Handle(_pySubMesh)::DownCast( id_subMesh->second );
1340 return Handle(_pySubMesh)();
1344 //================================================================================
1346 * \brief Change order of commands in the script
1347 * \param theCmd1 - One command
1348 * \param theCmd2 - Another command
1350 //================================================================================
1352 void _pyGen::ExchangeCommands( Handle(_pyCommand) theCmd1, Handle(_pyCommand) theCmd2 )
1354 list< Handle(_pyCommand) >::iterator pos1, pos2;
1355 pos1 = find( myCommands.begin(), myCommands.end(), theCmd1 );
1356 pos2 = find( myCommands.begin(), myCommands.end(), theCmd2 );
1357 myCommands.insert( pos1, theCmd2 );
1358 myCommands.insert( pos2, theCmd1 );
1359 myCommands.erase( pos1 );
1360 myCommands.erase( pos2 );
1362 int nb1 = theCmd1->GetOrderNb();
1363 theCmd1->SetOrderNb( theCmd2->GetOrderNb() );
1364 theCmd2->SetOrderNb( nb1 );
1365 // cout << "BECOME " << theCmd1->GetOrderNb() << "\t" << theCmd1->GetString() << endl
1366 // << "BECOME " << theCmd2->GetOrderNb() << "\t" << theCmd2->GetString() << endl << endl;
1369 //================================================================================
1371 * \brief Set one command after the other
1372 * \param theCmd - Command to move
1373 * \param theAfterCmd - Command ater which to insert the first one
1375 //================================================================================
1377 void _pyGen::SetCommandAfter( Handle(_pyCommand) theCmd, Handle(_pyCommand) theAfterCmd )
1379 setNeighbourCommand( theCmd, theAfterCmd, true );
1382 //================================================================================
1384 * \brief Set one command before the other
1385 * \param theCmd - Command to move
1386 * \param theBeforeCmd - Command before which to insert the first one
1388 //================================================================================
1390 void _pyGen::SetCommandBefore( Handle(_pyCommand) theCmd, Handle(_pyCommand) theBeforeCmd )
1392 setNeighbourCommand( theCmd, theBeforeCmd, false );
1395 //================================================================================
1397 * \brief Set one command before or after the other
1398 * \param theCmd - Command to move
1399 * \param theOtherCmd - Command ater or before which to insert the first one
1401 //================================================================================
1403 void _pyGen::setNeighbourCommand( Handle(_pyCommand)& theCmd,
1404 Handle(_pyCommand)& theOtherCmd,
1405 const bool theIsAfter )
1407 list< Handle(_pyCommand) >::iterator pos;
1408 pos = find( myCommands.begin(), myCommands.end(), theCmd );
1409 myCommands.erase( pos );
1410 pos = find( myCommands.begin(), myCommands.end(), theOtherCmd );
1411 myCommands.insert( (theIsAfter ? ++pos : pos), theCmd );
1414 for ( pos = myCommands.begin(); pos != myCommands.end(); ++pos)
1415 (*pos)->SetOrderNb( i++ );
1418 //================================================================================
1420 * \brief Call _pyFilter.AddUser() if a filter is used as a command arg
1422 //================================================================================
1424 // void _pyGen::addFilterUser( Handle(_pyCommand)& theCommand, const Handle(_pyObject)& user )
1426 // No more needed after adding _pyObject::myArgCommands
1428 // const char filterPrefix[] = "aFilter0x";
1429 // if ( theCommand->GetString().Search( filterPrefix ) < 1 )
1432 // for ( int i = theCommand->GetNbArgs(); i > 0; --i )
1434 // const _AString & arg = theCommand->GetArg( i );
1435 // // NOT TREATED CASE: arg == "[something, aFilter0x36a2f60]"
1436 // if ( arg.Search( filterPrefix ) != 1 )
1439 // Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( FindObject( arg ));
1440 // if ( !filter.IsNull() )
1442 // filter->AddUser( user );
1443 // if ( !filter->GetNewID().IsEmpty() )
1444 // theCommand->SetArg( i, filter->GetNewID() );
1449 //================================================================================
1451 * \brief Set command be last in list of commands
1452 * \param theCmd - Command to be last
1454 //================================================================================
1456 Handle(_pyCommand)& _pyGen::GetLastCommand()
1458 return myLastCommand;
1461 //================================================================================
1463 * \brief Set method to access to object wrapped with python class
1464 * \param theID - The wrapped object entry
1465 * \param theMethod - The accessor method
1467 //================================================================================
1469 void _pyGen::SetAccessorMethod(const _pyID& theID, const char* theMethod )
1471 myID2AccessorMethod.Bind( theID, (char*) theMethod );
1474 //================================================================================
1476 * \brief Generated new ID for object and assign with existing name
1477 * \param theID - ID of existing object
1479 //================================================================================
1481 _pyID _pyGen::GenerateNewID( const _pyID& theID )
1486 aNewID = theID + _pyID( ":" ) + _pyID( index++ );
1488 while ( myObjectNames.IsBound( aNewID ) );
1490 myObjectNames.Bind( aNewID, myObjectNames.IsBound( theID )
1491 ? (myObjectNames.Find( theID ) + _pyID( "_" ) + _pyID( index-1 ))
1492 : _pyID( "A" ) + aNewID );
1496 //================================================================================
1498 * \brief Stores theObj in myObjects
1500 //================================================================================
1502 void _pyGen::AddObject( Handle(_pyObject)& theObj )
1504 if ( theObj.IsNull() ) return;
1506 CheckObjectIsReCreated( theObj );
1508 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1509 myMeshes.insert( make_pair( theObj->GetID(), Handle(_pyMesh)::DownCast( theObj )));
1511 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1512 myMeshEditors.insert( make_pair( theObj->GetID(), Handle(_pyMeshEditor)::DownCast( theObj )));
1515 myObjects.insert( make_pair( theObj->GetID(), theObj ));
1518 //================================================================================
1520 * \brief Erases an existing object with the same ID. This method should be called
1521 * before storing theObj in _pyGen
1523 //================================================================================
1525 void _pyGen::CheckObjectIsReCreated( Handle(_pyObject)& theObj )
1527 if ( theObj.IsNull() || !_pyCommand::IsStudyEntry( theObj->GetID() ))
1530 const bool isHyp = theObj->IsKind( STANDARD_TYPE( _pyHypothesis ));
1531 Handle(_pyObject) existing =
1532 isHyp ? FindHyp( theObj->GetID() ) : FindObject( theObj->GetID() );
1533 if ( !existing.IsNull() && existing != theObj )
1535 existing->SetRemovedFromStudy( true );
1536 existing->ClearCommands();
1539 if ( myHypos.count( theObj->GetID() ))
1540 myHypos.erase( theObj->GetID() );
1542 else if ( myMeshes.count( theObj->GetID() ))
1544 myMeshes.erase( theObj->GetID() );
1546 else if ( myObjects.count( theObj->GetID() ))
1548 myObjects.erase( theObj->GetID() );
1553 //================================================================================
1555 * \brief Re-register an object with other ID to make it Process() commands of
1556 * other object having this ID
1558 //================================================================================
1560 void _pyGen::SetProxyObject( const _pyID& theID, Handle(_pyObject)& theObj )
1562 if ( theObj.IsNull() ) return;
1564 if ( theObj->IsKind( STANDARD_TYPE( _pyMesh )))
1565 myMeshes.insert( make_pair( theID, Handle(_pyMesh)::DownCast( theObj )));
1567 else if ( theObj->IsKind( STANDARD_TYPE( _pyMeshEditor )))
1568 myMeshEditors.insert( make_pair( theID, Handle(_pyMeshEditor)::DownCast( theObj )));
1571 myObjects.insert( make_pair( theID, theObj ));
1574 //================================================================================
1576 * \brief Finds a _pyObject by ID
1578 //================================================================================
1580 Handle(_pyObject) _pyGen::FindObject( const _pyID& theObjID ) const
1583 map< _pyID, Handle(_pyObject) >::const_iterator id_obj = myObjects.find( theObjID );
1584 if ( id_obj != myObjects.end() )
1585 return id_obj->second;
1588 map< _pyID, Handle(_pyMesh) >::const_iterator id_obj = myMeshes.find( theObjID );
1589 if ( id_obj != myMeshes.end() )
1590 return id_obj->second;
1593 // map< _pyID, Handle(_pyMeshEditor) >::const_iterator id_obj = myMeshEditors.find( theObjID );
1594 // if ( id_obj != myMeshEditors.end() )
1595 // return id_obj->second;
1597 return Handle(_pyObject)();
1600 //================================================================================
1602 * \brief Check if a study entry is under GEOM component
1604 //================================================================================
1606 bool _pyGen::IsGeomObject(const _pyID& theObjID) const
1610 return ( myGeomIDIndex <= theObjID.Length() &&
1611 int( theObjID.Value( myGeomIDIndex )) == myGeomIDNb &&
1612 _pyCommand::IsStudyEntry( theObjID ));
1617 //================================================================================
1619 * \brief Returns true if an object is not present in a study
1621 //================================================================================
1623 bool _pyGen::IsNotPublished(const _pyID& theObjID) const
1625 if ( theObjID.IsEmpty() ) return false;
1627 if ( myObjectNames.IsBound( theObjID ))
1628 return false; // SMESH object is in study
1630 // either the SMESH object is not in study or it is a GEOM object
1631 if ( IsGeomObject( theObjID ))
1633 SALOMEDS::SObject_wrap so = myStudy->FindObjectID( theObjID.ToCString() );
1634 if ( so->_is_nil() ) return true;
1635 CORBA::Object_var obj = so->GetObject();
1636 return CORBA::is_nil( obj );
1638 return true; // SMESH object not in study
1641 //================================================================================
1643 * \brief Add an object to myRemovedObjIDs that leads to that SetName() for
1644 * this object is not dumped
1645 * \param [in] theObjID - entry of the object whose creation command was eliminated
1647 //================================================================================
1649 void _pyGen::ObjectCreationRemoved(const _pyID& theObjID)
1651 myRemovedObjIDs.insert( theObjID );
1654 //================================================================================
1656 * \brief Return reader of hypotheses of plugins
1658 //================================================================================
1660 Handle( _pyHypothesisReader ) _pyGen::GetHypothesisReader() const
1662 if (myHypReader.IsNull() )
1663 ((_pyGen*) this)->myHypReader = new _pyHypothesisReader;
1669 //================================================================================
1671 * \brief Mesh created by SMESH_Gen
1673 //================================================================================
1675 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd)
1676 : _pyObject( theCreationCmd ), myGeomNotInStudy( false )
1678 if ( theCreationCmd->GetMethod() == "CreateMesh" && theGen->IsNotPublished( GetGeom() ))
1679 myGeomNotInStudy = true;
1681 // convert my creation command --> smeshpy.Mesh(...)
1682 Handle(_pyCommand) creationCmd = GetCreationCmd();
1683 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1684 creationCmd->SetMethod( "Mesh" );
1685 theGen->SetAccessorMethod( GetID(), _pyMesh::AccessorMethod() );
1688 //================================================================================
1690 * \brief Mesh created by SMESH_MeshEditor
1692 //================================================================================
1694 _pyMesh::_pyMesh(const Handle(_pyCommand) theCreationCmd, const _pyID& meshId):
1695 _pyObject(theCreationCmd,meshId), myGeomNotInStudy(false )
1697 if ( theCreationCmd->MethodStartsFrom( "CreateMeshesFrom" ))
1699 // this mesh depends on the exported mesh
1700 const TCollection_AsciiString& file = theCreationCmd->GetArg( 1 );
1701 if ( !file.IsEmpty() )
1703 ExportedMeshData& exportData = theGen->FindExportedMesh( file );
1704 addFatherMesh( exportData.myMesh );
1705 if ( !exportData.myLastComputeCmd.IsNull() )
1707 // restore cleared Compute() by which the exported mesh was generated
1708 exportData.myLastComputeCmd->GetString() = exportData.myLastComputeCmdString;
1709 // protect that Compute() cmd from clearing
1710 if ( exportData.myMesh->myLastComputeCmd == exportData.myLastComputeCmd )
1711 exportData.myMesh->myLastComputeCmd.Nullify();
1715 else if ( theCreationCmd->MethodStartsFrom( "Concatenate" ))
1717 // this mesh depends on concatenated meshes
1718 const TCollection_AsciiString& meshIDs = theCreationCmd->GetArg( 1 );
1719 list< _pyID > idList = theCreationCmd->GetStudyEntries( meshIDs );
1720 list< _pyID >::iterator meshID = idList.begin();
1721 for ( ; meshID != idList.end(); ++meshID )
1722 addFatherMesh( *meshID );
1724 else if ( theCreationCmd->GetMethod() == "CopyMesh" )
1726 // this mesh depends on a copied IdSource
1727 const _pyID& objID = theCreationCmd->GetArg( 1 );
1728 addFatherMesh( objID );
1730 else if ( theCreationCmd->GetMethod().Search("MakeMesh") != -1 ||
1731 theCreationCmd->GetMethod() == "MakeBoundaryMesh" ||
1732 theCreationCmd->GetMethod() == "MakeBoundaryElements" )
1734 // this mesh depends on a source mesh
1735 // (theCreationCmd is already Process()ed by _pyMeshEditor)
1736 const _pyID& meshID = theCreationCmd->GetObject();
1737 addFatherMesh( meshID );
1740 // convert my creation command
1741 Handle(_pyCommand) creationCmd = GetCreationCmd();
1742 creationCmd->SetObject( SMESH_2smeshpy::SmeshpyName() );
1743 theGen->SetAccessorMethod( meshId, _pyMesh::AccessorMethod() );
1746 //================================================================================
1748 * \brief Convert an IDL API command of SMESH::SMESH_Mesh to a method call of python Mesh
1749 * \param theCommand - Engine method called for this mesh
1751 //================================================================================
1753 void _pyMesh::Process( const Handle(_pyCommand)& theCommand )
1755 // some methods of SMESH_Mesh interface needs special conversion
1756 // to methods of Mesh python class
1758 // 1. GetSubMesh(geom, name) + AddHypothesis(geom, algo)
1759 // --> in Mesh_Algorithm.Create(mesh, geom, hypo, so)
1760 // 2. AddHypothesis(geom, hyp)
1761 // --> in Mesh_Algorithm.Hypothesis(hyp, args, so)
1762 // 3. CreateGroupFromGEOM(type, name, grp)
1763 // --> in Mesh.Group(grp, name="")
1764 // 4. ExportToMED(f, auto_groups, version)
1765 // --> in Mesh.ExportMED( f, auto_groups, version )
1768 const TCollection_AsciiString& method = theCommand->GetMethod();
1769 // ----------------------------------------------------------------------
1770 if ( method == "Compute" ) // in snapshot mode, clear the previous Compute()
1772 if ( !theGen->IsToKeepAllCommands() ) // !historical
1774 list< Handle(_pyHypothesis) >::iterator hyp;
1775 if ( !myLastComputeCmd.IsNull() )
1777 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1778 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1780 myLastComputeCmd->Clear();
1782 myLastComputeCmd = theCommand;
1784 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1785 (*hyp)->MeshComputed( myLastComputeCmd );
1789 // ----------------------------------------------------------------------
1790 else if ( method == "Clear" ) // in snapshot mode, clear all previous commands
1792 if ( !theGen->IsToKeepAllCommands() ) // !historical
1795 myChildMeshes.empty() ? 0 : myChildMeshes.back()->GetCreationCmd()->GetOrderNb();
1796 // list< Handle(_pyCommand) >::reverse_iterator cmd = myProcessedCmds.rbegin();
1797 // for ( ; cmd != myProcessedCmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1799 if ( !myLastComputeCmd.IsNull() )
1801 list< Handle(_pyHypothesis) >::iterator hyp;
1802 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
1803 (*hyp)->ComputeDiscarded( myLastComputeCmd );
1805 myLastComputeCmd->Clear();
1808 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
1809 for ( ; e != myEditors.end(); ++e )
1811 list< Handle(_pyCommand)>& cmds = (*e)->GetProcessedCmds();
1812 list< Handle(_pyCommand) >::reverse_iterator cmd = cmds.rbegin();
1813 for ( ; cmd != cmds.rend() && (*cmd)->GetOrderNb() > untilCmdNb; ++cmd )
1814 if ( !(*cmd)->IsEmpty() )
1816 if ( (*cmd)->GetStudyEntries( (*cmd)->GetResultValue() ).empty() ) // no object created
1820 myLastComputeCmd = theCommand; // to clear Clear() the same way as Compute()
1823 // ----------------------------------------------------------------------
1824 else if ( method == "GetSubMesh" ) { // collect submeshes of the mesh
1825 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( theCommand->GetResultValue() );
1826 if ( !subMesh.IsNull() ) {
1827 subMesh->SetCreator( this );
1828 mySubmeshes.push_back( subMesh );
1831 // ----------------------------------------------------------------------
1832 else if ( method == "AddHypothesis" ) { // mesh.AddHypothesis(geom, HYPO )
1833 myAddHypCmds.push_back( theCommand );
1835 const _pyID& hypID = theCommand->GetArg( 2 );
1836 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1837 if ( !hyp.IsNull() ) {
1838 myHypos.push_back( hyp );
1839 if ( hyp->GetMesh().IsEmpty() )
1840 hyp->SetMesh( this->GetID() );
1843 // ----------------------------------------------------------------------
1844 else if ( method == "CreateGroup" ||
1845 method == "CreateGroupFromGEOM" ||
1846 method == "CreateGroupFromFilter" )
1848 Handle(_pyGroup) group = new _pyGroup( theCommand );
1849 myGroups.push_back( group );
1850 theGen->AddObject( group );
1852 // ----------------------------------------------------------------------
1853 // update list of groups
1854 else if ( method == "GetGroups" )
1856 bool allGroupsRemoved = true;
1857 TCollection_AsciiString grIDs = theCommand->GetResultValue();
1858 list< _pyID > idList = theCommand->GetStudyEntries( grIDs );
1859 list< _pyID >::iterator grID = idList.begin();
1860 const int nbGroupsBefore = myGroups.size();
1861 Handle(_pyObject) obj;
1862 for ( ; grID != idList.end(); ++grID )
1864 obj = theGen->FindObject( *grID );
1867 Handle(_pyGroup) group = new _pyGroup( theCommand, *grID );
1868 theGen->AddObject( group );
1869 myGroups.push_back( group );
1872 if ( !obj->CanClear() )
1873 allGroupsRemoved = false;
1875 if ( nbGroupsBefore == myGroups.size() ) // no new _pyGroup created
1876 obj->AddProcessedCmd( theCommand ); // to clear theCommand if all groups are removed
1878 if ( !allGroupsRemoved && !theGen->IsToKeepAllCommands() )
1880 // check if the preceding command is Compute();
1881 // if GetGroups() is just after Compute(), this can mean that the groups
1882 // were created by some algorithm and hence Compute() should not be discarded
1883 std::list< Handle(_pyCommand) >& cmdList = theGen->GetCommands();
1884 std::list< Handle(_pyCommand) >::iterator cmd = cmdList.begin();
1885 while ( (*cmd)->GetMethod() == "GetGroups" )
1887 if ( myLastComputeCmd == (*cmd))
1888 // protect last Compute() from clearing by the next Compute()
1889 myLastComputeCmd.Nullify();
1892 // ----------------------------------------------------------------------
1893 // notify a group about full removal
1894 else if ( method == "RemoveGroupWithContents" ||
1895 method == "RemoveGroup")
1897 if ( !theGen->IsToKeepAllCommands() ) { // snapshot mode
1898 const _pyID groupID = theCommand->GetArg( 1 );
1899 Handle(_pyGroup) grp = Handle(_pyGroup)::DownCast( theGen->FindObject( groupID ));
1900 if ( !grp.IsNull() )
1902 if ( method == "RemoveGroupWithContents" )
1903 grp->RemovedWithContents();
1904 // to clear RemoveGroup() if the group creation is cleared
1905 grp->AddProcessedCmd( theCommand );
1909 // ----------------------------------------------------------------------
1910 else if ( theCommand->MethodStartsFrom( "Export" ))
1912 if ( method == "ExportToMED" || // ExportToMED() --> ExportMED()
1913 method == "ExportToMEDX" ) // ExportToMEDX() --> ExportMED()
1915 theCommand->SetMethod( "ExportMED" );
1916 if ( theCommand->GetNbArgs() == 5 )
1918 // ExportToMEDX(...,autoDimension) -> ExportToMEDX(...,meshPart=None,autoDimension)
1919 _AString autoDimension = theCommand->GetArg( 5 );
1920 theCommand->SetArg( 5, "None" );
1921 theCommand->SetArg( 6, autoDimension );
1924 else if ( method == "ExportCGNS" )
1925 { // ExportCGNS(part, ...) -> ExportCGNS(..., part)
1926 _pyID partID = theCommand->GetArg( 1 );
1927 int nbArgs = theCommand->GetNbArgs();
1928 for ( int i = 2; i <= nbArgs; ++i )
1929 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1930 theCommand->SetArg( nbArgs, partID );
1932 else if ( method == "ExportGMF" )
1933 { // ExportGMF(part,file,bool) -> ExportCGNS(file, part)
1934 _pyID partID = theCommand->GetArg( 1 );
1935 _AString file = theCommand->GetArg( 2 );
1936 theCommand->RemoveArgs();
1937 theCommand->SetArg( 1, file );
1938 theCommand->SetArg( 2, partID );
1940 else if ( theCommand->MethodStartsFrom( "ExportPartTo" ))
1941 { // ExportPartTo*(part, ...) -> Export*(..., part)
1943 // remove "PartTo" from the method
1944 TCollection_AsciiString newMethod = method;
1945 newMethod.Remove( 7, 6 );
1946 theCommand->SetMethod( newMethod );
1947 // make the 1st arg be the last one (or last but one for ExportMED())
1948 _pyID partID = theCommand->GetArg( 1 );
1949 int nbArgs = theCommand->GetNbArgs() - (newMethod == "ExportMED");
1950 for ( int i = 2; i <= nbArgs; ++i )
1951 theCommand->SetArg( i-1, theCommand->GetArg( i ));
1952 theCommand->SetArg( nbArgs, partID );
1954 // remember file name
1955 theGen->AddExportedMesh( theCommand->GetArg( 1 ),
1956 ExportedMeshData( this, myLastComputeCmd ));
1958 // ----------------------------------------------------------------------
1959 else if ( method == "RemoveHypothesis" ) // (geom, hyp)
1961 _pyID hypID = theCommand->GetArg( 2 );
1962 _pyID geomID = theCommand->GetArg( 1 );
1963 bool isLocal = ( geomID != GetGeom() );
1965 // check if this mesh still has corresponding addition command
1966 Handle(_pyCommand) addCmd;
1967 list< Handle(_pyCommand) >::iterator cmd;
1968 list< Handle(_pyCommand) >* addCmds[2] = { &myAddHypCmds, &myNotConvertedAddHypCmds };
1969 for ( int i = 0; i < 2; ++i )
1971 list< Handle(_pyCommand )> & addHypCmds = *(addCmds[i]);
1972 for ( cmd = addHypCmds.begin(); cmd != addHypCmds.end(); )
1974 bool sameHyp = true;
1975 if ( hypID != (*cmd)->GetArg( 1 ) && hypID != (*cmd)->GetArg( 2 ))
1976 sameHyp = false; // other hyp
1977 if ( (*cmd)->GetNbArgs() == 2 &&
1978 geomID != (*cmd)->GetArg( 1 ) && geomID != (*cmd)->GetArg( 2 ))
1979 sameHyp = false; // other geom
1980 if ( (*cmd)->GetNbArgs() == 1 && isLocal )
1981 sameHyp = false; // other geom
1985 cmd = addHypCmds.erase( cmd );
1986 if ( !theGen->IsToKeepAllCommands() ) {
1988 theCommand->Clear();
1997 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
1998 if ( !theCommand->IsEmpty() && !hypID.IsEmpty() ) {
1999 // RemoveHypothesis(geom, hyp) --> RemoveHypothesis( hyp, geom=0 )
2000 _pyID geom = theCommand->GetArg( 1 );
2001 theCommand->RemoveArgs();
2002 theCommand->SetArg( 1, hypID );
2003 if ( geom != GetGeom() )
2004 theCommand->SetArg( 2, geom );
2006 // remove hyp from myHypos
2007 myHypos.remove( hyp );
2009 // check for SubMesh order commands
2010 else if ( method == "GetMeshOrder" || method == "SetMeshOrder" )
2012 // make commands GetSubMesh() returning sub-meshes be before using sub-meshes
2013 // by GetMeshOrder() and SetMeshOrder(), since by defalut GetSubMesh()
2014 // commands are moved at the end of the script
2015 TCollection_AsciiString subIDs =
2016 ( method == "SetMeshOrder" ) ? theCommand->GetArg(1) : theCommand->GetResultValue();
2017 list< _pyID > idList = theCommand->GetStudyEntries( subIDs );
2018 list< _pyID >::iterator subID = idList.begin();
2019 for ( ; subID != idList.end(); ++subID )
2021 Handle(_pySubMesh) subMesh = theGen->FindSubMesh( *subID );
2022 if ( !subMesh.IsNull() )
2023 subMesh->Process( theCommand ); // it moves GetSubMesh() before theCommand
2026 // add accessor method if necessary
2029 if ( NeedMeshAccess( theCommand ))
2030 // apply theCommand to the mesh wrapped by smeshpy mesh
2031 AddMeshAccess( theCommand );
2035 //================================================================================
2037 * \brief Return True if addition of accesor method is needed
2039 //================================================================================
2041 bool _pyMesh::NeedMeshAccess( const Handle(_pyCommand)& theCommand )
2043 // names of SMESH_Mesh methods fully equal to methods of python class Mesh,
2044 // so no conversion is needed for them at all:
2045 static TStringSet sameMethods;
2046 if ( sameMethods.empty() ) {
2047 const char * names[] =
2048 { "ExportDAT","ExportUNV","ExportSTL","ExportSAUV", "RemoveGroup","RemoveGroupWithContents",
2049 "GetGroups","UnionGroups","IntersectGroups","CutGroups","GetLog","GetId","ClearLog",
2050 "GetStudyId","HasDuplicatedGroupNamesMED","GetMEDMesh","NbNodes","NbElements",
2051 "NbEdges","NbEdgesOfOrder","NbFaces","NbFacesOfOrder","NbTriangles",
2052 "NbTrianglesOfOrder","NbQuadrangles","NbQuadranglesOfOrder","NbPolygons","NbVolumes",
2053 "NbVolumesOfOrder","NbTetras","NbTetrasOfOrder","NbHexas","NbHexasOfOrder",
2054 "NbPyramids","NbPyramidsOfOrder","NbPrisms","NbPrismsOfOrder","NbPolyhedrons",
2055 "NbSubMesh","GetElementsId","GetElementsByType","GetNodesId","GetElementType",
2056 "GetSubMeshElementsId","GetSubMeshNodesId","GetSubMeshElementType","Dump","GetNodeXYZ",
2057 "GetNodeInverseElements","GetShapeID","GetShapeIDForElem","GetElemNbNodes",
2058 "GetElemNode","IsMediumNode","IsMediumNodeOfAnyElem","ElemNbEdges","ElemNbFaces",
2059 "IsPoly","IsQuadratic","BaryCenter","GetHypothesisList", "SetAutoColor", "GetAutoColor",
2060 "Clear", "ConvertToStandalone", "GetMeshOrder", "SetMeshOrder"
2061 ,"" }; // <- mark of end
2062 sameMethods.Insert( names );
2065 return !sameMethods.Contains( theCommand->GetMethod() );
2068 //================================================================================
2070 * \brief Convert creation and addition of all algos and hypos
2072 //================================================================================
2074 void _pyMesh::Flush()
2077 // get the meshes this mesh depends on via hypotheses
2078 list< Handle(_pyMesh) > fatherMeshes;
2079 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2080 for ( ; hyp != myHypos.end(); ++hyp )
2081 if ( ! (*hyp)->GetReferredMeshesAndGeom( fatherMeshes ))
2082 myGeomNotInStudy = true;
2084 list< Handle(_pyMesh) >::iterator m = fatherMeshes.begin();
2085 for ( ; m != fatherMeshes.end(); ++m )
2086 addFatherMesh( *m );
2087 // if ( removedGeom )
2088 // SetRemovedFromStudy(); // as reffered geometry not in study
2090 if ( myGeomNotInStudy )
2093 list < Handle(_pyCommand) >::iterator cmd;
2095 // try to convert algo addition like this:
2096 // mesh.AddHypothesis(geom, ALGO ) --> ALGO = mesh.Algo()
2097 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2099 Handle(_pyCommand) addCmd = *cmd;
2101 _pyID algoID = addCmd->GetArg( 2 );
2102 Handle(_pyHypothesis) algo = theGen->FindHyp( algoID );
2103 if ( algo.IsNull() || !algo->IsAlgo() )
2106 // check and create new algorithm instance if it is already wrapped
2107 if ( algo->IsWrapped() ) {
2108 _pyID localAlgoID = theGen->GenerateNewID( algoID );
2109 TCollection_AsciiString aNewCmdStr = addCmd->GetIndentation() + localAlgoID +
2110 TCollection_AsciiString( " = " ) + theGen->GetID() +
2111 TCollection_AsciiString( ".CreateHypothesis( \"" ) + algo->GetAlgoType() +
2112 TCollection_AsciiString( "\" )" );
2114 Handle(_pyCommand) newCmd = theGen->AddCommand( aNewCmdStr );
2115 Handle(_pyAlgorithm) newAlgo = Handle(_pyAlgorithm)::DownCast(theGen->FindHyp( localAlgoID ));
2116 if ( !newAlgo.IsNull() ) {
2117 newAlgo->Assign( algo, this->GetID() );
2118 newAlgo->SetCreationCmd( newCmd );
2120 // set algorithm creation
2121 theGen->SetCommandBefore( newCmd, addCmd );
2122 myHypos.push_back( newAlgo );
2123 if ( !myLastComputeCmd.IsNull() &&
2124 newCmd->GetOrderNb() == myLastComputeCmd->GetOrderNb() + 1)
2125 newAlgo->MeshComputed( myLastComputeCmd );
2130 _pyID geom = addCmd->GetArg( 1 );
2131 bool isLocalAlgo = ( geom != GetGeom() );
2134 if ( algo->Addition2Creation( addCmd, this->GetID() )) // OK
2136 // wrapped algo is created after mesh creation
2137 GetCreationCmd()->AddDependantCmd( addCmd );
2139 if ( isLocalAlgo ) {
2140 // mesh.AddHypothesis(geom, ALGO ) --> mesh.AlgoMethod(geom)
2141 addCmd->SetArg( addCmd->GetNbArgs() + 1,
2142 TCollection_AsciiString( "geom=" ) + geom );
2143 // sm = mesh.GetSubMesh(geom, name) --> sm = ALGO.GetSubMesh()
2144 list < Handle(_pySubMesh) >::iterator smIt;
2145 for ( smIt = mySubmeshes.begin(); smIt != mySubmeshes.end(); ++smIt ) {
2146 Handle(_pySubMesh) subMesh = *smIt;
2147 Handle(_pyCommand) subCmd = subMesh->GetCreationCmd();
2148 if ( geom == subCmd->GetArg( 1 )) {
2149 subCmd->SetObject( algo->GetID() );
2150 subCmd->RemoveArgs();
2151 subMesh->SetCreator( algo );
2156 else // KO - ALGO was already created
2158 // mesh.AddHypothesis(geom, ALGO) --> mesh.AddHypothesis(ALGO, geom=0)
2159 addCmd->RemoveArgs();
2160 addCmd->SetArg( 1, algoID );
2162 addCmd->SetArg( 2, geom );
2163 myNotConvertedAddHypCmds.push_back( addCmd );
2167 // try to convert hypo addition like this:
2168 // mesh.AddHypothesis(geom, HYPO ) --> HYPO = algo.Hypo()
2169 for ( cmd = myAddHypCmds.begin(); cmd != myAddHypCmds.end(); ++cmd )
2171 Handle(_pyCommand) addCmd = *cmd;
2172 _pyID hypID = addCmd->GetArg( 2 );
2173 Handle(_pyHypothesis) hyp = theGen->FindHyp( hypID );
2174 if ( hyp.IsNull() || hyp->IsAlgo() )
2176 bool converted = hyp->Addition2Creation( addCmd, this->GetID() );
2178 // mesh.AddHypothesis(geom, HYP) --> mesh.AddHypothesis(HYP, geom=0)
2179 _pyID geom = addCmd->GetArg( 1 );
2180 addCmd->RemoveArgs();
2181 addCmd->SetArg( 1, hypID );
2182 if ( geom != GetGeom() )
2183 addCmd->SetArg( 2, geom );
2184 myNotConvertedAddHypCmds.push_back( addCmd );
2188 myAddHypCmds.clear();
2189 mySubmeshes.clear();
2192 list< Handle(_pyHypothesis) >::iterator hyp = myHypos.begin();
2193 for ( hyp = myHypos.begin(); hyp != myHypos.end(); ++hyp )
2197 //================================================================================
2199 * \brief Sets myIsPublished of me and of all objects depending on me.
2201 //================================================================================
2203 void _pyMesh::SetRemovedFromStudy(const bool isRemoved)
2205 _pyObject::SetRemovedFromStudy(isRemoved);
2207 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2208 for ( ; sm != mySubmeshes.end(); ++sm )
2209 (*sm)->SetRemovedFromStudy(isRemoved);
2211 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2212 for ( ; gr != myGroups.end(); ++gr )
2213 (*gr)->SetRemovedFromStudy(isRemoved);
2215 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2216 for ( ; m != myChildMeshes.end(); ++m )
2217 (*m)->SetRemovedFromStudy(isRemoved);
2219 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2220 for ( ; e != myEditors.end(); ++e )
2221 (*e)->SetRemovedFromStudy(isRemoved);
2224 //================================================================================
2226 * \brief Return true if none of myChildMeshes is in study
2228 //================================================================================
2230 bool _pyMesh::CanClear()
2235 list< Handle(_pyMesh) >::iterator m = myChildMeshes.begin();
2236 for ( ; m != myChildMeshes.end(); ++m )
2237 if ( !(*m)->CanClear() )
2243 //================================================================================
2245 * \brief Clear my commands and commands of mesh editor
2247 //================================================================================
2249 void _pyMesh::ClearCommands()
2255 // mark all sub-objects as not removed, except child meshes
2256 list< Handle(_pyMesh) > children;
2257 children.swap( myChildMeshes );
2258 SetRemovedFromStudy( false );
2259 children.swap( myChildMeshes );
2263 _pyObject::ClearCommands();
2265 list< Handle(_pySubMesh) >::iterator sm = mySubmeshes.begin();
2266 for ( ; sm != mySubmeshes.end(); ++sm )
2267 (*sm)->ClearCommands();
2269 list< Handle(_pyGroup) >::iterator gr = myGroups.begin();
2270 for ( ; gr != myGroups.end(); ++gr )
2271 (*gr)->ClearCommands();
2273 list< Handle(_pyMeshEditor)>::iterator e = myEditors.begin();
2274 for ( ; e != myEditors.end(); ++e )
2275 (*e)->ClearCommands();
2278 //================================================================================
2280 * \brief Add a father mesh by ID
2282 //================================================================================
2284 void _pyMesh::addFatherMesh( const _pyID& meshID )
2286 if ( !meshID.IsEmpty() && meshID != GetID() )
2287 addFatherMesh( Handle(_pyMesh)::DownCast( theGen->FindObject( meshID )));
2290 //================================================================================
2292 * \brief Add a father mesh
2294 //================================================================================
2296 void _pyMesh::addFatherMesh( const Handle(_pyMesh)& mesh )
2298 if ( !mesh.IsNull() && mesh->GetID() != GetID() )
2300 //myFatherMeshes.push_back( mesh );
2301 mesh->myChildMeshes.push_back( this );
2303 // protect last Compute() from clearing by the next Compute()
2304 mesh->myLastComputeCmd.Nullify();
2308 //================================================================================
2310 * \brief MeshEditor convert its commands to ones of mesh
2312 //================================================================================
2314 _pyMeshEditor::_pyMeshEditor(const Handle(_pyCommand)& theCreationCmd):
2315 _pyObject( theCreationCmd )
2317 myMesh = theCreationCmd->GetObject();
2318 myCreationCmdStr = theCreationCmd->GetString();
2319 theCreationCmd->Clear();
2321 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2322 if ( !mesh.IsNull() )
2323 mesh->AddEditor( this );
2326 //================================================================================
2328 * \brief convert its commands to ones of mesh
2330 //================================================================================
2332 void _pyMeshEditor::Process( const Handle(_pyCommand)& theCommand)
2334 // Names of SMESH_MeshEditor methods fully equal to methods of the python class Mesh, so
2335 // commands calling these methods are converted to calls of Mesh methods without
2336 // additional modifs, only object is changed from MeshEditor to Mesh.
2337 static TStringSet sameMethods;
2338 if ( sameMethods.empty() ) {
2339 const char * names[] = {
2340 "RemoveElements","RemoveNodes","RemoveOrphanNodes",
2341 "AddNode","Add0DElement","AddEdge","AddFace","AddPolygonalFace","AddBall",
2342 "AddVolume","AddPolyhedralVolume","AddPolyhedralVolumeByFaces",
2343 "MoveNode", "MoveClosestNodeToPoint",
2344 "InverseDiag","DeleteDiag","Reorient","ReorientObject",
2345 "TriToQuad","TriToQuadObject", "QuadTo4Tri", "SplitQuad","SplitQuadObject",
2346 "BestSplit","Smooth","SmoothObject","SmoothParametric","SmoothParametricObject",
2347 "ConvertToQuadratic","ConvertFromQuadratic","RenumberNodes","RenumberElements",
2348 "RotationSweep","RotationSweepObject","RotationSweepObject1D","RotationSweepObject2D",
2349 "ExtrusionSweep","AdvancedExtrusion","ExtrusionSweepObject","ExtrusionSweepObject1D",
2350 "ExtrusionSweepObject2D","ExtrusionAlongPath","ExtrusionAlongPathObject",
2351 "ExtrusionAlongPathX","ExtrusionAlongPathObject1D","ExtrusionAlongPathObject2D",
2352 "Mirror","MirrorObject","Translate","TranslateObject","Rotate","RotateObject",
2353 "FindCoincidentNodes","MergeNodes","FindEqualElements",
2354 "MergeElements","MergeEqualElements","SewFreeBorders","SewConformFreeBorders",
2355 "SewBorderToSide","SewSideElements","ChangeElemNodes","GetLastCreatedNodes",
2356 "GetLastCreatedElems",
2357 "MirrorMakeMesh","MirrorObjectMakeMesh","TranslateMakeMesh","TranslateObjectMakeMesh",
2358 "Scale","ScaleMakeMesh","RotateMakeMesh","RotateObjectMakeMesh","MakeBoundaryMesh",
2359 "MakeBoundaryElements", "SplitVolumesIntoTetra",
2360 "DoubleElements","DoubleNodes","DoubleNode","DoubleNodeGroup","DoubleNodeGroups",
2361 "DoubleNodeElem","DoubleNodeElemInRegion","DoubleNodeElemGroup",
2362 "DoubleNodeElemGroupInRegion","DoubleNodeElemGroups","DoubleNodeElemGroupsInRegion",
2363 "DoubleNodesOnGroupBoundaries","CreateFlatElementsOnFacesGroups","CreateHoleSkin"
2364 ,"" }; // <- mark of the end
2365 sameMethods.Insert( names );
2368 // names of SMESH_MeshEditor commands in which only a method name must be replaced
2369 TStringMap diffMethods;
2370 if ( diffMethods.empty() ) {
2371 const char * orig2newName[] = {
2372 // original name --------------> new name
2373 "ExtrusionAlongPathObjX" , "ExtrusionAlongPathX",
2374 "FindCoincidentNodesOnPartBut", "FindCoincidentNodesOnPart",
2375 "ConvertToQuadraticObject" , "ConvertToQuadratic",
2376 "ConvertFromQuadraticObject" , "ConvertFromQuadratic",
2377 "Create0DElementsOnAllNodes" , "Add0DElementsToAllNodes",
2378 ""};// <- mark of the end
2379 diffMethods.Insert( orig2newName );
2382 // names of SMESH_MeshEditor methods which differ from methods of Mesh class
2383 // only by last two arguments
2384 static TStringSet diffLastTwoArgsMethods;
2385 if (diffLastTwoArgsMethods.empty() ) {
2386 const char * names[] = {
2387 "MirrorMakeGroups","MirrorObjectMakeGroups",
2388 "TranslateMakeGroups","TranslateObjectMakeGroups","ScaleMakeGroups",
2389 "RotateMakeGroups","RotateObjectMakeGroups",
2390 ""};// <- mark of the end
2391 diffLastTwoArgsMethods.Insert( names );
2394 // only a method name is to change?
2395 const TCollection_AsciiString & method = theCommand->GetMethod();
2396 bool isPyMeshMethod = sameMethods.Contains( method );
2397 if ( !isPyMeshMethod )
2399 TCollection_AsciiString newMethod = diffMethods.Value( method );
2400 if (( isPyMeshMethod = ( newMethod.Length() > 0 )))
2401 theCommand->SetMethod( newMethod );
2403 // ConvertToBiQuadratic(...) -> ConvertToQuadratic(...,True)
2404 if ( !isPyMeshMethod && (method == "ConvertToBiQuadratic" || method == "ConvertToBiQuadraticObject") )
2406 isPyMeshMethod = true;
2407 theCommand->SetMethod( method.SubString( 1, 9) + method.SubString( 12, method.Length()));
2408 theCommand->SetArg( theCommand->GetNbArgs() + 1, "True" );
2411 if ( !isPyMeshMethod )
2413 // Replace SMESH_MeshEditor "*MakeGroups" functions by the Mesh
2414 // functions with the flag "theMakeGroups = True" like:
2415 // SMESH_MeshEditor.CmdMakeGroups => Mesh.Cmd(...,True)
2416 int pos = method.Search("MakeGroups");
2419 isPyMeshMethod = true;
2420 bool is0DmethId = ( method == "ExtrusionSweepMakeGroups0D" );
2421 bool is0DmethObj = ( method == "ExtrusionSweepObject0DMakeGroups");
2423 // 1. Remove "MakeGroups" from the Command
2424 TCollection_AsciiString aMethod = theCommand->GetMethod();
2425 int nbArgsToAdd = diffLastTwoArgsMethods.Contains(aMethod) ? 2 : 1;
2428 pos = pos-2; //Remove "0D" from the Command too
2429 aMethod.Trunc(pos-1);
2430 theCommand->SetMethod(aMethod);
2432 // 2. And add last "True" argument(s)
2433 while(nbArgsToAdd--)
2434 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2435 if( is0DmethId || is0DmethObj )
2436 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2440 // ExtrusionSweep0D() -> ExtrusionSweep()
2441 // ExtrusionSweepObject0D() -> ExtrusionSweepObject()
2442 if ( !isPyMeshMethod && ( method == "ExtrusionSweep0D" ||
2443 method == "ExtrusionSweepObject0D" ))
2445 isPyMeshMethod = true;
2446 theCommand->SetMethod( method.SubString( 1, method.Length()-2));
2447 theCommand->SetArg(theCommand->GetNbArgs()+1,"False"); //sets flag "MakeGroups = False"
2448 theCommand->SetArg(theCommand->GetNbArgs()+1,"True"); //sets flag "IsNode = True"
2451 // DoubleNode...New(...) -> DoubleNode...(...,True)
2452 if ( !isPyMeshMethod && ( method == "DoubleNodeElemGroupNew" ||
2453 method == "DoubleNodeElemGroupsNew" ||
2454 method == "DoubleNodeGroupNew" ||
2455 method == "DoubleNodeGroupsNew" ||
2456 method == "DoubleNodeElemGroup2New" ||
2457 method == "DoubleNodeElemGroups2New"))
2459 isPyMeshMethod = true;
2460 const int excessLen = 3 + int( method.Value( method.Length()-3 ) == '2' );
2461 theCommand->SetMethod( method.SubString( 1, method.Length()-excessLen));
2462 if ( excessLen == 3 )
2464 theCommand->SetArg(theCommand->GetNbArgs()+1,"True");
2466 else if ( theCommand->GetArg(4) == "0" ||
2467 theCommand->GetArg(5) == "0" )
2469 // [ nothing, Group ] = DoubleNodeGroup2New(,,,False, True) ->
2470 // Group = DoubleNodeGroup2New(,,,False, True)
2471 _pyID groupID = theCommand->GetResultValue( 1 + int( theCommand->GetArg(4) == "0"));
2472 theCommand->SetResultValue( groupID );
2475 // FindAmongElementsByPoint(meshPart, x, y, z, elementType) ->
2476 // FindElementsByPoint(x, y, z, elementType, meshPart)
2477 if ( !isPyMeshMethod && method == "FindAmongElementsByPoint" )
2479 isPyMeshMethod = true;
2480 theCommand->SetMethod( "FindElementsByPoint" );
2481 // make the 1st arg be the last one
2482 _pyID partID = theCommand->GetArg( 1 );
2483 int nbArgs = theCommand->GetNbArgs();
2484 for ( int i = 2; i <= nbArgs; ++i )
2485 theCommand->SetArg( i-1, theCommand->GetArg( i ));
2486 theCommand->SetArg( nbArgs, partID );
2488 // Reorient2D( mesh, dir, face, point ) -> Reorient2D( mesh, dir, faceORpoint )
2489 if ( !isPyMeshMethod && method == "Reorient2D" )
2491 isPyMeshMethod = true;
2492 _AString mesh = theCommand->GetArg( 1 );
2493 _AString dir = theCommand->GetArg( 2 );
2494 _AString face = theCommand->GetArg( 3 );
2495 _AString point = theCommand->GetArg( 4 );
2496 theCommand->RemoveArgs();
2497 theCommand->SetArg( 1, mesh );
2498 theCommand->SetArg( 2, dir );
2499 if ( face.Value(1) == '-' || face.Value(1) == '0' ) // invalid: face <= 0
2500 theCommand->SetArg( 3, point );
2502 theCommand->SetArg( 3, face );
2505 if ( method == "QuadToTri" || method == "QuadToTriObject" )
2507 isPyMeshMethod = true;
2508 int crit_arg = theCommand->GetNbArgs();
2509 const _AString& crit = theCommand->GetArg(crit_arg);
2510 if (crit.Search("MaxElementLength2D") != -1)
2511 theCommand->SetArg(crit_arg, "");
2514 if ( isPyMeshMethod )
2516 theCommand->SetObject( myMesh );
2520 // editor creation command is needed only if any editor function is called
2521 theGen->AddMeshAccessorMethod( theCommand ); // for *Object() methods
2522 if ( !myCreationCmdStr.IsEmpty() ) {
2523 GetCreationCmd()->GetString() = myCreationCmdStr;
2524 myCreationCmdStr.Clear();
2529 //================================================================================
2531 * \brief Return true if my mesh can be removed
2533 //================================================================================
2535 bool _pyMeshEditor::CanClear()
2537 Handle(_pyMesh) mesh = ObjectToMesh( theGen->FindObject( myMesh ));
2538 return mesh.IsNull() ? true : mesh->CanClear();
2541 //================================================================================
2543 * \brief _pyHypothesis constructor
2544 * \param theCreationCmd -
2546 //================================================================================
2548 _pyHypothesis::_pyHypothesis(const Handle(_pyCommand)& theCreationCmd):
2549 _pyObject( theCreationCmd ), myCurCrMethod(0)
2551 myIsAlgo = myIsWrapped = /*myIsConverted = myIsLocal = myDim = */false;
2554 //================================================================================
2556 * \brief Creates algorithm or hypothesis
2557 * \param theCreationCmd - The engine command creating a hypothesis
2558 * \retval Handle(_pyHypothesis) - Result _pyHypothesis
2560 //================================================================================
2562 Handle(_pyHypothesis) _pyHypothesis::NewHypothesis( const Handle(_pyCommand)& theCreationCmd)
2564 // theCreationCmd: CreateHypothesis( "theHypType", "theLibName" )
2565 ASSERT (( theCreationCmd->GetMethod() == "CreateHypothesis"));
2567 Handle(_pyHypothesis) hyp, algo;
2570 const TCollection_AsciiString & hypTypeQuoted = theCreationCmd->GetArg( 1 );
2571 if ( hypTypeQuoted.IsEmpty() )
2574 TCollection_AsciiString hypType =
2575 hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
2577 algo = new _pyAlgorithm( theCreationCmd );
2578 hyp = new _pyHypothesis( theCreationCmd );
2580 if ( hypType == "NumberOfSegments" ) {
2581 hyp = new _pyNumberOfSegmentsHyp( theCreationCmd );
2582 hyp->SetConvMethodAndType( "NumberOfSegments", "Regular_1D");
2583 // arg of SetNumberOfSegments() will become the 1-st arg of hyp creation command
2584 hyp->AddArgMethod( "SetNumberOfSegments" );
2585 // arg of SetScaleFactor() will become the 2-nd arg of hyp creation command
2586 hyp->AddArgMethod( "SetScaleFactor" );
2587 hyp->AddArgMethod( "SetReversedEdges" );
2588 // same for ""CompositeSegment_1D:
2589 hyp->SetConvMethodAndType( "NumberOfSegments", "CompositeSegment_1D");
2590 hyp->AddArgMethod( "SetNumberOfSegments" );
2591 hyp->AddArgMethod( "SetScaleFactor" );
2592 hyp->AddArgMethod( "SetReversedEdges" );
2594 else if ( hypType == "SegmentLengthAroundVertex" ) {
2595 hyp = new _pySegmentLengthAroundVertexHyp( theCreationCmd );
2596 hyp->SetConvMethodAndType( "LengthNearVertex", "Regular_1D" );
2597 hyp->AddArgMethod( "SetLength" );
2598 // same for ""CompositeSegment_1D:
2599 hyp->SetConvMethodAndType( "LengthNearVertex", "CompositeSegment_1D");
2600 hyp->AddArgMethod( "SetLength" );
2602 else if ( hypType == "LayerDistribution2D" ) {
2603 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get2DHypothesis" );
2604 hyp->SetConvMethodAndType( "LayerDistribution", "RadialQuadrangle_1D2D");
2606 else if ( hypType == "LayerDistribution" ) {
2607 hyp = new _pyLayerDistributionHypo( theCreationCmd, "Get3DHypothesis" );
2608 hyp->SetConvMethodAndType( "LayerDistribution", "RadialPrism_3D");
2610 else if ( hypType == "CartesianParameters3D" ) {
2611 hyp = new _pyComplexParamHypo( theCreationCmd );
2612 hyp->SetConvMethodAndType( "SetGrid", "Cartesian_3D");
2613 for ( int iArg = 0; iArg < 4; ++iArg )
2614 hyp->setCreationArg( iArg+1, "[]");
2618 hyp = theGen->GetHypothesisReader()->GetHypothesis( hypType, theCreationCmd );
2621 return algo->IsValid() ? algo : hyp;
2624 //================================================================================
2626 * \brief Returns true if addition of this hypothesis to a given mesh can be
2627 * wrapped into hypothesis creation
2629 //================================================================================
2631 bool _pyHypothesis::IsWrappable(const _pyID& theMesh) const
2633 if ( !myIsWrapped && myMesh == theMesh && IsInStudy() )
2635 Handle(_pyObject) pyMesh = theGen->FindObject( myMesh );
2636 if ( !pyMesh.IsNull() && pyMesh->IsInStudy() )
2642 //================================================================================
2644 * \brief Convert the command adding a hypothesis to mesh into a smesh command
2645 * \param theCmd - The command like mesh.AddHypothesis( geom, hypo )
2646 * \param theAlgo - The algo that can create this hypo
2647 * \retval bool - false if the command cant be converted
2649 //================================================================================
2651 bool _pyHypothesis::Addition2Creation( const Handle(_pyCommand)& theCmd,
2652 const _pyID& theMesh)
2654 ASSERT(( theCmd->GetMethod() == "AddHypothesis" ));
2656 if ( !IsWrappable( theMesh ))
2659 myGeom = theCmd->GetArg( 1 );
2661 Handle(_pyHypothesis) algo;
2663 // find algo created on myGeom in theMesh
2664 algo = theGen->FindAlgo( myGeom, theMesh, this );
2665 if ( algo.IsNull() )
2667 // attach hypothesis creation command to be after algo creation command
2668 // because it can be new created instance of algorithm
2669 algo->GetCreationCmd()->AddDependantCmd( theCmd );
2673 // mesh.AddHypothesis(geom,hyp) --> hyp = <theMesh or algo>.myCreationMethod(args)
2674 theCmd->SetResultValue( GetID() );
2675 theCmd->SetObject( IsAlgo() ? theMesh : algo->GetID());
2676 theCmd->SetMethod( IsAlgo() ? GetAlgoCreationMethod() : GetCreationMethod( algo->GetAlgoType() ));
2677 // set args (geom will be set by _pyMesh calling this method)
2678 theCmd->RemoveArgs();
2679 for ( size_t i = 0; i < myCurCrMethod->myArgs.size(); ++i ) {
2680 if ( !myCurCrMethod->myArgs[ i ].IsEmpty() )
2681 theCmd->SetArg( i+1, myCurCrMethod->myArgs[ i ]);
2683 theCmd->SetArg( i+1, "[]");
2685 // set a new creation command
2686 GetCreationCmd()->Clear();
2687 // replace creation command by wrapped instance
2688 // please note, that hypothesis attaches to algo creation command (see upper)
2689 SetCreationCmd( theCmd );
2692 // clear commands setting arg values
2693 list < Handle(_pyCommand) >::iterator argCmd = myArgCommands.begin();
2694 for ( ; argCmd != myArgCommands.end(); ++argCmd )
2697 // set unknown arg commands after hypo creation
2698 Handle(_pyCommand) afterCmd = myIsWrapped ? theCmd : GetCreationCmd();
2699 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2700 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2701 afterCmd->AddDependantCmd( *cmd );
2707 //================================================================================
2709 * \brief Remember hypothesis parameter values
2710 * \param theCommand - The called hypothesis method
2712 //================================================================================
2714 void _pyHypothesis::Process( const Handle(_pyCommand)& theCommand)
2716 ASSERT( !myIsAlgo );
2717 if ( !theGen->IsToKeepAllCommands() )
2718 rememberCmdOfParameter( theCommand );
2720 bool usedCommand = false;
2721 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2722 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2724 CreationMethod& crMethod = type2meth->second;
2725 for ( size_t i = 0; i < crMethod.myArgMethods.size(); ++i ) {
2726 if ( crMethod.myArgMethods[ i ] == theCommand->GetMethod() ) {
2728 myArgCommands.push_back( theCommand );
2730 while ( crMethod.myArgs.size() < i+1 )
2731 crMethod.myArgs.push_back( "[]" );
2732 crMethod.myArgs[ i ] = theCommand->GetArg( crMethod.myArgNb[i] );
2737 myUnusedCommands.push_back( theCommand );
2740 //================================================================================
2742 * \brief Finish conversion
2744 //================================================================================
2746 void _pyHypothesis::Flush()
2750 list < Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
2751 for ( ; cmd != myArgCommands.end(); ++cmd ) {
2752 // Add access to a wrapped mesh
2753 theGen->AddMeshAccessorMethod( *cmd );
2754 // Add access to a wrapped algorithm
2755 theGen->AddAlgoAccessorMethod( *cmd );
2757 cmd = myUnusedCommands.begin();
2758 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2759 // Add access to a wrapped mesh
2760 theGen->AddMeshAccessorMethod( *cmd );
2761 // Add access to a wrapped algorithm
2762 theGen->AddAlgoAccessorMethod( *cmd );
2765 // forget previous hypothesis modifications
2766 myArgCommands.clear();
2767 myUnusedCommands.clear();
2770 //================================================================================
2772 * \brief clear creation, arg and unkown commands
2774 //================================================================================
2776 void _pyHypothesis::ClearAllCommands()
2778 GetCreationCmd()->Clear();
2779 list<Handle(_pyCommand)>::iterator cmd = myArgCommands.begin();
2780 for ( ; cmd != myArgCommands.end(); ++cmd )
2782 cmd = myUnusedCommands.begin();
2783 for ( ; cmd != myUnusedCommands.end(); ++cmd )
2788 //================================================================================
2790 * \brief Assign fields of theOther to me except myIsWrapped
2792 //================================================================================
2794 void _pyHypothesis::Assign( const Handle(_pyHypothesis)& theOther,
2795 const _pyID& theMesh )
2797 // myCreationCmd = theOther->myCreationCmd;
2798 myIsAlgo = theOther->myIsAlgo;
2799 myIsWrapped = false;
2800 myGeom = theOther->myGeom;
2802 myAlgoType2CreationMethod = theOther->myAlgoType2CreationMethod;
2803 myAccumulativeMethods = theOther->myAccumulativeMethods;
2804 //myUnusedCommands = theOther->myUnusedCommands;
2805 // init myCurCrMethod
2806 GetCreationMethod( theOther->GetAlgoType() );
2809 //================================================================================
2811 * \brief Analyze my erasability depending on myReferredObjs
2813 //================================================================================
2815 bool _pyHypothesis::CanClear()
2819 list< Handle(_pyObject) >::iterator obj = myReferredObjs.begin();
2820 for ( ; obj != myReferredObjs.end(); ++obj )
2821 if ( (*obj)->CanClear() )
2828 //================================================================================
2830 * \brief Clear my commands depending on usage by meshes
2832 //================================================================================
2834 void _pyHypothesis::ClearCommands()
2836 // if ( !theGen->IsToKeepAllCommands() )
2838 // bool isUsed = false;
2839 // int lastComputeOrder = 0;
2840 // list<Handle(_pyCommand) >::iterator cmd = myComputeCmds.begin();
2841 // for ( ; cmd != myComputeCmds.end(); ++cmd )
2842 // if ( ! (*cmd)->IsEmpty() )
2845 // if ( (*cmd)->GetOrderNb() > lastComputeOrder )
2846 // lastComputeOrder = (*cmd)->GetOrderNb();
2850 // SetRemovedFromStudy( true );
2854 // // clear my commands invoked after lastComputeOrder
2855 // // map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2856 // // for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2858 // // list< Handle(_pyCommand)> & cmds = m2c->second;
2859 // // if ( !cmds.empty() && cmds.back()->GetOrderNb() > lastComputeOrder )
2860 // // cmds.back()->Clear();
2864 _pyObject::ClearCommands();
2867 //================================================================================
2869 * \brief Find arguments that are objects like mesh, group, geometry
2870 * \param meshes - referred meshes (directly or indirrectly)
2871 * \retval bool - false if a referred geometry is not in the study
2873 //================================================================================
2875 bool _pyHypothesis::GetReferredMeshesAndGeom( list< Handle(_pyMesh) >& meshes )
2877 if ( IsAlgo() ) return true;
2879 bool geomPublished = true;
2880 vector< _AString > args;
2881 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
2882 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
2884 CreationMethod& crMethod = type2meth->second;
2885 args.insert( args.end(), crMethod.myArgs.begin(), crMethod.myArgs.end());
2887 list<Handle(_pyCommand)>::iterator cmd = myUnusedCommands.begin();
2888 for ( ; cmd != myUnusedCommands.end(); ++cmd ) {
2889 for ( int nb = (*cmd)->GetNbArgs(); nb; --nb )
2890 args.push_back( (*cmd)->GetArg( nb ));
2893 for ( size_t i = 0; i < args.size(); ++i )
2895 list< _pyID > idList = _pyCommand::GetStudyEntries( args[ i ]);
2896 if ( idList.empty() && !args[ i ].IsEmpty() )
2897 idList.push_back( args[ i ]);
2898 list< _pyID >::iterator id = idList.begin();
2899 for ( ; id != idList.end(); ++id )
2901 Handle(_pyObject) obj = theGen->FindObject( *id );
2902 if ( obj.IsNull() ) obj = theGen->FindHyp( *id );
2905 if ( theGen->IsGeomObject( *id ) && theGen->IsNotPublished( *id ))
2906 geomPublished = false;
2910 myReferredObjs.push_back( obj );
2911 Handle(_pyMesh) mesh = ObjectToMesh( obj );
2912 if ( !mesh.IsNull() )
2913 meshes.push_back( mesh );
2914 // prevent clearing not published hyps referred e.g. by "LayerDistribution"
2915 else if ( obj->IsKind( STANDARD_TYPE( _pyHypothesis )) && this->IsInStudy() )
2916 obj->SetRemovedFromStudy( false );
2920 return geomPublished;
2923 //================================================================================
2925 * \brief Remember theCommand setting a parameter
2927 //================================================================================
2929 void _pyHypothesis::rememberCmdOfParameter( const Handle(_pyCommand) & theCommand )
2931 // parameters are discriminated by method name
2932 _AString method = theCommand->GetMethod();
2933 if ( myAccumulativeMethods.count( method ))
2934 return; // this method adds values and not override the previus value
2936 // discriminate commands setting different parameters via one method
2937 // by passing parameter names like e.g. SetOption("size", "0.2")
2938 if ( theCommand->GetString().FirstLocationInSet( "'\"", 1, theCommand->Length() ) &&
2939 theCommand->GetNbArgs() > 1 )
2941 // mangle method by appending a 1st textual arg
2942 for ( int iArg = 1; iArg <= theCommand->GetNbArgs(); ++iArg )
2944 const TCollection_AsciiString& arg = theCommand->GetArg( iArg );
2945 if ( arg.Value(1) != '\"' && arg.Value(1) != '\'' ) continue;
2946 if ( !isalpha( arg.Value(2))) continue;
2951 // parameters are discriminated by method name
2952 list< Handle(_pyCommand)>& cmds = myMeth2Commands[ method /*theCommand->GetMethod()*/ ];
2953 if ( !cmds.empty() && !isCmdUsedForCompute( cmds.back() ))
2955 cmds.back()->Clear(); // previous parameter value has not been used
2956 cmds.back() = theCommand;
2960 cmds.push_back( theCommand );
2964 //================================================================================
2966 * \brief Return true if a setting parameter command ha been used to compute mesh
2968 //================================================================================
2970 bool _pyHypothesis::isCmdUsedForCompute( const Handle(_pyCommand) & cmd,
2971 _pyCommand::TAddr avoidComputeAddr ) const
2973 bool isUsed = false;
2974 map< _pyCommand::TAddr, list<Handle(_pyCommand) > >::const_iterator addr2cmds =
2975 myComputeAddr2Cmds.begin();
2976 for ( ; addr2cmds != myComputeAddr2Cmds.end() && !isUsed; ++addr2cmds )
2978 if ( addr2cmds->first == avoidComputeAddr ) continue;
2979 const list<Handle(_pyCommand)> & cmds = addr2cmds->second;
2980 isUsed = ( std::find( cmds.begin(), cmds.end(), cmd ) != cmds.end() );
2985 //================================================================================
2987 * \brief Save commands setting parameters as they are used for a mesh computation
2989 //================================================================================
2991 void _pyHypothesis::MeshComputed( const Handle(_pyCommand)& theComputeCmd )
2993 myComputeCmds.push_back( theComputeCmd );
2994 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
2996 map<TCollection_AsciiString, list< Handle(_pyCommand) > >::iterator m2c;
2997 for ( m2c = myMeth2Commands.begin(); m2c != myMeth2Commands.end(); ++m2c )
2998 savedCmds.push_back( m2c->second.back() );
3001 //================================================================================
3003 * \brief Clear commands setting parameters as a mesh computed using them is cleared
3005 //================================================================================
3007 void _pyHypothesis::ComputeDiscarded( const Handle(_pyCommand)& theComputeCmd )
3009 list<Handle(_pyCommand)>& savedCmds = myComputeAddr2Cmds[ theComputeCmd->GetAddress() ];
3011 list<Handle(_pyCommand)>::iterator cmd = savedCmds.begin();
3012 for ( ; cmd != savedCmds.end(); ++cmd )
3014 // check if a cmd has been used to compute another mesh
3015 if ( isCmdUsedForCompute( *cmd, theComputeCmd->GetAddress() ))
3017 // check if a cmd is a sole command setting its parameter;
3018 // don't use method name for search as it can change
3019 map<TCollection_AsciiString, list<Handle(_pyCommand)> >::iterator
3020 m2cmds = myMeth2Commands.begin();
3021 for ( ; m2cmds != myMeth2Commands.end(); ++m2cmds )
3023 list< Handle(_pyCommand)>& cmds = m2cmds->second;
3024 list< Handle(_pyCommand)>::iterator cmdIt = std::find( cmds.begin(), cmds.end(), *cmd );
3025 if ( cmdIt != cmds.end() )
3027 if ( cmds.back() != *cmd )
3029 cmds.erase( cmdIt );
3036 myComputeAddr2Cmds.erase( theComputeCmd->GetAddress() );
3039 //================================================================================
3041 * \brief Sets an argNb-th argument of current creation command
3042 * \param argNb - argument index countered from 1
3044 //================================================================================
3046 void _pyHypothesis::setCreationArg( const int argNb, const _AString& arg )
3048 if ( myCurCrMethod )
3050 while ( myCurCrMethod->myArgs.size() < argNb )
3051 myCurCrMethod->myArgs.push_back( "None" );
3052 if ( arg.IsEmpty() )
3053 myCurCrMethod->myArgs[ argNb-1 ] = "None";
3055 myCurCrMethod->myArgs[ argNb-1 ] = arg;
3060 //================================================================================
3062 * \brief Remember hypothesis parameter values
3063 * \param theCommand - The called hypothesis method
3065 //================================================================================
3067 void _pyComplexParamHypo::Process( const Handle(_pyCommand)& theCommand)
3069 if ( GetAlgoType() == "Cartesian_3D" )
3071 // CartesianParameters3D hyp
3073 if ( theCommand->GetMethod() == "SetSizeThreshold" )
3075 setCreationArg( 4, theCommand->GetArg( 1 ));
3076 myArgCommands.push_back( theCommand );
3079 if ( theCommand->GetMethod() == "SetGrid" ||
3080 theCommand->GetMethod() == "SetGridSpacing" )
3082 TCollection_AsciiString axis = theCommand->GetArg( theCommand->GetNbArgs() );
3083 int iArg = axis.Value(1) - '0';
3084 if ( theCommand->GetMethod() == "SetGrid" )
3086 setCreationArg( 1+iArg, theCommand->GetArg( 1 ));
3090 myCurCrMethod->myArgs[ iArg ] = "[ ";
3091 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 1 );
3092 myCurCrMethod->myArgs[ iArg ] += ", ";
3093 myCurCrMethod->myArgs[ iArg ] += theCommand->GetArg( 2 );
3094 myCurCrMethod->myArgs[ iArg ] += "]";
3096 myArgCommands.push_back( theCommand );
3097 rememberCmdOfParameter( theCommand );
3102 if( theCommand->GetMethod() == "SetLength" )
3104 // NOW it is OBSOLETE
3105 // ex: hyp.SetLength(start, 1)
3106 // hyp.SetLength(end, 0)
3107 ASSERT(( theCommand->GetArg( 2 ).IsIntegerValue() ));
3108 int i = 1 - theCommand->GetArg( 2 ).IntegerValue();
3109 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3110 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3112 CreationMethod& crMethod = type2meth->second;
3113 while ( crMethod.myArgs.size() < i+1 )
3114 crMethod.myArgs.push_back( "[]" );
3115 crMethod.myArgs[ i ] = theCommand->GetArg( 1 ); // arg value
3117 myArgCommands.push_back( theCommand );
3121 _pyHypothesis::Process( theCommand );
3124 //================================================================================
3126 * \brief Clear SetObjectEntry() as it is called by methods of Mesh_Segment
3128 //================================================================================
3130 void _pyComplexParamHypo::Flush()
3134 list < Handle(_pyCommand) >::iterator cmd = myUnusedCommands.begin();
3135 for ( ; cmd != myUnusedCommands.end(); ++cmd )
3136 if ((*cmd)->GetMethod() == "SetObjectEntry" )
3141 //================================================================================
3143 * \brief Convert methods of 1D hypotheses to my own methods
3144 * \param theCommand - The called hypothesis method
3146 //================================================================================
3148 void _pyLayerDistributionHypo::Process( const Handle(_pyCommand)& theCommand)
3150 if ( theCommand->GetMethod() != "SetLayerDistribution" )
3153 const _pyID& hyp1dID = theCommand->GetArg( 1 );
3154 // Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3155 // if ( hyp1d.IsNull() && ! my1dHyp.IsNull()) // apparently hypId changed at study restoration
3157 // TCollection_AsciiString cmd =
3158 // my1dHyp->GetCreationCmd()->GetIndentation() + hyp1dID + " = " + my1dHyp->GetID();
3159 // Handle(_pyCommand) newCmd = theGen->AddCommand( cmd );
3160 // theGen->SetCommandAfter( newCmd, my1dHyp->GetCreationCmd() );
3163 // else if ( !my1dHyp.IsNull() && hyp1dID != my1dHyp->GetID() )
3165 // // 1D hypo is already set, so distribution changes and the old
3166 // // 1D hypo is thrown away
3167 // my1dHyp->ClearAllCommands();
3170 // //my1dHyp->SetRemovedFromStudy( false );
3172 // if ( !myArgCommands.empty() )
3173 // myArgCommands.back()->Clear();
3174 myCurCrMethod->myArgs.push_back( hyp1dID );
3175 myArgCommands.push_back( theCommand );
3178 //================================================================================
3181 * \param theAdditionCmd - command to be converted
3182 * \param theMesh - mesh instance
3183 * \retval bool - status
3185 //================================================================================
3187 bool _pyLayerDistributionHypo::Addition2Creation( const Handle(_pyCommand)& theAdditionCmd,
3188 const _pyID& theMesh)
3190 myIsWrapped = false;
3192 if ( my1dHyp.IsNull() )
3195 // set "SetLayerDistribution()" after addition cmd
3196 theAdditionCmd->AddDependantCmd( myArgCommands.front() );
3198 _pyID geom = theAdditionCmd->GetArg( 1 );
3200 Handle(_pyHypothesis) algo = theGen->FindAlgo( geom, theMesh, this );
3201 if ( !algo.IsNull() )
3203 my1dHyp->SetMesh( theMesh );
3204 my1dHyp->SetConvMethodAndType(my1dHyp->GetAlgoCreationMethod().ToCString(),
3205 algo->GetAlgoType().ToCString());
3206 if ( !my1dHyp->Addition2Creation( theAdditionCmd, theMesh ))
3209 // clear "SetLayerDistribution()" cmd
3210 myArgCommands.back()->Clear();
3212 // Convert my creation => me = RadialPrismAlgo.Get3DHypothesis()
3214 // find RadialPrism algo created on <geom> for theMesh
3215 GetCreationCmd()->SetObject( algo->GetID() );
3216 GetCreationCmd()->SetMethod( myAlgoMethod );
3217 GetCreationCmd()->RemoveArgs();
3218 theAdditionCmd->AddDependantCmd( GetCreationCmd() );
3224 //================================================================================
3228 //================================================================================
3230 void _pyLayerDistributionHypo::Flush()
3232 // as creation of 1D hyp was written later then it's edition,
3233 // we need to find all it's edition calls and process them
3234 list< Handle(_pyCommand) >::iterator cmd = myArgCommands.begin();
3236 for ( cmd = myArgCommands.begin(); cmd != myArgCommands.end(); ++cmd )
3238 const _pyID& hyp1dID = (*cmd)->GetArg( 1 );
3239 if ( hyp1dID.IsEmpty() ) continue;
3241 Handle(_pyHypothesis) hyp1d = theGen->FindHyp( hyp1dID );
3243 // make a new name for 1D hyp = "HypType" + "_Distribution"
3245 if ( hyp1d.IsNull() ) // apparently hypId changed at study restoration
3247 if ( prevNewName.IsEmpty() ) continue;
3248 newName = prevNewName;
3252 if ( hyp1d->IsWrapped() ) {
3253 newName = hyp1d->GetCreationCmd()->GetMethod();
3256 TCollection_AsciiString hypTypeQuoted = hyp1d->GetCreationCmd()->GetArg(1);
3257 newName = hypTypeQuoted.SubString( 2, hypTypeQuoted.Length() - 1 );
3259 newName += "_Distribution";
3260 prevNewName = newName;
3262 hyp1d->GetCreationCmd()->SetResultValue( newName );
3264 list< Handle(_pyCommand) >& cmds = theGen->GetCommands();
3265 list< Handle(_pyCommand) >::iterator cmdIt = cmds.begin();
3266 for ( ; cmdIt != cmds.end(); ++cmdIt ) {
3267 const _pyID& objID = (*cmdIt)->GetObject();
3268 if ( objID == hyp1dID ) {
3269 if ( !hyp1d.IsNull() )
3271 hyp1d->Process( *cmdIt );
3272 hyp1d->GetCreationCmd()->AddDependantCmd( *cmdIt );
3274 ( *cmdIt )->SetObject( newName );
3277 // Set new hyp name to SetLayerDistribution(hyp1dID) cmd
3278 (*cmd)->SetArg( 1, newName );
3282 //================================================================================
3284 * \brief additionally to Addition2Creation, clears SetDistrType() command
3285 * \param theCmd - AddHypothesis() command
3286 * \param theMesh - mesh to which a hypothesis is added
3287 * \retval bool - convertion result
3289 //================================================================================
3291 bool _pyNumberOfSegmentsHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3292 const _pyID& theMesh)
3294 if ( IsWrappable( theMesh ) && myCurCrMethod->myArgs.size() > 1 ) {
3295 // scale factor (2-nd arg) is provided: clear SetDistrType(1) command
3296 bool scaleDistrType = false;
3297 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3298 for ( ; cmd != myUnusedCommands.rend(); ++cmd ) {
3299 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3300 if ( (*cmd)->GetArg( 1 ) == "1" ) {
3301 scaleDistrType = true;
3304 else if ( !scaleDistrType ) {
3305 // distribution type changed: remove scale factor from args
3306 TType2CrMethod::iterator type2meth = myAlgoType2CreationMethod.begin();
3307 for ( ; type2meth != myAlgoType2CreationMethod.end(); ++type2meth )
3309 CreationMethod& crMethod = type2meth->second;
3310 if ( crMethod.myArgs.size() == 2 )
3311 crMethod.myArgs.pop_back();
3318 return _pyHypothesis::Addition2Creation( theCmd, theMesh );
3321 //================================================================================
3323 * \brief remove repeated commands defining distribution
3325 //================================================================================
3327 void _pyNumberOfSegmentsHyp::Flush()
3329 // find number of the last SetDistrType() command
3330 list<Handle(_pyCommand)>::reverse_iterator cmd = myUnusedCommands.rbegin();
3331 int distrTypeNb = 0;
3332 for ( ; !distrTypeNb && cmd != myUnusedCommands.rend(); ++cmd )
3333 if ( (*cmd)->GetMethod() == "SetDistrType" ) {
3334 if ( cmd != myUnusedCommands.rbegin() )
3335 distrTypeNb = (*cmd)->GetOrderNb();
3337 else if (IsWrapped() && (*cmd)->GetMethod() == "SetObjectEntry" ) {
3340 // clear commands before the last SetDistrType()
3341 list<Handle(_pyCommand)> * cmds[2] = { &myArgCommands, &myUnusedCommands };
3342 set< int > treatedCmdNbs; // avoid treating same cmd twice
3343 for ( int i = 0; i < 2; ++i ) {
3344 set<TCollection_AsciiString> uniqueMethods;
3345 list<Handle(_pyCommand)> & cmdList = *cmds[i];
3346 for ( cmd = cmdList.rbegin(); cmd != cmdList.rend(); ++cmd )
3348 if ( !treatedCmdNbs.insert( (*cmd)->GetOrderNb() ).second )
3349 continue;// avoid treating same cmd twice
3350 bool clear = ( (*cmd)->GetOrderNb() < distrTypeNb );
3351 const TCollection_AsciiString& method = (*cmd)->GetMethod();
3352 if ( !clear || method == "SetNumberOfSegments" ) {
3353 bool isNewInSet = uniqueMethods.insert( method ).second;
3354 clear = !isNewInSet;
3363 //================================================================================
3365 * \brief Convert the command adding "SegmentLengthAroundVertex" to mesh
3366 * into regular1D.LengthNearVertex( length, vertex )
3367 * \param theCmd - The command like mesh.AddHypothesis( vertex, SegmentLengthAroundVertex )
3368 * \param theMesh - The mesh needing this hypo
3369 * \retval bool - false if the command cant be converted
3371 //================================================================================
3373 bool _pySegmentLengthAroundVertexHyp::Addition2Creation( const Handle(_pyCommand)& theCmd,
3374 const _pyID& theMeshID)
3376 if ( IsWrappable( theMeshID )) {
3378 _pyID vertex = theCmd->GetArg( 1 );
3380 // the problem here is that segment algo will not be found
3381 // by pyHypothesis::Addition2Creation() for <vertex>, so we try to find
3382 // geometry where segment algorithm is assigned
3383 Handle(_pyHypothesis) algo;
3384 _pyID geom = vertex;
3385 while ( algo.IsNull() && !geom.IsEmpty()) {
3386 // try to find geom as a father of <vertex>
3387 geom = FatherID( geom );
3388 algo = theGen->FindAlgo( geom, theMeshID, this );
3390 if ( algo.IsNull() )
3391 return false; // also possible to find geom as brother of veretex...
3392 // set geom instead of vertex
3393 theCmd->SetArg( 1, geom );
3395 // set vertex as a second arg
3396 if ( myCurCrMethod->myArgs.size() < 1) setCreationArg( 1, "1" ); // :(
3397 setCreationArg( 2, vertex );
3399 // mesh.AddHypothesis(vertex, SegmentLengthAroundVertex) -->
3400 // theMeshID.LengthNearVertex( length, vertex )
3401 return _pyHypothesis::Addition2Creation( theCmd, theMeshID );
3406 //================================================================================
3408 * \brief _pyAlgorithm constructor
3409 * \param theCreationCmd - The command like "algo = smeshgen.CreateHypothesis(type,lib)"
3411 //================================================================================
3413 _pyAlgorithm::_pyAlgorithm(const Handle(_pyCommand)& theCreationCmd)
3414 : _pyHypothesis( theCreationCmd )
3419 //================================================================================
3421 * \brief Convert the command adding an algorithm to mesh
3422 * \param theCmd - The command like mesh.AddHypothesis( geom, algo )
3423 * \param theMesh - The mesh needing this algo
3424 * \retval bool - false if the command cant be converted
3426 //================================================================================
3428 bool _pyAlgorithm::Addition2Creation( const Handle(_pyCommand)& theCmd,
3429 const _pyID& theMeshID)
3431 // mesh.AddHypothesis(geom,algo) --> theMeshID.myCreationMethod()
3432 if ( _pyHypothesis::Addition2Creation( theCmd, theMeshID )) {
3433 theGen->SetAccessorMethod( GetID(), "GetAlgorithm()" );
3439 //================================================================================
3441 * \brief Return starting position of a part of python command
3442 * \param thePartIndex - The index of command part
3443 * \retval int - Part position
3445 //================================================================================
3447 int _pyCommand::GetBegPos( int thePartIndex )
3451 if ( myBegPos.Length() < thePartIndex )
3453 ASSERT( thePartIndex > 0 );
3454 return myBegPos( thePartIndex );
3457 //================================================================================
3459 * \brief Store starting position of a part of python command
3460 * \param thePartIndex - The index of command part
3461 * \param thePosition - Part position
3463 //================================================================================
3465 void _pyCommand::SetBegPos( int thePartIndex, int thePosition )
3467 while ( myBegPos.Length() < thePartIndex )
3468 myBegPos.Append( UNKNOWN );
3469 ASSERT( thePartIndex > 0 );
3470 myBegPos( thePartIndex ) = thePosition;
3473 //================================================================================
3475 * \brief Returns whitespace symbols at the line beginning
3476 * \retval TCollection_AsciiString - result
3478 //================================================================================
3480 TCollection_AsciiString _pyCommand::GetIndentation()
3483 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3484 GetWord( myString, end, true );
3486 end = GetBegPos( RESULT_IND );
3487 return myString.SubString( 1, end - 1 );
3490 //================================================================================
3492 * \brief Return substring of python command looking like ResultValue = Obj.Meth()
3493 * \retval const TCollection_AsciiString & - ResultValue substring
3495 //================================================================================
3497 const TCollection_AsciiString & _pyCommand::GetResultValue()
3499 if ( GetBegPos( RESULT_IND ) == UNKNOWN )
3501 SetBegPos( RESULT_IND, EMPTY );
3502 int begPos, endPos = myString.Location( "=", 1, Length() );
3506 while ( begPos < endPos && isspace( myString.Value( begPos ))) ++begPos;
3507 if ( begPos < endPos )
3509 SetBegPos( RESULT_IND, begPos );
3511 while ( begPos < endPos && isspace( myString.Value( endPos ))) --endPos;
3512 myRes = myString.SubString( begPos, endPos );
3519 //================================================================================
3521 * \brief Return number of python command result value ResultValue = Obj.Meth()
3523 //================================================================================
3525 int _pyCommand::GetNbResultValues()
3529 int endPos = myString.Location( "=", 1, Length() );
3530 while ( begPos < endPos )
3532 _AString str = GetWord( myString, begPos, true );
3533 begPos = begPos+ str.Length();
3540 //================================================================================
3542 * \brief Return substring of python command looking like
3543 * ResultValue1 , ResultValue2,... = Obj.Meth() with res index
3544 * \retval const TCollection_AsciiString & - ResultValue with res index substring
3546 //================================================================================
3547 TCollection_AsciiString _pyCommand::GetResultValue(int res)
3550 if ( SkipSpaces( myString, begPos ) && myString.Value( begPos ) == '[' )
3551 ++begPos; // skip [, else the whole list is returned
3552 int endPos = myString.Location( "=", 1, Length() );
3554 while ( begPos < endPos) {
3555 _AString result = GetWord( myString, begPos, true );
3556 begPos = begPos + result.Length();
3559 result.RemoveAll('[');
3560 result.RemoveAll(']');
3566 return theEmptyString;
3569 //================================================================================
3571 * \brief Return substring of python command looking like ResVal = Object.Meth()
3572 * \retval const TCollection_AsciiString & - Object substring
3574 //================================================================================
3576 const TCollection_AsciiString & _pyCommand::GetObject()
3578 if ( GetBegPos( OBJECT_IND ) == UNKNOWN )
3581 int begPos = GetBegPos( RESULT_IND );
3583 begPos = myString.Location( "=", 1, Length() ) + 1;
3584 // is '=' in the string argument (for example, name) or not
3585 int nb1 = 0; // number of ' character at the left of =
3586 int nb2 = 0; // number of " character at the left of =
3587 for ( int i = 1; i < begPos-1; i++ ) {
3588 if ( myString.Value( i )=='\'' )
3590 else if ( myString.Value( i )=='"' )
3593 // if number of ' or " is not divisible by 2,
3594 // then get an object at the start of the command
3595 if ( nb1 % 2 != 0 || nb2 % 2 != 0 )
3599 begPos += myRes.Length();
3601 myObj = GetWord( myString, begPos, true );
3602 if ( begPos != EMPTY )
3604 // check if object is complex,
3605 // so far consider case like "smesh.Method()"
3606 if ( int bracketPos = myString.Location( "(", begPos, Length() )) {
3607 //if ( bracketPos==0 ) bracketPos = Length();
3608 int dotPos = begPos+myObj.Length();
3609 while ( dotPos+1 < bracketPos ) {
3610 if ( int pos = myString.Location( ".", dotPos+1, bracketPos ))
3615 if ( dotPos > begPos+myObj.Length() )
3616 myObj = myString.SubString( begPos, dotPos-1 );
3619 // 1st word after '=' is an object
3620 // else // no method -> no object
3626 SetBegPos( OBJECT_IND, begPos );
3632 //================================================================================
3634 * \brief Return substring of python command looking like ResVal = Obj.Method()
3635 * \retval const TCollection_AsciiString & - Method substring
3637 //================================================================================
3639 const TCollection_AsciiString & _pyCommand::GetMethod()
3641 if ( GetBegPos( METHOD_IND ) == UNKNOWN )
3644 int begPos = GetBegPos( OBJECT_IND ) + myObj.Length();
3645 bool forward = true;
3647 begPos = myString.Location( "(", 1, Length() ) - 1;
3651 myMeth = GetWord( myString, begPos, forward );
3652 SetBegPos( METHOD_IND, begPos );
3658 //================================================================================
3660 * \brief Returns true if there are brackets after the method
3662 //================================================================================
3664 bool _pyCommand::IsMethodCall()
3666 if ( GetMethod().IsEmpty() )
3668 const char* s = myString.ToCString() + GetBegPos( METHOD_IND ) + myMeth.Length() - 1;
3669 return ( s[0] == '(' || s[1] == '(' );
3672 //================================================================================
3674 * \brief Return substring of python command looking like ResVal = Obj.Meth(Arg1,...)
3675 * \retval const TCollection_AsciiString & - Arg<index> substring
3677 //================================================================================
3679 const TCollection_AsciiString & _pyCommand::GetArg( int index )
3681 if ( GetBegPos( ARG1_IND ) == UNKNOWN )
3685 int pos = GetBegPos( METHOD_IND ) + myMeth.Length();
3687 pos = myString.Location( "(", 1, Length() );
3691 // we are at or before '(', skip it if present
3693 while ( pos <= Length() && myString.Value( pos ) != '(' ) ++pos;
3694 if ( pos > Length() )
3698 SetBegPos( ARG1_IND, 0 ); // even no '('
3699 return theEmptyString;
3703 list< TCollection_AsciiString > separatorStack( 1, ",)");
3704 bool ignoreNesting = false;
3706 while ( pos <= Length() )
3708 const char chr = myString.Value( pos );
3710 if ( separatorStack.back().Location( chr, 1, separatorStack.back().Length()))
3712 if ( separatorStack.size() == 1 ) // a comma dividing args or a terminal ')' found
3714 while ( pos-1 >= prevPos && isspace( myString.Value( prevPos )))
3716 TCollection_AsciiString arg;
3717 if ( pos-1 >= prevPos ) {
3718 arg = myString.SubString( prevPos, pos-1 );
3719 arg.RightAdjust(); // remove spaces
3722 if ( !arg.IsEmpty() || chr == ',' )
3724 SetBegPos( ARG1_IND + myArgs.Length(), prevPos );
3725 myArgs.Append( arg );
3731 else // end of nesting args found
3733 separatorStack.pop_back();
3734 ignoreNesting = false;
3737 else if ( !ignoreNesting )
3740 case '(' : separatorStack.push_back(")"); break;
3741 case '[' : separatorStack.push_back("]"); break;
3742 case '\'': separatorStack.push_back("'"); ignoreNesting=true; break;
3743 case '"' : separatorStack.push_back("\""); ignoreNesting=true; break;
3750 if ( myArgs.Length() < index )
3751 return theEmptyString;
3752 return myArgs( index );
3755 //================================================================================
3757 * \brief Check if char is a word part
3758 * \param c - The character to check
3759 * \retval bool - The check result
3761 //================================================================================
3763 static inline bool isWord(const char c, const bool dotIsWord)
3766 !isspace(c) && c != ',' && c != '=' && c != ')' && c != '(' && ( dotIsWord || c != '.');
3769 //================================================================================
3771 * \brief Looks for a word in the string and returns word's beginning
3772 * \param theString - The input string
3773 * \param theStartPos - The position to start the search, returning word's beginning
3774 * \param theForward - The search direction
3775 * \retval TCollection_AsciiString - The found word
3777 //================================================================================
3779 TCollection_AsciiString _pyCommand::GetWord( const _AString & theString,
3781 const bool theForward,
3782 const bool dotIsWord )
3784 int beg = theStartPos, end = theStartPos;
3785 theStartPos = EMPTY;
3786 if ( beg < 1 || beg > theString.Length() )
3787 return theEmptyString;
3789 if ( theForward ) { // search forward
3791 while ( beg <= theString.Length() && !isWord( theString.Value( beg ), dotIsWord))
3793 if ( beg > theString.Length() )
3794 return theEmptyString; // no word found
3797 char begChar = theString.Value( beg );
3798 if ( begChar == '"' || begChar == '\'' || begChar == '[') {
3799 char endChar = ( begChar == '[' ) ? ']' : begChar;
3800 // end is at the corresponding quoting mark or bracket
3801 while ( end < theString.Length() &&
3802 ( theString.Value( end ) != endChar || theString.Value( end-1 ) == '\\'))
3806 while ( end <= theString.Length() && isWord( theString.Value( end ), dotIsWord))
3811 else { // search backward
3813 while ( end > 0 && !isWord( theString.Value( end ), dotIsWord))
3816 return theEmptyString; // no word found
3818 char endChar = theString.Value( end );
3819 if ( endChar == '"' || endChar == '\'' || endChar == ']') {
3820 char begChar = ( endChar == ']' ) ? '[' : endChar;
3821 // beg is at the corresponding quoting mark
3823 ( theString.Value( beg ) != begChar || theString.Value( beg-1 ) == '\\'))
3827 while ( beg > 0 && isWord( theString.Value( beg ), dotIsWord))
3833 //cout << theString << " ---- " << beg << " - " << end << endl;
3834 return theString.SubString( beg, end );
3837 //================================================================================
3839 * \brief Returns true if the string looks like a study entry
3841 //================================================================================
3843 bool _pyCommand::IsStudyEntry( const TCollection_AsciiString& str )
3845 if ( str.Length() < 5 ) return false;
3847 int nbColons = 0, isColon;
3848 for ( int i = 1; i <= str.Length(); ++i )
3850 char c = str.Value(i);
3851 if (!( isColon = (c == ':')) && ( c < '0' || c > '9' ))
3853 nbColons += isColon;
3855 return nbColons > 2 && str.Length()-nbColons > 2;
3858 //================================================================================
3860 * \brief Returns true if the string looks like an object ID but not like a list,
3861 * string, command etc.
3863 //================================================================================
3865 bool _pyCommand::IsID( const TCollection_AsciiString& str )
3867 if ( str.Length() < 1 ) return false;
3869 if ( isdigit( str.Value( 1 )))
3870 return IsStudyEntry( str );
3872 for ( int i = 1; i <= str.Length(); ++i )
3873 if ( !isalnum( str.Value( i )) && !str.Value( i ) != '_' )
3879 //================================================================================
3881 * \brief Finds entries in a sting
3883 //================================================================================
3885 std::list< _pyID > _pyCommand::GetStudyEntries( const TCollection_AsciiString& str )
3887 std::list< _pyID > resList;
3889 while ( ++pos <= str.Length() )
3891 if ( !isdigit( str.Value( pos ))) continue;
3892 if ( pos != 1 && ( isalpha( str.Value( pos-1 ) || str.Value( pos-1 ) == ':'))) continue;
3895 while ( ++end <= str.Length() && ( isdigit( str.Value( end )) || str.Value( end ) == ':' ));
3896 _pyID entry = str.SubString( pos, end-1 );
3898 if ( IsStudyEntry( entry ))
3899 resList.push_back( entry );
3904 //================================================================================
3906 * \brief Look for position where not space char is
3907 * \param theString - The string
3908 * \param thePos - The position to search from and which returns result
3909 * \retval bool - false if there are only space after thePos in theString
3911 //================================================================================
3913 bool _pyCommand::SkipSpaces( const TCollection_AsciiString & theString, int & thePos )
3915 if ( thePos < 1 || thePos > theString.Length() )
3918 while ( thePos <= theString.Length() && isspace( theString.Value( thePos )))
3921 return thePos <= theString.Length();
3924 //================================================================================
3926 * \brief Modify a part of the command
3927 * \param thePartIndex - The index of the part
3928 * \param thePart - The new part string
3929 * \param theOldPart - The old part
3931 //================================================================================
3933 void _pyCommand::SetPart(int thePartIndex, const TCollection_AsciiString& thePart,
3934 TCollection_AsciiString& theOldPart)
3936 int pos = GetBegPos( thePartIndex );
3937 if ( pos <= Length() && theOldPart != thePart)
3939 TCollection_AsciiString seperator;
3941 pos = GetBegPos( thePartIndex + 1 );
3942 if ( pos < 1 ) return;
3943 switch ( thePartIndex ) {
3944 case RESULT_IND: seperator = " = "; break;
3945 case OBJECT_IND: seperator = "."; break;
3946 case METHOD_IND: seperator = "()"; break;
3950 myString.Remove( pos, theOldPart.Length() );
3951 if ( !seperator.IsEmpty() )
3952 myString.Insert( pos , seperator );
3953 myString.Insert( pos, thePart );
3954 // update starting positions of the following parts
3955 int posDelta = thePart.Length() + seperator.Length() - theOldPart.Length();
3956 for ( int i = thePartIndex + 1; i <= myBegPos.Length(); ++i ) {
3957 if ( myBegPos( i ) > 0 )
3958 myBegPos( i ) += posDelta;
3960 theOldPart = thePart;
3964 //================================================================================
3966 * \brief Set agrument
3967 * \param index - The argument index, it counts from 1
3968 * \param theArg - The argument string
3970 //================================================================================
3972 void _pyCommand::SetArg( int index, const TCollection_AsciiString& theArg)
3975 int argInd = ARG1_IND + index - 1;
3976 int pos = GetBegPos( argInd );
3977 if ( pos < 1 ) // no index-th arg exist, append inexistent args
3979 // find a closing parenthesis
3980 if ( GetNbArgs() != 0 && index <= GetNbArgs() ) {
3981 int lastArgInd = GetNbArgs();
3982 pos = GetBegPos( ARG1_IND + lastArgInd - 1 ) + GetArg( lastArgInd ).Length();
3983 while ( pos > 0 && pos <= Length() && myString.Value( pos ) != ')' )
3988 while ( pos > 0 && myString.Value( pos ) != ')' )
3991 if ( pos < 1 || myString.Value( pos ) != ')' ) { // no parentheses at all
3995 while ( myArgs.Length() < index ) {
3996 if ( myArgs.Length() )
3997 myString.Insert( pos++, "," );
3998 myArgs.Append("None");
3999 myString.Insert( pos, myArgs.Last() );
4000 SetBegPos( ARG1_IND + myArgs.Length() - 1, pos );
4001 pos += myArgs.Last().Length();
4004 SetPart( argInd, theArg, myArgs( index ));
4007 //================================================================================
4009 * \brief Empty arg list
4011 //================================================================================
4013 void _pyCommand::RemoveArgs()
4015 if ( int pos = myString.Location( '(', Max( 1, GetBegPos( METHOD_IND )), Length() ))
4016 myString.Trunc( pos );
4019 if ( myBegPos.Length() >= ARG1_IND )
4020 myBegPos.Remove( ARG1_IND, myBegPos.Length() );
4023 //================================================================================
4025 * \brief Comment a python command
4027 //================================================================================
4029 void _pyCommand::Comment()
4031 if ( IsEmpty() ) return;
4034 while ( i <= Length() && isspace( myString.Value(i) )) ++i;
4035 if ( i <= Length() )
4037 myString.Insert( i, "#" );
4038 for ( int iPart = 1; iPart <= myBegPos.Length(); ++iPart )
4040 int begPos = GetBegPos( iPart + 1 );
4041 if ( begPos != UNKNOWN )
4042 SetBegPos( iPart + 1, begPos + 1 );
4047 //================================================================================
4049 * \brief Set dependent commands after this one
4051 //================================================================================
4053 bool _pyCommand::SetDependentCmdsAfter() const
4055 bool orderChanged = false;
4056 list< Handle(_pyCommand)>::const_reverse_iterator cmd = myDependentCmds.rbegin();
4057 for ( ; cmd != myDependentCmds.rend(); ++cmd ) {
4058 if ( (*cmd)->GetOrderNb() < GetOrderNb() ) {
4059 orderChanged = true;
4060 theGen->SetCommandAfter( *cmd, this );
4061 (*cmd)->SetDependentCmdsAfter();
4064 return orderChanged;
4066 //================================================================================
4068 * \brief Insert accessor method after theObjectID
4069 * \param theObjectID - id of the accessed object
4070 * \param theAcsMethod - name of the method giving access to the object
4071 * \retval bool - false if theObjectID is not found in the command string
4073 //================================================================================
4075 bool _pyCommand::AddAccessorMethod( _pyID theObjectID, const char* theAcsMethod )
4077 if ( !theAcsMethod )
4079 // start object search from the object, i.e. ignore result
4081 int beg = GetBegPos( OBJECT_IND );
4082 if ( beg < 1 || beg > Length() )
4085 while (( beg = myString.Location( theObjectID, beg, Length() )))
4087 // check that theObjectID is not just a part of a longer ID
4088 int afterEnd = beg + theObjectID.Length();
4089 Standard_Character c = myString.Value( afterEnd );
4090 if ( !isalnum( c ) && c != ':' ) {
4091 // check if accessor method already present
4093 myString.Location( (char*) theAcsMethod, afterEnd, Length() ) != afterEnd+1) {
4095 int oldLen = Length();
4096 myString.Insert( afterEnd, (char*) theAcsMethod );
4097 myString.Insert( afterEnd, "." );
4098 // update starting positions of the parts following the modified one
4099 int posDelta = Length() - oldLen;
4100 for ( int i = 1; i <= myBegPos.Length(); ++i ) {
4101 if ( myBegPos( i ) > afterEnd )
4102 myBegPos( i ) += posDelta;
4107 beg = afterEnd; // is a part - next search
4112 //================================================================================
4114 * \brief Creates pyObject
4116 //================================================================================
4118 _pyObject::_pyObject(const Handle(_pyCommand)& theCreationCmd, const _pyID& theID)
4119 : myID(theID), myCreationCmd(theCreationCmd), myIsPublished(false)
4124 //================================================================================
4126 * \brief Set up myID and myIsPublished
4128 //================================================================================
4130 void _pyObject::setID(const _pyID& theID)
4133 myIsPublished = !theGen->IsNotPublished( GetID() );
4136 //================================================================================
4138 * \brief Clear myCreationCmd and myProcessedCmds
4140 //================================================================================
4142 void _pyObject::ClearCommands()
4147 if ( !myCreationCmd.IsNull() )
4148 myCreationCmd->Clear();
4150 list< Handle(_pyCommand) >::iterator cmd = myProcessedCmds.begin();
4151 for ( ; cmd != myProcessedCmds.end(); ++cmd )
4155 //================================================================================
4157 * \brief Return method name giving access to an interaface object wrapped by python class
4158 * \retval const char* - method name
4160 //================================================================================
4162 const char* _pyObject::AccessorMethod() const
4166 //================================================================================
4168 * \brief Return ID of a father
4170 //================================================================================
4172 _pyID _pyObject::FatherID(const _pyID & childID)
4174 int colPos = childID.SearchFromEnd(':');
4176 return childID.SubString( 1, colPos-1 );
4180 //================================================================================
4182 * \brief SelfEraser erases creation command if no more it's commands invoked
4184 //================================================================================
4186 _pySelfEraser::_pySelfEraser(const Handle(_pyCommand)& theCreationCmd)
4187 :_pyObject(theCreationCmd), myIgnoreOwnCalls(false)
4189 myIsPublished = true; // prevent clearing as a not published
4190 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4193 //================================================================================
4195 * \brief SelfEraser erases creation command if no more it's commands invoked
4197 //================================================================================
4199 void _pySelfEraser::Flush()
4201 bool toErase = false;
4202 if ( myIgnoreOwnCalls ) // check if this obj is used as argument
4205 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4206 for ( ; cmd != myArgCmds.end(); ++cmd )
4207 nbArgUses += !(*cmd)->IsEmpty();
4208 toErase = ( nbArgUses < 1 );
4212 int nbCalls = GetNbCalls();
4215 // ignore cleared commands
4216 std::list< Handle(_pyCommand) >& cmds = GetProcessedCmds();
4217 std::list< Handle(_pyCommand) >::const_iterator cmd = cmds.begin();
4218 for ( ; cmd != cmds.end(); ++cmd )
4219 nbCalls -= (*cmd)->IsEmpty();
4221 toErase = ( nbCalls < 1 );
4225 myIsPublished = false;
4226 _pyObject::ClearCommands();
4230 //================================================================================
4232 * \brief _pySubMesh constructor
4234 //================================================================================
4236 _pySubMesh::_pySubMesh(const Handle(_pyCommand)& theCreationCmd, bool toKeepAgrCmds):
4237 _pyObject(theCreationCmd)
4239 myMesh = ObjectToMesh( theGen->FindObject( theCreationCmd->GetObject() ));
4240 if ( toKeepAgrCmds )
4241 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4244 //================================================================================
4246 * \brief Return true if a sub-mesh can be used as argument of the given method
4248 //================================================================================
4250 bool _pySubMesh::CanBeArgOfMethod(const _AString& theMethodName)
4253 // // names of all methods where a sub-mesh can be used as argument
4254 // static TStringSet methods;
4255 // if ( methods.empty() ) {
4256 // const char * names[] = {
4257 // // methods of SMESH_Gen
4259 // // methods of SMESH_Group
4261 // // methods of SMESH_Measurements
4263 // // methods of SMESH_Mesh
4264 // "ExportPartToMED","ExportCGNS","ExportPartToDAT","ExportPartToUNV","ExportPartToSTL",
4266 // // methods of SMESH_MeshEditor
4267 // "ReorientObject","Reorient2D","TriToQuadObject","QuadToTriObject","SplitQuadObject",
4268 // "SplitVolumesIntoTetra","SmoothObject","SmoothParametricObject","ConvertFromQuadraticObject",
4269 // "RotationSweepObject","RotationSweepObjectMakeGroups","RotationSweepObject1D",
4270 // "RotationSweepObject1DMakeGroups","RotationSweepObject2D","RotationSweepObject2DMakeGroups",
4271 // "ExtrusionSweepObject","ExtrusionSweepObjectMakeGroups","ExtrusionSweepObject0D",
4272 // "ExtrusionSweepObject0DMakeGroups","ExtrusionSweepObject1D","ExtrusionSweepObject2D",
4273 // "ExtrusionSweepObject1DMakeGroups","ExtrusionSweepObject2DMakeGroups",
4274 // "ExtrusionAlongPathObjX","ExtrusionAlongPathObject","ExtrusionAlongPathObjectMakeGroups",
4275 // "ExtrusionAlongPathObject1D","ExtrusionAlongPathObject1DMakeGroups",
4276 // "ExtrusionAlongPathObject2D","ExtrusionAlongPathObject2DMakeGroups","MirrorObject",
4277 // "MirrorObjectMakeGroups","MirrorObjectMakeMesh","TranslateObject","Scale",
4278 // "TranslateObjectMakeGroups","TranslateObjectMakeMesh","ScaleMakeGroups","ScaleMakeMesh",
4279 // "RotateObject","RotateObjectMakeGroups","RotateObjectMakeMesh","FindCoincidentNodesOnPart",
4280 // "FindCoincidentNodesOnPartBut","FindEqualElements","FindAmongElementsByPoint",
4281 // "MakeBoundaryMesh","Create0DElementsOnAllNodes",
4282 // "" }; // <- mark of end
4283 // methods.Insert( names );
4285 // return methods.Contains( theMethodName );
4288 //================================================================================
4290 * \brief count invoked commands
4292 //================================================================================
4294 void _pySubMesh::Process( const Handle(_pyCommand)& theCommand )
4296 _pyObject::Process(theCommand); // count calls of Process()
4299 //================================================================================
4301 * \brief Move creation command depending on invoked commands
4303 //================================================================================
4305 void _pySubMesh::Flush()
4307 if ( GetNbCalls() == 0 && myArgCmds.empty() ) // move to the end of all commands
4308 theGen->GetLastCommand()->AddDependantCmd( GetCreationCmd() );
4309 else if ( !myCreator.IsNull() )
4310 // move to be just after creator
4311 myCreator->GetCreationCmd()->AddDependantCmd( GetCreationCmd() );
4313 // move sub-mesh usage after creation cmd
4314 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4315 for ( ; cmd != myArgCmds.end(); ++cmd )
4316 if ( !(*cmd)->IsEmpty() )
4317 GetCreationCmd()->AddDependantCmd( *cmd );
4320 //================================================================================
4322 * \brief Creates _pyGroup
4324 //================================================================================
4326 _pyGroup::_pyGroup(const Handle(_pyCommand)& theCreationCmd, const _pyID & id)
4327 :_pySubMesh(theCreationCmd, /*toKeepAgrCmds=*/false)
4329 if ( !id.IsEmpty() )
4332 myCanClearCreationCmd = true;
4334 const _AString& method = theCreationCmd->GetMethod();
4335 if ( method == "CreateGroup" ) // CreateGroup() --> CreateEmptyGroup()
4337 theCreationCmd->SetMethod( "CreateEmptyGroup" );
4339 // ----------------------------------------------------------------------
4340 else if ( method == "CreateGroupFromGEOM" ) // (type, name, grp)
4342 _pyID geom = theCreationCmd->GetArg( 3 );
4343 // VSR 24/12/2010. PAL21106: always use GroupOnGeom() function on dump
4344 // next if(){...} section is commented
4345 //if ( sameGroupType( geom, theCreationCmd->GetArg( 1 )) ) { // --> Group(geom)
4346 // theCreationCmd->SetMethod( "Group" );
4347 // theCreationCmd->RemoveArgs();
4348 // theCreationCmd->SetArg( 1, geom );
4351 // ------------------------->>>>> GroupOnGeom( geom, name, typ )
4352 _pyID type = theCreationCmd->GetArg( 1 );
4353 _pyID name = theCreationCmd->GetArg( 2 );
4354 theCreationCmd->SetMethod( "GroupOnGeom" );
4355 theCreationCmd->RemoveArgs();
4356 theCreationCmd->SetArg( 1, geom );
4357 theCreationCmd->SetArg( 2, name );
4358 theCreationCmd->SetArg( 3, type );
4361 else if ( method == "CreateGroupFromFilter" )
4363 // -> GroupOnFilter(typ, name, aFilter0x4743dc0 -> aFilter_1)
4364 theCreationCmd->SetMethod( "GroupOnFilter" );
4366 _pyID filterID = theCreationCmd->GetArg(3);
4367 Handle(_pyFilter) filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4368 if ( !filter.IsNull())
4370 if ( !filter->GetNewID().IsEmpty() )
4371 theCreationCmd->SetArg( 3, filter->GetNewID() );
4372 //filter->AddUser( this );
4376 else if ( method == "GetGroups" )
4378 myCanClearCreationCmd = ( theCreationCmd->GetNbResultValues() == 1 );
4382 // theCreationCmd does something else apart from creation of this group
4383 // and thus it can't be cleared if this group is removed
4384 myCanClearCreationCmd = false;
4388 //================================================================================
4390 * \brief Check if "[ group1, group2 ] = mesh.GetGroups()" creation command
4393 //================================================================================
4395 bool _pyGroup::CanClear()
4400 if ( !myCanClearCreationCmd &&
4401 !myCreationCmd.IsNull() &&
4402 myCreationCmd->GetMethod() == "GetGroups" )
4404 TCollection_AsciiString grIDs = myCreationCmd->GetResultValue();
4405 list< _pyID > idList = myCreationCmd->GetStudyEntries( grIDs );
4406 list< _pyID >::iterator grID = idList.begin();
4407 if ( GetID() == *grID )
4409 myCanClearCreationCmd = true;
4410 list< Handle(_pyGroup ) > groups;
4411 for ( ; grID != idList.end(); ++grID )
4413 Handle(_pyGroup) group = Handle(_pyGroup)::DownCast( theGen->FindObject( *grID ));
4414 if ( group.IsNull() ) continue;
4415 groups.push_back( group );
4416 if ( group->IsInStudy() )
4417 myCanClearCreationCmd = false;
4419 // set myCanClearCreationCmd == true to all groups
4420 list< Handle(_pyGroup ) >::iterator group = groups.begin();
4421 for ( ; group != groups.end(); ++group )
4422 (*group)->myCanClearCreationCmd = myCanClearCreationCmd;
4426 return myCanClearCreationCmd;
4429 //================================================================================
4431 * \brief set myCanClearCreationCmd = true if the main action of the creation
4432 * command is discarded
4434 //================================================================================
4436 void _pyGroup::RemovedWithContents()
4438 // this code would be appropriate if Add0DElementsToAllNodes() returned only new nodes
4439 // via a created group
4440 //if ( GetCreationCmd()->GetMethod() == "Add0DElementsToAllNodes")
4441 // myCanClearCreationCmd = true;
4444 //================================================================================
4446 * \brief To convert creation of a group by filter
4448 //================================================================================
4450 void _pyGroup::Process( const Handle(_pyCommand)& theCommand)
4452 // Convert the following set of commands into mesh.MakeGroupByFilter(groupName, theFilter)
4453 // group = mesh.CreateEmptyGroup( elemType, groupName )
4454 // aFilter.SetMesh(mesh)
4455 // nbAdd = group.AddFrom( aFilter )
4456 Handle(_pyFilter) filter;
4457 if ( theCommand->GetMethod() == "AddFrom" )
4459 _pyID idSource = theCommand->GetArg(1);
4460 // check if idSource is a filter
4461 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( idSource ));
4462 if ( !filter.IsNull() )
4464 // find aFilter.SetMesh(mesh) to clear it, it should be just before theCommand
4465 list< Handle(_pyCommand) >::reverse_iterator cmdIt = theGen->GetCommands().rbegin();
4466 while ( *cmdIt != theCommand ) ++cmdIt;
4467 while ( (*cmdIt)->GetOrderNb() != 1 )
4469 const Handle(_pyCommand)& setMeshCmd = *(++cmdIt);
4470 if ((setMeshCmd->GetObject() == idSource ||
4471 setMeshCmd->GetObject() == filter->GetNewID() )
4473 setMeshCmd->GetMethod() == "SetMesh")
4475 setMeshCmd->Clear();
4479 // replace 3 commands by one
4480 theCommand->Clear();
4481 const Handle(_pyCommand)& makeGroupCmd = GetCreationCmd();
4482 TCollection_AsciiString name = makeGroupCmd->GetArg( 2 );
4483 if ( !filter->GetNewID().IsEmpty() )
4484 idSource = filter->GetNewID();
4485 makeGroupCmd->SetMethod( "MakeGroupByFilter" );
4486 makeGroupCmd->SetArg( 1, name );
4487 makeGroupCmd->SetArg( 2, idSource );
4488 filter->AddArgCmd( makeGroupCmd );
4491 else if ( theCommand->GetMethod() == "SetFilter" )
4493 // set new name of a filter or clear the command if the same filter is set
4494 _pyID filterID = theCommand->GetArg(1);
4495 filter = Handle(_pyFilter)::DownCast( theGen->FindObject( filterID ));
4496 if ( !myFilter.IsNull() && filter == myFilter )
4497 theCommand->Clear();
4498 else if ( !filter.IsNull() && !filter->GetNewID().IsEmpty() )
4499 theCommand->SetArg( 1, filter->GetNewID() );
4502 else if ( theCommand->GetMethod() == "GetFilter" )
4504 // GetFilter() returns a filter with other ID, make myFilter process
4505 // calls of the returned filter
4506 if ( !myFilter.IsNull() )
4508 theGen->SetProxyObject( theCommand->GetResultValue(), myFilter );
4509 theCommand->Clear();
4513 // if ( !filter.IsNull() )
4514 // filter->AddUser( this );
4516 theGen->AddMeshAccessorMethod( theCommand );
4519 //================================================================================
4521 * \brief Prevent clearing "DoubleNode...() command if a group created by it is removed
4523 //================================================================================
4525 void _pyGroup::Flush()
4527 if ( !theGen->IsToKeepAllCommands() &&
4528 !myCreationCmd.IsNull() && !myCanClearCreationCmd )
4530 myCreationCmd.Nullify(); // this way myCreationCmd won't be cleared
4534 //================================================================================
4536 * \brief Constructor of _pyFilter
4538 //================================================================================
4540 _pyFilter::_pyFilter(const Handle(_pyCommand)& theCreationCmd, const _pyID& newID/*=""*/)
4541 :_pyObject(theCreationCmd), myNewID( newID )
4543 //myIsPublished = true; // prevent clearing as a not published
4544 theGen->KeepAgrCmds( GetID() ); // ask to fill myArgCmds
4547 //================================================================================
4549 * \brief To convert creation of a filter by criteria and
4550 * to replace an old name by a new one
4552 //================================================================================
4554 void _pyFilter::Process( const Handle(_pyCommand)& theCommand)
4556 if ( theCommand->GetObject() == GetID() )
4557 _pyObject::Process(theCommand); // count commands
4559 if ( !myNewID.IsEmpty() )
4560 theCommand->SetObject( myNewID );
4562 // Convert the following set of commands into smesh.GetFilterFromCriteria(criteria)
4563 // aFilter0x2aaab0487080 = aFilterManager.CreateFilter()
4564 // aFilter0x2aaab0487080.SetCriteria(aCriteria)
4565 if ( GetNbCalls() == 1 && // none method was called before this SetCriteria() call
4566 theCommand->GetMethod() == "SetCriteria")
4568 // aFilter.SetCriteria(aCriteria) ->
4569 // aFilter = smesh.GetFilterFromCriteria(criteria)
4570 if ( myNewID.IsEmpty() )
4571 theCommand->SetResultValue( GetID() );
4573 theCommand->SetResultValue( myNewID );
4574 theCommand->SetObject( SMESH_2smeshpy::GenName() );
4575 theCommand->SetMethod( "GetFilterFromCriteria" );
4577 // Swap "aFilterManager.CreateFilter()" and "smesh.GetFilterFromCriteria(criteria)"
4578 GetCreationCmd()->Clear();
4579 GetCreationCmd()->GetString() = theCommand->GetString();
4580 theCommand->Clear();
4581 theCommand->AddDependantCmd( GetCreationCmd() );
4583 else if ( theCommand->GetMethod() == "SetMesh" )
4585 if ( myMesh == theCommand->GetArg( 1 ))
4586 theCommand->Clear();
4588 myMesh = theCommand->GetArg( 1 );
4589 theGen->AddMeshAccessorMethod( theCommand );
4593 //================================================================================
4595 * \brief Set new filter name to the creation command and to myArgCmds
4597 //================================================================================
4599 void _pyFilter::Flush()
4601 if ( myNewID.IsEmpty() ) return;
4603 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4604 for ( ; cmd != myArgCmds.end(); ++cmd )
4605 if ( !(*cmd)->IsEmpty() )
4607 _AString cmdStr = (*cmd)->GetString();
4608 _AString id = GetID();
4609 int pos = cmdStr.Search( id );
4612 cmdStr.Remove( pos, id.Length() );
4613 cmdStr.Insert( pos, myNewID );
4616 (*cmd)->GetString() = cmdStr;
4619 if ( !GetCreationCmd()->IsEmpty() )
4620 GetCreationCmd()->SetResultValue( myNewID );
4623 //================================================================================
4625 * \brief Return true if all my users can be cleared
4627 //================================================================================
4629 bool _pyObject::CanClear()
4631 list< Handle(_pyCommand) >::iterator cmd = myArgCmds.begin();
4632 for ( ; cmd != myArgCmds.end(); ++cmd )
4633 if ( !(*cmd)->IsEmpty() )
4635 Handle(_pyObject) obj = theGen->FindObject( (*cmd)->GetObject() );
4636 if ( !obj.IsNull() && !obj->CanClear() )
4639 return ( !myIsPublished );
4642 //================================================================================
4644 * \brief Reads _pyHypothesis'es from resource files of mesher Plugins
4646 //================================================================================
4648 _pyHypothesisReader::_pyHypothesisReader()
4651 vector< string > xmlPaths = SMESH_Gen::GetPluginXMLPaths();
4652 LDOMParser xmlParser;
4653 for ( size_t i = 0; i < xmlPaths.size(); ++i )
4655 bool error = xmlParser.parse( xmlPaths[i].c_str() );
4659 INFOS( xmlParser.GetError(data) );
4662 // <algorithm type="Regular_1D"
4663 // label-id="Wire discretisation"
4666 // <algo>Regular_1D=Segment()</algo>
4667 // <hypo>LocalLength=LocalLength(SetLength(1),,SetPrecision(1))</hypo>
4669 LDOM_Document xmlDoc = xmlParser.getDocument();
4670 LDOM_NodeList algoNodeList = xmlDoc.getElementsByTagName( "algorithm" );
4671 for ( int i = 0; i < algoNodeList.getLength(); ++i )
4673 LDOM_Node algoNode = algoNodeList.item( i );
4674 LDOM_Element& algoElem = (LDOM_Element&) algoNode;
4675 LDOM_NodeList pyAlgoNodeList = algoElem.getElementsByTagName( "algo" );
4676 if ( pyAlgoNodeList.getLength() < 1 ) continue;
4678 _AString text, algoType, method, arg;
4679 for ( int iA = 0; iA < pyAlgoNodeList.getLength(); ++iA )
4681 LDOM_Node pyAlgoNode = pyAlgoNodeList.item( iA );
4682 LDOM_Node textNode = pyAlgoNode.getFirstChild();
4683 text = textNode.getNodeValue();
4684 Handle(_pyCommand) algoCmd = new _pyCommand( text );
4685 algoType = algoCmd->GetResultValue();
4686 method = algoCmd->GetMethod();
4687 arg = algoCmd->GetArg(1);
4688 if ( !algoType.IsEmpty() && !method.IsEmpty() )
4690 Handle(_pyAlgorithm) algo = new _pyAlgorithm( algoCmd );
4691 algo->SetConvMethodAndType( method, algoType );
4692 if ( !arg.IsEmpty() )
4693 algo->setCreationArg( 1, arg );
4695 myType2Hyp[ algoType ] = algo;
4699 if ( algoType.IsEmpty() ) continue;
4701 LDOM_NodeList pyHypoNodeList = algoElem.getElementsByTagName( "hypo" );
4703 Handle( _pyHypothesis ) hyp;
4704 for ( int iH = 0; iH < pyHypoNodeList.getLength(); ++iH )
4706 LDOM_Node pyHypoNode = pyHypoNodeList.item( iH );
4707 LDOM_Node textNode = pyHypoNode.getFirstChild();
4708 text = textNode.getNodeValue();
4709 Handle(_pyCommand) hypoCmd = new _pyCommand( text );
4710 hypType = hypoCmd->GetResultValue();
4711 method = hypoCmd->GetMethod();
4712 if ( !hypType.IsEmpty() && !method.IsEmpty() )
4714 map<_AString, Handle(_pyHypothesis)>::iterator type2hyp = myType2Hyp.find( hypType );
4715 if ( type2hyp == myType2Hyp.end() )
4716 hyp = new _pyHypothesis( hypoCmd );
4718 hyp = type2hyp->second;
4719 hyp->SetConvMethodAndType( method, algoType );
4720 for ( int iArg = 1; iArg <= hypoCmd->GetNbArgs(); ++iArg )
4722 _pyCommand argCmd( hypoCmd->GetArg( iArg ));
4723 _AString argMethod = argCmd.GetMethod();
4724 _AString argNbText = argCmd.GetArg( 1 );
4725 if ( argMethod.IsEmpty() && !argCmd.IsEmpty() )
4726 hyp->setCreationArg( 1, argCmd.GetString() ); // e.g. Parameters(smesh.SIMPLE)
4728 hyp->AddArgMethod( argMethod,
4729 argNbText.IsIntegerValue() ? argNbText.IntegerValue() : 1 );
4731 myType2Hyp[ hypType ] = hyp;
4735 // <hypothesis type="BLSURF_Parameters"
4739 // <accumulative-methods>
4740 // SetEnforcedVertex,
4741 // SetEnforcedVertexNamed
4742 // </accumulative-methods>
4746 LDOM_NodeList hypNodeList = xmlDoc.getElementsByTagName( "hypothesis" );
4747 for ( int i = 0; i < hypNodeList.getLength(); ++i )
4749 LDOM_Node hypNode = hypNodeList.item( i );
4750 LDOM_Element& hypElem = (LDOM_Element&) hypNode;
4751 _AString hypType = hypElem.getAttribute("type");
4752 LDOM_NodeList methNodeList = hypElem.getElementsByTagName( "accumulative-methods" );
4753 if ( methNodeList.getLength() != 1 || hypType.IsEmpty() ) continue;
4755 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4756 if ( type2hyp == myType2Hyp.end() ) continue;
4758 LDOM_Node methNode = methNodeList.item( 0 );
4759 LDOM_Node textNode = methNode.getFirstChild();
4760 _AString text = textNode.getNodeValue();
4764 method = _pyCommand::GetWord( text, pos, /*forward= */true );
4765 pos += method.Length();
4766 type2hyp->second->AddAccumulativeMethod( method );
4768 while ( !method.IsEmpty() );
4771 } // loop on xmlPaths
4774 //================================================================================
4776 * \brief Returns a new hypothesis initialized according to the read information
4778 //================================================================================
4780 Handle(_pyHypothesis)
4781 _pyHypothesisReader::GetHypothesis(const _AString& hypType,
4782 const Handle(_pyCommand)& creationCmd) const
4784 Handle(_pyHypothesis) resHyp, sampleHyp;
4786 map<_AString, Handle(_pyHypothesis)>::const_iterator type2hyp = myType2Hyp.find( hypType );
4787 if ( type2hyp != myType2Hyp.end() )
4788 sampleHyp = type2hyp->second;
4790 if ( sampleHyp.IsNull() )
4792 resHyp = new _pyHypothesis(creationCmd);
4796 if ( sampleHyp->IsAlgo() )
4797 resHyp = new _pyAlgorithm( creationCmd );
4799 resHyp = new _pyHypothesis(creationCmd);
4800 resHyp->Assign( sampleHyp, _pyID() );
4805 //================================================================================
4807 * \brief Adds an object ID to some family of IDs with a common prefix
4808 * \param [in] str - the object ID
4809 * \return bool - \c false if \a str does not have the same prefix as \a this family
4810 * (for internal usage)
4812 //================================================================================
4814 bool _pyStringFamily::Add( const char* str )
4816 if ( strncmp( str, _prefix.ToCString(), _prefix.Length() ) != 0 )
4817 return false; // expected prefix is missing
4819 str += _prefix.Length(); // skip _prefix
4821 // try to add to some of child falimies
4822 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4823 for ( ; itSub != _subFams.end(); ++itSub )
4824 if ( itSub->Add( str ))
4827 // no suitable family found - add str to _strings or create a new child family
4829 // look for a proper place within sorted _strings
4830 std::list< _AString >::iterator itStr = _strings.begin();
4831 while ( itStr != _strings.end() && itStr->IsLess( str ))
4833 if ( itStr != _strings.end() && itStr->IsEqual( str ))
4834 return true; // same ID already kept
4836 const int minPrefixSize = 4;
4838 // count "smaller" strings with the same prefix
4839 std::list< _AString >::iterator itLess = itStr; --itLess;
4841 for ( ; itLess != _strings.end(); --itLess )
4842 if ( strncmp( str, itLess->ToCString(), minPrefixSize ) == 0 )
4847 // count "greater" strings with the same prefix
4848 std::list< _AString >::iterator itMore = itStr;
4850 for ( ; itMore != _strings.end(); ++itMore )
4851 if ( strncmp( str, itMore->ToCString(), minPrefixSize ) == 0 )
4856 if ( nbLess + nbMore > 1 ) // ------- ADD a NEW CHILD FAMILY -------------
4858 // look for a maximal prefix length
4859 // int lessPrefSize = 3, morePrefSize = 3;
4860 // if ( nbLess > 0 )
4861 // while( itLess->ToCString()[ lessPrefSize ] == str[ lessPrefSize ] )
4863 // if ( nbMore > 0 )
4864 // while ( itMore->ToCString()[ morePrefSize ] == str[ morePrefSize ] )
4866 // int prefixSize = 3;
4867 // if ( nbLess == 0 )
4868 // prefixSize = morePrefSize;
4869 // else if ( nbMore == 0 )
4870 // prefixSize = lessPrefSize;
4872 // prefixSize = Min( lessPrefSize, morePrefSize );
4873 int prefixSize = minPrefixSize;
4874 _AString newPrefix ( str, prefixSize );
4876 // look for a proper place within _subFams sorted by _prefix
4877 for ( itSub = _subFams.begin(); itSub != _subFams.end(); ++itSub )
4878 if ( !itSub->_prefix.IsLess( newPrefix ))
4881 // add the new _pyStringFamily
4882 itSub = _subFams.insert( itSub, _pyStringFamily());
4883 _pyStringFamily& newSubFam = *itSub;
4884 newSubFam._prefix = newPrefix;
4886 // pass this->_strings to newSubFam._strings
4887 for ( itStr = itLess; nbLess > 0; --nbLess, ++itStr )
4888 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4889 newSubFam._strings.push_back( str + prefixSize );
4890 for ( ; nbMore > 0; --nbMore, ++itStr )
4891 newSubFam._strings.push_back( itStr->ToCString() + prefixSize );
4893 _strings.erase( itLess, ++itMore );
4895 else // to few string to make a family fot them
4897 _strings.insert( itStr, str );
4902 //================================================================================
4904 * \brief Finds an object ID in the command
4905 * \param [in] longStr - the command string
4906 * \param [out] subStr - the found object ID
4907 * \return bool - \c true if the object ID found
4909 //================================================================================
4911 bool _pyStringFamily::IsIn( const _AString& longStr, _AString& subStr )
4913 const char* s = longStr.ToCString();
4916 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4918 for ( ; itSub != _subFams.end(); ++itSub )
4920 if (( pos = longStr.Search( itSub->_prefix )-1) > 6-1 ) // 6 = strlen("a=b.c(")
4921 if (( len = itSub->isIn( s + pos + itSub->_prefix.Length() )) >= 0 )
4923 subStr = _AString( s + pos, len + itSub->_prefix.Length() );
4927 // look among _strings
4928 std::list< _AString >::iterator itStr = _strings.begin();
4929 for ( ; itStr != _strings.end(); ++itStr )
4930 if ( longStr.Search( *itStr ) > itStr->Length() )
4938 //================================================================================
4940 * \brief Return remainder length of the object ID after my _prefix
4941 * \param [in] str - remainder of the command after my _prefix
4942 * \return int - length of the object ID or -1 if not found
4944 //================================================================================
4946 int _pyStringFamily::isIn( const char* str )
4948 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4950 for ( ; itSub != _subFams.end(); ++itSub )
4952 int cmp = strncmp( str, itSub->_prefix.ToCString(), itSub->_prefix.Length() );
4955 if (( len = itSub->isIn( str + itSub->_prefix.Length() )) >= 0 )
4956 return itSub->_prefix.Length() + len;
4961 if ( !_strings.empty() )
4963 std::list< _AString >::iterator itStr = _strings.begin();
4964 bool firstEmpty = itStr->IsEmpty();
4967 for ( ; itStr != _strings.end(); ++itStr )
4969 int cmp = strncmp( str, itStr->ToCString(), itStr->Length() );
4971 return itStr->Length();
4982 //================================================================================
4986 //================================================================================
4988 void _pyStringFamily::Print( int level )
4990 cout << string( level, ' ' ) << "prefix = '" << _prefix << "' : ";
4991 std::list< _AString >::iterator itStr = _strings.begin();
4992 for ( ; itStr != _strings.end(); ++itStr )
4993 cout << *itStr << " | ";
4995 std::list< _pyStringFamily >::iterator itSub = _subFams.begin();
4996 for ( ; itSub != _subFams.end(); ++itSub )
4997 itSub->Print( level + 1 );
4999 cout << string( 70, '-' ) << endl;