Salome HOME
PR: true singleton instance of smesh
[modules/smesh.git] / src / SMESH_SWIG / smeshBuilder.py
1 # Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
2 #
3 # This library is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU Lesser General Public
5 # License as published by the Free Software Foundation; either
6 # version 2.1 of the License.
7 #
8 # This library is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser General Public
14 # License along with this library; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 #
19 #  File   : smeshBuilder.py
20 #  Author : Francis KLOSS, OCC
21 #  Module : SMESH
22
23 ## @package smeshBuilder
24 #  Python API for SALOME %Mesh module
25
26 ## @defgroup l1_auxiliary Auxiliary methods and structures
27 ## @defgroup l1_creating  Creating meshes
28 ## @{
29 ##   @defgroup l2_impexp     Importing and exporting meshes
30 ##   @defgroup l2_construct  Constructing meshes
31 ##   @defgroup l2_algorithms Defining Algorithms
32 ##   @{
33 ##     @defgroup l3_algos_basic   Basic meshing algorithms
34 ##     @defgroup l3_algos_proj    Projection Algorithms
35 ##     @defgroup l3_algos_radialp Radial Prism
36 ##     @defgroup l3_algos_segmarv Segments around Vertex
37 ##     @defgroup l3_algos_3dextr  3D extrusion meshing algorithm
38
39 ##   @}
40 ##   @defgroup l2_hypotheses Defining hypotheses
41 ##   @{
42 ##     @defgroup l3_hypos_1dhyps 1D Meshing Hypotheses
43 ##     @defgroup l3_hypos_2dhyps 2D Meshing Hypotheses
44 ##     @defgroup l3_hypos_maxvol Max Element Volume hypothesis
45 ##     @defgroup l3_hypos_quad Quadrangle Parameters hypothesis
46 ##     @defgroup l3_hypos_additi Additional Hypotheses
47
48 ##   @}
49 ##   @defgroup l2_submeshes Constructing submeshes
50 ##   @defgroup l2_compounds Building Compounds
51 ##   @defgroup l2_editing   Editing Meshes
52
53 ## @}
54 ## @defgroup l1_meshinfo  Mesh Information
55 ## @defgroup l1_controls  Quality controls and Filtering
56 ## @defgroup l1_grouping  Grouping elements
57 ## @{
58 ##   @defgroup l2_grps_create Creating groups
59 ##   @defgroup l2_grps_edit   Editing groups
60 ##   @defgroup l2_grps_operon Using operations on groups
61 ##   @defgroup l2_grps_delete Deleting Groups
62
63 ## @}
64 ## @defgroup l1_modifying Modifying meshes
65 ## @{
66 ##   @defgroup l2_modif_add      Adding nodes and elements
67 ##   @defgroup l2_modif_del      Removing nodes and elements
68 ##   @defgroup l2_modif_edit     Modifying nodes and elements
69 ##   @defgroup l2_modif_renumber Renumbering nodes and elements
70 ##   @defgroup l2_modif_trsf     Transforming meshes (Translation, Rotation, Symmetry, Sewing, Merging)
71 ##   @defgroup l2_modif_movenode Moving nodes
72 ##   @defgroup l2_modif_throughp Mesh through point
73 ##   @defgroup l2_modif_invdiag  Diagonal inversion of elements
74 ##   @defgroup l2_modif_unitetri Uniting triangles
75 ##   @defgroup l2_modif_changori Changing orientation of elements
76 ##   @defgroup l2_modif_cutquadr Cutting quadrangles
77 ##   @defgroup l2_modif_smooth   Smoothing
78 ##   @defgroup l2_modif_extrurev Extrusion and Revolution
79 ##   @defgroup l2_modif_patterns Pattern mapping
80 ##   @defgroup l2_modif_tofromqu Convert to/from Quadratic Mesh
81
82 ## @}
83 ## @defgroup l1_measurements Measurements
84
85 import salome
86 from salome.geom import geomBuilder
87
88 import SMESH # This is necessary for back compatibility
89 from   SMESH import *
90 from   salome.smesh.smesh_algorithm import Mesh_Algorithm
91
92 import SALOME
93 import SALOMEDS
94 import os
95
96 ## @addtogroup l1_auxiliary
97 ## @{
98
99 ## Converts an angle from degrees to radians
100 def DegreesToRadians(AngleInDegrees):
101     from math import pi
102     return AngleInDegrees * pi / 180.0
103
104 import salome_notebook
105 notebook = salome_notebook.notebook
106 # Salome notebook variable separator
107 var_separator = ":"
108
109 ## Return list of variable values from salome notebook.
110 #  The last argument, if is callable, is used to modify values got from notebook
111 def ParseParameters(*args):
112     Result = []
113     Parameters = ""
114     hasVariables = False
115     varModifFun=None
116     if args and callable( args[-1] ):
117         args, varModifFun = args[:-1], args[-1]
118     for parameter in args:
119
120         Parameters += str(parameter) + var_separator
121
122         if isinstance(parameter,str):
123             # check if there is an inexistent variable name
124             if not notebook.isVariable(parameter):
125                 raise ValueError, "Variable with name '" + parameter + "' doesn't exist!!!"
126             parameter = notebook.get(parameter)
127             hasVariables = True
128             if varModifFun:
129                 parameter = varModifFun(parameter)
130                 pass
131             pass
132         Result.append(parameter)
133
134         pass
135     Parameters = Parameters[:-1]
136     Result.append( Parameters )
137     Result.append( hasVariables )
138     return Result
139
140 # Parse parameters converting variables to radians
141 def ParseAngles(*args):
142     return ParseParameters( *( args + (DegreesToRadians, )))
143
144 # Substitute PointStruct.__init__() to create SMESH.PointStruct using notebook variables.
145 # Parameters are stored in PointStruct.parameters attribute
146 def __initPointStruct(point,*args):
147     point.x, point.y, point.z, point.parameters,hasVars = ParseParameters(*args)
148     pass
149 SMESH.PointStruct.__init__ = __initPointStruct
150
151 # Substitute AxisStruct.__init__() to create SMESH.AxisStruct using notebook variables.
152 # Parameters are stored in AxisStruct.parameters attribute
153 def __initAxisStruct(ax,*args):
154     ax.x, ax.y, ax.z, ax.vx, ax.vy, ax.vz, ax.parameters,hasVars = ParseParameters(*args)
155     pass
156 SMESH.AxisStruct.__init__ = __initAxisStruct
157
158 smeshPrecisionConfusion = 1.e-07
159 def IsEqual(val1, val2, tol=smeshPrecisionConfusion):
160     if abs(val1 - val2) < tol:
161         return True
162     return False
163
164 NO_NAME = "NoName"
165
166 ## Gets object name
167 def GetName(obj):
168     if obj:
169         # object not null
170         if isinstance(obj, SALOMEDS._objref_SObject):
171             # study object
172             return obj.GetName()
173         try:
174             ior  = salome.orb.object_to_string(obj)
175         except:
176             ior = None
177         if ior:
178             # CORBA object
179             studies = salome.myStudyManager.GetOpenStudies()
180             for sname in studies:
181                 s = salome.myStudyManager.GetStudyByName(sname)
182                 if not s: continue
183                 sobj = s.FindObjectIOR(ior)
184                 if not sobj: continue
185                 return sobj.GetName()
186             if hasattr(obj, "GetName"):
187                 # unknown CORBA object, having GetName() method
188                 return obj.GetName()
189             else:
190                 # unknown CORBA object, no GetName() method
191                 return NO_NAME
192             pass
193         if hasattr(obj, "GetName"):
194             # unknown non-CORBA object, having GetName() method
195             return obj.GetName()
196         pass
197     raise RuntimeError, "Null or invalid object"
198
199 ## Prints error message if a hypothesis was not assigned.
200 def TreatHypoStatus(status, hypName, geomName, isAlgo):
201     if isAlgo:
202         hypType = "algorithm"
203     else:
204         hypType = "hypothesis"
205         pass
206     if status == HYP_UNKNOWN_FATAL :
207         reason = "for unknown reason"
208     elif status == HYP_INCOMPATIBLE :
209         reason = "this hypothesis mismatches the algorithm"
210     elif status == HYP_NOTCONFORM :
211         reason = "a non-conform mesh would be built"
212     elif status == HYP_ALREADY_EXIST :
213         if isAlgo: return # it does not influence anything
214         reason = hypType + " of the same dimension is already assigned to this shape"
215     elif status == HYP_BAD_DIM :
216         reason = hypType + " mismatches the shape"
217     elif status == HYP_CONCURENT :
218         reason = "there are concurrent hypotheses on sub-shapes"
219     elif status == HYP_BAD_SUBSHAPE :
220         reason = "the shape is neither the main one, nor its sub-shape, nor a valid group"
221     elif status == HYP_BAD_GEOMETRY:
222         reason = "geometry mismatches the expectation of the algorithm"
223     elif status == HYP_HIDDEN_ALGO:
224         reason = "it is hidden by an algorithm of an upper dimension, which generates elements of all dimensions"
225     elif status == HYP_HIDING_ALGO:
226         reason = "it hides algorithms of lower dimensions by generating elements of all dimensions"
227     elif status == HYP_NEED_SHAPE:
228         reason = "Algorithm can't work without shape"
229     else:
230         return
231     hypName = '"' + hypName + '"'
232     geomName= '"' + geomName+ '"'
233     if status < HYP_UNKNOWN_FATAL and not geomName =='""':
234         print hypName, "was assigned to",    geomName,"but", reason
235     elif not geomName == '""':
236         print hypName, "was not assigned to",geomName,":", reason
237     else:
238         print hypName, "was not assigned:", reason
239         pass
240
241 ## Private method. Add geom (sub-shape of the main shape) into the study if not yet there
242 def AssureGeomPublished(mesh, geom, name=''):
243     if not isinstance( geom, geomBuilder.GEOM._objref_GEOM_Object ):
244         return
245     if not geom.GetStudyEntry() and \
246            mesh.smeshpyD.GetCurrentStudy():
247         ## set the study
248         studyID = mesh.smeshpyD.GetCurrentStudy()._get_StudyId()
249         if studyID != mesh.geompyD.myStudyId:
250             mesh.geompyD.init_geom( mesh.smeshpyD.GetCurrentStudy())
251         ## get a name
252         if not name and geom.GetShapeType() != geomBuilder.GEOM.COMPOUND:
253             # for all groups SubShapeName() returns "Compound_-1"
254             name = mesh.geompyD.SubShapeName(geom, mesh.geom)
255         if not name:
256             name = "%s_%s"%(geom.GetShapeType(), id(geom)%10000)
257         ## publish
258         mesh.geompyD.addToStudyInFather( mesh.geom, geom, name )
259     return
260
261 ## Return the first vertex of a geometrical edge by ignoring orientation
262 def FirstVertexOnCurve(edge):
263     vv = geomBuilder.SubShapeAll( edge, geomBuilder.geomBuilder.ShapeType["VERTEX"])
264     if not vv:
265         raise TypeError, "Given object has no vertices"
266     if len( vv ) == 1: return vv[0]
267     v0   = geomBuilder.MakeVertexOnCurve(edge,0.)
268     xyz  = geomBuilder.PointCoordinates( v0 ) # coords of the first vertex
269     xyz1 = geomBuilder.PointCoordinates( vv[0] )
270     xyz2 = geomBuilder.PointCoordinates( vv[1] )
271     dist1, dist2 = 0,0
272     for i in range(3):
273         dist1 += abs( xyz[i] - xyz1[i] )
274         dist2 += abs( xyz[i] - xyz2[i] )
275     if dist1 < dist2:
276         return vv[0]
277     else:
278         return vv[1]
279
280 # end of l1_auxiliary
281 ## @}
282
283
284 # Warning: smeshInst is a singleton
285 smeshInst = None
286 engine = None
287 doLcc = False
288 created = False
289
290 ## This class allows to create, load or manipulate meshes
291 #  It has a set of methods to create load or copy meshes, to combine several meshes.
292 #  It also has methods to get infos on meshes.
293 class smeshBuilder(object, SMESH._objref_SMESH_Gen):
294
295     # MirrorType enumeration
296     POINT = SMESH_MeshEditor.POINT
297     AXIS =  SMESH_MeshEditor.AXIS
298     PLANE = SMESH_MeshEditor.PLANE
299
300     # Smooth_Method enumeration
301     LAPLACIAN_SMOOTH = SMESH_MeshEditor.LAPLACIAN_SMOOTH
302     CENTROIDAL_SMOOTH = SMESH_MeshEditor.CENTROIDAL_SMOOTH
303
304     PrecisionConfusion = smeshPrecisionConfusion
305
306     # TopAbs_State enumeration
307     [TopAbs_IN, TopAbs_OUT, TopAbs_ON, TopAbs_UNKNOWN] = range(4)
308
309     # Methods of splitting a hexahedron into tetrahedra
310     Hex_5Tet, Hex_6Tet, Hex_24Tet = 1, 2, 3
311
312     def __new__(cls):
313         global engine
314         global smeshInst
315         global doLcc
316         #print "==== __new__", engine, smeshInst, doLcc
317
318         if smeshInst is None:
319             # smesh engine is either retrieved from engine, or created
320             smeshInst = engine
321             # Following test avoids a recursive loop
322             if doLcc:
323                 if smeshInst is not None:
324                     # smesh engine not created: existing engine found
325                     doLcc = False
326                 if doLcc:
327                     doLcc = False
328                     # FindOrLoadComponent called:
329                     # 1. CORBA resolution of server
330                     # 2. the __new__ method is called again
331                     #print "==== smeshInst = lcc.FindOrLoadComponent ", engine, smeshInst, doLcc
332                     smeshInst = salome.lcc.FindOrLoadComponent( "FactoryServer", "SMESH" )
333             else:
334                 # FindOrLoadComponent not called
335                 if smeshInst is None:
336                     # smeshBuilder instance is created from lcc.FindOrLoadComponent
337                     #print "==== smeshInst = super(smeshBuilder,cls).__new__(cls) ", engine, smeshInst, doLcc
338                     smeshInst = super(smeshBuilder,cls).__new__(cls)
339                 else:
340                     # smesh engine not created: existing engine found
341                     #print "==== existing ", engine, smeshInst, doLcc
342                     pass
343             #print "====1 ", smeshInst
344             return smeshInst
345
346         #print "====2 ", smeshInst
347         return smeshInst
348
349     def __init__(self):
350         global created
351         #print "--------------- smeshbuilder __init__ ---", created
352         if not created:
353           created = True
354           SMESH._objref_SMESH_Gen.__init__(self)
355
356     ## Dump component to the Python script
357     #  This method overrides IDL function to allow default values for the parameters.
358     def DumpPython(self, theStudy, theIsPublished=True, theIsMultiFile=True):
359         return SMESH._objref_SMESH_Gen.DumpPython(self, theStudy, theIsPublished, theIsMultiFile)
360
361     ## Set mode of DumpPython(), \a historical or \a snapshot.
362     # In the \a historical mode, the Python Dump script includes all commands
363     # performed by SMESH engine. In the \a snapshot mode, commands
364     # relating to objects removed from the Study are excluded from the script
365     # as well as commands not influencing the current state of meshes
366     def SetDumpPythonHistorical(self, isHistorical):
367         if isHistorical: val = "true"
368         else:            val = "false"
369         SMESH._objref_SMESH_Gen.SetOption(self, "historical_python_dump", val)
370
371     ## Sets the current study and Geometry component
372     #  @ingroup l1_auxiliary
373     def init_smesh(self,theStudy,geompyD = None):
374         #print "init_smesh"
375         self.SetCurrentStudy(theStudy,geompyD)
376
377     ## Creates an empty Mesh. This mesh can have an underlying geometry.
378     #  @param obj the Geometrical object on which the mesh is built. If not defined,
379     #             the mesh will have no underlying geometry.
380     #  @param name the name for the new mesh.
381     #  @return an instance of Mesh class.
382     #  @ingroup l2_construct
383     def Mesh(self, obj=0, name=0):
384         if isinstance(obj,str):
385             obj,name = name,obj
386         return Mesh(self,self.geompyD,obj,name)
387
388     ## Returns a long value from enumeration
389     #  @ingroup l1_controls
390     def EnumToLong(self,theItem):
391         return theItem._v
392
393     ## Returns a string representation of the color.
394     #  To be used with filters.
395     #  @param c color value (SALOMEDS.Color)
396     #  @ingroup l1_controls
397     def ColorToString(self,c):
398         val = ""
399         if isinstance(c, SALOMEDS.Color):
400             val = "%s;%s;%s" % (c.R, c.G, c.B)
401         elif isinstance(c, str):
402             val = c
403         else:
404             raise ValueError, "Color value should be of string or SALOMEDS.Color type"
405         return val
406
407     ## Gets PointStruct from vertex
408     #  @param theVertex a GEOM object(vertex)
409     #  @return SMESH.PointStruct
410     #  @ingroup l1_auxiliary
411     def GetPointStruct(self,theVertex):
412         [x, y, z] = self.geompyD.PointCoordinates(theVertex)
413         return PointStruct(x,y,z)
414
415     ## Gets DirStruct from vector
416     #  @param theVector a GEOM object(vector)
417     #  @return SMESH.DirStruct
418     #  @ingroup l1_auxiliary
419     def GetDirStruct(self,theVector):
420         vertices = self.geompyD.SubShapeAll( theVector, geomBuilder.geomBuilder.ShapeType["VERTEX"] )
421         if(len(vertices) != 2):
422             print "Error: vector object is incorrect."
423             return None
424         p1 = self.geompyD.PointCoordinates(vertices[0])
425         p2 = self.geompyD.PointCoordinates(vertices[1])
426         pnt = PointStruct(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
427         dirst = DirStruct(pnt)
428         return dirst
429
430     ## Makes DirStruct from a triplet
431     #  @param x,y,z vector components
432     #  @return SMESH.DirStruct
433     #  @ingroup l1_auxiliary
434     def MakeDirStruct(self,x,y,z):
435         pnt = PointStruct(x,y,z)
436         return DirStruct(pnt)
437
438     ## Get AxisStruct from object
439     #  @param theObj a GEOM object (line or plane)
440     #  @return SMESH.AxisStruct
441     #  @ingroup l1_auxiliary
442     def GetAxisStruct(self,theObj):
443         edges = self.geompyD.SubShapeAll( theObj, geomBuilder.geomBuilder.ShapeType["EDGE"] )
444         if len(edges) > 1:
445             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
446             vertex3, vertex4 = self.geompyD.SubShapeAll( edges[1], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
447             vertex1 = self.geompyD.PointCoordinates(vertex1)
448             vertex2 = self.geompyD.PointCoordinates(vertex2)
449             vertex3 = self.geompyD.PointCoordinates(vertex3)
450             vertex4 = self.geompyD.PointCoordinates(vertex4)
451             v1 = [vertex2[0]-vertex1[0], vertex2[1]-vertex1[1], vertex2[2]-vertex1[2]]
452             v2 = [vertex4[0]-vertex3[0], vertex4[1]-vertex3[1], vertex4[2]-vertex3[2]]
453             normal = [ v1[1]*v2[2]-v2[1]*v1[2], v1[2]*v2[0]-v2[2]*v1[0], v1[0]*v2[1]-v2[0]*v1[1] ]
454             axis = AxisStruct(vertex1[0], vertex1[1], vertex1[2], normal[0], normal[1], normal[2])
455             return axis
456         elif len(edges) == 1:
457             vertex1, vertex2 = self.geompyD.SubShapeAll( edges[0], geomBuilder.geomBuilder.ShapeType["VERTEX"] )
458             p1 = self.geompyD.PointCoordinates( vertex1 )
459             p2 = self.geompyD.PointCoordinates( vertex2 )
460             axis = AxisStruct(p1[0], p1[1], p1[2], p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])
461             return axis
462         return None
463
464     # From SMESH_Gen interface:
465     # ------------------------
466
467     ## Sets the given name to the object
468     #  @param obj the object to rename
469     #  @param name a new object name
470     #  @ingroup l1_auxiliary
471     def SetName(self, obj, name):
472         if isinstance( obj, Mesh ):
473             obj = obj.GetMesh()
474         elif isinstance( obj, Mesh_Algorithm ):
475             obj = obj.GetAlgorithm()
476         ior  = salome.orb.object_to_string(obj)
477         SMESH._objref_SMESH_Gen.SetName(self, ior, name)
478
479     ## Sets the current mode
480     #  @ingroup l1_auxiliary
481     def SetEmbeddedMode( self,theMode ):
482         #self.SetEmbeddedMode(theMode)
483         SMESH._objref_SMESH_Gen.SetEmbeddedMode(self,theMode)
484
485     ## Gets the current mode
486     #  @ingroup l1_auxiliary
487     def IsEmbeddedMode(self):
488         #return self.IsEmbeddedMode()
489         return SMESH._objref_SMESH_Gen.IsEmbeddedMode(self)
490
491     ## Sets the current study
492     #  @ingroup l1_auxiliary
493     def SetCurrentStudy( self, theStudy, geompyD = None ):
494         #self.SetCurrentStudy(theStudy)
495         if not geompyD:
496             from salome.geom import geomBuilder
497             geompyD = geomBuilder.geom
498             pass
499         self.geompyD=geompyD
500         self.SetGeomEngine(geompyD)
501         SMESH._objref_SMESH_Gen.SetCurrentStudy(self,theStudy)
502         global notebook
503         if theStudy:
504             notebook = salome_notebook.NoteBook( theStudy )
505         else:
506             notebook = salome_notebook.NoteBook( salome_notebook.PseudoStudyForNoteBook() )
507
508     ## Gets the current study
509     #  @ingroup l1_auxiliary
510     def GetCurrentStudy(self):
511         #return self.GetCurrentStudy()
512         return SMESH._objref_SMESH_Gen.GetCurrentStudy(self)
513
514     ## Creates a Mesh object importing data from the given UNV file
515     #  @return an instance of Mesh class
516     #  @ingroup l2_impexp
517     def CreateMeshesFromUNV( self,theFileName ):
518         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromUNV(self,theFileName)
519         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
520         return aMesh
521
522     ## Creates a Mesh object(s) importing data from the given MED file
523     #  @return a list of Mesh class instances
524     #  @ingroup l2_impexp
525     def CreateMeshesFromMED( self,theFileName ):
526         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromMED(self,theFileName)
527         aMeshes = []
528         for iMesh in range(len(aSmeshMeshes)) :
529             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
530             aMeshes.append(aMesh)
531         return aMeshes, aStatus
532
533     ## Creates a Mesh object(s) importing data from the given SAUV file
534     #  @return a list of Mesh class instances
535     #  @ingroup l2_impexp
536     def CreateMeshesFromSAUV( self,theFileName ):
537         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromSAUV(self,theFileName)
538         aMeshes = []
539         for iMesh in range(len(aSmeshMeshes)) :
540             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
541             aMeshes.append(aMesh)
542         return aMeshes, aStatus
543
544     ## Creates a Mesh object importing data from the given STL file
545     #  @return an instance of Mesh class
546     #  @ingroup l2_impexp
547     def CreateMeshesFromSTL( self, theFileName ):
548         aSmeshMesh = SMESH._objref_SMESH_Gen.CreateMeshesFromSTL(self,theFileName)
549         aMesh = Mesh(self, self.geompyD, aSmeshMesh)
550         return aMesh
551
552     ## Creates Mesh objects importing data from the given CGNS file
553     #  @return an instance of Mesh class
554     #  @ingroup l2_impexp
555     def CreateMeshesFromCGNS( self, theFileName ):
556         aSmeshMeshes, aStatus = SMESH._objref_SMESH_Gen.CreateMeshesFromCGNS(self,theFileName)
557         aMeshes = []
558         for iMesh in range(len(aSmeshMeshes)) :
559             aMesh = Mesh(self, self.geompyD, aSmeshMeshes[iMesh])
560             aMeshes.append(aMesh)
561         return aMeshes, aStatus
562
563     ## Creates a Mesh object importing data from the given GMF file
564     #  @return [ an instance of Mesh class, SMESH::ComputeError ]
565     #  @ingroup l2_impexp
566     def CreateMeshesFromGMF( self, theFileName ):
567         aSmeshMesh, error = SMESH._objref_SMESH_Gen.CreateMeshesFromGMF(self,
568                                                                         theFileName,
569                                                                         True)
570         if error.comment: print "*** CreateMeshesFromGMF() errors:\n", error.comment
571         return Mesh(self, self.geompyD, aSmeshMesh), error
572
573     ## Concatenate the given meshes into one mesh.
574     #  @return an instance of Mesh class
575     #  @param meshes the meshes to combine into one mesh
576     #  @param uniteIdenticalGroups if true, groups with same names are united, else they are renamed
577     #  @param mergeNodesAndElements if true, equal nodes and elements aremerged
578     #  @param mergeTolerance tolerance for merging nodes
579     #  @param allGroups forces creation of groups of all elements
580     #  @param name name of a new mesh
581     def Concatenate( self, meshes, uniteIdenticalGroups,
582                      mergeNodesAndElements = False, mergeTolerance = 1e-5, allGroups = False,
583                      name = ""):
584         if not meshes: return None
585         for i,m in enumerate(meshes):
586             if isinstance(m, Mesh):
587                 meshes[i] = m.GetMesh()
588         mergeTolerance,Parameters,hasVars = ParseParameters(mergeTolerance)
589         meshes[0].SetParameters(Parameters)
590         if allGroups:
591             aSmeshMesh = SMESH._objref_SMESH_Gen.ConcatenateWithGroups(
592                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
593         else:
594             aSmeshMesh = SMESH._objref_SMESH_Gen.Concatenate(
595                 self,meshes,uniteIdenticalGroups,mergeNodesAndElements,mergeTolerance)
596         aMesh = Mesh(self, self.geompyD, aSmeshMesh, name=name)
597         return aMesh
598
599     ## Create a mesh by copying a part of another mesh.
600     #  @param meshPart a part of mesh to copy, either a Mesh, a sub-mesh or a group;
601     #                  to copy nodes or elements not contained in any mesh object,
602     #                  pass result of Mesh.GetIDSource( list_of_ids, type ) as meshPart
603     #  @param meshName a name of the new mesh
604     #  @param toCopyGroups to create in the new mesh groups the copied elements belongs to
605     #  @param toKeepIDs to preserve IDs of the copied elements or not
606     #  @return an instance of Mesh class
607     def CopyMesh( self, meshPart, meshName, toCopyGroups=False, toKeepIDs=False):
608         if (isinstance( meshPart, Mesh )):
609             meshPart = meshPart.GetMesh()
610         mesh = SMESH._objref_SMESH_Gen.CopyMesh( self,meshPart,meshName,toCopyGroups,toKeepIDs )
611         return Mesh(self, self.geompyD, mesh)
612
613     ## From SMESH_Gen interface
614     #  @return the list of integer values
615     #  @ingroup l1_auxiliary
616     def GetSubShapesId( self, theMainObject, theListOfSubObjects ):
617         return SMESH._objref_SMESH_Gen.GetSubShapesId(self,theMainObject, theListOfSubObjects)
618
619     ## From SMESH_Gen interface. Creates a pattern
620     #  @return an instance of SMESH_Pattern
621     #
622     #  <a href="../tui_modifying_meshes_page.html#tui_pattern_mapping">Example of Patterns usage</a>
623     #  @ingroup l2_modif_patterns
624     def GetPattern(self):
625         return SMESH._objref_SMESH_Gen.GetPattern(self)
626
627     ## Sets number of segments per diagonal of boundary box of geometry by which
628     #  default segment length of appropriate 1D hypotheses is defined.
629     #  Default value is 10
630     #  @ingroup l1_auxiliary
631     def SetBoundaryBoxSegmentation(self, nbSegments):
632         SMESH._objref_SMESH_Gen.SetBoundaryBoxSegmentation(self,nbSegments)
633
634     # Filtering. Auxiliary functions:
635     # ------------------------------
636
637     ## Creates an empty criterion
638     #  @return SMESH.Filter.Criterion
639     #  @ingroup l1_controls
640     def GetEmptyCriterion(self):
641         Type = self.EnumToLong(FT_Undefined)
642         Compare = self.EnumToLong(FT_Undefined)
643         Threshold = 0
644         ThresholdStr = ""
645         ThresholdID = ""
646         UnaryOp = self.EnumToLong(FT_Undefined)
647         BinaryOp = self.EnumToLong(FT_Undefined)
648         Tolerance = 1e-07
649         TypeOfElement = ALL
650         Precision = -1 ##@1e-07
651         return Filter.Criterion(Type, Compare, Threshold, ThresholdStr, ThresholdID,
652                                 UnaryOp, BinaryOp, Tolerance, TypeOfElement, Precision)
653
654     ## Creates a criterion by the given parameters
655     #  \n Criterion structures allow to define complex filters by combining them with logical operations (AND / OR) (see example below)
656     #  @param elementType the type of elements(NODE, EDGE, FACE, VOLUME)
657     #  @param CritType the type of criterion (FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc.)
658     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
659     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
660     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
661     #  @param BinaryOp a binary logical operation FT_LogicalAND, FT_LogicalOR or
662     #                  FT_Undefined (must be for the last criterion of all criteria)
663     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
664     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
665     #  @return SMESH.Filter.Criterion
666     #
667     #  <a href="../tui_filters_page.html#combining_filters">Example of Criteria usage</a>
668     #  @ingroup l1_controls
669     def GetCriterion(self,elementType,
670                      CritType,
671                      Compare = FT_EqualTo,
672                      Threshold="",
673                      UnaryOp=FT_Undefined,
674                      BinaryOp=FT_Undefined,
675                      Tolerance=1e-07):
676         if not CritType in SMESH.FunctorType._items:
677             raise TypeError, "CritType should be of SMESH.FunctorType"
678         aCriterion = self.GetEmptyCriterion()
679         aCriterion.TypeOfElement = elementType
680         aCriterion.Type = self.EnumToLong(CritType)
681         aCriterion.Tolerance = Tolerance
682
683         aThreshold = Threshold
684
685         if Compare in [FT_LessThan, FT_MoreThan, FT_EqualTo]:
686             aCriterion.Compare = self.EnumToLong(Compare)
687         elif Compare == "=" or Compare == "==":
688             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
689         elif Compare == "<":
690             aCriterion.Compare = self.EnumToLong(FT_LessThan)
691         elif Compare == ">":
692             aCriterion.Compare = self.EnumToLong(FT_MoreThan)
693         elif Compare != FT_Undefined:
694             aCriterion.Compare = self.EnumToLong(FT_EqualTo)
695             aThreshold = Compare
696
697         if CritType in [FT_BelongToGeom,     FT_BelongToPlane, FT_BelongToGenSurface,
698                         FT_BelongToCylinder, FT_LyingOnGeom]:
699             # Checks that Threshold is GEOM object
700             if isinstance(aThreshold, geomBuilder.GEOM._objref_GEOM_Object):
701                 aCriterion.ThresholdStr = GetName(aThreshold)
702                 aCriterion.ThresholdID  = aThreshold.GetStudyEntry()
703                 if not aCriterion.ThresholdID:
704                     name = aCriterion.ThresholdStr
705                     if not name:
706                         name = "%s_%s"%(aThreshold.GetShapeType(), id(aThreshold)%10000)
707                     aCriterion.ThresholdID = self.geompyD.addToStudy( aThreshold, name )
708                     #raise RuntimeError, "Threshold shape must be published"
709             else:
710                 print "Error: The Threshold should be a shape."
711                 return None
712             if isinstance(UnaryOp,float):
713                 aCriterion.Tolerance = UnaryOp
714                 UnaryOp = FT_Undefined
715                 pass
716         elif CritType == FT_RangeOfIds:
717             # Checks that Threshold is string
718             if isinstance(aThreshold, str):
719                 aCriterion.ThresholdStr = aThreshold
720             else:
721                 print "Error: The Threshold should be a string."
722                 return None
723         elif CritType == FT_CoplanarFaces:
724             # Checks the Threshold
725             if isinstance(aThreshold, int):
726                 aCriterion.ThresholdID = str(aThreshold)
727             elif isinstance(aThreshold, str):
728                 ID = int(aThreshold)
729                 if ID < 1:
730                     raise ValueError, "Invalid ID of mesh face: '%s'"%aThreshold
731                 aCriterion.ThresholdID = aThreshold
732             else:
733                 raise ValueError,\
734                       "The Threshold should be an ID of mesh face and not '%s'"%aThreshold
735         elif CritType == FT_ElemGeomType:
736             # Checks the Threshold
737             try:
738                 aCriterion.Threshold = self.EnumToLong(aThreshold)
739                 assert( aThreshold in SMESH.GeometryType._items )
740             except:
741                 if isinstance(aThreshold, int):
742                     aCriterion.Threshold = aThreshold
743                 else:
744                     print "Error: The Threshold should be an integer or SMESH.GeometryType."
745                     return None
746                 pass
747             pass
748         elif CritType == FT_EntityType:
749             # Checks the Threshold
750             try:
751                 aCriterion.Threshold = self.EnumToLong(aThreshold)
752                 assert( aThreshold in SMESH.EntityType._items )
753             except:
754                 if isinstance(aThreshold, int):
755                     aCriterion.Threshold = aThreshold
756                 else:
757                     print "Error: The Threshold should be an integer or SMESH.EntityType."
758                     return None
759                 pass
760             pass
761         
762         elif CritType == FT_GroupColor:
763             # Checks the Threshold
764             try:
765                 aCriterion.ThresholdStr = self.ColorToString(aThreshold)
766             except:
767                 print "Error: The threshold value should be of SALOMEDS.Color type"
768                 return None
769             pass
770         elif CritType in [FT_FreeBorders, FT_FreeEdges, FT_FreeNodes, FT_FreeFaces,
771                           FT_LinearOrQuadratic, FT_BadOrientedVolume,
772                           FT_BareBorderFace, FT_BareBorderVolume,
773                           FT_OverConstrainedFace, FT_OverConstrainedVolume,
774                           FT_EqualNodes,FT_EqualEdges,FT_EqualFaces,FT_EqualVolumes ]:
775             # At this point the Threshold is unnecessary
776             if aThreshold ==  FT_LogicalNOT:
777                 aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
778             elif aThreshold in [FT_LogicalAND, FT_LogicalOR]:
779                 aCriterion.BinaryOp = aThreshold
780         else:
781             # Check Threshold
782             try:
783                 aThreshold = float(aThreshold)
784                 aCriterion.Threshold = aThreshold
785             except:
786                 print "Error: The Threshold should be a number."
787                 return None
788
789         if Threshold ==  FT_LogicalNOT or UnaryOp ==  FT_LogicalNOT:
790             aCriterion.UnaryOp = self.EnumToLong(FT_LogicalNOT)
791
792         if Threshold in [FT_LogicalAND, FT_LogicalOR]:
793             aCriterion.BinaryOp = self.EnumToLong(Threshold)
794
795         if UnaryOp in [FT_LogicalAND, FT_LogicalOR]:
796             aCriterion.BinaryOp = self.EnumToLong(UnaryOp)
797
798         if BinaryOp in [FT_LogicalAND, FT_LogicalOR]:
799             aCriterion.BinaryOp = self.EnumToLong(BinaryOp)
800
801         return aCriterion
802
803     ## Creates a filter with the given parameters
804     #  @param elementType the type of elements in the group
805     #  @param CritType the type of criterion ( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
806     #  @param Compare  belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
807     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
808     #  @param UnaryOp  FT_LogicalNOT or FT_Undefined
809     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
810     #         FT_LyingOnGeom, FT_CoplanarFaces and FT_EqualNodes criteria
811     #  @return SMESH_Filter
812     #
813     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
814     #  @ingroup l1_controls
815     def GetFilter(self,elementType,
816                   CritType=FT_Undefined,
817                   Compare=FT_EqualTo,
818                   Threshold="",
819                   UnaryOp=FT_Undefined,
820                   Tolerance=1e-07):
821         aCriterion = self.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
822         aFilterMgr = self.CreateFilterManager()
823         aFilter = aFilterMgr.CreateFilter()
824         aCriteria = []
825         aCriteria.append(aCriterion)
826         aFilter.SetCriteria(aCriteria)
827         aFilterMgr.UnRegister()
828         return aFilter
829
830     ## Creates a filter from criteria
831     #  @param criteria a list of criteria
832     #  @return SMESH_Filter
833     #
834     #  <a href="../tui_filters_page.html#tui_filters">Example of Filters usage</a>
835     #  @ingroup l1_controls
836     def GetFilterFromCriteria(self,criteria):
837         aFilterMgr = self.CreateFilterManager()
838         aFilter = aFilterMgr.CreateFilter()
839         aFilter.SetCriteria(criteria)
840         aFilterMgr.UnRegister()
841         return aFilter
842
843     ## Creates a numerical functor by its type
844     #  @param theCriterion FT_...; functor type
845     #  @return SMESH_NumericalFunctor
846     #  @ingroup l1_controls
847     def GetFunctor(self,theCriterion):
848         if isinstance( theCriterion, SMESH._objref_NumericalFunctor ):
849             return theCriterion
850         aFilterMgr = self.CreateFilterManager()
851         functor = None
852         if theCriterion == FT_AspectRatio:
853             functor = aFilterMgr.CreateAspectRatio()
854         elif theCriterion == FT_AspectRatio3D:
855             functor = aFilterMgr.CreateAspectRatio3D()
856         elif theCriterion == FT_Warping:
857             functor = aFilterMgr.CreateWarping()
858         elif theCriterion == FT_MinimumAngle:
859             functor = aFilterMgr.CreateMinimumAngle()
860         elif theCriterion == FT_Taper:
861             functor = aFilterMgr.CreateTaper()
862         elif theCriterion == FT_Skew:
863             functor = aFilterMgr.CreateSkew()
864         elif theCriterion == FT_Area:
865             functor = aFilterMgr.CreateArea()
866         elif theCriterion == FT_Volume3D:
867             functor = aFilterMgr.CreateVolume3D()
868         elif theCriterion == FT_MaxElementLength2D:
869             functor = aFilterMgr.CreateMaxElementLength2D()
870         elif theCriterion == FT_MaxElementLength3D:
871             functor = aFilterMgr.CreateMaxElementLength3D()
872         elif theCriterion == FT_MultiConnection:
873             functor = aFilterMgr.CreateMultiConnection()
874         elif theCriterion == FT_MultiConnection2D:
875             functor = aFilterMgr.CreateMultiConnection2D()
876         elif theCriterion == FT_Length:
877             functor = aFilterMgr.CreateLength()
878         elif theCriterion == FT_Length2D:
879             functor = aFilterMgr.CreateLength2D()
880         else:
881             print "Error: given parameter is not numerical functor type."
882         aFilterMgr.UnRegister()
883         return functor
884
885     ## Creates hypothesis
886     #  @param theHType mesh hypothesis type (string)
887     #  @param theLibName mesh plug-in library name
888     #  @return created hypothesis instance
889     def CreateHypothesis(self, theHType, theLibName="libStdMeshersEngine.so"):
890         hyp = SMESH._objref_SMESH_Gen.CreateHypothesis(self, theHType, theLibName )
891
892         if isinstance( hyp, SMESH._objref_SMESH_Algo ):
893             return hyp
894
895         # wrap hypothesis methods
896         #print "HYPOTHESIS", theHType
897         for meth_name in dir( hyp.__class__ ):
898             if not meth_name.startswith("Get") and \
899                not meth_name in dir ( SMESH._objref_SMESH_Hypothesis ):
900                 method = getattr ( hyp.__class__, meth_name )
901                 if callable(method):
902                     setattr( hyp, meth_name, hypMethodWrapper( hyp, method ))
903
904         return hyp
905
906     ## Gets the mesh statistic
907     #  @return dictionary "element type" - "count of elements"
908     #  @ingroup l1_meshinfo
909     def GetMeshInfo(self, obj):
910         if isinstance( obj, Mesh ):
911             obj = obj.GetMesh()
912         d = {}
913         if hasattr(obj, "GetMeshInfo"):
914             values = obj.GetMeshInfo()
915             for i in range(SMESH.Entity_Last._v):
916                 if i < len(values): d[SMESH.EntityType._item(i)]=values[i]
917             pass
918         return d
919
920     ## Get minimum distance between two objects
921     #
922     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
923     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
924     #
925     #  @param src1 first source object
926     #  @param src2 second source object
927     #  @param id1 node/element id from the first source
928     #  @param id2 node/element id from the second (or first) source
929     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
930     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
931     #  @return minimum distance value
932     #  @sa GetMinDistance()
933     #  @ingroup l1_measurements
934     def MinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
935         result = self.GetMinDistance(src1, src2, id1, id2, isElem1, isElem2)
936         if result is None:
937             result = 0.0
938         else:
939             result = result.value
940         return result
941
942     ## Get measure structure specifying minimum distance data between two objects
943     #
944     #  If @a src2 is None, and @a id2 = 0, distance from @a src1 / @a id1 to the origin is computed.
945     #  If @a src2 is None, and @a id2 != 0, it is assumed that both @a id1 and @a id2 belong to @a src1.
946     #
947     #  @param src1 first source object
948     #  @param src2 second source object
949     #  @param id1 node/element id from the first source
950     #  @param id2 node/element id from the second (or first) source
951     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
952     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
953     #  @return Measure structure or None if input data is invalid
954     #  @sa MinDistance()
955     #  @ingroup l1_measurements
956     def GetMinDistance(self, src1, src2=None, id1=0, id2=0, isElem1=False, isElem2=False):
957         if isinstance(src1, Mesh): src1 = src1.mesh
958         if isinstance(src2, Mesh): src2 = src2.mesh
959         if src2 is None and id2 != 0: src2 = src1
960         if not hasattr(src1, "_narrow"): return None
961         src1 = src1._narrow(SMESH.SMESH_IDSource)
962         if not src1: return None
963         if id1 != 0:
964             m = src1.GetMesh()
965             e = m.GetMeshEditor()
966             if isElem1:
967                 src1 = e.MakeIDSource([id1], SMESH.FACE)
968             else:
969                 src1 = e.MakeIDSource([id1], SMESH.NODE)
970             pass
971         if hasattr(src2, "_narrow"):
972             src2 = src2._narrow(SMESH.SMESH_IDSource)
973             if src2 and id2 != 0:
974                 m = src2.GetMesh()
975                 e = m.GetMeshEditor()
976                 if isElem2:
977                     src2 = e.MakeIDSource([id2], SMESH.FACE)
978                 else:
979                     src2 = e.MakeIDSource([id2], SMESH.NODE)
980                 pass
981             pass
982         aMeasurements = self.CreateMeasurements()
983         result = aMeasurements.MinDistance(src1, src2)
984         aMeasurements.UnRegister()
985         return result
986
987     ## Get bounding box of the specified object(s)
988     #  @param objects single source object or list of source objects
989     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
990     #  @sa GetBoundingBox()
991     #  @ingroup l1_measurements
992     def BoundingBox(self, objects):
993         result = self.GetBoundingBox(objects)
994         if result is None:
995             result = (0.0,)*6
996         else:
997             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
998         return result
999
1000     ## Get measure structure specifying bounding box data of the specified object(s)
1001     #  @param objects single source object or list of source objects
1002     #  @return Measure structure
1003     #  @sa BoundingBox()
1004     #  @ingroup l1_measurements
1005     def GetBoundingBox(self, objects):
1006         if isinstance(objects, tuple):
1007             objects = list(objects)
1008         if not isinstance(objects, list):
1009             objects = [objects]
1010         srclist = []
1011         for o in objects:
1012             if isinstance(o, Mesh):
1013                 srclist.append(o.mesh)
1014             elif hasattr(o, "_narrow"):
1015                 src = o._narrow(SMESH.SMESH_IDSource)
1016                 if src: srclist.append(src)
1017                 pass
1018             pass
1019         aMeasurements = self.CreateMeasurements()
1020         result = aMeasurements.BoundingBox(srclist)
1021         aMeasurements.UnRegister()
1022         return result
1023
1024 import omniORB
1025 #Registering the new proxy for SMESH_Gen
1026 omniORB.registerObjref(SMESH._objref_SMESH_Gen._NP_RepositoryId, smeshBuilder)
1027
1028 ## Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1029 #  interface to create or load meshes.
1030 #
1031 #  Typical use is:
1032 #  \code
1033 #    import salome
1034 #    salome.salome_init()
1035 #    from salome.smesh import smeshBuilder
1036 #    smesh = smeshBuilder.New(theStudy)
1037 #  \endcode
1038 #  @param  study     SALOME study, generally obtained by salome.myStudy.
1039 #  @param  instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1040 #  @return smeshBuilder instance
1041
1042 def New( study, instance=None):
1043     """
1044     Create a new smeshBuilder instance.The smeshBuilder class provides the Python
1045     interface to create or load meshes.
1046
1047     Typical use is:
1048         import salome
1049         salome.salome_init()
1050         from salome.smesh import smeshBuilder
1051         smesh = smeshBuilder.New(theStudy)
1052
1053     Parameters:
1054         study     SALOME study, generally obtained by salome.myStudy.
1055         instance  CORBA proxy of SMESH Engine. If None, the default Engine is used.
1056     Returns:
1057         smeshBuilder instance
1058     """
1059     global engine
1060     global smeshInst
1061     global doLcc
1062     engine = instance
1063     if engine is None:
1064       doLcc = True
1065     smeshInst = smeshBuilder()
1066     assert isinstance(smeshInst,smeshBuilder), "Smesh engine class is %s but should be smeshBuilder.smeshBuilder. Import salome.smesh.smeshBuilder before creating the instance."%smeshInst.__class__
1067     smeshInst.init_smesh(study)
1068     return smeshInst
1069
1070
1071 # Public class: Mesh
1072 # ==================
1073
1074 ## This class allows defining and managing a mesh.
1075 #  It has a set of methods to build a mesh on the given geometry, including the definition of sub-meshes.
1076 #  It also has methods to define groups of mesh elements, to modify a mesh (by addition of
1077 #  new nodes and elements and by changing the existing entities), to get information
1078 #  about a mesh and to export a mesh into different formats.
1079 class Mesh:
1080
1081     geom = 0
1082     mesh = 0
1083     editor = 0
1084
1085     ## Constructor
1086     #
1087     #  Creates a mesh on the shape \a obj (or an empty mesh if \a obj is equal to 0) and
1088     #  sets the GUI name of this mesh to \a name.
1089     #  @param smeshpyD an instance of smeshBuilder class
1090     #  @param geompyD an instance of geomBuilder class
1091     #  @param obj Shape to be meshed or SMESH_Mesh object
1092     #  @param name Study name of the mesh
1093     #  @ingroup l2_construct
1094     def __init__(self, smeshpyD, geompyD, obj=0, name=0):
1095         self.smeshpyD=smeshpyD
1096         self.geompyD=geompyD
1097         if obj is None:
1098             obj = 0
1099         objHasName = False
1100         if obj != 0:
1101             if isinstance(obj, geomBuilder.GEOM._objref_GEOM_Object):
1102                 self.geom = obj
1103                 objHasName = True
1104                 # publish geom of mesh (issue 0021122)
1105                 if not self.geom.GetStudyEntry() and smeshpyD.GetCurrentStudy():
1106                     objHasName = False
1107                     studyID = smeshpyD.GetCurrentStudy()._get_StudyId()
1108                     if studyID != geompyD.myStudyId:
1109                         geompyD.init_geom( smeshpyD.GetCurrentStudy())
1110                         pass
1111                     if name:
1112                         geo_name = name + " shape"
1113                     else:
1114                         geo_name = "%s_%s to mesh"%(self.geom.GetShapeType(), id(self.geom)%100)
1115                     geompyD.addToStudy( self.geom, geo_name )
1116                 self.mesh = self.smeshpyD.CreateMesh(self.geom)
1117
1118             elif isinstance(obj, SMESH._objref_SMESH_Mesh):
1119                 self.SetMesh(obj)
1120         else:
1121             self.mesh = self.smeshpyD.CreateEmptyMesh()
1122         if name:
1123             self.smeshpyD.SetName(self.mesh, name)
1124         elif objHasName:
1125             self.smeshpyD.SetName(self.mesh, GetName(obj)) # + " mesh"
1126
1127         if not self.geom:
1128             self.geom = self.mesh.GetShapeToMesh()
1129
1130         self.editor   = self.mesh.GetMeshEditor()
1131         self.functors = [None] * SMESH.FT_Undefined._v
1132
1133         # set self to algoCreator's
1134         for attrName in dir(self):
1135             attr = getattr( self, attrName )
1136             if isinstance( attr, algoCreator ):
1137                 #print "algoCreator ", attrName
1138                 setattr( self, attrName, attr.copy( self ))
1139
1140     ## Initializes the Mesh object from an instance of SMESH_Mesh interface
1141     #  @param theMesh a SMESH_Mesh object
1142     #  @ingroup l2_construct
1143     def SetMesh(self, theMesh):
1144         if self.mesh: self.mesh.UnRegister()
1145         self.mesh = theMesh
1146         if self.mesh:
1147             self.mesh.Register()
1148             self.geom = self.mesh.GetShapeToMesh()
1149
1150     ## Returns the mesh, that is an instance of SMESH_Mesh interface
1151     #  @return a SMESH_Mesh object
1152     #  @ingroup l2_construct
1153     def GetMesh(self):
1154         return self.mesh
1155
1156     ## Gets the name of the mesh
1157     #  @return the name of the mesh as a string
1158     #  @ingroup l2_construct
1159     def GetName(self):
1160         name = GetName(self.GetMesh())
1161         return name
1162
1163     ## Sets a name to the mesh
1164     #  @param name a new name of the mesh
1165     #  @ingroup l2_construct
1166     def SetName(self, name):
1167         self.smeshpyD.SetName(self.GetMesh(), name)
1168
1169     ## Gets the subMesh object associated to a \a theSubObject geometrical object.
1170     #  The subMesh object gives access to the IDs of nodes and elements.
1171     #  @param geom a geometrical object (shape)
1172     #  @param name a name for the submesh
1173     #  @return an object of type SMESH_SubMesh, representing a part of mesh, which lies on the given shape
1174     #  @ingroup l2_submeshes
1175     def GetSubMesh(self, geom, name):
1176         AssureGeomPublished( self, geom, name )
1177         submesh = self.mesh.GetSubMesh( geom, name )
1178         return submesh
1179
1180     ## Returns the shape associated to the mesh
1181     #  @return a GEOM_Object
1182     #  @ingroup l2_construct
1183     def GetShape(self):
1184         return self.geom
1185
1186     ## Associates the given shape to the mesh (entails the recreation of the mesh)
1187     #  @param geom the shape to be meshed (GEOM_Object)
1188     #  @ingroup l2_construct
1189     def SetShape(self, geom):
1190         self.mesh = self.smeshpyD.CreateMesh(geom)
1191
1192     ## Loads mesh from the study after opening the study
1193     def Load(self):
1194         self.mesh.Load()
1195
1196     ## Returns true if the hypotheses are defined well
1197     #  @param theSubObject a sub-shape of a mesh shape
1198     #  @return True or False
1199     #  @ingroup l2_construct
1200     def IsReadyToCompute(self, theSubObject):
1201         return self.smeshpyD.IsReadyToCompute(self.mesh, theSubObject)
1202
1203     ## Returns errors of hypotheses definition.
1204     #  The list of errors is empty if everything is OK.
1205     #  @param theSubObject a sub-shape of a mesh shape
1206     #  @return a list of errors
1207     #  @ingroup l2_construct
1208     def GetAlgoState(self, theSubObject):
1209         return self.smeshpyD.GetAlgoState(self.mesh, theSubObject)
1210
1211     ## Returns a geometrical object on which the given element was built.
1212     #  The returned geometrical object, if not nil, is either found in the
1213     #  study or published by this method with the given name
1214     #  @param theElementID the id of the mesh element
1215     #  @param theGeomName the user-defined name of the geometrical object
1216     #  @return GEOM::GEOM_Object instance
1217     #  @ingroup l2_construct
1218     def GetGeometryByMeshElement(self, theElementID, theGeomName):
1219         return self.smeshpyD.GetGeometryByMeshElement( self.mesh, theElementID, theGeomName )
1220
1221     ## Returns the mesh dimension depending on the dimension of the underlying shape
1222     #  or, if the mesh is not based on any shape, basing on deimension of elements
1223     #  @return mesh dimension as an integer value [0,3]
1224     #  @ingroup l1_auxiliary
1225     def MeshDimension(self):
1226         if self.mesh.HasShapeToMesh():
1227             shells = self.geompyD.SubShapeAllIDs( self.geom, self.geompyD.ShapeType["SOLID"] )
1228             if len( shells ) > 0 :
1229                 return 3
1230             elif self.geompyD.NumberOfFaces( self.geom ) > 0 :
1231                 return 2
1232             elif self.geompyD.NumberOfEdges( self.geom ) > 0 :
1233                 return 1
1234             else:
1235                 return 0;
1236         else:
1237             if self.NbVolumes() > 0: return 3
1238             if self.NbFaces()   > 0: return 2
1239             if self.NbEdges()   > 0: return 1
1240         return 0
1241
1242     ## Evaluates size of prospective mesh on a shape
1243     #  @return a list where i-th element is a number of elements of i-th SMESH.EntityType
1244     #  To know predicted number of e.g. edges, inquire it this way
1245     #  Evaluate()[ EnumToLong( Entity_Edge )]
1246     def Evaluate(self, geom=0):
1247         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1248             if self.geom == 0:
1249                 geom = self.mesh.GetShapeToMesh()
1250             else:
1251                 geom = self.geom
1252         return self.smeshpyD.Evaluate(self.mesh, geom)
1253
1254
1255     ## Computes the mesh and returns the status of the computation
1256     #  @param geom geomtrical shape on which mesh data should be computed
1257     #  @param discardModifs if True and the mesh has been edited since
1258     #         a last total re-compute and that may prevent successful partial re-compute,
1259     #         then the mesh is cleaned before Compute()
1260     #  @return True or False
1261     #  @ingroup l2_construct
1262     def Compute(self, geom=0, discardModifs=False):
1263         if geom == 0 or not isinstance(geom, geomBuilder.GEOM._objref_GEOM_Object):
1264             if self.geom == 0:
1265                 geom = self.mesh.GetShapeToMesh()
1266             else:
1267                 geom = self.geom
1268         ok = False
1269         try:
1270             if discardModifs and self.mesh.HasModificationsToDiscard(): # issue 0020693
1271                 self.mesh.Clear()
1272             ok = self.smeshpyD.Compute(self.mesh, geom)
1273         except SALOME.SALOME_Exception, ex:
1274             print "Mesh computation failed, exception caught:"
1275             print "    ", ex.details.text
1276         except:
1277             import traceback
1278             print "Mesh computation failed, exception caught:"
1279             traceback.print_exc()
1280         if True:#not ok:
1281             allReasons = ""
1282
1283             # Treat compute errors
1284             computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, geom )
1285             for err in computeErrors:
1286                 shapeText = ""
1287                 if self.mesh.HasShapeToMesh():
1288                     try:
1289                         mainIOR  = salome.orb.object_to_string(geom)
1290                         for sname in salome.myStudyManager.GetOpenStudies():
1291                             s = salome.myStudyManager.GetStudyByName(sname)
1292                             if not s: continue
1293                             mainSO = s.FindObjectIOR(mainIOR)
1294                             if not mainSO: continue
1295                             if err.subShapeID == 1:
1296                                 shapeText = ' on "%s"' % mainSO.GetName()
1297                             subIt = s.NewChildIterator(mainSO)
1298                             while subIt.More():
1299                                 subSO = subIt.Value()
1300                                 subIt.Next()
1301                                 obj = subSO.GetObject()
1302                                 if not obj: continue
1303                                 go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1304                                 if not go: continue
1305                                 ids = go.GetSubShapeIndices()
1306                                 if len(ids) == 1 and ids[0] == err.subShapeID:
1307                                     shapeText = ' on "%s"' % subSO.GetName()
1308                                     break
1309                         if not shapeText:
1310                             shape = self.geompyD.GetSubShape( geom, [err.subShapeID])
1311                             if shape:
1312                                 shapeText = " on %s #%s" % (shape.GetShapeType(), err.subShapeID)
1313                             else:
1314                                 shapeText = " on subshape #%s" % (err.subShapeID)
1315                     except:
1316                         shapeText = " on subshape #%s" % (err.subShapeID)
1317                 errText = ""
1318                 stdErrors = ["OK",                   #COMPERR_OK
1319                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1320                              "std::exception",       #COMPERR_STD_EXCEPTION
1321                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1322                              "..",                   #COMPERR_SLM_EXCEPTION
1323                              "Unknown exception",    #COMPERR_EXCEPTION
1324                              "Memory allocation problem", #COMPERR_MEMORY_PB
1325                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1326                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1327                              "Warning",              #COMPERR_WARNING
1328                              "Computation cancelled",#COMPERR_CANCELED
1329                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1330                 if err.code > 0:
1331                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1332                 else:
1333                     errText = "code %s" % -err.code
1334                 if errText: errText += ". "
1335                 errText += err.comment
1336                 if allReasons != "":allReasons += "\n"
1337                 allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1338                 pass
1339
1340             # Treat hyp errors
1341             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1342             for err in errors:
1343                 if err.isGlobalAlgo:
1344                     glob = "global"
1345                 else:
1346                     glob = "local"
1347                     pass
1348                 dim = err.algoDim
1349                 name = err.algoName
1350                 if len(name) == 0:
1351                     reason = '%s %sD algorithm is missing' % (glob, dim)
1352                 elif err.state == HYP_MISSING:
1353                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1354                               % (glob, dim, name, dim))
1355                 elif err.state == HYP_NOTCONFORM:
1356                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1357                 elif err.state == HYP_BAD_PARAMETER:
1358                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1359                               % ( glob, dim, name ))
1360                 elif err.state == HYP_BAD_GEOMETRY:
1361                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1362                               'geometry' % ( glob, dim, name ))
1363                 elif err.state == HYP_HIDDEN_ALGO:
1364                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1365                               'algorithm of upper dimension generating %sD mesh'
1366                               % ( glob, dim, name, glob, dim ))
1367                 else:
1368                     reason = ("For unknown reason. "
1369                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1370                     pass
1371                 if allReasons != "":allReasons += "\n"
1372                 allReasons += "-  " + reason
1373                 pass
1374             if not ok or allReasons != "":
1375                 msg = '"' + GetName(self.mesh) + '"'
1376                 if ok: msg += " has been computed with warnings"
1377                 else:  msg += " has not been computed"
1378                 if allReasons != "": msg += ":"
1379                 else:                msg += "."
1380                 print msg
1381                 print allReasons
1382             pass
1383         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1384             smeshgui = salome.ImportComponentGUI("SMESH")
1385             smeshgui.Init(self.mesh.GetStudyId())
1386             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1387             salome.sg.updateObjBrowser(1)
1388             pass
1389         return ok
1390
1391     ## Return submesh objects list in meshing order
1392     #  @return list of list of submesh objects
1393     #  @ingroup l2_construct
1394     def GetMeshOrder(self):
1395         return self.mesh.GetMeshOrder()
1396
1397     ## Return submesh objects list in meshing order
1398     #  @return list of list of submesh objects
1399     #  @ingroup l2_construct
1400     def SetMeshOrder(self, submeshes):
1401         return self.mesh.SetMeshOrder(submeshes)
1402
1403     ## Removes all nodes and elements
1404     #  @ingroup l2_construct
1405     def Clear(self):
1406         self.mesh.Clear()
1407         if ( salome.sg.hasDesktop() and 
1408              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() )):
1409             smeshgui = salome.ImportComponentGUI("SMESH")
1410             smeshgui.Init(self.mesh.GetStudyId())
1411             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1412             salome.sg.updateObjBrowser(1)
1413
1414     ## Removes all nodes and elements of indicated shape
1415     #  @ingroup l2_construct
1416     def ClearSubMesh(self, geomId):
1417         self.mesh.ClearSubMesh(geomId)
1418         if salome.sg.hasDesktop():
1419             smeshgui = salome.ImportComponentGUI("SMESH")
1420             smeshgui.Init(self.mesh.GetStudyId())
1421             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1422             salome.sg.updateObjBrowser(1)
1423
1424     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + NETGEN
1425     #  @param fineness [0.0,1.0] defines mesh fineness
1426     #  @return True or False
1427     #  @ingroup l3_algos_basic
1428     def AutomaticTetrahedralization(self, fineness=0):
1429         dim = self.MeshDimension()
1430         # assign hypotheses
1431         self.RemoveGlobalHypotheses()
1432         self.Segment().AutomaticLength(fineness)
1433         if dim > 1 :
1434             self.Triangle().LengthFromEdges()
1435             pass
1436         if dim > 2 :
1437             from salome.NETGENPlugin.NETGENPluginBuilder import NETGEN
1438             self.Tetrahedron(NETGEN)
1439             pass
1440         return self.Compute()
1441
1442     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1443     #  @param fineness [0.0, 1.0] defines mesh fineness
1444     #  @return True or False
1445     #  @ingroup l3_algos_basic
1446     def AutomaticHexahedralization(self, fineness=0):
1447         dim = self.MeshDimension()
1448         # assign the hypotheses
1449         self.RemoveGlobalHypotheses()
1450         self.Segment().AutomaticLength(fineness)
1451         if dim > 1 :
1452             self.Quadrangle()
1453             pass
1454         if dim > 2 :
1455             self.Hexahedron()
1456             pass
1457         return self.Compute()
1458
1459     ## Assigns a hypothesis
1460     #  @param hyp a hypothesis to assign
1461     #  @param geom a subhape of mesh geometry
1462     #  @return SMESH.Hypothesis_Status
1463     #  @ingroup l2_hypotheses
1464     def AddHypothesis(self, hyp, geom=0):
1465         if isinstance( hyp, Mesh_Algorithm ):
1466             hyp = hyp.GetAlgorithm()
1467             pass
1468         if not geom:
1469             geom = self.geom
1470             if not geom:
1471                 geom = self.mesh.GetShapeToMesh()
1472             pass
1473         AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1474         status = self.mesh.AddHypothesis(geom, hyp)
1475         isAlgo = hyp._narrow( SMESH_Algo )
1476         hyp_name = GetName( hyp )
1477         geom_name = ""
1478         if geom:
1479             geom_name = GetName( geom )
1480         TreatHypoStatus( status, hyp_name, geom_name, isAlgo )
1481         return status
1482
1483     ## Return True if an algorithm of hypothesis is assigned to a given shape
1484     #  @param hyp a hypothesis to check
1485     #  @param geom a subhape of mesh geometry
1486     #  @return True of False
1487     #  @ingroup l2_hypotheses
1488     def IsUsedHypothesis(self, hyp, geom):
1489         if not hyp: # or not geom
1490             return False
1491         if isinstance( hyp, Mesh_Algorithm ):
1492             hyp = hyp.GetAlgorithm()
1493             pass
1494         hyps = self.GetHypothesisList(geom)
1495         for h in hyps:
1496             if h.GetId() == hyp.GetId():
1497                 return True
1498         return False
1499
1500     ## Unassigns a hypothesis
1501     #  @param hyp a hypothesis to unassign
1502     #  @param geom a sub-shape of mesh geometry
1503     #  @return SMESH.Hypothesis_Status
1504     #  @ingroup l2_hypotheses
1505     def RemoveHypothesis(self, hyp, geom=0):
1506         if isinstance( hyp, Mesh_Algorithm ):
1507             hyp = hyp.GetAlgorithm()
1508             pass
1509         shape = geom
1510         if not shape:
1511             shape = self.geom
1512             pass
1513         if self.IsUsedHypothesis( hyp, shape ):
1514             return self.mesh.RemoveHypothesis( shape, hyp )
1515         hypName = GetName( hyp )
1516         geoName = GetName( shape )
1517         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1518         return None
1519
1520     ## Gets the list of hypotheses added on a geometry
1521     #  @param geom a sub-shape of mesh geometry
1522     #  @return the sequence of SMESH_Hypothesis
1523     #  @ingroup l2_hypotheses
1524     def GetHypothesisList(self, geom):
1525         return self.mesh.GetHypothesisList( geom )
1526
1527     ## Removes all global hypotheses
1528     #  @ingroup l2_hypotheses
1529     def RemoveGlobalHypotheses(self):
1530         current_hyps = self.mesh.GetHypothesisList( self.geom )
1531         for hyp in current_hyps:
1532             self.mesh.RemoveHypothesis( self.geom, hyp )
1533             pass
1534         pass
1535
1536    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1537     ## allowing to overwrite the file if it exists or add the exported data to its contents
1538     #  @param f is the file name
1539     #  @param auto_groups boolean parameter for creating/not creating
1540     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1541     #  the typical use is auto_groups=false.
1542     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1543     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1544     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1545     #  @ingroup l2_impexp
1546     def ExportMED(self, f, auto_groups=0, version=MED_V2_2, overwrite=1, meshPart=None):
1547         if meshPart:
1548             if isinstance( meshPart, list ):
1549                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1550             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite )
1551         else:
1552             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite)
1553
1554     ## Exports the mesh in a file in SAUV format
1555     #  @param f is the file name
1556     #  @param auto_groups boolean parameter for creating/not creating
1557     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1558     #  the typical use is auto_groups=false.
1559     #  @ingroup l2_impexp
1560     def ExportSAUV(self, f, auto_groups=0):
1561         self.mesh.ExportSAUV(f, auto_groups)
1562
1563     ## Exports the mesh in a file in DAT format
1564     #  @param f the file name
1565     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1566     #  @ingroup l2_impexp
1567     def ExportDAT(self, f, meshPart=None):
1568         if meshPart:
1569             if isinstance( meshPart, list ):
1570                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1571             self.mesh.ExportPartToDAT( meshPart, f )
1572         else:
1573             self.mesh.ExportDAT(f)
1574
1575     ## Exports the mesh in a file in UNV format
1576     #  @param f the file name
1577     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1578     #  @ingroup l2_impexp
1579     def ExportUNV(self, f, meshPart=None):
1580         if meshPart:
1581             if isinstance( meshPart, list ):
1582                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1583             self.mesh.ExportPartToUNV( meshPart, f )
1584         else:
1585             self.mesh.ExportUNV(f)
1586
1587     ## Export the mesh in a file in STL format
1588     #  @param f the file name
1589     #  @param ascii defines the file encoding
1590     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1591     #  @ingroup l2_impexp
1592     def ExportSTL(self, f, ascii=1, meshPart=None):
1593         if meshPart:
1594             if isinstance( meshPart, list ):
1595                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1596             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1597         else:
1598             self.mesh.ExportSTL(f, ascii)
1599
1600     ## Exports the mesh in a file in CGNS format
1601     #  @param f is the file name
1602     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1603     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1604     #  @ingroup l2_impexp
1605     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1606         if isinstance( meshPart, list ):
1607             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1608         if isinstance( meshPart, Mesh ):
1609             meshPart = meshPart.mesh
1610         elif not meshPart:
1611             meshPart = self.mesh
1612         self.mesh.ExportCGNS(meshPart, f, overwrite)
1613
1614     ## Exports the mesh in a file in GMF format
1615     #  @param f is the file name
1616     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1617     #  @ingroup l2_impexp
1618     def ExportGMF(self, f, meshPart=None):
1619         if isinstance( meshPart, list ):
1620             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1621         if isinstance( meshPart, Mesh ):
1622             meshPart = meshPart.mesh
1623         elif not meshPart:
1624             meshPart = self.mesh
1625         self.mesh.ExportGMF(meshPart, f, True)
1626
1627     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1628     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1629     ## allowing to overwrite the file if it exists or add the exported data to its contents
1630     #  @param f the file name
1631     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1632     #  @param opt boolean parameter for creating/not creating
1633     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1634     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1635     #  @ingroup l2_impexp
1636     def ExportToMED(self, f, version, opt=0, overwrite=1):
1637         self.mesh.ExportToMEDX(f, opt, version, overwrite)
1638
1639     # Operations with groups:
1640     # ----------------------
1641
1642     ## Creates an empty mesh group
1643     #  @param elementType the type of elements in the group
1644     #  @param name the name of the mesh group
1645     #  @return SMESH_Group
1646     #  @ingroup l2_grps_create
1647     def CreateEmptyGroup(self, elementType, name):
1648         return self.mesh.CreateGroup(elementType, name)
1649
1650     ## Creates a mesh group based on the geometric object \a grp
1651     #  and gives a \a name, \n if this parameter is not defined
1652     #  the name is the same as the geometric group name \n
1653     #  Note: Works like GroupOnGeom().
1654     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1655     #  @param name the name of the mesh group
1656     #  @return SMESH_GroupOnGeom
1657     #  @ingroup l2_grps_create
1658     def Group(self, grp, name=""):
1659         return self.GroupOnGeom(grp, name)
1660
1661     ## Creates a mesh group based on the geometrical object \a grp
1662     #  and gives a \a name, \n if this parameter is not defined
1663     #  the name is the same as the geometrical group name
1664     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1665     #  @param name the name of the mesh group
1666     #  @param typ  the type of elements in the group. If not set, it is
1667     #              automatically detected by the type of the geometry
1668     #  @return SMESH_GroupOnGeom
1669     #  @ingroup l2_grps_create
1670     def GroupOnGeom(self, grp, name="", typ=None):
1671         AssureGeomPublished( self, grp, name )
1672         if name == "":
1673             name = grp.GetName()
1674         if not typ:
1675             typ = self._groupTypeFromShape( grp )
1676         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1677
1678     ## Pivate method to get a type of group on geometry
1679     def _groupTypeFromShape( self, shape ):
1680         tgeo = str(shape.GetShapeType())
1681         if tgeo == "VERTEX":
1682             typ = NODE
1683         elif tgeo == "EDGE":
1684             typ = EDGE
1685         elif tgeo == "FACE" or tgeo == "SHELL":
1686             typ = FACE
1687         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1688             typ = VOLUME
1689         elif tgeo == "COMPOUND":
1690             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1691             if not sub:
1692                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1693             return self._groupTypeFromShape( sub[0] )
1694         else:
1695             raise ValueError, \
1696                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1697         return typ
1698
1699     ## Creates a mesh group with given \a name based on the \a filter which
1700     ## is a special type of group dynamically updating it's contents during
1701     ## mesh modification
1702     #  @param typ  the type of elements in the group
1703     #  @param name the name of the mesh group
1704     #  @param filter the filter defining group contents
1705     #  @return SMESH_GroupOnFilter
1706     #  @ingroup l2_grps_create
1707     def GroupOnFilter(self, typ, name, filter):
1708         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1709
1710     ## Creates a mesh group by the given ids of elements
1711     #  @param groupName the name of the mesh group
1712     #  @param elementType the type of elements in the group
1713     #  @param elemIDs the list of ids
1714     #  @return SMESH_Group
1715     #  @ingroup l2_grps_create
1716     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1717         group = self.mesh.CreateGroup(elementType, groupName)
1718         group.Add(elemIDs)
1719         return group
1720
1721     ## Creates a mesh group by the given conditions
1722     #  @param groupName the name of the mesh group
1723     #  @param elementType the type of elements in the group
1724     #  @param CritType the type of criterion( FT_Taper, FT_Area, FT_RangeOfIds, FT_LyingOnGeom etc. )
1725     #  @param Compare belongs to {FT_LessThan, FT_MoreThan, FT_EqualTo}
1726     #  @param Threshold the threshold value (range of id ids as string, shape, numeric)
1727     #  @param UnaryOp FT_LogicalNOT or FT_Undefined
1728     #  @param Tolerance the tolerance used by FT_BelongToGeom, FT_BelongToSurface,
1729     #         FT_LyingOnGeom, FT_CoplanarFaces criteria
1730     #  @return SMESH_Group
1731     #  @ingroup l2_grps_create
1732     def MakeGroup(self,
1733                   groupName,
1734                   elementType,
1735                   CritType=FT_Undefined,
1736                   Compare=FT_EqualTo,
1737                   Threshold="",
1738                   UnaryOp=FT_Undefined,
1739                   Tolerance=1e-07):
1740         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
1741         group = self.MakeGroupByCriterion(groupName, aCriterion)
1742         return group
1743
1744     ## Creates a mesh group by the given criterion
1745     #  @param groupName the name of the mesh group
1746     #  @param Criterion the instance of Criterion class
1747     #  @return SMESH_Group
1748     #  @ingroup l2_grps_create
1749     def MakeGroupByCriterion(self, groupName, Criterion):
1750         aFilterMgr = self.smeshpyD.CreateFilterManager()
1751         aFilter = aFilterMgr.CreateFilter()
1752         aCriteria = []
1753         aCriteria.append(Criterion)
1754         aFilter.SetCriteria(aCriteria)
1755         group = self.MakeGroupByFilter(groupName, aFilter)
1756         aFilterMgr.UnRegister()
1757         return group
1758
1759     ## Creates a mesh group by the given criteria (list of criteria)
1760     #  @param groupName the name of the mesh group
1761     #  @param theCriteria the list of criteria
1762     #  @return SMESH_Group
1763     #  @ingroup l2_grps_create
1764     def MakeGroupByCriteria(self, groupName, theCriteria):
1765         aFilterMgr = self.smeshpyD.CreateFilterManager()
1766         aFilter = aFilterMgr.CreateFilter()
1767         aFilter.SetCriteria(theCriteria)
1768         group = self.MakeGroupByFilter(groupName, aFilter)
1769         aFilterMgr.UnRegister()
1770         return group
1771
1772     ## Creates a mesh group by the given filter
1773     #  @param groupName the name of the mesh group
1774     #  @param theFilter the instance of Filter class
1775     #  @return SMESH_Group
1776     #  @ingroup l2_grps_create
1777     def MakeGroupByFilter(self, groupName, theFilter):
1778         group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
1779         theFilter.SetMesh( self.mesh )
1780         group.AddFrom( theFilter )
1781         return group
1782
1783     ## Removes a group
1784     #  @ingroup l2_grps_delete
1785     def RemoveGroup(self, group):
1786         self.mesh.RemoveGroup(group)
1787
1788     ## Removes a group with its contents
1789     #  @ingroup l2_grps_delete
1790     def RemoveGroupWithContents(self, group):
1791         self.mesh.RemoveGroupWithContents(group)
1792
1793     ## Gets the list of groups existing in the mesh
1794     #  @return a sequence of SMESH_GroupBase
1795     #  @ingroup l2_grps_create
1796     def GetGroups(self):
1797         return self.mesh.GetGroups()
1798
1799     ## Gets the number of groups existing in the mesh
1800     #  @return the quantity of groups as an integer value
1801     #  @ingroup l2_grps_create
1802     def NbGroups(self):
1803         return self.mesh.NbGroups()
1804
1805     ## Gets the list of names of groups existing in the mesh
1806     #  @return list of strings
1807     #  @ingroup l2_grps_create
1808     def GetGroupNames(self):
1809         groups = self.GetGroups()
1810         names = []
1811         for group in groups:
1812             names.append(group.GetName())
1813         return names
1814
1815     ## Produces a union of two groups
1816     #  A new group is created. All mesh elements that are
1817     #  present in the initial groups are added to the new one
1818     #  @return an instance of SMESH_Group
1819     #  @ingroup l2_grps_operon
1820     def UnionGroups(self, group1, group2, name):
1821         return self.mesh.UnionGroups(group1, group2, name)
1822
1823     ## Produces a union list of groups
1824     #  New group is created. All mesh elements that are present in
1825     #  initial groups are added to the new one
1826     #  @return an instance of SMESH_Group
1827     #  @ingroup l2_grps_operon
1828     def UnionListOfGroups(self, groups, name):
1829       return self.mesh.UnionListOfGroups(groups, name)
1830
1831     ## Prodices an intersection of two groups
1832     #  A new group is created. All mesh elements that are common
1833     #  for the two initial groups are added to the new one.
1834     #  @return an instance of SMESH_Group
1835     #  @ingroup l2_grps_operon
1836     def IntersectGroups(self, group1, group2, name):
1837         return self.mesh.IntersectGroups(group1, group2, name)
1838
1839     ## Produces an intersection of groups
1840     #  New group is created. All mesh elements that are present in all
1841     #  initial groups simultaneously are added to the new one
1842     #  @return an instance of SMESH_Group
1843     #  @ingroup l2_grps_operon
1844     def IntersectListOfGroups(self, groups, name):
1845       return self.mesh.IntersectListOfGroups(groups, name)
1846
1847     ## Produces a cut of two groups
1848     #  A new group is created. All mesh elements that are present in
1849     #  the main group but are not present in the tool group are added to the new one
1850     #  @return an instance of SMESH_Group
1851     #  @ingroup l2_grps_operon
1852     def CutGroups(self, main_group, tool_group, name):
1853         return self.mesh.CutGroups(main_group, tool_group, name)
1854
1855     ## Produces a cut of groups
1856     #  A new group is created. All mesh elements that are present in main groups
1857     #  but do not present in tool groups are added to the new one
1858     #  @return an instance of SMESH_Group
1859     #  @ingroup l2_grps_operon
1860     def CutListOfGroups(self, main_groups, tool_groups, name):
1861       return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
1862
1863     ## Produces a group of elements of specified type using list of existing groups
1864     #  A new group is created. System
1865     #  1) extracts all nodes on which groups elements are built
1866     #  2) combines all elements of specified dimension laying on these nodes
1867     #  @return an instance of SMESH_Group
1868     #  @ingroup l2_grps_operon
1869     def CreateDimGroup(self, groups, elem_type, name):
1870       return self.mesh.CreateDimGroup(groups, elem_type, name)
1871
1872
1873     ## Convert group on geom into standalone group
1874     #  @ingroup l2_grps_delete
1875     def ConvertToStandalone(self, group):
1876         return self.mesh.ConvertToStandalone(group)
1877
1878     # Get some info about mesh:
1879     # ------------------------
1880
1881     ## Returns the log of nodes and elements added or removed
1882     #  since the previous clear of the log.
1883     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
1884     #  @return list of log_block structures:
1885     #                                        commandType
1886     #                                        number
1887     #                                        coords
1888     #                                        indexes
1889     #  @ingroup l1_auxiliary
1890     def GetLog(self, clearAfterGet):
1891         return self.mesh.GetLog(clearAfterGet)
1892
1893     ## Clears the log of nodes and elements added or removed since the previous
1894     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
1895     #  @ingroup l1_auxiliary
1896     def ClearLog(self):
1897         self.mesh.ClearLog()
1898
1899     ## Toggles auto color mode on the object.
1900     #  @param theAutoColor the flag which toggles auto color mode.
1901     #  @ingroup l1_auxiliary
1902     def SetAutoColor(self, theAutoColor):
1903         self.mesh.SetAutoColor(theAutoColor)
1904
1905     ## Gets flag of object auto color mode.
1906     #  @return True or False
1907     #  @ingroup l1_auxiliary
1908     def GetAutoColor(self):
1909         return self.mesh.GetAutoColor()
1910
1911     ## Gets the internal ID
1912     #  @return integer value, which is the internal Id of the mesh
1913     #  @ingroup l1_auxiliary
1914     def GetId(self):
1915         return self.mesh.GetId()
1916
1917     ## Get the study Id
1918     #  @return integer value, which is the study Id of the mesh
1919     #  @ingroup l1_auxiliary
1920     def GetStudyId(self):
1921         return self.mesh.GetStudyId()
1922
1923     ## Checks the group names for duplications.
1924     #  Consider the maximum group name length stored in MED file.
1925     #  @return True or False
1926     #  @ingroup l1_auxiliary
1927     def HasDuplicatedGroupNamesMED(self):
1928         return self.mesh.HasDuplicatedGroupNamesMED()
1929
1930     ## Obtains the mesh editor tool
1931     #  @return an instance of SMESH_MeshEditor
1932     #  @ingroup l1_modifying
1933     def GetMeshEditor(self):
1934         return self.editor
1935
1936     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
1937     #  can be passed as argument to a method accepting mesh, group or sub-mesh
1938     #  @return an instance of SMESH_IDSource
1939     #  @ingroup l1_auxiliary
1940     def GetIDSource(self, ids, elemType):
1941         return self.editor.MakeIDSource(ids, elemType)
1942
1943     ## Gets MED Mesh
1944     #  @return an instance of SALOME_MED::MESH
1945     #  @ingroup l1_auxiliary
1946     def GetMEDMesh(self):
1947         return self.mesh.GetMEDMesh()
1948
1949
1950     # Get informations about mesh contents:
1951     # ------------------------------------
1952
1953     ## Gets the mesh stattistic
1954     #  @return dictionary type element - count of elements
1955     #  @ingroup l1_meshinfo
1956     def GetMeshInfo(self, obj = None):
1957         if not obj: obj = self.mesh
1958         return self.smeshpyD.GetMeshInfo(obj)
1959
1960     ## Returns the number of nodes in the mesh
1961     #  @return an integer value
1962     #  @ingroup l1_meshinfo
1963     def NbNodes(self):
1964         return self.mesh.NbNodes()
1965
1966     ## Returns the number of elements in the mesh
1967     #  @return an integer value
1968     #  @ingroup l1_meshinfo
1969     def NbElements(self):
1970         return self.mesh.NbElements()
1971
1972     ## Returns the number of 0d elements in the mesh
1973     #  @return an integer value
1974     #  @ingroup l1_meshinfo
1975     def Nb0DElements(self):
1976         return self.mesh.Nb0DElements()
1977
1978     ## Returns the number of ball discrete elements in the mesh
1979     #  @return an integer value
1980     #  @ingroup l1_meshinfo
1981     def NbBalls(self):
1982         return self.mesh.NbBalls()
1983
1984     ## Returns the number of edges in the mesh
1985     #  @return an integer value
1986     #  @ingroup l1_meshinfo
1987     def NbEdges(self):
1988         return self.mesh.NbEdges()
1989
1990     ## Returns the number of edges with the given order in the mesh
1991     #  @param elementOrder the order of elements:
1992     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
1993     #  @return an integer value
1994     #  @ingroup l1_meshinfo
1995     def NbEdgesOfOrder(self, elementOrder):
1996         return self.mesh.NbEdgesOfOrder(elementOrder)
1997
1998     ## Returns the number of faces in the mesh
1999     #  @return an integer value
2000     #  @ingroup l1_meshinfo
2001     def NbFaces(self):
2002         return self.mesh.NbFaces()
2003
2004     ## Returns the number of faces with the given order in the mesh
2005     #  @param elementOrder the order of elements:
2006     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2007     #  @return an integer value
2008     #  @ingroup l1_meshinfo
2009     def NbFacesOfOrder(self, elementOrder):
2010         return self.mesh.NbFacesOfOrder(elementOrder)
2011
2012     ## Returns the number of triangles in the mesh
2013     #  @return an integer value
2014     #  @ingroup l1_meshinfo
2015     def NbTriangles(self):
2016         return self.mesh.NbTriangles()
2017
2018     ## Returns the number of triangles with the given order in the mesh
2019     #  @param elementOrder is the order of elements:
2020     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2021     #  @return an integer value
2022     #  @ingroup l1_meshinfo
2023     def NbTrianglesOfOrder(self, elementOrder):
2024         return self.mesh.NbTrianglesOfOrder(elementOrder)
2025
2026     ## Returns the number of quadrangles in the mesh
2027     #  @return an integer value
2028     #  @ingroup l1_meshinfo
2029     def NbQuadrangles(self):
2030         return self.mesh.NbQuadrangles()
2031
2032     ## Returns the number of quadrangles with the given order in the mesh
2033     #  @param elementOrder the order of elements:
2034     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2035     #  @return an integer value
2036     #  @ingroup l1_meshinfo
2037     def NbQuadranglesOfOrder(self, elementOrder):
2038         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2039
2040     ## Returns the number of biquadratic quadrangles in the mesh
2041     #  @return an integer value
2042     #  @ingroup l1_meshinfo
2043     def NbBiQuadQuadrangles(self):
2044         return self.mesh.NbBiQuadQuadrangles()
2045
2046     ## Returns the number of polygons in the mesh
2047     #  @return an integer value
2048     #  @ingroup l1_meshinfo
2049     def NbPolygons(self):
2050         return self.mesh.NbPolygons()
2051
2052     ## Returns the number of volumes in the mesh
2053     #  @return an integer value
2054     #  @ingroup l1_meshinfo
2055     def NbVolumes(self):
2056         return self.mesh.NbVolumes()
2057
2058     ## Returns the number of volumes with the given order in the mesh
2059     #  @param elementOrder  the order of elements:
2060     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2061     #  @return an integer value
2062     #  @ingroup l1_meshinfo
2063     def NbVolumesOfOrder(self, elementOrder):
2064         return self.mesh.NbVolumesOfOrder(elementOrder)
2065
2066     ## Returns the number of tetrahedrons in the mesh
2067     #  @return an integer value
2068     #  @ingroup l1_meshinfo
2069     def NbTetras(self):
2070         return self.mesh.NbTetras()
2071
2072     ## Returns the number of tetrahedrons with the given order in the mesh
2073     #  @param elementOrder  the order of elements:
2074     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2075     #  @return an integer value
2076     #  @ingroup l1_meshinfo
2077     def NbTetrasOfOrder(self, elementOrder):
2078         return self.mesh.NbTetrasOfOrder(elementOrder)
2079
2080     ## Returns the number of hexahedrons in the mesh
2081     #  @return an integer value
2082     #  @ingroup l1_meshinfo
2083     def NbHexas(self):
2084         return self.mesh.NbHexas()
2085
2086     ## Returns the number of hexahedrons with the given order in the mesh
2087     #  @param elementOrder  the order of elements:
2088     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2089     #  @return an integer value
2090     #  @ingroup l1_meshinfo
2091     def NbHexasOfOrder(self, elementOrder):
2092         return self.mesh.NbHexasOfOrder(elementOrder)
2093
2094     ## Returns the number of triquadratic hexahedrons in the mesh
2095     #  @return an integer value
2096     #  @ingroup l1_meshinfo
2097     def NbTriQuadraticHexas(self):
2098         return self.mesh.NbTriQuadraticHexas()
2099
2100     ## Returns the number of pyramids in the mesh
2101     #  @return an integer value
2102     #  @ingroup l1_meshinfo
2103     def NbPyramids(self):
2104         return self.mesh.NbPyramids()
2105
2106     ## Returns the number of pyramids with the given order in the mesh
2107     #  @param elementOrder  the order of elements:
2108     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2109     #  @return an integer value
2110     #  @ingroup l1_meshinfo
2111     def NbPyramidsOfOrder(self, elementOrder):
2112         return self.mesh.NbPyramidsOfOrder(elementOrder)
2113
2114     ## Returns the number of prisms in the mesh
2115     #  @return an integer value
2116     #  @ingroup l1_meshinfo
2117     def NbPrisms(self):
2118         return self.mesh.NbPrisms()
2119
2120     ## Returns the number of prisms with the given order in the mesh
2121     #  @param elementOrder  the order of elements:
2122     #         ORDER_ANY, ORDER_LINEAR or ORDER_QUADRATIC
2123     #  @return an integer value
2124     #  @ingroup l1_meshinfo
2125     def NbPrismsOfOrder(self, elementOrder):
2126         return self.mesh.NbPrismsOfOrder(elementOrder)
2127
2128     ## Returns the number of hexagonal prisms in the mesh
2129     #  @return an integer value
2130     #  @ingroup l1_meshinfo
2131     def NbHexagonalPrisms(self):
2132         return self.mesh.NbHexagonalPrisms()
2133
2134     ## Returns the number of polyhedrons in the mesh
2135     #  @return an integer value
2136     #  @ingroup l1_meshinfo
2137     def NbPolyhedrons(self):
2138         return self.mesh.NbPolyhedrons()
2139
2140     ## Returns the number of submeshes in the mesh
2141     #  @return an integer value
2142     #  @ingroup l1_meshinfo
2143     def NbSubMesh(self):
2144         return self.mesh.NbSubMesh()
2145
2146     ## Returns the list of mesh elements IDs
2147     #  @return the list of integer values
2148     #  @ingroup l1_meshinfo
2149     def GetElementsId(self):
2150         return self.mesh.GetElementsId()
2151
2152     ## Returns the list of IDs of mesh elements with the given type
2153     #  @param elementType  the required type of elements (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2154     #  @return list of integer values
2155     #  @ingroup l1_meshinfo
2156     def GetElementsByType(self, elementType):
2157         return self.mesh.GetElementsByType(elementType)
2158
2159     ## Returns the list of mesh nodes IDs
2160     #  @return the list of integer values
2161     #  @ingroup l1_meshinfo
2162     def GetNodesId(self):
2163         return self.mesh.GetNodesId()
2164
2165     # Get the information about mesh elements:
2166     # ------------------------------------
2167
2168     ## Returns the type of mesh element
2169     #  @return the value from SMESH::ElementType enumeration
2170     #  @ingroup l1_meshinfo
2171     def GetElementType(self, id, iselem):
2172         return self.mesh.GetElementType(id, iselem)
2173
2174     ## Returns the geometric type of mesh element
2175     #  @return the value from SMESH::EntityType enumeration
2176     #  @ingroup l1_meshinfo
2177     def GetElementGeomType(self, id):
2178         return self.mesh.GetElementGeomType(id)
2179
2180     ## Returns the list of submesh elements IDs
2181     #  @param Shape a geom object(sub-shape) IOR
2182     #         Shape must be the sub-shape of a ShapeToMesh()
2183     #  @return the list of integer values
2184     #  @ingroup l1_meshinfo
2185     def GetSubMeshElementsId(self, Shape):
2186         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2187             ShapeID = Shape.GetSubShapeIndices()[0]
2188         else:
2189             ShapeID = Shape
2190         return self.mesh.GetSubMeshElementsId(ShapeID)
2191
2192     ## Returns the list of submesh nodes IDs
2193     #  @param Shape a geom object(sub-shape) IOR
2194     #         Shape must be the sub-shape of a ShapeToMesh()
2195     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2196     #  @return the list of integer values
2197     #  @ingroup l1_meshinfo
2198     def GetSubMeshNodesId(self, Shape, all):
2199         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2200             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2201         else:
2202             ShapeID = Shape
2203         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2204
2205     ## Returns type of elements on given shape
2206     #  @param Shape a geom object(sub-shape) IOR
2207     #         Shape must be a sub-shape of a ShapeToMesh()
2208     #  @return element type
2209     #  @ingroup l1_meshinfo
2210     def GetSubMeshElementType(self, Shape):
2211         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2212             ShapeID = Shape.GetSubShapeIndices()[0]
2213         else:
2214             ShapeID = Shape
2215         return self.mesh.GetSubMeshElementType(ShapeID)
2216
2217     ## Gets the mesh description
2218     #  @return string value
2219     #  @ingroup l1_meshinfo
2220     def Dump(self):
2221         return self.mesh.Dump()
2222
2223
2224     # Get the information about nodes and elements of a mesh by its IDs:
2225     # -----------------------------------------------------------
2226
2227     ## Gets XYZ coordinates of a node
2228     #  \n If there is no nodes for the given ID - returns an empty list
2229     #  @return a list of double precision values
2230     #  @ingroup l1_meshinfo
2231     def GetNodeXYZ(self, id):
2232         return self.mesh.GetNodeXYZ(id)
2233
2234     ## Returns list of IDs of inverse elements for the given node
2235     #  \n If there is no node for the given ID - returns an empty list
2236     #  @return a list of integer values
2237     #  @ingroup l1_meshinfo
2238     def GetNodeInverseElements(self, id):
2239         return self.mesh.GetNodeInverseElements(id)
2240
2241     ## @brief Returns the position of a node on the shape
2242     #  @return SMESH::NodePosition
2243     #  @ingroup l1_meshinfo
2244     def GetNodePosition(self,NodeID):
2245         return self.mesh.GetNodePosition(NodeID)
2246
2247     ## @brief Returns the position of an element on the shape
2248     #  @return SMESH::ElementPosition
2249     #  @ingroup l1_meshinfo
2250     def GetElementPosition(self,ElemID):
2251         return self.mesh.GetElementPosition(ElemID)
2252
2253     ## If the given element is a node, returns the ID of shape
2254     #  \n If there is no node for the given ID - returns -1
2255     #  @return an integer value
2256     #  @ingroup l1_meshinfo
2257     def GetShapeID(self, id):
2258         return self.mesh.GetShapeID(id)
2259
2260     ## Returns the ID of the result shape after
2261     #  FindShape() from SMESH_MeshEditor for the given element
2262     #  \n If there is no element for the given ID - returns -1
2263     #  @return an integer value
2264     #  @ingroup l1_meshinfo
2265     def GetShapeIDForElem(self,id):
2266         return self.mesh.GetShapeIDForElem(id)
2267
2268     ## Returns the number of nodes for the given element
2269     #  \n If there is no element for the given ID - returns -1
2270     #  @return an integer value
2271     #  @ingroup l1_meshinfo
2272     def GetElemNbNodes(self, id):
2273         return self.mesh.GetElemNbNodes(id)
2274
2275     ## Returns the node ID the given (zero based) index for the given element
2276     #  \n If there is no element for the given ID - returns -1
2277     #  \n If there is no node for the given index - returns -2
2278     #  @return an integer value
2279     #  @ingroup l1_meshinfo
2280     def GetElemNode(self, id, index):
2281         return self.mesh.GetElemNode(id, index)
2282
2283     ## Returns the IDs of nodes of the given element
2284     #  @return a list of integer values
2285     #  @ingroup l1_meshinfo
2286     def GetElemNodes(self, id):
2287         return self.mesh.GetElemNodes(id)
2288
2289     ## Returns true if the given node is the medium node in the given quadratic element
2290     #  @ingroup l1_meshinfo
2291     def IsMediumNode(self, elementID, nodeID):
2292         return self.mesh.IsMediumNode(elementID, nodeID)
2293
2294     ## Returns true if the given node is the medium node in one of quadratic elements
2295     #  @ingroup l1_meshinfo
2296     def IsMediumNodeOfAnyElem(self, nodeID, elementType):
2297         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2298
2299     ## Returns the number of edges for the given element
2300     #  @ingroup l1_meshinfo
2301     def ElemNbEdges(self, id):
2302         return self.mesh.ElemNbEdges(id)
2303
2304     ## Returns the number of faces for the given element
2305     #  @ingroup l1_meshinfo
2306     def ElemNbFaces(self, id):
2307         return self.mesh.ElemNbFaces(id)
2308
2309     ## Returns nodes of given face (counted from zero) for given volumic element.
2310     #  @ingroup l1_meshinfo
2311     def GetElemFaceNodes(self,elemId, faceIndex):
2312         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2313
2314     ## Returns an element based on all given nodes.
2315     #  @ingroup l1_meshinfo
2316     def FindElementByNodes(self,nodes):
2317         return self.mesh.FindElementByNodes(nodes)
2318
2319     ## Returns true if the given element is a polygon
2320     #  @ingroup l1_meshinfo
2321     def IsPoly(self, id):
2322         return self.mesh.IsPoly(id)
2323
2324     ## Returns true if the given element is quadratic
2325     #  @ingroup l1_meshinfo
2326     def IsQuadratic(self, id):
2327         return self.mesh.IsQuadratic(id)
2328
2329     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2330     #  @ingroup l1_meshinfo
2331     def GetBallDiameter(self, id):
2332         return self.mesh.GetBallDiameter(id)
2333
2334     ## Returns XYZ coordinates of the barycenter of the given element
2335     #  \n If there is no element for the given ID - returns an empty list
2336     #  @return a list of three double values
2337     #  @ingroup l1_meshinfo
2338     def BaryCenter(self, id):
2339         return self.mesh.BaryCenter(id)
2340
2341     ## Passes mesh elements through the given filter and return IDs of fitting elements
2342     #  @param theFilter SMESH_Filter
2343     #  @return a list of ids
2344     #  @ingroup l1_controls
2345     def GetIdsFromFilter(self, theFilter):
2346         theFilter.SetMesh( self.mesh )
2347         return theFilter.GetIDs()
2348
2349     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2350     #  Returns a list of special structures (borders).
2351     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2352     #  @ingroup l1_controls
2353     def GetFreeBorders(self):
2354         aFilterMgr = self.smeshpyD.CreateFilterManager()
2355         aPredicate = aFilterMgr.CreateFreeEdges()
2356         aPredicate.SetMesh(self.mesh)
2357         aBorders = aPredicate.GetBorders()
2358         aFilterMgr.UnRegister()
2359         return aBorders
2360
2361
2362     # Get mesh measurements information:
2363     # ------------------------------------
2364
2365     ## Get minimum distance between two nodes, elements or distance to the origin
2366     #  @param id1 first node/element id
2367     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2368     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2369     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2370     #  @return minimum distance value
2371     #  @sa GetMinDistance()
2372     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2373         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2374         return aMeasure.value
2375
2376     ## Get measure structure specifying minimum distance data between two objects
2377     #  @param id1 first node/element id
2378     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2379     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2380     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2381     #  @return Measure structure
2382     #  @sa MinDistance()
2383     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2384         if isElem1:
2385             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2386         else:
2387             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2388         if id2 != 0:
2389             if isElem2:
2390                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2391             else:
2392                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2393             pass
2394         else:
2395             id2 = None
2396
2397         aMeasurements = self.smeshpyD.CreateMeasurements()
2398         aMeasure = aMeasurements.MinDistance(id1, id2)
2399         aMeasurements.UnRegister()
2400         return aMeasure
2401
2402     ## Get bounding box of the specified object(s)
2403     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2404     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2405     #  @c False specifies that @a objects are nodes
2406     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2407     #  @sa GetBoundingBox()
2408     def BoundingBox(self, objects=None, isElem=False):
2409         result = self.GetBoundingBox(objects, isElem)
2410         if result is None:
2411             result = (0.0,)*6
2412         else:
2413             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2414         return result
2415
2416     ## Get measure structure specifying bounding box data of the specified object(s)
2417     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2418     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2419     #  @c False specifies that @a objects are nodes
2420     #  @return Measure structure
2421     #  @sa BoundingBox()
2422     def GetBoundingBox(self, IDs=None, isElem=False):
2423         if IDs is None:
2424             IDs = [self.mesh]
2425         elif isinstance(IDs, tuple):
2426             IDs = list(IDs)
2427         if not isinstance(IDs, list):
2428             IDs = [IDs]
2429         if len(IDs) > 0 and isinstance(IDs[0], int):
2430             IDs = [IDs]
2431         srclist = []
2432         for o in IDs:
2433             if isinstance(o, Mesh):
2434                 srclist.append(o.mesh)
2435             elif hasattr(o, "_narrow"):
2436                 src = o._narrow(SMESH.SMESH_IDSource)
2437                 if src: srclist.append(src)
2438                 pass
2439             elif isinstance(o, list):
2440                 if isElem:
2441                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2442                 else:
2443                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2444                 pass
2445             pass
2446         aMeasurements = self.smeshpyD.CreateMeasurements()
2447         aMeasure = aMeasurements.BoundingBox(srclist)
2448         aMeasurements.UnRegister()
2449         return aMeasure
2450
2451     # Mesh edition (SMESH_MeshEditor functionality):
2452     # ---------------------------------------------
2453
2454     ## Removes the elements from the mesh by ids
2455     #  @param IDsOfElements is a list of ids of elements to remove
2456     #  @return True or False
2457     #  @ingroup l2_modif_del
2458     def RemoveElements(self, IDsOfElements):
2459         return self.editor.RemoveElements(IDsOfElements)
2460
2461     ## Removes nodes from mesh by ids
2462     #  @param IDsOfNodes is a list of ids of nodes to remove
2463     #  @return True or False
2464     #  @ingroup l2_modif_del
2465     def RemoveNodes(self, IDsOfNodes):
2466         return self.editor.RemoveNodes(IDsOfNodes)
2467
2468     ## Removes all orphan (free) nodes from mesh
2469     #  @return number of the removed nodes
2470     #  @ingroup l2_modif_del
2471     def RemoveOrphanNodes(self):
2472         return self.editor.RemoveOrphanNodes()
2473
2474     ## Add a node to the mesh by coordinates
2475     #  @return Id of the new node
2476     #  @ingroup l2_modif_add
2477     def AddNode(self, x, y, z):
2478         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2479         if hasVars: self.mesh.SetParameters(Parameters)
2480         return self.editor.AddNode( x, y, z)
2481
2482     ## Creates a 0D element on a node with given number.
2483     #  @param IDOfNode the ID of node for creation of the element.
2484     #  @return the Id of the new 0D element
2485     #  @ingroup l2_modif_add
2486     def Add0DElement(self, IDOfNode):
2487         return self.editor.Add0DElement(IDOfNode)
2488
2489     ## Create 0D elements on all nodes of the given elements except those 
2490     #  nodes on which a 0D element already exists.
2491     #  @param theObject an object on whose nodes 0D elements will be created.
2492     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2493     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2494     #  @param theGroupName optional name of a group to add 0D elements created
2495     #         and/or found on nodes of \a theObject.
2496     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2497     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2498     #          can be retrieved from the returned object by calling GetIDs()
2499     #  @ingroup l2_modif_add
2500     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2501         if isinstance( theObject, Mesh ):
2502             theObject = theObject.GetMesh()
2503         if isinstance( theObject, list ):
2504             theObject = self.GetIDSource( theObject, SMESH.ALL )
2505         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2506
2507     ## Creates a ball element on a node with given ID.
2508     #  @param IDOfNode the ID of node for creation of the element.
2509     #  @param diameter the bal diameter.
2510     #  @return the Id of the new ball element
2511     #  @ingroup l2_modif_add
2512     def AddBall(self, IDOfNode, diameter):
2513         return self.editor.AddBall( IDOfNode, diameter )
2514
2515     ## Creates a linear or quadratic edge (this is determined
2516     #  by the number of given nodes).
2517     #  @param IDsOfNodes the list of node IDs for creation of the element.
2518     #  The order of nodes in this list should correspond to the description
2519     #  of MED. \n This description is located by the following link:
2520     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2521     #  @return the Id of the new edge
2522     #  @ingroup l2_modif_add
2523     def AddEdge(self, IDsOfNodes):
2524         return self.editor.AddEdge(IDsOfNodes)
2525
2526     ## Creates a linear or quadratic face (this is determined
2527     #  by the number of given nodes).
2528     #  @param IDsOfNodes the list of node IDs for creation of the element.
2529     #  The order of nodes in this list should correspond to the description
2530     #  of MED. \n This description is located by the following link:
2531     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2532     #  @return the Id of the new face
2533     #  @ingroup l2_modif_add
2534     def AddFace(self, IDsOfNodes):
2535         return self.editor.AddFace(IDsOfNodes)
2536
2537     ## Adds a polygonal face to the mesh by the list of node IDs
2538     #  @param IdsOfNodes the list of node IDs for creation of the element.
2539     #  @return the Id of the new face
2540     #  @ingroup l2_modif_add
2541     def AddPolygonalFace(self, IdsOfNodes):
2542         return self.editor.AddPolygonalFace(IdsOfNodes)
2543
2544     ## Creates both simple and quadratic volume (this is determined
2545     #  by the number of given nodes).
2546     #  @param IDsOfNodes the list of node IDs for creation of the element.
2547     #  The order of nodes in this list should correspond to the description
2548     #  of MED. \n This description is located by the following link:
2549     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2550     #  @return the Id of the new volumic element
2551     #  @ingroup l2_modif_add
2552     def AddVolume(self, IDsOfNodes):
2553         return self.editor.AddVolume(IDsOfNodes)
2554
2555     ## Creates a volume of many faces, giving nodes for each face.
2556     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2557     #  @param Quantities the list of integer values, Quantities[i]
2558     #         gives the quantity of nodes in face number i.
2559     #  @return the Id of the new volumic element
2560     #  @ingroup l2_modif_add
2561     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2562         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2563
2564     ## Creates a volume of many faces, giving the IDs of the existing faces.
2565     #  @param IdsOfFaces the list of face IDs for volume creation.
2566     #
2567     #  Note:  The created volume will refer only to the nodes
2568     #         of the given faces, not to the faces themselves.
2569     #  @return the Id of the new volumic element
2570     #  @ingroup l2_modif_add
2571     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2572         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2573
2574
2575     ## @brief Binds a node to a vertex
2576     #  @param NodeID a node ID
2577     #  @param Vertex a vertex or vertex ID
2578     #  @return True if succeed else raises an exception
2579     #  @ingroup l2_modif_add
2580     def SetNodeOnVertex(self, NodeID, Vertex):
2581         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2582             VertexID = Vertex.GetSubShapeIndices()[0]
2583         else:
2584             VertexID = Vertex
2585         try:
2586             self.editor.SetNodeOnVertex(NodeID, VertexID)
2587         except SALOME.SALOME_Exception, inst:
2588             raise ValueError, inst.details.text
2589         return True
2590
2591
2592     ## @brief Stores the node position on an edge
2593     #  @param NodeID a node ID
2594     #  @param Edge an edge or edge ID
2595     #  @param paramOnEdge a parameter on the edge where the node is located
2596     #  @return True if succeed else raises an exception
2597     #  @ingroup l2_modif_add
2598     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2599         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2600             EdgeID = Edge.GetSubShapeIndices()[0]
2601         else:
2602             EdgeID = Edge
2603         try:
2604             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2605         except SALOME.SALOME_Exception, inst:
2606             raise ValueError, inst.details.text
2607         return True
2608
2609     ## @brief Stores node position on a face
2610     #  @param NodeID a node ID
2611     #  @param Face a face or face ID
2612     #  @param u U parameter on the face where the node is located
2613     #  @param v V parameter on the face where the node is located
2614     #  @return True if succeed else raises an exception
2615     #  @ingroup l2_modif_add
2616     def SetNodeOnFace(self, NodeID, Face, u, v):
2617         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2618             FaceID = Face.GetSubShapeIndices()[0]
2619         else:
2620             FaceID = Face
2621         try:
2622             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2623         except SALOME.SALOME_Exception, inst:
2624             raise ValueError, inst.details.text
2625         return True
2626
2627     ## @brief Binds a node to a solid
2628     #  @param NodeID a node ID
2629     #  @param Solid  a solid or solid ID
2630     #  @return True if succeed else raises an exception
2631     #  @ingroup l2_modif_add
2632     def SetNodeInVolume(self, NodeID, Solid):
2633         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2634             SolidID = Solid.GetSubShapeIndices()[0]
2635         else:
2636             SolidID = Solid
2637         try:
2638             self.editor.SetNodeInVolume(NodeID, SolidID)
2639         except SALOME.SALOME_Exception, inst:
2640             raise ValueError, inst.details.text
2641         return True
2642
2643     ## @brief Bind an element to a shape
2644     #  @param ElementID an element ID
2645     #  @param Shape a shape or shape ID
2646     #  @return True if succeed else raises an exception
2647     #  @ingroup l2_modif_add
2648     def SetMeshElementOnShape(self, ElementID, Shape):
2649         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2650             ShapeID = Shape.GetSubShapeIndices()[0]
2651         else:
2652             ShapeID = Shape
2653         try:
2654             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2655         except SALOME.SALOME_Exception, inst:
2656             raise ValueError, inst.details.text
2657         return True
2658
2659
2660     ## Moves the node with the given id
2661     #  @param NodeID the id of the node
2662     #  @param x  a new X coordinate
2663     #  @param y  a new Y coordinate
2664     #  @param z  a new Z coordinate
2665     #  @return True if succeed else False
2666     #  @ingroup l2_modif_movenode
2667     def MoveNode(self, NodeID, x, y, z):
2668         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2669         if hasVars: self.mesh.SetParameters(Parameters)
2670         return self.editor.MoveNode(NodeID, x, y, z)
2671
2672     ## Finds the node closest to a point and moves it to a point location
2673     #  @param x  the X coordinate of a point
2674     #  @param y  the Y coordinate of a point
2675     #  @param z  the Z coordinate of a point
2676     #  @param NodeID if specified (>0), the node with this ID is moved,
2677     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
2678     #  @return the ID of a node
2679     #  @ingroup l2_modif_throughp
2680     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
2681         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2682         if hasVars: self.mesh.SetParameters(Parameters)
2683         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
2684
2685     ## Finds the node closest to a point
2686     #  @param x  the X coordinate of a point
2687     #  @param y  the Y coordinate of a point
2688     #  @param z  the Z coordinate of a point
2689     #  @return the ID of a node
2690     #  @ingroup l2_modif_throughp
2691     def FindNodeClosestTo(self, x, y, z):
2692         #preview = self.mesh.GetMeshEditPreviewer()
2693         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
2694         return self.editor.FindNodeClosestTo(x, y, z)
2695
2696     ## Finds the elements where a point lays IN or ON
2697     #  @param x  the X coordinate of a point
2698     #  @param y  the Y coordinate of a point
2699     #  @param z  the Z coordinate of a point
2700     #  @param elementType type of elements to find (SMESH.ALL type
2701     #         means elements of any type excluding nodes, discrete and 0D elements)
2702     #  @param meshPart a part of mesh (group, sub-mesh) to search within
2703     #  @return list of IDs of found elements
2704     #  @ingroup l2_modif_throughp
2705     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
2706         if meshPart:
2707             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
2708         else:
2709             return self.editor.FindElementsByPoint(x, y, z, elementType)
2710
2711     # Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
2712     # 0-IN, 1-OUT, 2-ON, 3-UNKNOWN
2713     # TopAbs_UNKNOWN state means that either mesh is wrong or the analysis fails.
2714
2715     def GetPointState(self, x, y, z):
2716         return self.editor.GetPointState(x, y, z)
2717
2718     ## Finds the node closest to a point and moves it to a point location
2719     #  @param x  the X coordinate of a point
2720     #  @param y  the Y coordinate of a point
2721     #  @param z  the Z coordinate of a point
2722     #  @return the ID of a moved node
2723     #  @ingroup l2_modif_throughp
2724     def MeshToPassThroughAPoint(self, x, y, z):
2725         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
2726
2727     ## Replaces two neighbour triangles sharing Node1-Node2 link
2728     #  with the triangles built on the same 4 nodes but having other common link.
2729     #  @param NodeID1  the ID of the first node
2730     #  @param NodeID2  the ID of the second node
2731     #  @return false if proper faces were not found
2732     #  @ingroup l2_modif_invdiag
2733     def InverseDiag(self, NodeID1, NodeID2):
2734         return self.editor.InverseDiag(NodeID1, NodeID2)
2735
2736     ## Replaces two neighbour triangles sharing Node1-Node2 link
2737     #  with a quadrangle built on the same 4 nodes.
2738     #  @param NodeID1  the ID of the first node
2739     #  @param NodeID2  the ID of the second node
2740     #  @return false if proper faces were not found
2741     #  @ingroup l2_modif_unitetri
2742     def DeleteDiag(self, NodeID1, NodeID2):
2743         return self.editor.DeleteDiag(NodeID1, NodeID2)
2744
2745     ## Reorients elements by ids
2746     #  @param IDsOfElements if undefined reorients all mesh elements
2747     #  @return True if succeed else False
2748     #  @ingroup l2_modif_changori
2749     def Reorient(self, IDsOfElements=None):
2750         if IDsOfElements == None:
2751             IDsOfElements = self.GetElementsId()
2752         return self.editor.Reorient(IDsOfElements)
2753
2754     ## Reorients all elements of the object
2755     #  @param theObject mesh, submesh or group
2756     #  @return True if succeed else False
2757     #  @ingroup l2_modif_changori
2758     def ReorientObject(self, theObject):
2759         if ( isinstance( theObject, Mesh )):
2760             theObject = theObject.GetMesh()
2761         return self.editor.ReorientObject(theObject)
2762
2763     ## Reorient faces contained in \a the2DObject.
2764     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
2765     #  @param theDirection is a desired direction of normal of \a theFace.
2766     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
2767     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
2768     #         compared with theDirection. It can be either ID of face or a point
2769     #         by which the face will be found. The point can be given as either
2770     #         a GEOM vertex or a list of point coordinates.
2771     #  @return number of reoriented faces
2772     #  @ingroup l2_modif_changori
2773     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
2774         # check the2DObject
2775         if isinstance( the2DObject, Mesh ):
2776             the2DObject = the2DObject.GetMesh()
2777         if isinstance( the2DObject, list ):
2778             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
2779         # check theDirection
2780         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
2781             theDirection = self.smeshpyD.GetDirStruct( theDirection )
2782         if isinstance( theDirection, list ):
2783             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
2784         # prepare theFace and thePoint
2785         theFace = theFaceOrPoint
2786         thePoint = PointStruct(0,0,0)
2787         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
2788             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
2789             theFace = -1
2790         if isinstance( theFaceOrPoint, list ):
2791             thePoint = PointStruct( *theFaceOrPoint )
2792             theFace = -1
2793         if isinstance( theFaceOrPoint, PointStruct ):
2794             thePoint = theFaceOrPoint
2795             theFace = -1
2796         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
2797
2798     ## Fuses the neighbouring triangles into quadrangles.
2799     #  @param IDsOfElements The triangles to be fused,
2800     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2801     #                       choose a neighbour to fuse with.
2802     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
2803     #                       is still performed; theMaxAngle is mesured in radians.
2804     #                       Also it could be a name of variable which defines angle in degrees.
2805     #  @return TRUE in case of success, FALSE otherwise.
2806     #  @ingroup l2_modif_unitetri
2807     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
2808         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2809         self.mesh.SetParameters(Parameters)
2810         if not IDsOfElements:
2811             IDsOfElements = self.GetElementsId()
2812         Functor = self.smeshpyD.GetFunctor(theCriterion)
2813         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
2814
2815     ## Fuses the neighbouring triangles of the object into quadrangles
2816     #  @param theObject is mesh, submesh or group
2817     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2818     #         choose a neighbour to fuse with.
2819     #  @param MaxAngle   a max angle between element normals at which the fusion
2820     #                   is still performed; theMaxAngle is mesured in radians.
2821     #  @return TRUE in case of success, FALSE otherwise.
2822     #  @ingroup l2_modif_unitetri
2823     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
2824         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
2825         self.mesh.SetParameters(Parameters)
2826         if isinstance( theObject, Mesh ):
2827             theObject = theObject.GetMesh()
2828         Functor = self.smeshpyD.GetFunctor(theCriterion)
2829         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
2830
2831     ## Splits quadrangles into triangles.
2832     #
2833     #  @param IDsOfElements the faces to be splitted.
2834     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
2835     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2836     #         value, then quadrangles will be split by the smallest diagonal.
2837     #  @return TRUE in case of success, FALSE otherwise.
2838     #  @ingroup l2_modif_cutquadr
2839     def QuadToTri (self, IDsOfElements, theCriterion = None):
2840         if IDsOfElements == []:
2841             IDsOfElements = self.GetElementsId()
2842         if theCriterion is None:
2843             theCriterion = FT_MaxElementLength2D
2844         Functor = self.smeshpyD.GetFunctor(theCriterion)
2845         return self.editor.QuadToTri(IDsOfElements, Functor)
2846
2847     ## Splits quadrangles into triangles.
2848     #  @param theObject the object from which the list of elements is taken,
2849     #         this is mesh, submesh or group
2850     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
2851     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
2852     #         value, then quadrangles will be split by the smallest diagonal.
2853     #  @return TRUE in case of success, FALSE otherwise.
2854     #  @ingroup l2_modif_cutquadr
2855     def QuadToTriObject (self, theObject, theCriterion = None):
2856         if ( isinstance( theObject, Mesh )):
2857             theObject = theObject.GetMesh()
2858         if theCriterion is None:
2859             theCriterion = FT_MaxElementLength2D
2860         Functor = self.smeshpyD.GetFunctor(theCriterion)
2861         return self.editor.QuadToTriObject(theObject, Functor)
2862
2863     ## Splits quadrangles into triangles.
2864     #  @param IDsOfElements the faces to be splitted
2865     #  @param Diag13        is used to choose a diagonal for splitting.
2866     #  @return TRUE in case of success, FALSE otherwise.
2867     #  @ingroup l2_modif_cutquadr
2868     def SplitQuad (self, IDsOfElements, Diag13):
2869         if IDsOfElements == []:
2870             IDsOfElements = self.GetElementsId()
2871         return self.editor.SplitQuad(IDsOfElements, Diag13)
2872
2873     ## Splits quadrangles into triangles.
2874     #  @param theObject the object from which the list of elements is taken,
2875     #         this is mesh, submesh or group
2876     #  @param Diag13    is used to choose a diagonal for splitting.
2877     #  @return TRUE in case of success, FALSE otherwise.
2878     #  @ingroup l2_modif_cutquadr
2879     def SplitQuadObject (self, theObject, Diag13):
2880         if ( isinstance( theObject, Mesh )):
2881             theObject = theObject.GetMesh()
2882         return self.editor.SplitQuadObject(theObject, Diag13)
2883
2884     ## Finds a better splitting of the given quadrangle.
2885     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
2886     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
2887     #         choose a diagonal for splitting.
2888     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
2889     #          diagonal is better, 0 if error occurs.
2890     #  @ingroup l2_modif_cutquadr
2891     def BestSplit (self, IDOfQuad, theCriterion):
2892         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
2893
2894     ## Splits volumic elements into tetrahedrons
2895     #  @param elemIDs either list of elements or mesh or group or submesh
2896     #  @param method  flags passing splitting method: Hex_5Tet, Hex_6Tet, Hex_24Tet
2897     #         Hex_5Tet - split the hexahedron into 5 tetrahedrons, etc
2898     #  @ingroup l2_modif_cutquadr
2899     def SplitVolumesIntoTetra(self, elemIDs, method=smeshBuilder.Hex_5Tet ):
2900         if isinstance( elemIDs, Mesh ):
2901             elemIDs = elemIDs.GetMesh()
2902         if ( isinstance( elemIDs, list )):
2903             elemIDs = self.editor.MakeIDSource(elemIDs, SMESH.VOLUME)
2904         self.editor.SplitVolumesIntoTetra(elemIDs, method)
2905
2906     ## Splits quadrangle faces near triangular facets of volumes
2907     #
2908     #  @ingroup l1_auxiliary
2909     def SplitQuadsNearTriangularFacets(self):
2910         faces_array = self.GetElementsByType(SMESH.FACE)
2911         for face_id in faces_array:
2912             if self.GetElemNbNodes(face_id) == 4: # quadrangle
2913                 quad_nodes = self.mesh.GetElemNodes(face_id)
2914                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
2915                 isVolumeFound = False
2916                 for node1_elem in node1_elems:
2917                     if not isVolumeFound:
2918                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
2919                             nb_nodes = self.GetElemNbNodes(node1_elem)
2920                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
2921                                 volume_elem = node1_elem
2922                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
2923                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
2924                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
2925                                         isVolumeFound = True
2926                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
2927                                             self.SplitQuad([face_id], False) # diagonal 2-4
2928                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
2929                                         isVolumeFound = True
2930                                         self.SplitQuad([face_id], True) # diagonal 1-3
2931                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
2932                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
2933                                         isVolumeFound = True
2934                                         self.SplitQuad([face_id], True) # diagonal 1-3
2935
2936     ## @brief Splits hexahedrons into tetrahedrons.
2937     #
2938     #  This operation uses pattern mapping functionality for splitting.
2939     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
2940     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
2941     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
2942     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
2943     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
2944     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
2945     #  @return TRUE in case of success, FALSE otherwise.
2946     #  @ingroup l1_auxiliary
2947     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
2948         # Pattern:     5.---------.6
2949         #              /|#*      /|
2950         #             / | #*    / |
2951         #            /  |  # * /  |
2952         #           /   |   # /*  |
2953         # (0,0,1) 4.---------.7 * |
2954         #          |#*  |1   | # *|
2955         #          | # *.----|---#.2
2956         #          |  #/ *   |   /
2957         #          |  /#  *  |  /
2958         #          | /   # * | /
2959         #          |/      #*|/
2960         # (0,0,0) 0.---------.3
2961         pattern_tetra = "!!! Nb of points: \n 8 \n\
2962         !!! Points: \n\
2963         0 0 0  !- 0 \n\
2964         0 1 0  !- 1 \n\
2965         1 1 0  !- 2 \n\
2966         1 0 0  !- 3 \n\
2967         0 0 1  !- 4 \n\
2968         0 1 1  !- 5 \n\
2969         1 1 1  !- 6 \n\
2970         1 0 1  !- 7 \n\
2971         !!! Indices of points of 6 tetras: \n\
2972         0 3 4 1 \n\
2973         7 4 3 1 \n\
2974         4 7 5 1 \n\
2975         6 2 5 7 \n\
2976         1 5 2 7 \n\
2977         2 3 1 7 \n"
2978
2979         pattern = self.smeshpyD.GetPattern()
2980         isDone  = pattern.LoadFromFile(pattern_tetra)
2981         if not isDone:
2982             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
2983             return isDone
2984
2985         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
2986         isDone = pattern.MakeMesh(self.mesh, False, False)
2987         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
2988
2989         # split quafrangle faces near triangular facets of volumes
2990         self.SplitQuadsNearTriangularFacets()
2991
2992         return isDone
2993
2994     ## @brief Split hexahedrons into prisms.
2995     #
2996     #  Uses the pattern mapping functionality for splitting.
2997     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
2998     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
2999     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3000     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3001     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3002     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3003     #  @return TRUE in case of success, FALSE otherwise.
3004     #  @ingroup l1_auxiliary
3005     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3006         # Pattern:     5.---------.6
3007         #              /|#       /|
3008         #             / | #     / |
3009         #            /  |  #   /  |
3010         #           /   |   # /   |
3011         # (0,0,1) 4.---------.7   |
3012         #          |    |    |    |
3013         #          |   1.----|----.2
3014         #          |   / *   |   /
3015         #          |  /   *  |  /
3016         #          | /     * | /
3017         #          |/       *|/
3018         # (0,0,0) 0.---------.3
3019         pattern_prism = "!!! Nb of points: \n 8 \n\
3020         !!! Points: \n\
3021         0 0 0  !- 0 \n\
3022         0 1 0  !- 1 \n\
3023         1 1 0  !- 2 \n\
3024         1 0 0  !- 3 \n\
3025         0 0 1  !- 4 \n\
3026         0 1 1  !- 5 \n\
3027         1 1 1  !- 6 \n\
3028         1 0 1  !- 7 \n\
3029         !!! Indices of points of 2 prisms: \n\
3030         0 1 3 4 5 7 \n\
3031         2 3 1 6 7 5 \n"
3032
3033         pattern = self.smeshpyD.GetPattern()
3034         isDone  = pattern.LoadFromFile(pattern_prism)
3035         if not isDone:
3036             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3037             return isDone
3038
3039         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3040         isDone = pattern.MakeMesh(self.mesh, False, False)
3041         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3042
3043         # Splits quafrangle faces near triangular facets of volumes
3044         self.SplitQuadsNearTriangularFacets()
3045
3046         return isDone
3047
3048     ## Smoothes elements
3049     #  @param IDsOfElements the list if ids of elements to smooth
3050     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3051     #  Note that nodes built on edges and boundary nodes are always fixed.
3052     #  @param MaxNbOfIterations the maximum number of iterations
3053     #  @param MaxAspectRatio varies in range [1.0, inf]
3054     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3055     #  @return TRUE in case of success, FALSE otherwise.
3056     #  @ingroup l2_modif_smooth
3057     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3058                MaxNbOfIterations, MaxAspectRatio, Method):
3059         if IDsOfElements == []:
3060             IDsOfElements = self.GetElementsId()
3061         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3062         self.mesh.SetParameters(Parameters)
3063         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3064                                   MaxNbOfIterations, MaxAspectRatio, Method)
3065
3066     ## Smoothes elements which belong to the given object
3067     #  @param theObject the object to smooth
3068     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3069     #  Note that nodes built on edges and boundary nodes are always fixed.
3070     #  @param MaxNbOfIterations the maximum number of iterations
3071     #  @param MaxAspectRatio varies in range [1.0, inf]
3072     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3073     #  @return TRUE in case of success, FALSE otherwise.
3074     #  @ingroup l2_modif_smooth
3075     def SmoothObject(self, theObject, IDsOfFixedNodes,
3076                      MaxNbOfIterations, MaxAspectRatio, Method):
3077         if ( isinstance( theObject, Mesh )):
3078             theObject = theObject.GetMesh()
3079         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3080                                         MaxNbOfIterations, MaxAspectRatio, Method)
3081
3082     ## Parametrically smoothes the given elements
3083     #  @param IDsOfElements the list if ids of elements to smooth
3084     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3085     #  Note that nodes built on edges and boundary nodes are always fixed.
3086     #  @param MaxNbOfIterations the maximum number of iterations
3087     #  @param MaxAspectRatio varies in range [1.0, inf]
3088     #  @param Method is Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3089     #  @return TRUE in case of success, FALSE otherwise.
3090     #  @ingroup l2_modif_smooth
3091     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3092                          MaxNbOfIterations, MaxAspectRatio, Method):
3093         if IDsOfElements == []:
3094             IDsOfElements = self.GetElementsId()
3095         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3096         self.mesh.SetParameters(Parameters)
3097         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3098                                             MaxNbOfIterations, MaxAspectRatio, Method)
3099
3100     ## Parametrically smoothes the elements which belong to the given object
3101     #  @param theObject the object to smooth
3102     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3103     #  Note that nodes built on edges and boundary nodes are always fixed.
3104     #  @param MaxNbOfIterations the maximum number of iterations
3105     #  @param MaxAspectRatio varies in range [1.0, inf]
3106     #  @param Method Laplacian(LAPLACIAN_SMOOTH) or Centroidal(CENTROIDAL_SMOOTH)
3107     #  @return TRUE in case of success, FALSE otherwise.
3108     #  @ingroup l2_modif_smooth
3109     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3110                                MaxNbOfIterations, MaxAspectRatio, Method):
3111         if ( isinstance( theObject, Mesh )):
3112             theObject = theObject.GetMesh()
3113         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3114                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3115
3116     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3117     #  them with quadratic with the same id.
3118     #  @param theForce3d new node creation method:
3119     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3120     #         1 - the medium node lies at the middle of the line segments connecting start and end node of a mesh element
3121     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3122     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3123     #  @ingroup l2_modif_tofromqu
3124     def ConvertToQuadratic(self, theForce3d, theSubMesh=None, theToBiQuad=False):
3125         if theToBiQuad:
3126             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3127         else:
3128             if theSubMesh:
3129                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3130             else:
3131                 self.editor.ConvertToQuadratic(theForce3d)
3132             
3133     ## Converts the mesh from quadratic to ordinary,
3134     #  deletes old quadratic elements, \n replacing
3135     #  them with ordinary mesh elements with the same id.
3136     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3137     #  @ingroup l2_modif_tofromqu
3138     def ConvertFromQuadratic(self, theSubMesh=None):
3139         if theSubMesh:
3140             self.editor.ConvertFromQuadraticObject(theSubMesh)
3141         else:
3142             return self.editor.ConvertFromQuadratic()
3143
3144     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3145     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3146     #  @ingroup l2_modif_edit
3147     def  Make2DMeshFrom3D(self):
3148         return self.editor. Make2DMeshFrom3D()
3149
3150     ## Creates missing boundary elements
3151     #  @param elements - elements whose boundary is to be checked:
3152     #                    mesh, group, sub-mesh or list of elements
3153     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3154     #  @param dimension - defines type of boundary elements to create:
3155     #                     SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D
3156     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3157     #  @param groupName - a name of group to store created boundary elements in,
3158     #                     "" means not to create the group
3159     #  @param meshName - a name of new mesh to store created boundary elements in,
3160     #                     "" means not to create the new mesh
3161     #  @param toCopyElements - if true, the checked elements will be copied into
3162     #     the new mesh else only boundary elements will be copied into the new mesh
3163     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3164     #     boundary elements will be copied into the new mesh
3165     #  @return tuple (mesh, group) where bondary elements were added to
3166     #  @ingroup l2_modif_edit
3167     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3168                          toCopyElements=False, toCopyExistingBondary=False):
3169         if isinstance( elements, Mesh ):
3170             elements = elements.GetMesh()
3171         if ( isinstance( elements, list )):
3172             elemType = SMESH.ALL
3173             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3174             elements = self.editor.MakeIDSource(elements, elemType)
3175         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3176                                                    toCopyElements,toCopyExistingBondary)
3177         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3178         return mesh, group
3179
3180     ##
3181     # @brief Creates missing boundary elements around either the whole mesh or 
3182     #    groups of 2D elements
3183     #  @param dimension - defines type of boundary elements to create
3184     #  @param groupName - a name of group to store all boundary elements in,
3185     #    "" means not to create the group
3186     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3187     #    mesh + created boundary elements; "" means not to create the new mesh
3188     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3189     #    the new mesh else only boundary elements will be copied into the new mesh
3190     #  @param groups - groups of 2D elements to make boundary around
3191     #  @retval tuple( long, mesh, groups )
3192     #                 long - number of added boundary elements
3193     #                 mesh - the mesh where elements were added to
3194     #                 group - the group of boundary elements or None
3195     #
3196     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3197                              toCopyAll=False, groups=[]):
3198         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3199                                                            toCopyAll,groups)
3200         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3201         return nb, mesh, group
3202
3203     ## Renumber mesh nodes
3204     #  @ingroup l2_modif_renumber
3205     def RenumberNodes(self):
3206         self.editor.RenumberNodes()
3207
3208     ## Renumber mesh elements
3209     #  @ingroup l2_modif_renumber
3210     def RenumberElements(self):
3211         self.editor.RenumberElements()
3212
3213     ## Generates new elements by rotation of the elements around the axis
3214     #  @param IDsOfElements the list of ids of elements to sweep
3215     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3216     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3217     #  @param NbOfSteps the number of steps
3218     #  @param Tolerance tolerance
3219     #  @param MakeGroups forces the generation of new groups from existing ones
3220     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3221     #                    of all steps, else - size of each step
3222     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3223     #  @ingroup l2_modif_extrurev
3224     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3225                       MakeGroups=False, TotalAngle=False):
3226         if IDsOfElements == []:
3227             IDsOfElements = self.GetElementsId()
3228         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3229             Axis = self.smeshpyD.GetAxisStruct(Axis)
3230         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3231         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3232         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3233         self.mesh.SetParameters(Parameters)
3234         if TotalAngle and NbOfSteps:
3235             AngleInRadians /= NbOfSteps
3236         if MakeGroups:
3237             return self.editor.RotationSweepMakeGroups(IDsOfElements, Axis,
3238                                                        AngleInRadians, NbOfSteps, Tolerance)
3239         self.editor.RotationSweep(IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance)
3240         return []
3241
3242     ## Generates new elements by rotation of the elements of object around the axis
3243     #  @param theObject object which elements should be sweeped.
3244     #                   It can be a mesh, a sub mesh or a group.
3245     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3246     #  @param AngleInRadians the angle of Rotation
3247     #  @param NbOfSteps number of steps
3248     #  @param Tolerance tolerance
3249     #  @param MakeGroups forces the generation of new groups from existing ones
3250     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3251     #                    of all steps, else - size of each step
3252     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3253     #  @ingroup l2_modif_extrurev
3254     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3255                             MakeGroups=False, TotalAngle=False):
3256         if ( isinstance( theObject, Mesh )):
3257             theObject = theObject.GetMesh()
3258         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3259             Axis = self.smeshpyD.GetAxisStruct(Axis)
3260         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3261         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3262         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3263         self.mesh.SetParameters(Parameters)
3264         if TotalAngle and NbOfSteps:
3265             AngleInRadians /= NbOfSteps
3266         if MakeGroups:
3267             return self.editor.RotationSweepObjectMakeGroups(theObject, Axis, AngleInRadians,
3268                                                              NbOfSteps, Tolerance)
3269         self.editor.RotationSweepObject(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3270         return []
3271
3272     ## Generates new elements by rotation of the elements of object around the axis
3273     #  @param theObject object which elements should be sweeped.
3274     #                   It can be a mesh, a sub mesh or a group.
3275     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3276     #  @param AngleInRadians the angle of Rotation
3277     #  @param NbOfSteps number of steps
3278     #  @param Tolerance tolerance
3279     #  @param MakeGroups forces the generation of new groups from existing ones
3280     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3281     #                    of all steps, else - size of each step
3282     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3283     #  @ingroup l2_modif_extrurev
3284     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3285                               MakeGroups=False, TotalAngle=False):
3286         if ( isinstance( theObject, Mesh )):
3287             theObject = theObject.GetMesh()
3288         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3289             Axis = self.smeshpyD.GetAxisStruct(Axis)
3290         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3291         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3292         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3293         self.mesh.SetParameters(Parameters)
3294         if TotalAngle and NbOfSteps:
3295             AngleInRadians /= NbOfSteps
3296         if MakeGroups:
3297             return self.editor.RotationSweepObject1DMakeGroups(theObject, Axis, AngleInRadians,
3298                                                                NbOfSteps, Tolerance)
3299         self.editor.RotationSweepObject1D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3300         return []
3301
3302     ## Generates new elements by rotation of the elements of object around the axis
3303     #  @param theObject object which elements should be sweeped.
3304     #                   It can be a mesh, a sub mesh or a group.
3305     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3306     #  @param AngleInRadians the angle of Rotation
3307     #  @param NbOfSteps number of steps
3308     #  @param Tolerance tolerance
3309     #  @param MakeGroups forces the generation of new groups from existing ones
3310     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3311     #                    of all steps, else - size of each step
3312     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3313     #  @ingroup l2_modif_extrurev
3314     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3315                               MakeGroups=False, TotalAngle=False):
3316         if ( isinstance( theObject, Mesh )):
3317             theObject = theObject.GetMesh()
3318         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3319             Axis = self.smeshpyD.GetAxisStruct(Axis)
3320         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3321         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3322         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3323         self.mesh.SetParameters(Parameters)
3324         if TotalAngle and NbOfSteps:
3325             AngleInRadians /= NbOfSteps
3326         if MakeGroups:
3327             return self.editor.RotationSweepObject2DMakeGroups(theObject, Axis, AngleInRadians,
3328                                                              NbOfSteps, Tolerance)
3329         self.editor.RotationSweepObject2D(theObject, Axis, AngleInRadians, NbOfSteps, Tolerance)
3330         return []
3331
3332     ## Generates new elements by extrusion of the elements with given ids
3333     #  @param IDsOfElements the list of elements ids for extrusion
3334     #  @param StepVector vector or DirStruct or 3 vector components, defining
3335     #         the direction and value of extrusion for one step (the total extrusion
3336     #         length will be NbOfSteps * ||StepVector||)
3337     #  @param NbOfSteps the number of steps
3338     #  @param MakeGroups forces the generation of new groups from existing ones
3339     #  @param IsNodes is True if elements with given ids are nodes
3340     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3341     #  @ingroup l2_modif_extrurev
3342     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3343         if IDsOfElements == []:
3344             IDsOfElements = self.GetElementsId()
3345         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3346             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3347         if isinstance( StepVector, list ):
3348             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3349         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3350         Parameters = StepVector.PS.parameters + var_separator + Parameters
3351         self.mesh.SetParameters(Parameters)
3352         if MakeGroups:
3353             if(IsNodes):
3354                 return self.editor.ExtrusionSweepMakeGroups0D(IDsOfElements, StepVector, NbOfSteps)
3355             else:
3356                 return self.editor.ExtrusionSweepMakeGroups(IDsOfElements, StepVector, NbOfSteps)
3357         if(IsNodes):
3358             self.editor.ExtrusionSweep0D(IDsOfElements, StepVector, NbOfSteps)
3359         else:
3360             self.editor.ExtrusionSweep(IDsOfElements, StepVector, NbOfSteps)
3361         return []
3362
3363     ## Generates new elements by extrusion of the elements with given ids
3364     #  @param IDsOfElements is ids of elements
3365     #  @param StepVector vector or DirStruct or 3 vector components, defining
3366     #         the direction and value of extrusion for one step (the total extrusion
3367     #         length will be NbOfSteps * ||StepVector||)
3368     #  @param NbOfSteps the number of steps
3369     #  @param ExtrFlags sets flags for extrusion
3370     #  @param SewTolerance uses for comparing locations of nodes if flag
3371     #         EXTRUSION_FLAG_SEW is set
3372     #  @param MakeGroups forces the generation of new groups from existing ones
3373     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3374     #  @ingroup l2_modif_extrurev
3375     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3376                           ExtrFlags, SewTolerance, MakeGroups=False):
3377         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3378             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3379         if isinstance( StepVector, list ):
3380             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3381         if MakeGroups:
3382             return self.editor.AdvancedExtrusionMakeGroups(IDsOfElements, StepVector, NbOfSteps,
3383                                                            ExtrFlags, SewTolerance)
3384         self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3385                                       ExtrFlags, SewTolerance)
3386         return []
3387
3388     ## Generates new elements by extrusion of the elements which belong to the object
3389     #  @param theObject the object which elements should be processed.
3390     #                   It can be a mesh, a sub mesh or a group.
3391     #  @param StepVector vector or DirStruct or 3 vector components, defining
3392     #         the direction and value of extrusion for one step (the total extrusion
3393     #         length will be NbOfSteps * ||StepVector||)
3394     #  @param NbOfSteps the number of steps
3395     #  @param MakeGroups forces the generation of new groups from existing ones
3396     #  @param  IsNodes is True if elements which belong to the object are nodes
3397     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3398     #  @ingroup l2_modif_extrurev
3399     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3400         if ( isinstance( theObject, Mesh )):
3401             theObject = theObject.GetMesh()
3402         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3403             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3404         if isinstance( StepVector, list ):
3405             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3406         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3407         Parameters = StepVector.PS.parameters + var_separator + Parameters
3408         self.mesh.SetParameters(Parameters)
3409         if MakeGroups:
3410             if(IsNodes):
3411                 return self.editor.ExtrusionSweepObject0DMakeGroups(theObject, StepVector, NbOfSteps)
3412             else:
3413                 return self.editor.ExtrusionSweepObjectMakeGroups(theObject, StepVector, NbOfSteps)
3414         if(IsNodes):
3415             self.editor.ExtrusionSweepObject0D(theObject, StepVector, NbOfSteps)
3416         else:
3417             self.editor.ExtrusionSweepObject(theObject, StepVector, NbOfSteps)
3418         return []
3419
3420     ## Generates new elements by extrusion of the elements which belong to the object
3421     #  @param theObject object which elements should be processed.
3422     #                   It can be a mesh, a sub mesh or a group.
3423     #  @param StepVector vector or DirStruct or 3 vector components, defining
3424     #         the direction and value of extrusion for one step (the total extrusion
3425     #         length will be NbOfSteps * ||StepVector||)
3426     #  @param NbOfSteps the number of steps
3427     #  @param MakeGroups to generate new groups from existing ones
3428     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3429     #  @ingroup l2_modif_extrurev
3430     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3431         if ( isinstance( theObject, Mesh )):
3432             theObject = theObject.GetMesh()
3433         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3434             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3435         if isinstance( StepVector, list ):
3436             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3437         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3438         Parameters = StepVector.PS.parameters + var_separator + Parameters
3439         self.mesh.SetParameters(Parameters)
3440         if MakeGroups:
3441             return self.editor.ExtrusionSweepObject1DMakeGroups(theObject, StepVector, NbOfSteps)
3442         self.editor.ExtrusionSweepObject1D(theObject, StepVector, NbOfSteps)
3443         return []
3444
3445     ## Generates new elements by extrusion of the elements which belong to the object
3446     #  @param theObject object which elements should be processed.
3447     #                   It can be a mesh, a sub mesh or a group.
3448     #  @param StepVector vector or DirStruct or 3 vector components, defining
3449     #         the direction and value of extrusion for one step (the total extrusion
3450     #         length will be NbOfSteps * ||StepVector||)
3451     #  @param NbOfSteps the number of steps
3452     #  @param MakeGroups forces the generation of new groups from existing ones
3453     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3454     #  @ingroup l2_modif_extrurev
3455     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3456         if ( isinstance( theObject, Mesh )):
3457             theObject = theObject.GetMesh()
3458         if ( isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object)):
3459             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3460         if isinstance( StepVector, list ):
3461             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3462         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3463         Parameters = StepVector.PS.parameters + var_separator + Parameters
3464         self.mesh.SetParameters(Parameters)
3465         if MakeGroups:
3466             return self.editor.ExtrusionSweepObject2DMakeGroups(theObject, StepVector, NbOfSteps)
3467         self.editor.ExtrusionSweepObject2D(theObject, StepVector, NbOfSteps)
3468         return []
3469
3470
3471
3472     ## Generates new elements by extrusion of the given elements
3473     #  The path of extrusion must be a meshed edge.
3474     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
3475     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3476     #  @param NodeStart the start node from Path. Defines the direction of extrusion
3477     #  @param HasAngles allows the shape to be rotated around the path
3478     #                   to get the resulting mesh in a helical fashion
3479     #  @param Angles list of angles in radians
3480     #  @param LinearVariation forces the computation of rotation angles as linear
3481     #                         variation of the given Angles along path steps
3482     #  @param HasRefPoint allows using the reference point
3483     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3484     #         The User can specify any point as the Reference Point.
3485     #  @param MakeGroups forces the generation of new groups from existing ones
3486     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
3487     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3488     #          only SMESH::Extrusion_Error otherwise
3489     #  @ingroup l2_modif_extrurev
3490     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
3491                             HasAngles, Angles, LinearVariation,
3492                             HasRefPoint, RefPoint, MakeGroups, ElemType):
3493         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3494             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3495             pass
3496         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3497         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3498         self.mesh.SetParameters(Parameters)
3499
3500         if (isinstance(Path, Mesh)): Path = Path.GetMesh()
3501
3502         if isinstance(Base, list):
3503             IDsOfElements = []
3504             if Base == []: IDsOfElements = self.GetElementsId()
3505             else: IDsOfElements = Base
3506             return self.editor.ExtrusionAlongPathX(IDsOfElements, Path, NodeStart,
3507                                                    HasAngles, Angles, LinearVariation,
3508                                                    HasRefPoint, RefPoint, MakeGroups, ElemType)
3509         else:
3510             if isinstance(Base, Mesh): Base = Base.GetMesh()
3511             if isinstance(Base, SMESH._objref_SMESH_Mesh) or isinstance(Base, SMESH._objref_SMESH_Group) or isinstance(Base, SMESH._objref_SMESH_subMesh):
3512                 return self.editor.ExtrusionAlongPathObjX(Base, Path, NodeStart,
3513                                                           HasAngles, Angles, LinearVariation,
3514                                                           HasRefPoint, RefPoint, MakeGroups, ElemType)
3515             else:
3516                 raise RuntimeError, "Invalid Base for ExtrusionAlongPathX"
3517
3518
3519     ## Generates new elements by extrusion of the given elements
3520     #  The path of extrusion must be a meshed edge.
3521     #  @param IDsOfElements ids of elements
3522     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
3523     #  @param PathShape shape(edge) defines the sub-mesh for the path
3524     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3525     #  @param HasAngles allows the shape to be rotated around the path
3526     #                   to get the resulting mesh in a helical fashion
3527     #  @param Angles list of angles in radians
3528     #  @param HasRefPoint allows using the reference point
3529     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3530     #         The User can specify any point as the Reference Point.
3531     #  @param MakeGroups forces the generation of new groups from existing ones
3532     #  @param LinearVariation forces the computation of rotation angles as linear
3533     #                         variation of the given Angles along path steps
3534     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3535     #          only SMESH::Extrusion_Error otherwise
3536     #  @ingroup l2_modif_extrurev
3537     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
3538                            HasAngles, Angles, HasRefPoint, RefPoint,
3539                            MakeGroups=False, LinearVariation=False):
3540         if IDsOfElements == []:
3541             IDsOfElements = self.GetElementsId()
3542         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3543             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3544             pass
3545         if ( isinstance( PathMesh, Mesh )):
3546             PathMesh = PathMesh.GetMesh()
3547         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3548         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3549         self.mesh.SetParameters(Parameters)
3550         if HasAngles and Angles and LinearVariation:
3551             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3552             pass
3553         if MakeGroups:
3554             return self.editor.ExtrusionAlongPathMakeGroups(IDsOfElements, PathMesh,
3555                                                             PathShape, NodeStart, HasAngles,
3556                                                             Angles, HasRefPoint, RefPoint)
3557         return self.editor.ExtrusionAlongPath(IDsOfElements, PathMesh, PathShape,
3558                                               NodeStart, HasAngles, Angles, HasRefPoint, RefPoint)
3559
3560     ## Generates new elements by extrusion of the elements which belong to the object
3561     #  The path of extrusion must be a meshed edge.
3562     #  @param theObject the object which elements should be processed.
3563     #                   It can be a mesh, a sub mesh or a group.
3564     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3565     #  @param PathShape shape(edge) defines the sub-mesh for the path
3566     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3567     #  @param HasAngles allows the shape to be rotated around the path
3568     #                   to get the resulting mesh in a helical fashion
3569     #  @param Angles list of angles
3570     #  @param HasRefPoint allows using the reference point
3571     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3572     #         The User can specify any point as the Reference Point.
3573     #  @param MakeGroups forces the generation of new groups from existing ones
3574     #  @param LinearVariation forces the computation of rotation angles as linear
3575     #                         variation of the given Angles along path steps
3576     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3577     #          only SMESH::Extrusion_Error otherwise
3578     #  @ingroup l2_modif_extrurev
3579     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
3580                                  HasAngles, Angles, HasRefPoint, RefPoint,
3581                                  MakeGroups=False, LinearVariation=False):
3582         if ( isinstance( theObject, Mesh )):
3583             theObject = theObject.GetMesh()
3584         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3585             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3586         if ( isinstance( PathMesh, Mesh )):
3587             PathMesh = PathMesh.GetMesh()
3588         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3589         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3590         self.mesh.SetParameters(Parameters)
3591         if HasAngles and Angles and LinearVariation:
3592             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3593             pass
3594         if MakeGroups:
3595             return self.editor.ExtrusionAlongPathObjectMakeGroups(theObject, PathMesh,
3596                                                                   PathShape, NodeStart, HasAngles,
3597                                                                   Angles, HasRefPoint, RefPoint)
3598         return self.editor.ExtrusionAlongPathObject(theObject, PathMesh, PathShape,
3599                                                     NodeStart, HasAngles, Angles, HasRefPoint,
3600                                                     RefPoint)
3601
3602     ## Generates new elements by extrusion of the elements which belong to the object
3603     #  The path of extrusion must be a meshed edge.
3604     #  @param theObject the object which elements should be processed.
3605     #                   It can be a mesh, a sub mesh or a group.
3606     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3607     #  @param PathShape shape(edge) defines the sub-mesh for the path
3608     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3609     #  @param HasAngles allows the shape to be rotated around the path
3610     #                   to get the resulting mesh in a helical fashion
3611     #  @param Angles list of angles
3612     #  @param HasRefPoint allows using the reference point
3613     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3614     #         The User can specify any point as the Reference Point.
3615     #  @param MakeGroups forces the generation of new groups from existing ones
3616     #  @param LinearVariation forces the computation of rotation angles as linear
3617     #                         variation of the given Angles along path steps
3618     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3619     #          only SMESH::Extrusion_Error otherwise
3620     #  @ingroup l2_modif_extrurev
3621     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
3622                                    HasAngles, Angles, HasRefPoint, RefPoint,
3623                                    MakeGroups=False, LinearVariation=False):
3624         if ( isinstance( theObject, Mesh )):
3625             theObject = theObject.GetMesh()
3626         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3627             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3628         if ( isinstance( PathMesh, Mesh )):
3629             PathMesh = PathMesh.GetMesh()
3630         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3631         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3632         self.mesh.SetParameters(Parameters)
3633         if HasAngles and Angles and LinearVariation:
3634             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3635             pass
3636         if MakeGroups:
3637             return self.editor.ExtrusionAlongPathObject1DMakeGroups(theObject, PathMesh,
3638                                                                     PathShape, NodeStart, HasAngles,
3639                                                                     Angles, HasRefPoint, RefPoint)
3640         return self.editor.ExtrusionAlongPathObject1D(theObject, PathMesh, PathShape,
3641                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3642                                                       RefPoint)
3643
3644     ## Generates new elements by extrusion of the elements which belong to the object
3645     #  The path of extrusion must be a meshed edge.
3646     #  @param theObject the object which elements should be processed.
3647     #                   It can be a mesh, a sub mesh or a group.
3648     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
3649     #  @param PathShape shape(edge) defines the sub-mesh for the path
3650     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
3651     #  @param HasAngles allows the shape to be rotated around the path
3652     #                   to get the resulting mesh in a helical fashion
3653     #  @param Angles list of angles
3654     #  @param HasRefPoint allows using the reference point
3655     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
3656     #         The User can specify any point as the Reference Point.
3657     #  @param MakeGroups forces the generation of new groups from existing ones
3658     #  @param LinearVariation forces the computation of rotation angles as linear
3659     #                         variation of the given Angles along path steps
3660     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
3661     #          only SMESH::Extrusion_Error otherwise
3662     #  @ingroup l2_modif_extrurev
3663     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
3664                                    HasAngles, Angles, HasRefPoint, RefPoint,
3665                                    MakeGroups=False, LinearVariation=False):
3666         if ( isinstance( theObject, Mesh )):
3667             theObject = theObject.GetMesh()
3668         if ( isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object)):
3669             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3670         if ( isinstance( PathMesh, Mesh )):
3671             PathMesh = PathMesh.GetMesh()
3672         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3673         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3674         self.mesh.SetParameters(Parameters)
3675         if HasAngles and Angles and LinearVariation:
3676             Angles = self.editor.LinearAnglesVariation( PathMesh, PathShape, Angles )
3677             pass
3678         if MakeGroups:
3679             return self.editor.ExtrusionAlongPathObject2DMakeGroups(theObject, PathMesh,
3680                                                                     PathShape, NodeStart, HasAngles,
3681                                                                     Angles, HasRefPoint, RefPoint)
3682         return self.editor.ExtrusionAlongPathObject2D(theObject, PathMesh, PathShape,
3683                                                       NodeStart, HasAngles, Angles, HasRefPoint,
3684                                                       RefPoint)
3685
3686     ## Creates a symmetrical copy of mesh elements
3687     #  @param IDsOfElements list of elements ids
3688     #  @param Mirror is AxisStruct or geom object(point, line, plane)
3689     #  @param theMirrorType is  POINT, AXIS or PLANE
3690     #  If the Mirror is a geom object this parameter is unnecessary
3691     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
3692     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3693     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3694     #  @ingroup l2_modif_trsf
3695     def Mirror(self, IDsOfElements, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3696         if IDsOfElements == []:
3697             IDsOfElements = self.GetElementsId()
3698         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3699             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3700         self.mesh.SetParameters(Mirror.parameters)
3701         if Copy and MakeGroups:
3702             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
3703         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
3704         return []
3705
3706     ## Creates a new mesh by a symmetrical copy of mesh elements
3707     #  @param IDsOfElements the list of elements ids
3708     #  @param Mirror is AxisStruct or geom object (point, line, plane)
3709     #  @param theMirrorType is  POINT, AXIS or PLANE
3710     #  If the Mirror is a geom object this parameter is unnecessary
3711     #  @param MakeGroups to generate new groups from existing ones
3712     #  @param NewMeshName a name of the new mesh to create
3713     #  @return instance of Mesh class
3714     #  @ingroup l2_modif_trsf
3715     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType, MakeGroups=0, NewMeshName=""):
3716         if IDsOfElements == []:
3717             IDsOfElements = self.GetElementsId()
3718         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3719             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3720         self.mesh.SetParameters(Mirror.parameters)
3721         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
3722                                           MakeGroups, NewMeshName)
3723         return Mesh(self.smeshpyD,self.geompyD,mesh)
3724
3725     ## Creates a symmetrical copy of the object
3726     #  @param theObject mesh, submesh or group
3727     #  @param Mirror AxisStruct or geom object (point, line, plane)
3728     #  @param theMirrorType is  POINT, AXIS or PLANE
3729     #  If the Mirror is a geom object this parameter is unnecessary
3730     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
3731     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3732     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3733     #  @ingroup l2_modif_trsf
3734     def MirrorObject (self, theObject, Mirror, theMirrorType, Copy=0, MakeGroups=False):
3735         if ( isinstance( theObject, Mesh )):
3736             theObject = theObject.GetMesh()
3737         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3738             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3739         self.mesh.SetParameters(Mirror.parameters)
3740         if Copy and MakeGroups:
3741             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
3742         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
3743         return []
3744
3745     ## Creates a new mesh by a symmetrical copy of the object
3746     #  @param theObject mesh, submesh or group
3747     #  @param Mirror AxisStruct or geom object (point, line, plane)
3748     #  @param theMirrorType POINT, AXIS or PLANE
3749     #  If the Mirror is a geom object this parameter is unnecessary
3750     #  @param MakeGroups forces the generation of new groups from existing ones
3751     #  @param NewMeshName the name of the new mesh to create
3752     #  @return instance of Mesh class
3753     #  @ingroup l2_modif_trsf
3754     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType,MakeGroups=0, NewMeshName=""):
3755         if ( isinstance( theObject, Mesh )):
3756             theObject = theObject.GetMesh()
3757         if (isinstance(Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
3758             Mirror = self.smeshpyD.GetAxisStruct(Mirror)
3759         self.mesh.SetParameters(Mirror.parameters)
3760         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
3761                                                 MakeGroups, NewMeshName)
3762         return Mesh( self.smeshpyD,self.geompyD,mesh )
3763
3764     ## Translates the elements
3765     #  @param IDsOfElements list of elements ids
3766     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3767     #  @param Copy allows copying the translated elements
3768     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3769     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3770     #  @ingroup l2_modif_trsf
3771     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
3772         if IDsOfElements == []:
3773             IDsOfElements = self.GetElementsId()
3774         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3775             Vector = self.smeshpyD.GetDirStruct(Vector)
3776         if isinstance( Vector, list ):
3777             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3778         self.mesh.SetParameters(Vector.PS.parameters)
3779         if Copy and MakeGroups:
3780             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
3781         self.editor.Translate(IDsOfElements, Vector, Copy)
3782         return []
3783
3784     ## Creates a new mesh of translated elements
3785     #  @param IDsOfElements list of elements ids
3786     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
3787     #  @param MakeGroups forces the generation of new groups from existing ones
3788     #  @param NewMeshName the name of the newly created mesh
3789     #  @return instance of Mesh class
3790     #  @ingroup l2_modif_trsf
3791     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
3792         if IDsOfElements == []:
3793             IDsOfElements = self.GetElementsId()
3794         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3795             Vector = self.smeshpyD.GetDirStruct(Vector)
3796         if isinstance( Vector, list ):
3797             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3798         self.mesh.SetParameters(Vector.PS.parameters)
3799         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
3800         return Mesh ( self.smeshpyD, self.geompyD, mesh )
3801
3802     ## Translates the object
3803     #  @param theObject the object to translate (mesh, submesh, or group)
3804     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
3805     #  @param Copy allows copying the translated elements
3806     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3807     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3808     #  @ingroup l2_modif_trsf
3809     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
3810         if ( isinstance( theObject, Mesh )):
3811             theObject = theObject.GetMesh()
3812         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
3813             Vector = self.smeshpyD.GetDirStruct(Vector)
3814         if isinstance( Vector, list ):
3815             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3816         self.mesh.SetParameters(Vector.PS.parameters)
3817         if Copy and MakeGroups:
3818             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
3819         self.editor.TranslateObject(theObject, Vector, Copy)
3820         return []
3821
3822     ## Creates a new mesh from the translated object
3823     #  @param theObject the object to translate (mesh, submesh, or group)
3824     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
3825     #  @param MakeGroups forces the generation of new groups from existing ones
3826     #  @param NewMeshName the name of the newly created mesh
3827     #  @return instance of Mesh class
3828     #  @ingroup l2_modif_trsf
3829     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
3830         if isinstance( theObject, Mesh ):
3831             theObject = theObject.GetMesh()
3832         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
3833             Vector = self.smeshpyD.GetDirStruct(Vector)
3834         if isinstance( Vector, list ):
3835             Vector = self.smeshpyD.MakeDirStruct(*Vector)
3836         self.mesh.SetParameters(Vector.PS.parameters)
3837         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
3838         return Mesh( self.smeshpyD, self.geompyD, mesh )
3839
3840
3841
3842     ## Scales the object
3843     #  @param theObject - the object to translate (mesh, submesh, or group)
3844     #  @param thePoint - base point for scale
3845     #  @param theScaleFact - list of 1-3 scale factors for axises
3846     #  @param Copy - allows copying the translated elements
3847     #  @param MakeGroups - forces the generation of new groups from existing
3848     #                      ones (if Copy)
3849     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
3850     #          empty list otherwise
3851     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
3852         if ( isinstance( theObject, Mesh )):
3853             theObject = theObject.GetMesh()
3854         if ( isinstance( theObject, list )):
3855             theObject = self.GetIDSource(theObject, SMESH.ALL)
3856         if ( isinstance( theScaleFact, float )):
3857              theScaleFact = [theScaleFact]
3858         if ( isinstance( theScaleFact, int )):
3859              theScaleFact = [ float(theScaleFact)]
3860
3861         self.mesh.SetParameters(thePoint.parameters)
3862
3863         if Copy and MakeGroups:
3864             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
3865         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
3866         return []
3867
3868     ## Creates a new mesh from the translated object
3869     #  @param theObject - the object to translate (mesh, submesh, or group)
3870     #  @param thePoint - base point for scale
3871     #  @param theScaleFact - list of 1-3 scale factors for axises
3872     #  @param MakeGroups - forces the generation of new groups from existing ones
3873     #  @param NewMeshName - the name of the newly created mesh
3874     #  @return instance of Mesh class
3875     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
3876         if (isinstance(theObject, Mesh)):
3877             theObject = theObject.GetMesh()
3878         if ( isinstance( theObject, list )):
3879             theObject = self.GetIDSource(theObject,SMESH.ALL)
3880         if ( isinstance( theScaleFact, float )):
3881              theScaleFact = [theScaleFact]
3882         if ( isinstance( theScaleFact, int )):
3883              theScaleFact = [ float(theScaleFact)]
3884
3885         self.mesh.SetParameters(thePoint.parameters)
3886         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
3887                                          MakeGroups, NewMeshName)
3888         return Mesh( self.smeshpyD, self.geompyD, mesh )
3889
3890
3891
3892     ## Rotates the elements
3893     #  @param IDsOfElements list of elements ids
3894     #  @param Axis the axis of rotation (AxisStruct or geom line)
3895     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3896     #  @param Copy allows copying the rotated elements
3897     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3898     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3899     #  @ingroup l2_modif_trsf
3900     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
3901         if IDsOfElements == []:
3902             IDsOfElements = self.GetElementsId()
3903         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3904             Axis = self.smeshpyD.GetAxisStruct(Axis)
3905         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3906         Parameters = Axis.parameters + var_separator + Parameters
3907         self.mesh.SetParameters(Parameters)
3908         if Copy and MakeGroups:
3909             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
3910         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
3911         return []
3912
3913     ## Creates a new mesh of rotated elements
3914     #  @param IDsOfElements list of element ids
3915     #  @param Axis the axis of rotation (AxisStruct or geom line)
3916     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3917     #  @param MakeGroups forces the generation of new groups from existing ones
3918     #  @param NewMeshName the name of the newly created mesh
3919     #  @return instance of Mesh class
3920     #  @ingroup l2_modif_trsf
3921     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
3922         if IDsOfElements == []:
3923             IDsOfElements = self.GetElementsId()
3924         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3925             Axis = self.smeshpyD.GetAxisStruct(Axis)
3926         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3927         Parameters = Axis.parameters + var_separator + Parameters
3928         self.mesh.SetParameters(Parameters)
3929         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
3930                                           MakeGroups, NewMeshName)
3931         return Mesh( self.smeshpyD, self.geompyD, mesh )
3932
3933     ## Rotates the object
3934     #  @param theObject the object to rotate( mesh, submesh, or group)
3935     #  @param Axis the axis of rotation (AxisStruct or geom line)
3936     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
3937     #  @param Copy allows copying the rotated elements
3938     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
3939     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3940     #  @ingroup l2_modif_trsf
3941     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
3942         if (isinstance(theObject, Mesh)):
3943             theObject = theObject.GetMesh()
3944         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3945             Axis = self.smeshpyD.GetAxisStruct(Axis)
3946         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3947         Parameters = Axis.parameters + ":" + Parameters
3948         self.mesh.SetParameters(Parameters)
3949         if Copy and MakeGroups:
3950             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
3951         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
3952         return []
3953
3954     ## Creates a new mesh from the rotated object
3955     #  @param theObject the object to rotate (mesh, submesh, or group)
3956     #  @param Axis the axis of rotation (AxisStruct or geom line)
3957     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
3958     #  @param MakeGroups forces the generation of new groups from existing ones
3959     #  @param NewMeshName the name of the newly created mesh
3960     #  @return instance of Mesh class
3961     #  @ingroup l2_modif_trsf
3962     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
3963         if (isinstance( theObject, Mesh )):
3964             theObject = theObject.GetMesh()
3965         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
3966             Axis = self.smeshpyD.GetAxisStruct(Axis)
3967         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
3968         Parameters = Axis.parameters + ":" + Parameters
3969         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
3970                                                        MakeGroups, NewMeshName)
3971         self.mesh.SetParameters(Parameters)
3972         return Mesh( self.smeshpyD, self.geompyD, mesh )
3973
3974     ## Finds groups of ajacent nodes within Tolerance.
3975     #  @param Tolerance the value of tolerance
3976     #  @return the list of groups of nodes
3977     #  @ingroup l2_modif_trsf
3978     def FindCoincidentNodes (self, Tolerance):
3979         return self.editor.FindCoincidentNodes(Tolerance)
3980
3981     ## Finds groups of ajacent nodes within Tolerance.
3982     #  @param Tolerance the value of tolerance
3983     #  @param SubMeshOrGroup SubMesh or Group
3984     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
3985     #  @return the list of groups of nodes
3986     #  @ingroup l2_modif_trsf
3987     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance, exceptNodes=[]):
3988         if (isinstance( SubMeshOrGroup, Mesh )):
3989             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
3990         if not isinstance( exceptNodes, list):
3991             exceptNodes = [ exceptNodes ]
3992         if exceptNodes and isinstance( exceptNodes[0], int):
3993             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE)]
3994         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,exceptNodes)
3995
3996     ## Merges nodes
3997     #  @param GroupsOfNodes the list of groups of nodes
3998     #  @ingroup l2_modif_trsf
3999     def MergeNodes (self, GroupsOfNodes):
4000         self.editor.MergeNodes(GroupsOfNodes)
4001
4002     ## Finds the elements built on the same nodes.
4003     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4004     #  @return a list of groups of equal elements
4005     #  @ingroup l2_modif_trsf
4006     def FindEqualElements (self, MeshOrSubMeshOrGroup):
4007         if ( isinstance( MeshOrSubMeshOrGroup, Mesh )):
4008             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4009         return self.editor.FindEqualElements(MeshOrSubMeshOrGroup)
4010
4011     ## Merges elements in each given group.
4012     #  @param GroupsOfElementsID groups of elements for merging
4013     #  @ingroup l2_modif_trsf
4014     def MergeElements(self, GroupsOfElementsID):
4015         self.editor.MergeElements(GroupsOfElementsID)
4016
4017     ## Leaves one element and removes all other elements built on the same nodes.
4018     #  @ingroup l2_modif_trsf
4019     def MergeEqualElements(self):
4020         self.editor.MergeEqualElements()
4021
4022     ## Sews free borders
4023     #  @return SMESH::Sew_Error
4024     #  @ingroup l2_modif_trsf
4025     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4026                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4027                         CreatePolygons, CreatePolyedrs):
4028         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4029                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4030                                           CreatePolygons, CreatePolyedrs)
4031
4032     ## Sews conform free borders
4033     #  @return SMESH::Sew_Error
4034     #  @ingroup l2_modif_trsf
4035     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4036                                FirstNodeID2, SecondNodeID2):
4037         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4038                                                  FirstNodeID2, SecondNodeID2)
4039
4040     ## Sews border to side
4041     #  @return SMESH::Sew_Error
4042     #  @ingroup l2_modif_trsf
4043     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4044                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4045         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4046                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4047
4048     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4049     #  merged with the nodes of elements of Side2.
4050     #  The number of elements in theSide1 and in theSide2 must be
4051     #  equal and they should have similar nodal connectivity.
4052     #  The nodes to merge should belong to side borders and
4053     #  the first node should be linked to the second.
4054     #  @return SMESH::Sew_Error
4055     #  @ingroup l2_modif_trsf
4056     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4057                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4058                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4059         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4060                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4061                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4062
4063     ## Sets new nodes for the given element.
4064     #  @param ide the element id
4065     #  @param newIDs nodes ids
4066     #  @return If the number of nodes does not correspond to the type of element - returns false
4067     #  @ingroup l2_modif_edit
4068     def ChangeElemNodes(self, ide, newIDs):
4069         return self.editor.ChangeElemNodes(ide, newIDs)
4070
4071     ## If during the last operation of MeshEditor some nodes were
4072     #  created, this method returns the list of their IDs, \n
4073     #  if new nodes were not created - returns empty list
4074     #  @return the list of integer values (can be empty)
4075     #  @ingroup l1_auxiliary
4076     def GetLastCreatedNodes(self):
4077         return self.editor.GetLastCreatedNodes()
4078
4079     ## If during the last operation of MeshEditor some elements were
4080     #  created this method returns the list of their IDs, \n
4081     #  if new elements were not created - returns empty list
4082     #  @return the list of integer values (can be empty)
4083     #  @ingroup l1_auxiliary
4084     def GetLastCreatedElems(self):
4085         return self.editor.GetLastCreatedElems()
4086
4087      ## Creates a hole in a mesh by doubling the nodes of some particular elements
4088     #  @param theNodes identifiers of nodes to be doubled
4089     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4090     #         nodes. If list of element identifiers is empty then nodes are doubled but
4091     #         they not assigned to elements
4092     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4093     #  @ingroup l2_modif_edit
4094     def DoubleNodes(self, theNodes, theModifiedElems):
4095         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4096
4097     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4098     #  This method provided for convenience works as DoubleNodes() described above.
4099     #  @param theNodeId identifiers of node to be doubled
4100     #  @param theModifiedElems identifiers of elements to be updated
4101     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4102     #  @ingroup l2_modif_edit
4103     def DoubleNode(self, theNodeId, theModifiedElems):
4104         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4105
4106     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4107     #  This method provided for convenience works as DoubleNodes() described above.
4108     #  @param theNodes group of nodes to be doubled
4109     #  @param theModifiedElems group of elements to be updated.
4110     #  @param theMakeGroup forces the generation of a group containing new nodes.
4111     #  @return TRUE or a created group if operation has been completed successfully,
4112     #          FALSE or None otherwise
4113     #  @ingroup l2_modif_edit
4114     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4115         if theMakeGroup:
4116             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4117         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4118
4119     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4120     #  This method provided for convenience works as DoubleNodes() described above.
4121     #  @param theNodes list of groups of nodes to be doubled
4122     #  @param theModifiedElems list of groups of elements to be updated.
4123     #  @param theMakeGroup forces the generation of a group containing new nodes.
4124     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4125     #  @ingroup l2_modif_edit
4126     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4127         if theMakeGroup:
4128             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4129         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4130
4131     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4132     #  @param theElems - the list of elements (edges or faces) to be replicated
4133     #         The nodes for duplication could be found from these elements
4134     #  @param theNodesNot - list of nodes to NOT replicate
4135     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4136     #         replicated nodes should be associated to.
4137     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4138     #  @ingroup l2_modif_edit
4139     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4140         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4141
4142     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4143     #  @param theElems - the list of elements (edges or faces) to be replicated
4144     #         The nodes for duplication could be found from these elements
4145     #  @param theNodesNot - list of nodes to NOT replicate
4146     #  @param theShape - shape to detect affected elements (element which geometric center
4147     #         located on or inside shape).
4148     #         The replicated nodes should be associated to affected elements.
4149     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4150     #  @ingroup l2_modif_edit
4151     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4152         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4153
4154     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4155     #  This method provided for convenience works as DoubleNodes() described above.
4156     #  @param theElems - group of of elements (edges or faces) to be replicated
4157     #  @param theNodesNot - group of nodes not to replicated
4158     #  @param theAffectedElems - group of elements to which the replicated nodes
4159     #         should be associated to.
4160     #  @param theMakeGroup forces the generation of a group containing new elements.
4161     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4162     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4163     #          FALSE or None otherwise
4164     #  @ingroup l2_modif_edit
4165     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4166                              theMakeGroup=False, theMakeNodeGroup=False):
4167         if theMakeGroup or theMakeNodeGroup:
4168             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4169                                                             theAffectedElems,
4170                                                             theMakeGroup, theMakeNodeGroup)
4171             if theMakeGroup and theMakeNodeGroup:
4172                 return twoGroups
4173             else:
4174                 return twoGroups[ int(theMakeNodeGroup) ]
4175         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4176
4177     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4178     #  This method provided for convenience works as DoubleNodes() described above.
4179     #  @param theElems - group of of elements (edges or faces) to be replicated
4180     #  @param theNodesNot - group of nodes not to replicated
4181     #  @param theShape - shape to detect affected elements (element which geometric center
4182     #         located on or inside shape).
4183     #         The replicated nodes should be associated to affected elements.
4184     #  @ingroup l2_modif_edit
4185     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4186         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4187
4188     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4189     #  This method provided for convenience works as DoubleNodes() described above.
4190     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4191     #  @param theNodesNot - list of groups of nodes not to replicated
4192     #  @param theAffectedElems - group of elements to which the replicated nodes
4193     #         should be associated to.
4194     #  @param theMakeGroup forces the generation of a group containing new elements.
4195     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4196     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4197     #          FALSE or None otherwise
4198     #  @ingroup l2_modif_edit
4199     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4200                              theMakeGroup=False, theMakeNodeGroup=False):
4201         if theMakeGroup or theMakeNodeGroup:
4202             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4203                                                              theAffectedElems,
4204                                                              theMakeGroup, theMakeNodeGroup)
4205             if theMakeGroup and theMakeNodeGroup:
4206                 return twoGroups
4207             else:
4208                 return twoGroups[ int(theMakeNodeGroup) ]
4209         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4210
4211     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4212     #  This method provided for convenience works as DoubleNodes() described above.
4213     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4214     #  @param theNodesNot - list of groups of nodes not to replicated
4215     #  @param theShape - shape to detect affected elements (element which geometric center
4216     #         located on or inside shape).
4217     #         The replicated nodes should be associated to affected elements.
4218     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4219     #  @ingroup l2_modif_edit
4220     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4221         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4222
4223     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4224     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4225     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4226     #  @param theNodesNot - list of groups of nodes not to replicated
4227     #  @param theShape - shape to detect affected elements (element which geometric center
4228     #         located on or inside shape).
4229     #         The replicated nodes should be associated to affected elements.
4230     #  @return groups of affected elements
4231     #  @ingroup l2_modif_edit
4232     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4233         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4234
4235     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4236     # The list of groups must describe a partition of the mesh volumes.
4237     # The nodes of the internal faces at the boundaries of the groups are doubled.
4238     # In option, the internal faces are replaced by flat elements.
4239     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4240     # @param theDomains - list of groups of volumes
4241     # @param createJointElems - if TRUE, create the elements
4242     # @return TRUE if operation has been completed successfully, FALSE otherwise
4243     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems ):
4244        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems )
4245
4246     ## Double nodes on some external faces and create flat elements.
4247     # Flat elements are mainly used by some types of mechanic calculations.
4248     #
4249     # Each group of the list must be constituted of faces.
4250     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4251     # @param theGroupsOfFaces - list of groups of faces
4252     # @return TRUE if operation has been completed successfully, FALSE otherwise
4253     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4254         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4255     
4256     ## identify all the elements around a geom shape, get the faces delimiting the hole
4257     #
4258     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4259         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4260
4261     def _getFunctor(self, funcType ):
4262         fn = self.functors[ funcType._v ]
4263         if not fn:
4264             fn = self.smeshpyD.GetFunctor(funcType)
4265             fn.SetMesh(self.mesh)
4266             self.functors[ funcType._v ] = fn
4267         return fn
4268
4269     def _valueFromFunctor(self, funcType, elemId):
4270         fn = self._getFunctor( funcType )
4271         if fn.GetElementType() == self.GetElementType(elemId, True):
4272             val = fn.GetValue(elemId)
4273         else:
4274             val = 0
4275         return val
4276
4277     ## Get length of 1D element.
4278     #  @param elemId mesh element ID
4279     #  @return element's length value
4280     #  @ingroup l1_measurements
4281     def GetLength(self, elemId):
4282         return self._valueFromFunctor(SMESH.FT_Length, elemId)
4283
4284     ## Get area of 2D element.
4285     #  @param elemId mesh element ID
4286     #  @return element's area value
4287     #  @ingroup l1_measurements
4288     def GetArea(self, elemId):
4289         return self._valueFromFunctor(SMESH.FT_Area, elemId)
4290
4291     ## Get volume of 3D element.
4292     #  @param elemId mesh element ID
4293     #  @return element's volume value
4294     #  @ingroup l1_measurements
4295     def GetVolume(self, elemId):
4296         return self._valueFromFunctor(SMESH.FT_Volume3D, elemId)
4297
4298     ## Get maximum element length.
4299     #  @param elemId mesh element ID
4300     #  @return element's maximum length value
4301     #  @ingroup l1_measurements
4302     def GetMaxElementLength(self, elemId):
4303         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4304             ftype = SMESH.FT_MaxElementLength3D
4305         else:
4306             ftype = SMESH.FT_MaxElementLength2D
4307         return self._valueFromFunctor(ftype, elemId)
4308
4309     ## Get aspect ratio of 2D or 3D element.
4310     #  @param elemId mesh element ID
4311     #  @return element's aspect ratio value
4312     #  @ingroup l1_measurements
4313     def GetAspectRatio(self, elemId):
4314         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4315             ftype = SMESH.FT_AspectRatio3D
4316         else:
4317             ftype = SMESH.FT_AspectRatio
4318         return self._valueFromFunctor(ftype, elemId)
4319
4320     ## Get warping angle of 2D element.
4321     #  @param elemId mesh element ID
4322     #  @return element's warping angle value
4323     #  @ingroup l1_measurements
4324     def GetWarping(self, elemId):
4325         return self._valueFromFunctor(SMESH.FT_Warping, elemId)
4326
4327     ## Get minimum angle of 2D element.
4328     #  @param elemId mesh element ID
4329     #  @return element's minimum angle value
4330     #  @ingroup l1_measurements
4331     def GetMinimumAngle(self, elemId):
4332         return self._valueFromFunctor(SMESH.FT_MinimumAngle, elemId)
4333
4334     ## Get taper of 2D element.
4335     #  @param elemId mesh element ID
4336     #  @return element's taper value
4337     #  @ingroup l1_measurements
4338     def GetTaper(self, elemId):
4339         return self._valueFromFunctor(SMESH.FT_Taper, elemId)
4340
4341     ## Get skew of 2D element.
4342     #  @param elemId mesh element ID
4343     #  @return element's skew value
4344     #  @ingroup l1_measurements
4345     def GetSkew(self, elemId):
4346         return self._valueFromFunctor(SMESH.FT_Skew, elemId)
4347
4348     pass # end of Mesh class
4349     
4350 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4351 #
4352 class Pattern(SMESH._objref_SMESH_Pattern):
4353
4354     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4355         decrFun = lambda i: i-1
4356         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4357         theMesh.SetParameters(Parameters)
4358         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4359
4360     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4361         decrFun = lambda i: i-1
4362         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4363         theMesh.SetParameters(Parameters)
4364         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4365
4366 # Registering the new proxy for Pattern
4367 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4368
4369 ## Private class used to bind methods creating algorithms to the class Mesh
4370 #
4371 class algoCreator:
4372     def __init__(self):
4373         self.mesh = None
4374         self.defaultAlgoType = ""
4375         self.algoTypeToClass = {}
4376
4377     # Stores a python class of algorithm
4378     def add(self, algoClass):
4379         if type( algoClass ).__name__ == 'classobj' and \
4380            hasattr( algoClass, "algoType"):
4381             self.algoTypeToClass[ algoClass.algoType ] = algoClass
4382             if not self.defaultAlgoType and \
4383                hasattr( algoClass, "isDefault") and algoClass.isDefault:
4384                 self.defaultAlgoType = algoClass.algoType
4385             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
4386
4387     # creates a copy of self and assign mesh to the copy
4388     def copy(self, mesh):
4389         other = algoCreator()
4390         other.defaultAlgoType = self.defaultAlgoType
4391         other.algoTypeToClass  = self.algoTypeToClass
4392         other.mesh = mesh
4393         return other
4394
4395     # creates an instance of algorithm
4396     def __call__(self,algo="",geom=0,*args):
4397         algoType = self.defaultAlgoType
4398         for arg in args + (algo,geom):
4399             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
4400                 geom = arg
4401             if isinstance( arg, str ) and arg:
4402                 algoType = arg
4403         if not algoType and self.algoTypeToClass:
4404             algoType = self.algoTypeToClass.keys()[0]
4405         if self.algoTypeToClass.has_key( algoType ):
4406             #print "Create algo",algoType
4407             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
4408         raise RuntimeError, "No class found for algo type %s" % algoType
4409         return None
4410
4411 # Private class used to substitute and store variable parameters of hypotheses.
4412 #
4413 class hypMethodWrapper:
4414     def __init__(self, hyp, method):
4415         self.hyp    = hyp
4416         self.method = method
4417         #print "REBIND:", method.__name__
4418         return
4419
4420     # call a method of hypothesis with calling SetVarParameter() before
4421     def __call__(self,*args):
4422         if not args:
4423             return self.method( self.hyp, *args ) # hypothesis method with no args
4424
4425         #print "MethWrapper.__call__",self.method.__name__, args
4426         try:
4427             parsed = ParseParameters(*args)     # replace variables with their values
4428             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
4429             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
4430         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
4431             # maybe there is a replaced string arg which is not variable
4432             result = self.method( self.hyp, *args )
4433         except ValueError, detail: # raised by ParseParameters()
4434             try:
4435                 result = self.method( self.hyp, *args )
4436             except omniORB.CORBA.BAD_PARAM:
4437                 raise ValueError, detail # wrong variable name
4438
4439         return result
4440
4441 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
4442     #
4443     #print "pluginName: ", pluginName
4444     pluginBuilderName = pluginName + "Builder"
4445     try:
4446         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
4447     except Exception, e:
4448         print "Exception while loading %s: %s" % ( pluginBuilderName, e )
4449         continue
4450     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
4451     plugin = eval( pluginBuilderName )
4452     #print "  plugin:" , str(plugin)
4453
4454     # add methods creating algorithms to Mesh
4455     for k in dir( plugin ):
4456         if k[0] == '_': continue
4457         algo = getattr( plugin, k )
4458         #print "             algo:", str(algo)
4459         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
4460             #print "                     meshMethod:" , str(algo.meshMethod)
4461             if not hasattr( Mesh, algo.meshMethod ):
4462                 setattr( Mesh, algo.meshMethod, algoCreator() )
4463                 pass
4464             getattr( Mesh, algo.meshMethod ).add( algo )
4465             pass
4466         pass
4467     pass
4468 del pluginName