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