Salome HOME
dfc17fb4539b2d984575fc9debfb141c12934465
[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 = " on %s" % self.GetSubShapeName( err.subShapeID )
1429                 errText = ""
1430                 stdErrors = ["OK",                   #COMPERR_OK
1431                              "Invalid input mesh",   #COMPERR_BAD_INPUT_MESH
1432                              "std::exception",       #COMPERR_STD_EXCEPTION
1433                              "OCC exception",        #COMPERR_OCC_EXCEPTION
1434                              "..",                   #COMPERR_SLM_EXCEPTION
1435                              "Unknown exception",    #COMPERR_EXCEPTION
1436                              "Memory allocation problem", #COMPERR_MEMORY_PB
1437                              "Algorithm failed",     #COMPERR_ALGO_FAILED
1438                              "Unexpected geometry",  #COMPERR_BAD_SHAPE
1439                              "Warning",              #COMPERR_WARNING
1440                              "Computation cancelled",#COMPERR_CANCELED
1441                              "No mesh on sub-shape"] #COMPERR_NO_MESH_ON_SHAPE
1442                 if err.code > 0:
1443                     if err.code < len(stdErrors): errText = stdErrors[err.code]
1444                 else:
1445                     errText = "code %s" % -err.code
1446                 if errText: errText += ". "
1447                 errText += err.comment
1448                 if allReasons != "":allReasons += "\n"
1449                 if ok:
1450                     allReasons += '-  "%s"%s - %s' %(err.algoName, shapeText, errText)
1451                 else:
1452                     allReasons += '-  "%s" failed%s. Error: %s' %(err.algoName, shapeText, errText)
1453                 pass
1454
1455             # Treat hyp errors
1456             errors = self.smeshpyD.GetAlgoState( self.mesh, geom )
1457             for err in errors:
1458                 if err.isGlobalAlgo:
1459                     glob = "global"
1460                 else:
1461                     glob = "local"
1462                     pass
1463                 dim = err.algoDim
1464                 name = err.algoName
1465                 if len(name) == 0:
1466                     reason = '%s %sD algorithm is missing' % (glob, dim)
1467                 elif err.state == HYP_MISSING:
1468                     reason = ('%s %sD algorithm "%s" misses %sD hypothesis'
1469                               % (glob, dim, name, dim))
1470                 elif err.state == HYP_NOTCONFORM:
1471                     reason = 'Global "Not Conform mesh allowed" hypothesis is missing'
1472                 elif err.state == HYP_BAD_PARAMETER:
1473                     reason = ('Hypothesis of %s %sD algorithm "%s" has a bad parameter value'
1474                               % ( glob, dim, name ))
1475                 elif err.state == HYP_BAD_GEOMETRY:
1476                     reason = ('%s %sD algorithm "%s" is assigned to mismatching'
1477                               'geometry' % ( glob, dim, name ))
1478                 elif err.state == HYP_HIDDEN_ALGO:
1479                     reason = ('%s %sD algorithm "%s" is ignored due to presence of a %s '
1480                               'algorithm of upper dimension generating %sD mesh'
1481                               % ( glob, dim, name, glob, dim ))
1482                 else:
1483                     reason = ("For unknown reason. "
1484                               "Developer, revise Mesh.Compute() implementation in smeshBuilder.py!")
1485                     pass
1486                 if allReasons != "":allReasons += "\n"
1487                 allReasons += "-  " + reason
1488                 pass
1489             if not ok or allReasons != "":
1490                 msg = '"' + GetName(self.mesh) + '"'
1491                 if ok: msg += " has been computed with warnings"
1492                 else:  msg += " has not been computed"
1493                 if allReasons != "": msg += ":"
1494                 else:                msg += "."
1495                 print msg
1496                 print allReasons
1497             pass
1498         if salome.sg.hasDesktop() and self.mesh.GetStudyId() >= 0:
1499             smeshgui = salome.ImportComponentGUI("SMESH")
1500             smeshgui.Init(self.mesh.GetStudyId())
1501             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), ok, (self.NbNodes()==0) )
1502             if refresh: salome.sg.updateObjBrowser(1)
1503             pass
1504         return ok
1505
1506     ## Return a name of a sub-shape by its ID
1507     #  @param subShapeID a unique ID of a sub-shape
1508     #  @return a string describing the sub-shape; possible variants:
1509     #  - "Face_12"    (published sub-shape)
1510     #  - FACE #3      (not published sub-shape)
1511     #  - sub-shape #3 (invalid sub-shape ID)
1512     #  - #3           (error in this function)
1513     def GetSubShapeName(self, subShapeID ):
1514         if not self.mesh.HasShapeToMesh():
1515             return ""
1516         try:
1517             shapeText = ""
1518             mainIOR  = salome.orb.object_to_string( self.GetShape() )
1519             for sname in salome.myStudyManager.GetOpenStudies():
1520                 s = salome.myStudyManager.GetStudyByName(sname)
1521                 if not s: continue
1522                 mainSO = s.FindObjectIOR(mainIOR)
1523                 if not mainSO: continue
1524                 if subShapeID == 1:
1525                     shapeText = '"%s"' % mainSO.GetName()
1526                 subIt = s.NewChildIterator(mainSO)
1527                 while subIt.More():
1528                     subSO = subIt.Value()
1529                     subIt.Next()
1530                     obj = subSO.GetObject()
1531                     if not obj: continue
1532                     go = obj._narrow( geomBuilder.GEOM._objref_GEOM_Object )
1533                     if not go: continue
1534                     try:
1535                         ids = self.geompyD.GetSubShapeID( self.GetShape(), go )
1536                     except:
1537                         continue
1538                     if ids == subShapeID:
1539                         shapeText = '"%s"' % subSO.GetName()
1540                         break
1541             if not shapeText:
1542                 shape = self.geompyD.GetSubShape( self.GetShape(), [subShapeID])
1543                 if shape:
1544                     shapeText = '%s #%s' % (shape.GetShapeType(), subShapeID)
1545                 else:
1546                     shapeText = 'sub-shape #%s' % (subShapeID)
1547         except:
1548             shapeText = "#%s" % (subShapeID)
1549         return shapeText
1550
1551     ## Return a list of sub-shapes meshing of which failed, grouped into GEOM groups by
1552     #  error of an algorithm
1553     #  @param publish if @c True, the returned groups will be published in the study
1554     #  @return a list of GEOM groups each named after a failed algorithm
1555     def GetFailedShapes(self, publish=False):
1556
1557         algo2shapes = {}
1558         computeErrors = self.smeshpyD.GetComputeErrors( self.mesh, self.GetShape() )
1559         for err in computeErrors:
1560             shape = self.geompyD.GetSubShape( self.GetShape(), [err.subShapeID])
1561             if not shape: continue
1562             if err.algoName in algo2shapes:
1563                 algo2shapes[ err.algoName ].append( shape )
1564             else:
1565                 algo2shapes[ err.algoName ] = [ shape ]
1566             pass
1567
1568         groups = []
1569         for algoName, shapes in algo2shapes.items():
1570             while shapes:
1571                 groupType = self.smeshpyD.EnumToLong( shapes[0].GetShapeType() )
1572                 otherTypeShapes = []
1573                 sameTypeShapes  = []
1574                 group = self.geompyD.CreateGroup( self.geom, groupType )
1575                 for shape in shapes:
1576                     if shape.GetShapeType() == shapes[0].GetShapeType():
1577                         sameTypeShapes.append( shape )
1578                     else:
1579                         otherTypeShapes.append( shape )
1580                 self.geompyD.UnionList( group, sameTypeShapes )
1581                 if otherTypeShapes:
1582                     group.SetName( "%s %s" % ( algoName, shapes[0].GetShapeType() ))
1583                 else:
1584                     group.SetName( algoName )
1585                 groups.append( group )
1586                 shapes = otherTypeShapes
1587             pass
1588         if publish:
1589             for group in groups:
1590                 self.geompyD.addToStudyInFather( self.geom, group, group.GetName() )
1591         return groups
1592
1593     ## Return sub-mesh objects list in meshing order
1594     #  @return list of list of sub-meshes
1595     #  @ingroup l2_construct
1596     def GetMeshOrder(self):
1597         return self.mesh.GetMeshOrder()
1598
1599     ## Set order in which concurrent sub-meshes sould be meshed
1600     #  @param submeshes list of sub-meshes
1601     #  @ingroup l2_construct
1602     def SetMeshOrder(self, submeshes):
1603         return self.mesh.SetMeshOrder(submeshes)
1604
1605     ## Removes all nodes and elements
1606     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1607     #  @ingroup l2_construct
1608     def Clear(self, refresh=False):
1609         self.mesh.Clear()
1610         if ( salome.sg.hasDesktop() and 
1611              salome.myStudyManager.GetStudyByID( self.mesh.GetStudyId() ) ):
1612             smeshgui = salome.ImportComponentGUI("SMESH")
1613             smeshgui.Init(self.mesh.GetStudyId())
1614             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1615             if refresh: salome.sg.updateObjBrowser(1)
1616
1617     ## Removes all nodes and elements of indicated shape
1618     #  @param refresh if @c True, Object browser is automatically updated (when running in GUI)
1619     #  @param geomId the ID of a sub-shape to remove elements on
1620     #  @ingroup l2_construct
1621     def ClearSubMesh(self, geomId, refresh=False):
1622         self.mesh.ClearSubMesh(geomId)
1623         if salome.sg.hasDesktop():
1624             smeshgui = salome.ImportComponentGUI("SMESH")
1625             smeshgui.Init(self.mesh.GetStudyId())
1626             smeshgui.SetMeshIcon( salome.ObjectToID( self.mesh ), False, True )
1627             if refresh: salome.sg.updateObjBrowser(1)
1628
1629     ## Computes a tetrahedral mesh using AutomaticLength + MEFISTO + Tetrahedron
1630     #  @param fineness [0.0,1.0] defines mesh fineness
1631     #  @return True or False
1632     #  @ingroup l3_algos_basic
1633     def AutomaticTetrahedralization(self, fineness=0):
1634         dim = self.MeshDimension()
1635         # assign hypotheses
1636         self.RemoveGlobalHypotheses()
1637         self.Segment().AutomaticLength(fineness)
1638         if dim > 1 :
1639             self.Triangle().LengthFromEdges()
1640             pass
1641         if dim > 2 :
1642             self.Tetrahedron()
1643             pass
1644         return self.Compute()
1645
1646     ## Computes an hexahedral mesh using AutomaticLength + Quadrangle + Hexahedron
1647     #  @param fineness [0.0, 1.0] defines mesh fineness
1648     #  @return True or False
1649     #  @ingroup l3_algos_basic
1650     def AutomaticHexahedralization(self, fineness=0):
1651         dim = self.MeshDimension()
1652         # assign the hypotheses
1653         self.RemoveGlobalHypotheses()
1654         self.Segment().AutomaticLength(fineness)
1655         if dim > 1 :
1656             self.Quadrangle()
1657             pass
1658         if dim > 2 :
1659             self.Hexahedron()
1660             pass
1661         return self.Compute()
1662
1663     ## Assigns a hypothesis
1664     #  @param hyp a hypothesis to assign
1665     #  @param geom a subhape of mesh geometry
1666     #  @return SMESH.Hypothesis_Status
1667     #  @ingroup l2_hypotheses
1668     def AddHypothesis(self, hyp, geom=0):
1669         if isinstance( hyp, geomBuilder.GEOM._objref_GEOM_Object ):
1670             hyp, geom = geom, hyp
1671         if isinstance( hyp, Mesh_Algorithm ):
1672             hyp = hyp.GetAlgorithm()
1673             pass
1674         if not geom:
1675             geom = self.geom
1676             if not geom:
1677                 geom = self.mesh.GetShapeToMesh()
1678             pass
1679         isApplicable = True
1680         if self.mesh.HasShapeToMesh():
1681             hyp_type     = hyp.GetName()
1682             lib_name     = hyp.GetLibName()
1683             checkAll    = ( not geom.IsSame( self.mesh.GetShapeToMesh() ))
1684             if checkAll and geom:
1685                 checkAll = geom.GetType() == 37
1686             isApplicable = self.smeshpyD.IsApplicable(hyp_type, lib_name, geom, checkAll)
1687         if isApplicable:
1688             AssureGeomPublished( self, geom, "shape for %s" % hyp.GetName())
1689             status = self.mesh.AddHypothesis(geom, hyp)
1690         else:
1691             status = HYP_BAD_GEOMETRY,""
1692         hyp_name = GetName( hyp )
1693         geom_name = ""
1694         if geom:
1695             geom_name = geom.GetName()
1696         isAlgo = hyp._narrow( SMESH_Algo )
1697         TreatHypoStatus( status, hyp_name, geom_name, isAlgo, self )
1698         return status
1699
1700     ## Return True if an algorithm of hypothesis is assigned to a given shape
1701     #  @param hyp a hypothesis to check
1702     #  @param geom a subhape of mesh geometry
1703     #  @return True of False
1704     #  @ingroup l2_hypotheses
1705     def IsUsedHypothesis(self, hyp, geom):
1706         if not hyp: # or not geom
1707             return False
1708         if isinstance( hyp, Mesh_Algorithm ):
1709             hyp = hyp.GetAlgorithm()
1710             pass
1711         hyps = self.GetHypothesisList(geom)
1712         for h in hyps:
1713             if h.GetId() == hyp.GetId():
1714                 return True
1715         return False
1716
1717     ## Unassigns a hypothesis
1718     #  @param hyp a hypothesis to unassign
1719     #  @param geom a sub-shape of mesh geometry
1720     #  @return SMESH.Hypothesis_Status
1721     #  @ingroup l2_hypotheses
1722     def RemoveHypothesis(self, hyp, geom=0):
1723         if not hyp:
1724             return None
1725         if isinstance( hyp, Mesh_Algorithm ):
1726             hyp = hyp.GetAlgorithm()
1727             pass
1728         shape = geom
1729         if not shape:
1730             shape = self.geom
1731             pass
1732         if self.IsUsedHypothesis( hyp, shape ):
1733             return self.mesh.RemoveHypothesis( shape, hyp )
1734         hypName = GetName( hyp )
1735         geoName = GetName( shape )
1736         print "WARNING: RemoveHypothesis() failed as '%s' is not assigned to '%s' shape" % ( hypName, geoName )
1737         return None
1738
1739     ## Gets the list of hypotheses added on a geometry
1740     #  @param geom a sub-shape of mesh geometry
1741     #  @return the sequence of SMESH_Hypothesis
1742     #  @ingroup l2_hypotheses
1743     def GetHypothesisList(self, geom):
1744         return self.mesh.GetHypothesisList( geom )
1745
1746     ## Removes all global hypotheses
1747     #  @ingroup l2_hypotheses
1748     def RemoveGlobalHypotheses(self):
1749         current_hyps = self.mesh.GetHypothesisList( self.geom )
1750         for hyp in current_hyps:
1751             self.mesh.RemoveHypothesis( self.geom, hyp )
1752             pass
1753         pass
1754
1755    ## Exports the mesh in a file in MED format and chooses the \a version of MED format
1756     ## allowing to overwrite the file if it exists or add the exported data to its contents
1757     #  @param f is the file name
1758     #  @param auto_groups boolean parameter for creating/not creating
1759     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1760     #  the typical use is auto_groups=false.
1761     #  @param version MED format version(MED_V2_1 or MED_V2_2)
1762     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1763     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1764     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1765     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1766     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1767     #         - 3D in the rest cases.
1768     #         If @a autoDimension is @c False, the space dimension is always 3.
1769     #  @param fields : list of GEOM fields defined on the shape to mesh.
1770     #  @param geomAssocFields : each character of this string means a need to export a 
1771     #         corresponding field; correspondence between fields and characters is following:
1772     #         - 'v' stands for _vertices_ field;
1773     #         - 'e' stands for _edges_ field;
1774     #         - 'f' stands for _faces_ field;
1775     #         - 's' stands for _solids_ field.
1776     #  @ingroup l2_impexp
1777     def ExportMED(self, f, auto_groups=0, version=MED_V2_2,
1778                   overwrite=1, meshPart=None, autoDimension=True, fields=[], geomAssocFields=''):
1779         if meshPart or fields or geomAssocFields:
1780             unRegister = genObjUnRegister()
1781             if isinstance( meshPart, list ):
1782                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1783                 unRegister.set( meshPart )
1784             self.mesh.ExportPartToMED( meshPart, f, auto_groups, version, overwrite, autoDimension,
1785                                        fields, geomAssocFields)
1786         else:
1787             self.mesh.ExportToMEDX(f, auto_groups, version, overwrite, autoDimension)
1788
1789     ## Exports the mesh in a file in SAUV format
1790     #  @param f is the file name
1791     #  @param auto_groups boolean parameter for creating/not creating
1792     #  the groups Group_On_All_Nodes, Group_On_All_Faces, ... ;
1793     #  the typical use is auto_groups=false.
1794     #  @ingroup l2_impexp
1795     def ExportSAUV(self, f, auto_groups=0):
1796         self.mesh.ExportSAUV(f, auto_groups)
1797
1798     ## Exports the mesh in a file in DAT format
1799     #  @param f the file name
1800     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1801     #  @ingroup l2_impexp
1802     def ExportDAT(self, f, meshPart=None):
1803         if meshPart:
1804             unRegister = genObjUnRegister()
1805             if isinstance( meshPart, list ):
1806                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1807                 unRegister.set( meshPart )
1808             self.mesh.ExportPartToDAT( meshPart, f )
1809         else:
1810             self.mesh.ExportDAT(f)
1811
1812     ## Exports the mesh in a file in UNV format
1813     #  @param f the file name
1814     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1815     #  @ingroup l2_impexp
1816     def ExportUNV(self, f, meshPart=None):
1817         if meshPart:
1818             unRegister = genObjUnRegister()
1819             if isinstance( meshPart, list ):
1820                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1821                 unRegister.set( meshPart )
1822             self.mesh.ExportPartToUNV( meshPart, f )
1823         else:
1824             self.mesh.ExportUNV(f)
1825
1826     ## Export the mesh in a file in STL format
1827     #  @param f the file name
1828     #  @param ascii defines the file encoding
1829     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1830     #  @ingroup l2_impexp
1831     def ExportSTL(self, f, ascii=1, meshPart=None):
1832         if meshPart:
1833             unRegister = genObjUnRegister()
1834             if isinstance( meshPart, list ):
1835                 meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1836                 unRegister.set( meshPart )
1837             self.mesh.ExportPartToSTL( meshPart, f, ascii )
1838         else:
1839             self.mesh.ExportSTL(f, ascii)
1840
1841     ## Exports the mesh in a file in CGNS format
1842     #  @param f is the file name
1843     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1844     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1845     #  @ingroup l2_impexp
1846     def ExportCGNS(self, f, overwrite=1, meshPart=None):
1847         unRegister = genObjUnRegister()
1848         if isinstance( meshPart, list ):
1849             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1850             unRegister.set( meshPart )
1851         if isinstance( meshPart, Mesh ):
1852             meshPart = meshPart.mesh
1853         elif not meshPart:
1854             meshPart = self.mesh
1855         self.mesh.ExportCGNS(meshPart, f, overwrite)
1856
1857     ## Exports the mesh in a file in GMF format.
1858     #  GMF files must have .mesh extension for the ASCII format and .meshb for
1859     #  the bynary format. Other extensions are not allowed.
1860     #  @param f is the file name
1861     #  @param meshPart a part of mesh (group, sub-mesh) to export instead of the mesh
1862     #  @ingroup l2_impexp
1863     def ExportGMF(self, f, meshPart=None):
1864         unRegister = genObjUnRegister()
1865         if isinstance( meshPart, list ):
1866             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
1867             unRegister.set( meshPart )
1868         if isinstance( meshPart, Mesh ):
1869             meshPart = meshPart.mesh
1870         elif not meshPart:
1871             meshPart = self.mesh
1872         self.mesh.ExportGMF(meshPart, f, True)
1873
1874     ## Deprecated, used only for compatibility! Please, use ExportToMEDX() method instead.
1875     #  Exports the mesh in a file in MED format and chooses the \a version of MED format
1876     ## allowing to overwrite the file if it exists or add the exported data to its contents
1877     #  @param f the file name
1878     #  @param version values are SMESH.MED_V2_1, SMESH.MED_V2_2
1879     #  @param opt boolean parameter for creating/not creating
1880     #         the groups Group_On_All_Nodes, Group_On_All_Faces, ...
1881     #  @param overwrite boolean parameter for overwriting/not overwriting the file
1882     #  @param autoDimension: if @c True (default), a space dimension of a MED mesh can be either
1883     #         - 1D if all mesh nodes lie on OX coordinate axis, or
1884     #         - 2D if all mesh nodes lie on XOY coordinate plane, or
1885     #         - 3D in the rest cases.
1886     #
1887     #         If @a autoDimension is @c False, the space dimension is always 3.
1888     #  @ingroup l2_impexp
1889     def ExportToMED(self, f, version, opt=0, overwrite=1, autoDimension=True):
1890         self.mesh.ExportToMEDX(f, opt, version, overwrite, autoDimension)
1891
1892     # Operations with groups:
1893     # ----------------------
1894
1895     ## Creates an empty mesh group
1896     #  @param elementType the type of elements in the group; either of 
1897     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1898     #  @param name the name of the mesh group
1899     #  @return SMESH_Group
1900     #  @ingroup l2_grps_create
1901     def CreateEmptyGroup(self, elementType, name):
1902         return self.mesh.CreateGroup(elementType, name)
1903
1904     ## Creates a mesh group based on the geometric object \a grp
1905     #  and gives a \a name, \n if this parameter is not defined
1906     #  the name is the same as the geometric group name \n
1907     #  Note: Works like GroupOnGeom().
1908     #  @param grp  a geometric group, a vertex, an edge, a face or a solid
1909     #  @param name the name of the mesh group
1910     #  @return SMESH_GroupOnGeom
1911     #  @ingroup l2_grps_create
1912     def Group(self, grp, name=""):
1913         return self.GroupOnGeom(grp, name)
1914
1915     ## Creates a mesh group based on the geometrical object \a grp
1916     #  and gives a \a name, \n if this parameter is not defined
1917     #  the name is the same as the geometrical group name
1918     #  @param grp  a geometrical group, a vertex, an edge, a face or a solid
1919     #  @param name the name of the mesh group
1920     #  @param typ  the type of elements in the group; either of 
1921     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME). If not set, it is
1922     #         automatically detected by the type of the geometry
1923     #  @return SMESH_GroupOnGeom
1924     #  @ingroup l2_grps_create
1925     def GroupOnGeom(self, grp, name="", typ=None):
1926         AssureGeomPublished( self, grp, name )
1927         if name == "":
1928             name = grp.GetName()
1929         if not typ:
1930             typ = self._groupTypeFromShape( grp )
1931         return self.mesh.CreateGroupFromGEOM(typ, name, grp)
1932
1933     ## Pivate method to get a type of group on geometry
1934     def _groupTypeFromShape( self, shape ):
1935         tgeo = str(shape.GetShapeType())
1936         if tgeo == "VERTEX":
1937             typ = NODE
1938         elif tgeo == "EDGE":
1939             typ = EDGE
1940         elif tgeo == "FACE" or tgeo == "SHELL":
1941             typ = FACE
1942         elif tgeo == "SOLID" or tgeo == "COMPSOLID":
1943             typ = VOLUME
1944         elif tgeo == "COMPOUND":
1945             sub = self.geompyD.SubShapeAll( shape, self.geompyD.ShapeType["SHAPE"])
1946             if not sub:
1947                 raise ValueError,"_groupTypeFromShape(): empty geometric group or compound '%s'" % GetName(shape)
1948             return self._groupTypeFromShape( sub[0] )
1949         else:
1950             raise ValueError, \
1951                   "_groupTypeFromShape(): invalid geometry '%s'" % GetName(shape)
1952         return typ
1953
1954     ## Creates a mesh group with given \a name based on the \a filter which
1955     ## is a special type of group dynamically updating it's contents during
1956     ## mesh modification
1957     #  @param typ  the type of elements in the group; either of 
1958     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1959     #  @param name the name of the mesh group
1960     #  @param filter the filter defining group contents
1961     #  @return SMESH_GroupOnFilter
1962     #  @ingroup l2_grps_create
1963     def GroupOnFilter(self, typ, name, filter):
1964         return self.mesh.CreateGroupFromFilter(typ, name, filter)
1965
1966     ## Creates a mesh group by the given ids of elements
1967     #  @param groupName the name of the mesh group
1968     #  @param elementType the type of elements in the group; either of 
1969     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
1970     #  @param elemIDs the list of ids
1971     #  @return SMESH_Group
1972     #  @ingroup l2_grps_create
1973     def MakeGroupByIds(self, groupName, elementType, elemIDs):
1974         group = self.mesh.CreateGroup(elementType, groupName)
1975         if hasattr( elemIDs, "GetIDs" ):
1976             if hasattr( elemIDs, "SetMesh" ):
1977                 elemIDs.SetMesh( self.GetMesh() )
1978             group.AddFrom( elemIDs )
1979         else:
1980             group.Add(elemIDs)
1981         return group
1982
1983     ## Creates a mesh group by the given conditions
1984     #  @param groupName the name of the mesh group
1985     #  @param elementType the type of elements(SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME)
1986     #  @param CritType the type of criterion (SMESH.FT_Taper, SMESH.FT_Area, etc.)
1987     #          Type SMESH.FunctorType._items in the Python Console to see all values.
1988     #          Note that the items starting from FT_LessThan are not suitable for CritType.
1989     #  @param Compare  belongs to {SMESH.FT_LessThan, SMESH.FT_MoreThan, SMESH.FT_EqualTo}
1990     #  @param Threshold the threshold value (range of ids as string, shape, numeric)
1991     #  @param UnaryOp  SMESH.FT_LogicalNOT or SMESH.FT_Undefined
1992     #  @param Tolerance the tolerance used by SMESH.FT_BelongToGeom, SMESH.FT_BelongToSurface,
1993     #         SMESH.FT_LyingOnGeom, SMESH.FT_CoplanarFaces criteria
1994     #  @return SMESH_GroupOnFilter
1995     #  @ingroup l2_grps_create
1996     def MakeGroup(self,
1997                   groupName,
1998                   elementType,
1999                   CritType=FT_Undefined,
2000                   Compare=FT_EqualTo,
2001                   Threshold="",
2002                   UnaryOp=FT_Undefined,
2003                   Tolerance=1e-07):
2004         aCriterion = self.smeshpyD.GetCriterion(elementType, CritType, Compare, Threshold, UnaryOp, FT_Undefined,Tolerance)
2005         group = self.MakeGroupByCriterion(groupName, aCriterion)
2006         return group
2007
2008     ## Creates a mesh group by the given criterion
2009     #  @param groupName the name of the mesh group
2010     #  @param Criterion the instance of Criterion class
2011     #  @return SMESH_GroupOnFilter
2012     #  @ingroup l2_grps_create
2013     def MakeGroupByCriterion(self, groupName, Criterion):
2014         return self.MakeGroupByCriteria( groupName, [Criterion] )
2015
2016     ## Creates a mesh group by the given criteria (list of criteria)
2017     #  @param groupName the name of the mesh group
2018     #  @param theCriteria the list of criteria
2019     #  @param binOp binary operator used when binary operator of criteria is undefined
2020     #  @return SMESH_GroupOnFilter
2021     #  @ingroup l2_grps_create
2022     def MakeGroupByCriteria(self, groupName, theCriteria, binOp=SMESH.FT_LogicalAND):
2023         aFilter = self.smeshpyD.GetFilterFromCriteria( theCriteria, binOp )
2024         group = self.MakeGroupByFilter(groupName, aFilter)
2025         return group
2026
2027     ## Creates a mesh group by the given filter
2028     #  @param groupName the name of the mesh group
2029     #  @param theFilter the instance of Filter class
2030     #  @return SMESH_GroupOnFilter
2031     #  @ingroup l2_grps_create
2032     def MakeGroupByFilter(self, groupName, theFilter):
2033         #group = self.CreateEmptyGroup(theFilter.GetElementType(), groupName)
2034         #theFilter.SetMesh( self.mesh )
2035         #group.AddFrom( theFilter )
2036         group = self.GroupOnFilter( theFilter.GetElementType(), groupName, theFilter )
2037         return group
2038
2039     ## Removes a group
2040     #  @ingroup l2_grps_delete
2041     def RemoveGroup(self, group):
2042         self.mesh.RemoveGroup(group)
2043
2044     ## Removes a group with its contents
2045     #  @ingroup l2_grps_delete
2046     def RemoveGroupWithContents(self, group):
2047         self.mesh.RemoveGroupWithContents(group)
2048
2049     ## Gets the list of groups existing in the mesh in the order
2050     #  of creation (starting from the oldest one)
2051     #  @param elemType type of elements the groups contain; either of 
2052     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2053     #         by default groups of elements of all types are returned
2054     #  @return a sequence of SMESH_GroupBase
2055     #  @ingroup l2_grps_create
2056     def GetGroups(self, elemType = SMESH.ALL):
2057         groups = self.mesh.GetGroups()
2058         if elemType == SMESH.ALL:
2059             return groups
2060         typedGroups = []
2061         for g in groups:
2062             if g.GetType() == elemType:
2063                 typedGroups.append( g )
2064                 pass
2065             pass
2066         return typedGroups
2067
2068     ## Gets the number of groups existing in the mesh
2069     #  @return the quantity of groups as an integer value
2070     #  @ingroup l2_grps_create
2071     def NbGroups(self):
2072         return self.mesh.NbGroups()
2073
2074     ## Gets the list of names of groups existing in the mesh
2075     #  @return list of strings
2076     #  @ingroup l2_grps_create
2077     def GetGroupNames(self):
2078         groups = self.GetGroups()
2079         names = []
2080         for group in groups:
2081             names.append(group.GetName())
2082         return names
2083
2084     ## Finds groups by name and type
2085     #  @param name name of the group of interest
2086     #  @param elemType type of elements the groups contain; either of 
2087     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME);
2088     #         by default one group of any type of elements is returned
2089     #         if elemType == SMESH.ALL then all groups of any type are returned
2090     #  @return a list of SMESH_GroupBase's
2091     #  @ingroup l2_grps_create
2092     def GetGroupByName(self, name, elemType = None):
2093         groups = []
2094         for group in self.GetGroups():
2095             if group.GetName() == name:
2096                 if elemType is None:
2097                     return [group]
2098                 if ( elemType == SMESH.ALL or 
2099                      group.GetType() == elemType ):
2100                     groups.append( group )
2101         return groups
2102
2103     ## Produces a union of two groups.
2104     #  A new group is created. All mesh elements that are
2105     #  present in the initial groups are added to the new one
2106     #  @return an instance of SMESH_Group
2107     #  @ingroup l2_grps_operon
2108     def UnionGroups(self, group1, group2, name):
2109         return self.mesh.UnionGroups(group1, group2, name)
2110
2111     ## Produces a union list of groups.
2112     #  New group is created. All mesh elements that are present in
2113     #  initial groups are added to the new one
2114     #  @return an instance of SMESH_Group
2115     #  @ingroup l2_grps_operon
2116     def UnionListOfGroups(self, groups, name):
2117       return self.mesh.UnionListOfGroups(groups, name)
2118
2119     ## Prodices an intersection of two groups.
2120     #  A new group is created. All mesh elements that are common
2121     #  for the two initial groups are added to the new one.
2122     #  @return an instance of SMESH_Group
2123     #  @ingroup l2_grps_operon
2124     def IntersectGroups(self, group1, group2, name):
2125         return self.mesh.IntersectGroups(group1, group2, name)
2126
2127     ## Produces an intersection of groups.
2128     #  New group is created. All mesh elements that are present in all
2129     #  initial groups simultaneously are added to the new one
2130     #  @return an instance of SMESH_Group
2131     #  @ingroup l2_grps_operon
2132     def IntersectListOfGroups(self, groups, name):
2133       return self.mesh.IntersectListOfGroups(groups, name)
2134
2135     ## Produces a cut of two groups.
2136     #  A new group is created. All mesh elements that are present in
2137     #  the main group but are not present in the tool group are added to the new one
2138     #  @return an instance of SMESH_Group
2139     #  @ingroup l2_grps_operon
2140     def CutGroups(self, main_group, tool_group, name):
2141         return self.mesh.CutGroups(main_group, tool_group, name)
2142
2143     ## Produces a cut of groups.
2144     #  A new group is created. All mesh elements that are present in main groups
2145     #  but do not present in tool groups are added to the new one
2146     #  @return an instance of SMESH_Group
2147     #  @ingroup l2_grps_operon
2148     def CutListOfGroups(self, main_groups, tool_groups, name):
2149         return self.mesh.CutListOfGroups(main_groups, tool_groups, name)
2150
2151     ##
2152     #  Create a standalone group of entities basing on nodes of other groups.
2153     #  \param groups - list of groups, sub-meshes or filters, of any type.
2154     #  \param elemType - a type of elements to include to the new group; either of 
2155     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME).
2156     #  \param name - a name of the new group.
2157     #  \param nbCommonNodes - a criterion of inclusion of an element to the new group
2158     #         basing on number of element nodes common with reference \a groups.
2159     #         Meaning of possible values are:
2160     #         - SMESH.ALL_NODES - include if all nodes are common,
2161     #         - SMESH.MAIN - include if all corner nodes are common (meaningful for a quadratic mesh),
2162     #         - SMESH.AT_LEAST_ONE - include if one or more node is common,
2163     #         - SMEHS.MAJORITY - include if half of nodes or more are common.
2164     #  \param underlyingOnly - if \c True (default), an element is included to the
2165     #         new group provided that it is based on nodes of one element of \a groups.
2166     #  @return an instance of SMESH_Group
2167     #  @ingroup l2_grps_operon
2168     def CreateDimGroup(self, groups, elemType, name,
2169                        nbCommonNodes = SMESH.ALL_NODES, underlyingOnly = True):
2170         if isinstance( groups, SMESH._objref_SMESH_IDSource ):
2171             groups = [groups]
2172         return self.mesh.CreateDimGroup(groups, elemType, name, nbCommonNodes, underlyingOnly)
2173
2174
2175     ## Convert group on geom into standalone group
2176     #  @ingroup l2_grps_delete
2177     def ConvertToStandalone(self, group):
2178         return self.mesh.ConvertToStandalone(group)
2179
2180     # Get some info about mesh:
2181     # ------------------------
2182
2183     ## Returns the log of nodes and elements added or removed
2184     #  since the previous clear of the log.
2185     #  @param clearAfterGet log is emptied after Get (safe if concurrents access)
2186     #  @return list of log_block structures:
2187     #                                        commandType
2188     #                                        number
2189     #                                        coords
2190     #                                        indexes
2191     #  @ingroup l1_auxiliary
2192     def GetLog(self, clearAfterGet):
2193         return self.mesh.GetLog(clearAfterGet)
2194
2195     ## Clears the log of nodes and elements added or removed since the previous
2196     #  clear. Must be used immediately after GetLog if clearAfterGet is false.
2197     #  @ingroup l1_auxiliary
2198     def ClearLog(self):
2199         self.mesh.ClearLog()
2200
2201     ## Toggles auto color mode on the object.
2202     #  @param theAutoColor the flag which toggles auto color mode.
2203     #  @ingroup l1_auxiliary
2204     def SetAutoColor(self, theAutoColor):
2205         self.mesh.SetAutoColor(theAutoColor)
2206
2207     ## Gets flag of object auto color mode.
2208     #  @return True or False
2209     #  @ingroup l1_auxiliary
2210     def GetAutoColor(self):
2211         return self.mesh.GetAutoColor()
2212
2213     ## Gets the internal ID
2214     #  @return integer value, which is the internal Id of the mesh
2215     #  @ingroup l1_auxiliary
2216     def GetId(self):
2217         return self.mesh.GetId()
2218
2219     ## Get the study Id
2220     #  @return integer value, which is the study Id of the mesh
2221     #  @ingroup l1_auxiliary
2222     def GetStudyId(self):
2223         return self.mesh.GetStudyId()
2224
2225     ## Checks the group names for duplications.
2226     #  Consider the maximum group name length stored in MED file.
2227     #  @return True or False
2228     #  @ingroup l1_auxiliary
2229     def HasDuplicatedGroupNamesMED(self):
2230         return self.mesh.HasDuplicatedGroupNamesMED()
2231
2232     ## Obtains the mesh editor tool
2233     #  @return an instance of SMESH_MeshEditor
2234     #  @ingroup l1_modifying
2235     def GetMeshEditor(self):
2236         return self.editor
2237
2238     ## Wrap a list of IDs of elements or nodes into SMESH_IDSource which
2239     #  can be passed as argument to a method accepting mesh, group or sub-mesh
2240     #  @param ids list of IDs
2241     #  @param elemType type of elements; this parameter is used to distinguish
2242     #         IDs of nodes from IDs of elements; by default ids are treated as
2243     #         IDs of elements; use SMESH.NODE if ids are IDs of nodes.
2244     #  @return an instance of SMESH_IDSource
2245     #  @warning call UnRegister() for the returned object as soon as it is no more useful:
2246     #          idSrc = mesh.GetIDSource( [1,3,5], SMESH.NODE )
2247     #          mesh.DoSomething( idSrc )
2248     #          idSrc.UnRegister()
2249     #  @ingroup l1_auxiliary
2250     def GetIDSource(self, ids, elemType = SMESH.ALL):
2251         return self.editor.MakeIDSource(ids, elemType)
2252
2253
2254     # Get informations about mesh contents:
2255     # ------------------------------------
2256
2257     ## Gets the mesh stattistic
2258     #  @return dictionary type element - count of elements
2259     #  @ingroup l1_meshinfo
2260     def GetMeshInfo(self, obj = None):
2261         if not obj: obj = self.mesh
2262         return self.smeshpyD.GetMeshInfo(obj)
2263
2264     ## Returns the number of nodes in the mesh
2265     #  @return an integer value
2266     #  @ingroup l1_meshinfo
2267     def NbNodes(self):
2268         return self.mesh.NbNodes()
2269
2270     ## Returns the number of elements in the mesh
2271     #  @return an integer value
2272     #  @ingroup l1_meshinfo
2273     def NbElements(self):
2274         return self.mesh.NbElements()
2275
2276     ## Returns the number of 0d elements in the mesh
2277     #  @return an integer value
2278     #  @ingroup l1_meshinfo
2279     def Nb0DElements(self):
2280         return self.mesh.Nb0DElements()
2281
2282     ## Returns the number of ball discrete elements in the mesh
2283     #  @return an integer value
2284     #  @ingroup l1_meshinfo
2285     def NbBalls(self):
2286         return self.mesh.NbBalls()
2287
2288     ## Returns the number of edges in the mesh
2289     #  @return an integer value
2290     #  @ingroup l1_meshinfo
2291     def NbEdges(self):
2292         return self.mesh.NbEdges()
2293
2294     ## Returns the number of edges with the given order in the mesh
2295     #  @param elementOrder the order of elements:
2296     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2297     #  @return an integer value
2298     #  @ingroup l1_meshinfo
2299     def NbEdgesOfOrder(self, elementOrder):
2300         return self.mesh.NbEdgesOfOrder(elementOrder)
2301
2302     ## Returns the number of faces in the mesh
2303     #  @return an integer value
2304     #  @ingroup l1_meshinfo
2305     def NbFaces(self):
2306         return self.mesh.NbFaces()
2307
2308     ## Returns the number of faces with the given order in the mesh
2309     #  @param elementOrder the order of elements:
2310     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2311     #  @return an integer value
2312     #  @ingroup l1_meshinfo
2313     def NbFacesOfOrder(self, elementOrder):
2314         return self.mesh.NbFacesOfOrder(elementOrder)
2315
2316     ## Returns the number of triangles in the mesh
2317     #  @return an integer value
2318     #  @ingroup l1_meshinfo
2319     def NbTriangles(self):
2320         return self.mesh.NbTriangles()
2321
2322     ## Returns the number of triangles with the given order in the mesh
2323     #  @param elementOrder is the order of elements:
2324     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2325     #  @return an integer value
2326     #  @ingroup l1_meshinfo
2327     def NbTrianglesOfOrder(self, elementOrder):
2328         return self.mesh.NbTrianglesOfOrder(elementOrder)
2329
2330     ## Returns the number of biquadratic triangles in the mesh
2331     #  @return an integer value
2332     #  @ingroup l1_meshinfo
2333     def NbBiQuadTriangles(self):
2334         return self.mesh.NbBiQuadTriangles()
2335
2336     ## Returns the number of quadrangles in the mesh
2337     #  @return an integer value
2338     #  @ingroup l1_meshinfo
2339     def NbQuadrangles(self):
2340         return self.mesh.NbQuadrangles()
2341
2342     ## Returns the number of quadrangles with the given order in the mesh
2343     #  @param elementOrder the order of elements:
2344     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2345     #  @return an integer value
2346     #  @ingroup l1_meshinfo
2347     def NbQuadranglesOfOrder(self, elementOrder):
2348         return self.mesh.NbQuadranglesOfOrder(elementOrder)
2349
2350     ## Returns the number of biquadratic quadrangles in the mesh
2351     #  @return an integer value
2352     #  @ingroup l1_meshinfo
2353     def NbBiQuadQuadrangles(self):
2354         return self.mesh.NbBiQuadQuadrangles()
2355
2356     ## Returns the number of polygons of given order in the mesh
2357     #  @param elementOrder the order of elements:
2358     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2359     #  @return an integer value
2360     #  @ingroup l1_meshinfo
2361     def NbPolygons(self, elementOrder = SMESH.ORDER_ANY):
2362         return self.mesh.NbPolygonsOfOrder(elementOrder)
2363
2364     ## Returns the number of volumes in the mesh
2365     #  @return an integer value
2366     #  @ingroup l1_meshinfo
2367     def NbVolumes(self):
2368         return self.mesh.NbVolumes()
2369
2370     ## Returns the number of volumes with the given order in the mesh
2371     #  @param elementOrder  the order of elements:
2372     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2373     #  @return an integer value
2374     #  @ingroup l1_meshinfo
2375     def NbVolumesOfOrder(self, elementOrder):
2376         return self.mesh.NbVolumesOfOrder(elementOrder)
2377
2378     ## Returns the number of tetrahedrons in the mesh
2379     #  @return an integer value
2380     #  @ingroup l1_meshinfo
2381     def NbTetras(self):
2382         return self.mesh.NbTetras()
2383
2384     ## Returns the number of tetrahedrons with the given order in the mesh
2385     #  @param elementOrder  the order of elements:
2386     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2387     #  @return an integer value
2388     #  @ingroup l1_meshinfo
2389     def NbTetrasOfOrder(self, elementOrder):
2390         return self.mesh.NbTetrasOfOrder(elementOrder)
2391
2392     ## Returns the number of hexahedrons in the mesh
2393     #  @return an integer value
2394     #  @ingroup l1_meshinfo
2395     def NbHexas(self):
2396         return self.mesh.NbHexas()
2397
2398     ## Returns the number of hexahedrons with the given order in the mesh
2399     #  @param elementOrder  the order of elements:
2400     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2401     #  @return an integer value
2402     #  @ingroup l1_meshinfo
2403     def NbHexasOfOrder(self, elementOrder):
2404         return self.mesh.NbHexasOfOrder(elementOrder)
2405
2406     ## Returns the number of triquadratic hexahedrons in the mesh
2407     #  @return an integer value
2408     #  @ingroup l1_meshinfo
2409     def NbTriQuadraticHexas(self):
2410         return self.mesh.NbTriQuadraticHexas()
2411
2412     ## Returns the number of pyramids in the mesh
2413     #  @return an integer value
2414     #  @ingroup l1_meshinfo
2415     def NbPyramids(self):
2416         return self.mesh.NbPyramids()
2417
2418     ## Returns the number of pyramids with the given order in the mesh
2419     #  @param elementOrder  the order of elements:
2420     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2421     #  @return an integer value
2422     #  @ingroup l1_meshinfo
2423     def NbPyramidsOfOrder(self, elementOrder):
2424         return self.mesh.NbPyramidsOfOrder(elementOrder)
2425
2426     ## Returns the number of prisms in the mesh
2427     #  @return an integer value
2428     #  @ingroup l1_meshinfo
2429     def NbPrisms(self):
2430         return self.mesh.NbPrisms()
2431
2432     ## Returns the number of prisms with the given order in the mesh
2433     #  @param elementOrder  the order of elements:
2434     #         SMESH.ORDER_ANY, SMESH.ORDER_LINEAR or SMESH.ORDER_QUADRATIC
2435     #  @return an integer value
2436     #  @ingroup l1_meshinfo
2437     def NbPrismsOfOrder(self, elementOrder):
2438         return self.mesh.NbPrismsOfOrder(elementOrder)
2439
2440     ## Returns the number of hexagonal prisms in the mesh
2441     #  @return an integer value
2442     #  @ingroup l1_meshinfo
2443     def NbHexagonalPrisms(self):
2444         return self.mesh.NbHexagonalPrisms()
2445
2446     ## Returns the number of polyhedrons in the mesh
2447     #  @return an integer value
2448     #  @ingroup l1_meshinfo
2449     def NbPolyhedrons(self):
2450         return self.mesh.NbPolyhedrons()
2451
2452     ## Returns the number of submeshes in the mesh
2453     #  @return an integer value
2454     #  @ingroup l1_meshinfo
2455     def NbSubMesh(self):
2456         return self.mesh.NbSubMesh()
2457
2458     ## Returns the list of mesh elements IDs
2459     #  @return the list of integer values
2460     #  @ingroup l1_meshinfo
2461     def GetElementsId(self):
2462         return self.mesh.GetElementsId()
2463
2464     ## Returns the list of IDs of mesh elements with the given type
2465     #  @param elementType  the required type of elements, either of
2466     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2467     #  @return list of integer values
2468     #  @ingroup l1_meshinfo
2469     def GetElementsByType(self, elementType):
2470         return self.mesh.GetElementsByType(elementType)
2471
2472     ## Returns the list of mesh nodes IDs
2473     #  @return the list of integer values
2474     #  @ingroup l1_meshinfo
2475     def GetNodesId(self):
2476         return self.mesh.GetNodesId()
2477
2478     # Get the information about mesh elements:
2479     # ------------------------------------
2480
2481     ## Returns the type of mesh element
2482     #  @return the value from SMESH::ElementType enumeration
2483     #          Type SMESH.ElementType._items in the Python Console to see all possible values.
2484     #  @ingroup l1_meshinfo
2485     def GetElementType(self, id, iselem=True):
2486         return self.mesh.GetElementType(id, iselem)
2487
2488     ## Returns the geometric type of mesh element
2489     #  @return the value from SMESH::EntityType enumeration
2490     #          Type SMESH.EntityType._items in the Python Console to see all possible values.
2491     #  @ingroup l1_meshinfo
2492     def GetElementGeomType(self, id):
2493         return self.mesh.GetElementGeomType(id)
2494
2495     ## Returns the shape type of mesh element
2496     #  @return the value from SMESH::GeometryType enumeration.
2497     #          Type SMESH.GeometryType._items in the Python Console to see all possible values.
2498     #  @ingroup l1_meshinfo
2499     def GetElementShape(self, id):
2500         return self.mesh.GetElementShape(id)
2501
2502     ## Returns the list of submesh elements IDs
2503     #  @param Shape a geom object(sub-shape) IOR
2504     #         Shape must be the sub-shape of a ShapeToMesh()
2505     #  @return the list of integer values
2506     #  @ingroup l1_meshinfo
2507     def GetSubMeshElementsId(self, Shape):
2508         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2509             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2510         else:
2511             ShapeID = Shape
2512         return self.mesh.GetSubMeshElementsId(ShapeID)
2513
2514     ## Returns the list of submesh nodes IDs
2515     #  @param Shape a geom object(sub-shape) IOR
2516     #         Shape must be the sub-shape of a ShapeToMesh()
2517     #  @param all If true, gives all nodes of submesh elements, otherwise gives only submesh nodes
2518     #  @return the list of integer values
2519     #  @ingroup l1_meshinfo
2520     def GetSubMeshNodesId(self, Shape, all):
2521         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2522             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2523         else:
2524             ShapeID = Shape
2525         return self.mesh.GetSubMeshNodesId(ShapeID, all)
2526
2527     ## Returns type of elements on given shape
2528     #  @param Shape a geom object(sub-shape) IOR
2529     #         Shape must be a sub-shape of a ShapeToMesh()
2530     #  @return element type
2531     #  @ingroup l1_meshinfo
2532     def GetSubMeshElementType(self, Shape):
2533         if isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object):
2534             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2535         else:
2536             ShapeID = Shape
2537         return self.mesh.GetSubMeshElementType(ShapeID)
2538
2539     ## Gets the mesh description
2540     #  @return string value
2541     #  @ingroup l1_meshinfo
2542     def Dump(self):
2543         return self.mesh.Dump()
2544
2545
2546     # Get the information about nodes and elements of a mesh by its IDs:
2547     # -----------------------------------------------------------
2548
2549     ## Gets XYZ coordinates of a node
2550     #  \n If there is no nodes for the given ID - returns an empty list
2551     #  @return a list of double precision values
2552     #  @ingroup l1_meshinfo
2553     def GetNodeXYZ(self, id):
2554         return self.mesh.GetNodeXYZ(id)
2555
2556     ## Returns list of IDs of inverse elements for the given node
2557     #  \n If there is no node for the given ID - returns an empty list
2558     #  @return a list of integer values
2559     #  @ingroup l1_meshinfo
2560     def GetNodeInverseElements(self, id):
2561         return self.mesh.GetNodeInverseElements(id)
2562
2563     ## @brief Returns the position of a node on the shape
2564     #  @return SMESH::NodePosition
2565     #  @ingroup l1_meshinfo
2566     def GetNodePosition(self,NodeID):
2567         return self.mesh.GetNodePosition(NodeID)
2568
2569     ## @brief Returns the position of an element on the shape
2570     #  @return SMESH::ElementPosition
2571     #  @ingroup l1_meshinfo
2572     def GetElementPosition(self,ElemID):
2573         return self.mesh.GetElementPosition(ElemID)
2574
2575     ## Returns the ID of the shape, on which the given node was generated.
2576     #  @return an integer value > 0 or -1 if there is no node for the given
2577     #          ID or the node is not assigned to any geometry
2578     #  @ingroup l1_meshinfo
2579     def GetShapeID(self, id):
2580         return self.mesh.GetShapeID(id)
2581
2582     ## Returns the ID of the shape, on which the given element was generated.
2583     #  @return an integer value > 0 or -1 if there is no element for the given
2584     #          ID or the element is not assigned to any geometry
2585     #  @ingroup l1_meshinfo
2586     def GetShapeIDForElem(self,id):
2587         return self.mesh.GetShapeIDForElem(id)
2588
2589     ## Returns the number of nodes of the given element
2590     #  @return an integer value > 0 or -1 if there is no element for the given ID
2591     #  @ingroup l1_meshinfo
2592     def GetElemNbNodes(self, id):
2593         return self.mesh.GetElemNbNodes(id)
2594
2595     ## Returns the node ID the given (zero based) index for the given element
2596     #  \n If there is no element for the given ID - returns -1
2597     #  \n If there is no node for the given index - returns -2
2598     #  @return an integer value
2599     #  @ingroup l1_meshinfo
2600     def GetElemNode(self, id, index):
2601         return self.mesh.GetElemNode(id, index)
2602
2603     ## Returns the IDs of nodes of the given element
2604     #  @return a list of integer values
2605     #  @ingroup l1_meshinfo
2606     def GetElemNodes(self, id):
2607         return self.mesh.GetElemNodes(id)
2608
2609     ## Returns true if the given node is the medium node in the given quadratic element
2610     #  @ingroup l1_meshinfo
2611     def IsMediumNode(self, elementID, nodeID):
2612         return self.mesh.IsMediumNode(elementID, nodeID)
2613
2614     ## Returns true if the given node is the medium node in one of quadratic elements
2615     #  @param nodeID ID of the node
2616     #  @param elementType  the type of elements to check a state of the node, either of
2617     #         (SMESH.ALL, SMESH.NODE, SMESH.EDGE, SMESH.FACE or SMESH.VOLUME)
2618     #  @ingroup l1_meshinfo
2619     def IsMediumNodeOfAnyElem(self, nodeID, elementType = SMESH.ALL ):
2620         return self.mesh.IsMediumNodeOfAnyElem(nodeID, elementType)
2621
2622     ## Returns the number of edges for the given element
2623     #  @ingroup l1_meshinfo
2624     def ElemNbEdges(self, id):
2625         return self.mesh.ElemNbEdges(id)
2626
2627     ## Returns the number of faces for the given element
2628     #  @ingroup l1_meshinfo
2629     def ElemNbFaces(self, id):
2630         return self.mesh.ElemNbFaces(id)
2631
2632     ## Returns nodes of given face (counted from zero) for given volumic element.
2633     #  @ingroup l1_meshinfo
2634     def GetElemFaceNodes(self,elemId, faceIndex):
2635         return self.mesh.GetElemFaceNodes(elemId, faceIndex)
2636
2637     ## Returns three components of normal of given mesh face
2638     #  (or an empty array in KO case)
2639     #  @ingroup l1_meshinfo
2640     def GetFaceNormal(self, faceId, normalized=False):
2641         return self.mesh.GetFaceNormal(faceId,normalized)
2642
2643     ## Returns an element based on all given nodes.
2644     #  @ingroup l1_meshinfo
2645     def FindElementByNodes(self,nodes):
2646         return self.mesh.FindElementByNodes(nodes)
2647
2648     ## Returns true if the given element is a polygon
2649     #  @ingroup l1_meshinfo
2650     def IsPoly(self, id):
2651         return self.mesh.IsPoly(id)
2652
2653     ## Returns true if the given element is quadratic
2654     #  @ingroup l1_meshinfo
2655     def IsQuadratic(self, id):
2656         return self.mesh.IsQuadratic(id)
2657
2658     ## Returns diameter of a ball discrete element or zero in case of an invalid \a id
2659     #  @ingroup l1_meshinfo
2660     def GetBallDiameter(self, id):
2661         return self.mesh.GetBallDiameter(id)
2662
2663     ## Returns XYZ coordinates of the barycenter of the given element
2664     #  \n If there is no element for the given ID - returns an empty list
2665     #  @return a list of three double values
2666     #  @ingroup l1_meshinfo
2667     def BaryCenter(self, id):
2668         return self.mesh.BaryCenter(id)
2669
2670     ## Passes mesh elements through the given filter and return IDs of fitting elements
2671     #  @param theFilter SMESH_Filter
2672     #  @return a list of ids
2673     #  @ingroup l1_controls
2674     def GetIdsFromFilter(self, theFilter):
2675         theFilter.SetMesh( self.mesh )
2676         return theFilter.GetIDs()
2677
2678     ## Verifies whether a 2D mesh element has free edges (edges connected to one face only)\n
2679     #  Returns a list of special structures (borders).
2680     #  @return a list of SMESH.FreeEdges.Border structure: edge id and ids of two its nodes.
2681     #  @ingroup l1_controls
2682     def GetFreeBorders(self):
2683         aFilterMgr = self.smeshpyD.CreateFilterManager()
2684         aPredicate = aFilterMgr.CreateFreeEdges()
2685         aPredicate.SetMesh(self.mesh)
2686         aBorders = aPredicate.GetBorders()
2687         aFilterMgr.UnRegister()
2688         return aBorders
2689
2690
2691     # Get mesh measurements information:
2692     # ------------------------------------
2693
2694     ## Get minimum distance between two nodes, elements or distance to the origin
2695     #  @param id1 first node/element id
2696     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2697     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2698     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2699     #  @return minimum distance value
2700     #  @sa GetMinDistance()
2701     def MinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2702         aMeasure = self.GetMinDistance(id1, id2, isElem1, isElem2)
2703         return aMeasure.value
2704
2705     ## Get measure structure specifying minimum distance data between two objects
2706     #  @param id1 first node/element id
2707     #  @param id2 second node/element id (if 0, distance from @a id1 to the origin is computed)
2708     #  @param isElem1 @c True if @a id1 is element id, @c False if it is node id
2709     #  @param isElem2 @c True if @a id2 is element id, @c False if it is node id
2710     #  @return Measure structure
2711     #  @sa MinDistance()
2712     def GetMinDistance(self, id1, id2=0, isElem1=False, isElem2=False):
2713         if isElem1:
2714             id1 = self.editor.MakeIDSource([id1], SMESH.FACE)
2715         else:
2716             id1 = self.editor.MakeIDSource([id1], SMESH.NODE)
2717         if id2 != 0:
2718             if isElem2:
2719                 id2 = self.editor.MakeIDSource([id2], SMESH.FACE)
2720             else:
2721                 id2 = self.editor.MakeIDSource([id2], SMESH.NODE)
2722             pass
2723         else:
2724             id2 = None
2725
2726         aMeasurements = self.smeshpyD.CreateMeasurements()
2727         aMeasure = aMeasurements.MinDistance(id1, id2)
2728         genObjUnRegister([aMeasurements,id1, id2])
2729         return aMeasure
2730
2731     ## Get bounding box of the specified object(s)
2732     #  @param objects single source object or list of source objects or list of nodes/elements IDs
2733     #  @param isElem if @a objects is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2734     #  @c False specifies that @a objects are nodes
2735     #  @return tuple of six values (minX, minY, minZ, maxX, maxY, maxZ)
2736     #  @sa GetBoundingBox()
2737     def BoundingBox(self, objects=None, isElem=False):
2738         result = self.GetBoundingBox(objects, isElem)
2739         if result is None:
2740             result = (0.0,)*6
2741         else:
2742             result = (result.minX, result.minY, result.minZ, result.maxX, result.maxY, result.maxZ)
2743         return result
2744
2745     ## Get measure structure specifying bounding box data of the specified object(s)
2746     #  @param IDs single source object or list of source objects or list of nodes/elements IDs
2747     #  @param isElem if @a IDs is a list of IDs, @c True value in this parameters specifies that @a objects are elements,
2748     #  @c False specifies that @a objects are nodes
2749     #  @return Measure structure
2750     #  @sa BoundingBox()
2751     def GetBoundingBox(self, IDs=None, isElem=False):
2752         if IDs is None:
2753             IDs = [self.mesh]
2754         elif isinstance(IDs, tuple):
2755             IDs = list(IDs)
2756         if not isinstance(IDs, list):
2757             IDs = [IDs]
2758         if len(IDs) > 0 and isinstance(IDs[0], int):
2759             IDs = [IDs]
2760         srclist = []
2761         unRegister = genObjUnRegister()
2762         for o in IDs:
2763             if isinstance(o, Mesh):
2764                 srclist.append(o.mesh)
2765             elif hasattr(o, "_narrow"):
2766                 src = o._narrow(SMESH.SMESH_IDSource)
2767                 if src: srclist.append(src)
2768                 pass
2769             elif isinstance(o, list):
2770                 if isElem:
2771                     srclist.append(self.editor.MakeIDSource(o, SMESH.FACE))
2772                 else:
2773                     srclist.append(self.editor.MakeIDSource(o, SMESH.NODE))
2774                 unRegister.set( srclist[-1] )
2775                 pass
2776             pass
2777         aMeasurements = self.smeshpyD.CreateMeasurements()
2778         unRegister.set( aMeasurements )
2779         aMeasure = aMeasurements.BoundingBox(srclist)
2780         return aMeasure
2781
2782     # Mesh edition (SMESH_MeshEditor functionality):
2783     # ---------------------------------------------
2784
2785     ## Removes the elements from the mesh by ids
2786     #  @param IDsOfElements is a list of ids of elements to remove
2787     #  @return True or False
2788     #  @ingroup l2_modif_del
2789     def RemoveElements(self, IDsOfElements):
2790         return self.editor.RemoveElements(IDsOfElements)
2791
2792     ## Removes nodes from mesh by ids
2793     #  @param IDsOfNodes is a list of ids of nodes to remove
2794     #  @return True or False
2795     #  @ingroup l2_modif_del
2796     def RemoveNodes(self, IDsOfNodes):
2797         return self.editor.RemoveNodes(IDsOfNodes)
2798
2799     ## Removes all orphan (free) nodes from mesh
2800     #  @return number of the removed nodes
2801     #  @ingroup l2_modif_del
2802     def RemoveOrphanNodes(self):
2803         return self.editor.RemoveOrphanNodes()
2804
2805     ## Add a node to the mesh by coordinates
2806     #  @return Id of the new node
2807     #  @ingroup l2_modif_add
2808     def AddNode(self, x, y, z):
2809         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
2810         if hasVars: self.mesh.SetParameters(Parameters)
2811         return self.editor.AddNode( x, y, z)
2812
2813     ## Creates a 0D element on a node with given number.
2814     #  @param IDOfNode the ID of node for creation of the element.
2815     #  @return the Id of the new 0D element
2816     #  @ingroup l2_modif_add
2817     def Add0DElement(self, IDOfNode):
2818         return self.editor.Add0DElement(IDOfNode)
2819
2820     ## Create 0D elements on all nodes of the given elements except those 
2821     #  nodes on which a 0D element already exists.
2822     #  @param theObject an object on whose nodes 0D elements will be created.
2823     #         It can be mesh, sub-mesh, group, list of element IDs or a holder
2824     #         of nodes IDs created by calling mesh.GetIDSource( nodes, SMESH.NODE )
2825     #  @param theGroupName optional name of a group to add 0D elements created
2826     #         and/or found on nodes of \a theObject.
2827     #  @return an object (a new group or a temporary SMESH_IDSource) holding
2828     #          IDs of new and/or found 0D elements. IDs of 0D elements 
2829     #          can be retrieved from the returned object by calling GetIDs()
2830     #  @ingroup l2_modif_add
2831     def Add0DElementsToAllNodes(self, theObject, theGroupName=""):
2832         unRegister = genObjUnRegister()
2833         if isinstance( theObject, Mesh ):
2834             theObject = theObject.GetMesh()
2835         if isinstance( theObject, list ):
2836             theObject = self.GetIDSource( theObject, SMESH.ALL )
2837             unRegister.set( theObject )
2838         return self.editor.Create0DElementsOnAllNodes( theObject, theGroupName )
2839
2840     ## Creates a ball element on a node with given ID.
2841     #  @param IDOfNode the ID of node for creation of the element.
2842     #  @param diameter the bal diameter.
2843     #  @return the Id of the new ball element
2844     #  @ingroup l2_modif_add
2845     def AddBall(self, IDOfNode, diameter):
2846         return self.editor.AddBall( IDOfNode, diameter )
2847
2848     ## Creates a linear or quadratic edge (this is determined
2849     #  by the number of given nodes).
2850     #  @param IDsOfNodes the list of node IDs for creation of the element.
2851     #  The order of nodes in this list should correspond to the description
2852     #  of MED. \n This description is located by the following link:
2853     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2854     #  @return the Id of the new edge
2855     #  @ingroup l2_modif_add
2856     def AddEdge(self, IDsOfNodes):
2857         return self.editor.AddEdge(IDsOfNodes)
2858
2859     ## Creates a linear or quadratic face (this is determined
2860     #  by the number of given nodes).
2861     #  @param IDsOfNodes the list of node IDs for creation of the element.
2862     #  The order of nodes in this list should correspond to the description
2863     #  of MED. \n This description is located by the following link:
2864     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2865     #  @return the Id of the new face
2866     #  @ingroup l2_modif_add
2867     def AddFace(self, IDsOfNodes):
2868         return self.editor.AddFace(IDsOfNodes)
2869
2870     ## Adds a polygonal face to the mesh by the list of node IDs
2871     #  @param IdsOfNodes the list of node IDs for creation of the element.
2872     #  @return the Id of the new face
2873     #  @ingroup l2_modif_add
2874     def AddPolygonalFace(self, IdsOfNodes):
2875         return self.editor.AddPolygonalFace(IdsOfNodes)
2876
2877     ## Adds a quadratic polygonal face to the mesh by the list of node IDs
2878     #  @param IdsOfNodes the list of node IDs for creation of the element;
2879     #         corner nodes follow first.
2880     #  @return the Id of the new face
2881     #  @ingroup l2_modif_add
2882     def AddQuadPolygonalFace(self, IdsOfNodes):
2883         return self.editor.AddQuadPolygonalFace(IdsOfNodes)
2884
2885     ## Creates both simple and quadratic volume (this is determined
2886     #  by the number of given nodes).
2887     #  @param IDsOfNodes the list of node IDs for creation of the element.
2888     #  The order of nodes in this list should correspond to the description
2889     #  of MED. \n This description is located by the following link:
2890     #  http://www.code-aster.org/outils/med/html/modele_de_donnees.html#3.
2891     #  @return the Id of the new volumic element
2892     #  @ingroup l2_modif_add
2893     def AddVolume(self, IDsOfNodes):
2894         return self.editor.AddVolume(IDsOfNodes)
2895
2896     ## Creates a volume of many faces, giving nodes for each face.
2897     #  @param IdsOfNodes the list of node IDs for volume creation face by face.
2898     #  @param Quantities the list of integer values, Quantities[i]
2899     #         gives the quantity of nodes in face number i.
2900     #  @return the Id of the new volumic element
2901     #  @ingroup l2_modif_add
2902     def AddPolyhedralVolume (self, IdsOfNodes, Quantities):
2903         return self.editor.AddPolyhedralVolume(IdsOfNodes, Quantities)
2904
2905     ## Creates a volume of many faces, giving the IDs of the existing faces.
2906     #  @param IdsOfFaces the list of face IDs for volume creation.
2907     #
2908     #  Note:  The created volume will refer only to the nodes
2909     #         of the given faces, not to the faces themselves.
2910     #  @return the Id of the new volumic element
2911     #  @ingroup l2_modif_add
2912     def AddPolyhedralVolumeByFaces (self, IdsOfFaces):
2913         return self.editor.AddPolyhedralVolumeByFaces(IdsOfFaces)
2914
2915
2916     ## @brief Binds a node to a vertex
2917     #  @param NodeID a node ID
2918     #  @param Vertex a vertex or vertex ID
2919     #  @return True if succeed else raises an exception
2920     #  @ingroup l2_modif_add
2921     def SetNodeOnVertex(self, NodeID, Vertex):
2922         if ( isinstance( Vertex, geomBuilder.GEOM._objref_GEOM_Object)):
2923             VertexID = self.geompyD.GetSubShapeID( self.geom, Vertex )
2924         else:
2925             VertexID = Vertex
2926         try:
2927             self.editor.SetNodeOnVertex(NodeID, VertexID)
2928         except SALOME.SALOME_Exception, inst:
2929             raise ValueError, inst.details.text
2930         return True
2931
2932
2933     ## @brief Stores the node position on an edge
2934     #  @param NodeID a node ID
2935     #  @param Edge an edge or edge ID
2936     #  @param paramOnEdge a parameter on the edge where the node is located
2937     #  @return True if succeed else raises an exception
2938     #  @ingroup l2_modif_add
2939     def SetNodeOnEdge(self, NodeID, Edge, paramOnEdge):
2940         if ( isinstance( Edge, geomBuilder.GEOM._objref_GEOM_Object)):
2941             EdgeID = self.geompyD.GetSubShapeID( self.geom, Edge )
2942         else:
2943             EdgeID = Edge
2944         try:
2945             self.editor.SetNodeOnEdge(NodeID, EdgeID, paramOnEdge)
2946         except SALOME.SALOME_Exception, inst:
2947             raise ValueError, inst.details.text
2948         return True
2949
2950     ## @brief Stores node position on a face
2951     #  @param NodeID a node ID
2952     #  @param Face a face or face ID
2953     #  @param u U parameter on the face where the node is located
2954     #  @param v V parameter on the face where the node is located
2955     #  @return True if succeed else raises an exception
2956     #  @ingroup l2_modif_add
2957     def SetNodeOnFace(self, NodeID, Face, u, v):
2958         if ( isinstance( Face, geomBuilder.GEOM._objref_GEOM_Object)):
2959             FaceID = self.geompyD.GetSubShapeID( self.geom, Face )
2960         else:
2961             FaceID = Face
2962         try:
2963             self.editor.SetNodeOnFace(NodeID, FaceID, u, v)
2964         except SALOME.SALOME_Exception, inst:
2965             raise ValueError, inst.details.text
2966         return True
2967
2968     ## @brief Binds a node to a solid
2969     #  @param NodeID a node ID
2970     #  @param Solid  a solid or solid ID
2971     #  @return True if succeed else raises an exception
2972     #  @ingroup l2_modif_add
2973     def SetNodeInVolume(self, NodeID, Solid):
2974         if ( isinstance( Solid, geomBuilder.GEOM._objref_GEOM_Object)):
2975             SolidID = self.geompyD.GetSubShapeID( self.geom, Solid )
2976         else:
2977             SolidID = Solid
2978         try:
2979             self.editor.SetNodeInVolume(NodeID, SolidID)
2980         except SALOME.SALOME_Exception, inst:
2981             raise ValueError, inst.details.text
2982         return True
2983
2984     ## @brief Bind an element to a shape
2985     #  @param ElementID an element ID
2986     #  @param Shape a shape or shape ID
2987     #  @return True if succeed else raises an exception
2988     #  @ingroup l2_modif_add
2989     def SetMeshElementOnShape(self, ElementID, Shape):
2990         if ( isinstance( Shape, geomBuilder.GEOM._objref_GEOM_Object)):
2991             ShapeID = self.geompyD.GetSubShapeID( self.geom, Shape )
2992         else:
2993             ShapeID = Shape
2994         try:
2995             self.editor.SetMeshElementOnShape(ElementID, ShapeID)
2996         except SALOME.SALOME_Exception, inst:
2997             raise ValueError, inst.details.text
2998         return True
2999
3000
3001     ## Moves the node with the given id
3002     #  @param NodeID the id of the node
3003     #  @param x  a new X coordinate
3004     #  @param y  a new Y coordinate
3005     #  @param z  a new Z coordinate
3006     #  @return True if succeed else False
3007     #  @ingroup l2_modif_movenode
3008     def MoveNode(self, NodeID, x, y, z):
3009         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3010         if hasVars: self.mesh.SetParameters(Parameters)
3011         return self.editor.MoveNode(NodeID, x, y, z)
3012
3013     ## Finds the node closest to a point and moves it to a point location
3014     #  @param x  the X coordinate of a point
3015     #  @param y  the Y coordinate of a point
3016     #  @param z  the Z coordinate of a point
3017     #  @param NodeID if specified (>0), the node with this ID is moved,
3018     #  otherwise, the node closest to point (@a x,@a y,@a z) is moved
3019     #  @return the ID of a node
3020     #  @ingroup l2_modif_throughp
3021     def MoveClosestNodeToPoint(self, x, y, z, NodeID):
3022         x,y,z,Parameters,hasVars = ParseParameters(x,y,z)
3023         if hasVars: self.mesh.SetParameters(Parameters)
3024         return self.editor.MoveClosestNodeToPoint(x, y, z, NodeID)
3025
3026     ## Finds the node closest to a point
3027     #  @param x  the X coordinate of a point
3028     #  @param y  the Y coordinate of a point
3029     #  @param z  the Z coordinate of a point
3030     #  @return the ID of a node
3031     #  @ingroup l2_modif_throughp
3032     def FindNodeClosestTo(self, x, y, z):
3033         #preview = self.mesh.GetMeshEditPreviewer()
3034         #return preview.MoveClosestNodeToPoint(x, y, z, -1)
3035         return self.editor.FindNodeClosestTo(x, y, z)
3036
3037     ## Finds the elements where a point lays IN or ON
3038     #  @param x  the X coordinate of a point
3039     #  @param y  the Y coordinate of a point
3040     #  @param z  the Z coordinate of a point
3041     #  @param elementType type of elements to find; either of 
3042     #         (SMESH.NODE, SMESH.EDGE, SMESH.FACE, SMESH.VOLUME); SMESH.ALL type
3043     #         means elements of any type excluding nodes, discrete and 0D elements.
3044     #  @param meshPart a part of mesh (group, sub-mesh) to search within
3045     #  @return list of IDs of found elements
3046     #  @ingroup l2_modif_throughp
3047     def FindElementsByPoint(self, x, y, z, elementType = SMESH.ALL, meshPart=None):
3048         if meshPart:
3049             return self.editor.FindAmongElementsByPoint( meshPart, x, y, z, elementType );
3050         else:
3051             return self.editor.FindElementsByPoint(x, y, z, elementType)
3052
3053     ## Return point state in a closed 2D mesh in terms of TopAbs_State enumeration:
3054     #  0-IN, 1-OUT, 2-ON, 3-UNKNOWN
3055     #  UNKNOWN state means that either mesh is wrong or the analysis fails.
3056     def GetPointState(self, x, y, z):
3057         return self.editor.GetPointState(x, y, z)
3058
3059     ## Finds the node closest to a point and moves it to a point location
3060     #  @param x  the X coordinate of a point
3061     #  @param y  the Y coordinate of a point
3062     #  @param z  the Z coordinate of a point
3063     #  @return the ID of a moved node
3064     #  @ingroup l2_modif_throughp
3065     def MeshToPassThroughAPoint(self, x, y, z):
3066         return self.editor.MoveClosestNodeToPoint(x, y, z, -1)
3067
3068     ## Replaces two neighbour triangles sharing Node1-Node2 link
3069     #  with the triangles built on the same 4 nodes but having other common link.
3070     #  @param NodeID1  the ID of the first node
3071     #  @param NodeID2  the ID of the second node
3072     #  @return false if proper faces were not found
3073     #  @ingroup l2_modif_invdiag
3074     def InverseDiag(self, NodeID1, NodeID2):
3075         return self.editor.InverseDiag(NodeID1, NodeID2)
3076
3077     ## Replaces two neighbour triangles sharing Node1-Node2 link
3078     #  with a quadrangle built on the same 4 nodes.
3079     #  @param NodeID1  the ID of the first node
3080     #  @param NodeID2  the ID of the second node
3081     #  @return false if proper faces were not found
3082     #  @ingroup l2_modif_unitetri
3083     def DeleteDiag(self, NodeID1, NodeID2):
3084         return self.editor.DeleteDiag(NodeID1, NodeID2)
3085
3086     ## Reorients elements by ids
3087     #  @param IDsOfElements if undefined reorients all mesh elements
3088     #  @return True if succeed else False
3089     #  @ingroup l2_modif_changori
3090     def Reorient(self, IDsOfElements=None):
3091         if IDsOfElements == None:
3092             IDsOfElements = self.GetElementsId()
3093         return self.editor.Reorient(IDsOfElements)
3094
3095     ## Reorients all elements of the object
3096     #  @param theObject mesh, submesh or group
3097     #  @return True if succeed else False
3098     #  @ingroup l2_modif_changori
3099     def ReorientObject(self, theObject):
3100         if ( isinstance( theObject, Mesh )):
3101             theObject = theObject.GetMesh()
3102         return self.editor.ReorientObject(theObject)
3103
3104     ## Reorient faces contained in \a the2DObject.
3105     #  @param the2DObject is a mesh, sub-mesh, group or list of IDs of 2D elements
3106     #  @param theDirection is a desired direction of normal of \a theFace.
3107     #         It can be either a GEOM vector or a list of coordinates [x,y,z].
3108     #  @param theFaceOrPoint defines a face of \a the2DObject whose normal will be
3109     #         compared with theDirection. It can be either ID of face or a point
3110     #         by which the face will be found. The point can be given as either
3111     #         a GEOM vertex or a list of point coordinates.
3112     #  @return number of reoriented faces
3113     #  @ingroup l2_modif_changori
3114     def Reorient2D(self, the2DObject, theDirection, theFaceOrPoint ):
3115         unRegister = genObjUnRegister()
3116         # check the2DObject
3117         if isinstance( the2DObject, Mesh ):
3118             the2DObject = the2DObject.GetMesh()
3119         if isinstance( the2DObject, list ):
3120             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3121             unRegister.set( the2DObject )
3122         # check theDirection
3123         if isinstance( theDirection, geomBuilder.GEOM._objref_GEOM_Object):
3124             theDirection = self.smeshpyD.GetDirStruct( theDirection )
3125         if isinstance( theDirection, list ):
3126             theDirection = self.smeshpyD.MakeDirStruct( *theDirection  )
3127         # prepare theFace and thePoint
3128         theFace = theFaceOrPoint
3129         thePoint = PointStruct(0,0,0)
3130         if isinstance( theFaceOrPoint, geomBuilder.GEOM._objref_GEOM_Object):
3131             thePoint = self.smeshpyD.GetPointStruct( theFaceOrPoint )
3132             theFace = -1
3133         if isinstance( theFaceOrPoint, list ):
3134             thePoint = PointStruct( *theFaceOrPoint )
3135             theFace = -1
3136         if isinstance( theFaceOrPoint, PointStruct ):
3137             thePoint = theFaceOrPoint
3138             theFace = -1
3139         return self.editor.Reorient2D( the2DObject, theDirection, theFace, thePoint )
3140
3141     ## Reorient faces according to adjacent volumes.
3142     #  @param the2DObject is a mesh, sub-mesh, group or list of
3143     #         either IDs of faces or face groups.
3144     #  @param the3DObject is a mesh, sub-mesh, group or list of IDs of volumes.
3145     #  @param theOutsideNormal to orient faces to have their normals
3146     #         pointing either \a outside or \a inside the adjacent volumes.
3147     #  @return number of reoriented faces.
3148     #  @ingroup l2_modif_changori
3149     def Reorient2DBy3D(self, the2DObject, the3DObject, theOutsideNormal=True ):
3150         unRegister = genObjUnRegister()
3151         # check the2DObject
3152         if not isinstance( the2DObject, list ):
3153             the2DObject = [ the2DObject ]
3154         elif the2DObject and isinstance( the2DObject[0], int ):
3155             the2DObject = self.GetIDSource( the2DObject, SMESH.FACE )
3156             unRegister.set( the2DObject )
3157             the2DObject = [ the2DObject ]
3158         for i,obj2D in enumerate( the2DObject ):
3159             if isinstance( obj2D, Mesh ):
3160                 the2DObject[i] = obj2D.GetMesh()
3161             if isinstance( obj2D, list ):
3162                 the2DObject[i] = self.GetIDSource( obj2D, SMESH.FACE )
3163                 unRegister.set( the2DObject[i] )
3164         # check the3DObject
3165         if isinstance( the3DObject, Mesh ):
3166             the3DObject = the3DObject.GetMesh()
3167         if isinstance( the3DObject, list ):
3168             the3DObject = self.GetIDSource( the3DObject, SMESH.VOLUME )
3169             unRegister.set( the3DObject )
3170         return self.editor.Reorient2DBy3D( the2DObject, the3DObject, theOutsideNormal )
3171
3172     ## Fuses the neighbouring triangles into quadrangles.
3173     #  @param IDsOfElements The triangles to be fused.
3174     #  @param theCriterion  a numerical functor, in terms of enum SMESH.FunctorType, used to
3175     #          choose a neighbour to fuse with.
3176     #          Type SMESH.FunctorType._items in the Python Console to see all items.
3177     #          Note that not all items corresponds to numerical functors.
3178     #  @param MaxAngle      is the maximum angle between element normals at which the fusion
3179     #          is still performed; theMaxAngle is mesured in radians.
3180     #          Also it could be a name of variable which defines angle in degrees.
3181     #  @return TRUE in case of success, FALSE otherwise.
3182     #  @ingroup l2_modif_unitetri
3183     def TriToQuad(self, IDsOfElements, theCriterion, MaxAngle):
3184         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3185         self.mesh.SetParameters(Parameters)
3186         if not IDsOfElements:
3187             IDsOfElements = self.GetElementsId()
3188         Functor = self.smeshpyD.GetFunctor(theCriterion)
3189         return self.editor.TriToQuad(IDsOfElements, Functor, MaxAngle)
3190
3191     ## Fuses the neighbouring triangles of the object into quadrangles
3192     #  @param theObject is mesh, submesh or group
3193     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3194     #          choose a neighbour to fuse with.
3195     #          Type SMESH.FunctorType._items in the Python Console to see all items.
3196     #          Note that not all items corresponds to numerical functors.
3197     #  @param MaxAngle   a max angle between element normals at which the fusion
3198     #          is still performed; theMaxAngle is mesured in radians.
3199     #  @return TRUE in case of success, FALSE otherwise.
3200     #  @ingroup l2_modif_unitetri
3201     def TriToQuadObject (self, theObject, theCriterion, MaxAngle):
3202         MaxAngle,Parameters,hasVars = ParseAngles(MaxAngle)
3203         self.mesh.SetParameters(Parameters)
3204         if isinstance( theObject, Mesh ):
3205             theObject = theObject.GetMesh()
3206         Functor = self.smeshpyD.GetFunctor(theCriterion)
3207         return self.editor.TriToQuadObject(theObject, Functor, MaxAngle)
3208
3209     ## Splits quadrangles into triangles.
3210     #  @param IDsOfElements the faces to be splitted.
3211     #  @param theCriterion   is a numerical functor, in terms of enum SMESH.FunctorType, used to
3212     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3213     #         value, then quadrangles will be split by the smallest diagonal.
3214     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3215     #         Note that not all items corresponds to numerical functors.
3216     #  @return TRUE in case of success, FALSE otherwise.
3217     #  @ingroup l2_modif_cutquadr
3218     def QuadToTri (self, IDsOfElements, theCriterion = None):
3219         if IDsOfElements == []:
3220             IDsOfElements = self.GetElementsId()
3221         if theCriterion is None:
3222             theCriterion = FT_MaxElementLength2D
3223         Functor = self.smeshpyD.GetFunctor(theCriterion)
3224         return self.editor.QuadToTri(IDsOfElements, Functor)
3225
3226     ## Splits quadrangles into triangles.
3227     #  @param theObject the object from which the list of elements is taken,
3228     #         this is mesh, submesh or group
3229     #  @param theCriterion is a numerical functor, in terms of enum SMESH.FunctorType, used to
3230     #         choose a diagonal for splitting. If @a theCriterion is None, which is a default
3231     #         value, then quadrangles will be split by the smallest diagonal.
3232     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3233     #         Note that not all items corresponds to numerical functors.
3234     #  @return TRUE in case of success, FALSE otherwise.
3235     #  @ingroup l2_modif_cutquadr
3236     def QuadToTriObject (self, theObject, theCriterion = None):
3237         if ( isinstance( theObject, Mesh )):
3238             theObject = theObject.GetMesh()
3239         if theCriterion is None:
3240             theCriterion = FT_MaxElementLength2D
3241         Functor = self.smeshpyD.GetFunctor(theCriterion)
3242         return self.editor.QuadToTriObject(theObject, Functor)
3243
3244     ## Splits each of given quadrangles into 4 triangles. A node is added at the center of
3245     #  a quadrangle.
3246     #  @param theElements the faces to be splitted. This can be either mesh, sub-mesh,
3247     #         group or a list of face IDs. By default all quadrangles are split
3248     #  @ingroup l2_modif_cutquadr
3249     def QuadTo4Tri (self, theElements=[]):
3250         unRegister = genObjUnRegister()
3251         if isinstance( theElements, Mesh ):
3252             theElements = theElements.mesh
3253         elif not theElements:
3254             theElements = self.mesh
3255         elif isinstance( theElements, list ):
3256             theElements = self.GetIDSource( theElements, SMESH.FACE )
3257             unRegister.set( theElements )
3258         return self.editor.QuadTo4Tri( theElements )
3259
3260     ## Splits quadrangles into triangles.
3261     #  @param IDsOfElements the faces to be splitted
3262     #  @param Diag13        is used to choose a diagonal for splitting.
3263     #  @return TRUE in case of success, FALSE otherwise.
3264     #  @ingroup l2_modif_cutquadr
3265     def SplitQuad (self, IDsOfElements, Diag13):
3266         if IDsOfElements == []:
3267             IDsOfElements = self.GetElementsId()
3268         return self.editor.SplitQuad(IDsOfElements, Diag13)
3269
3270     ## Splits quadrangles into triangles.
3271     #  @param theObject the object from which the list of elements is taken,
3272     #         this is mesh, submesh or group
3273     #  @param Diag13    is used to choose a diagonal for splitting.
3274     #  @return TRUE in case of success, FALSE otherwise.
3275     #  @ingroup l2_modif_cutquadr
3276     def SplitQuadObject (self, theObject, Diag13):
3277         if ( isinstance( theObject, Mesh )):
3278             theObject = theObject.GetMesh()
3279         return self.editor.SplitQuadObject(theObject, Diag13)
3280
3281     ## Finds a better splitting of the given quadrangle.
3282     #  @param IDOfQuad   the ID of the quadrangle to be splitted.
3283     #  @param theCriterion  is a numerical functor, in terms of enum SMESH.FunctorType, used to
3284     #         choose a diagonal for splitting.
3285     #         Type SMESH.FunctorType._items in the Python Console to see all items.
3286     #         Note that not all items corresponds to numerical functors.
3287     #  @return 1 if 1-3 diagonal is better, 2 if 2-4
3288     #          diagonal is better, 0 if error occurs.
3289     #  @ingroup l2_modif_cutquadr
3290     def BestSplit (self, IDOfQuad, theCriterion):
3291         return self.editor.BestSplit(IDOfQuad, self.smeshpyD.GetFunctor(theCriterion))
3292
3293     ## Splits volumic elements into tetrahedrons
3294     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3295     #  @param method  flags passing splitting method:
3296     #         smesh.Hex_5Tet, smesh.Hex_6Tet, smesh.Hex_24Tet.
3297     #         smesh.Hex_5Tet - to split the hexahedron into 5 tetrahedrons, etc.
3298     #  @ingroup l2_modif_cutquadr
3299     def SplitVolumesIntoTetra(self, elems, method=smeshBuilder.Hex_5Tet ):
3300         unRegister = genObjUnRegister()
3301         if isinstance( elems, Mesh ):
3302             elems = elems.GetMesh()
3303         if ( isinstance( elems, list )):
3304             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3305             unRegister.set( elems )
3306         self.editor.SplitVolumesIntoTetra(elems, method)
3307         return
3308
3309     ## Split bi-quadratic elements into linear ones without creation of additional nodes:
3310     #   - bi-quadratic triangle will be split into 3 linear quadrangles;
3311     #   - bi-quadratic quadrangle will be split into 4 linear quadrangles;
3312     #   - tri-quadratic hexahedron will be split into 8 linear hexahedra.
3313     #   Quadratic elements of lower dimension  adjacent to the split bi-quadratic element
3314     #   will be split in order to keep the mesh conformal.
3315     #  @param elems - elements to split: sub-meshes, groups, filters or element IDs;
3316     #         if None (default), all bi-quadratic elements will be split
3317     #  @ingroup l2_modif_cutquadr
3318     def SplitBiQuadraticIntoLinear(self, elems=None):
3319         unRegister = genObjUnRegister()
3320         if elems and isinstance( elems, list ) and isinstance( elems[0], int ):
3321             elems = self.editor.MakeIDSource(elems, SMESH.ALL)
3322             unRegister.set( elems )
3323         if elems is None:
3324             elems = [ self.GetMesh() ]
3325         if isinstance( elems, Mesh ):
3326             elems = [ elems.GetMesh() ]
3327         if not isinstance( elems, list ):
3328             elems = [elems]
3329         self.editor.SplitBiQuadraticIntoLinear( elems )
3330
3331     ## Splits hexahedra into prisms
3332     #  @param elems either a list of elements or a mesh or a group or a submesh or a filter
3333     #  @param startHexPoint a point used to find a hexahedron for which @a facetNormal
3334     #         gives a normal vector defining facets to split into triangles.
3335     #         @a startHexPoint can be either a triple of coordinates or a vertex.
3336     #  @param facetNormal a normal to a facet to split into triangles of a
3337     #         hexahedron found by @a startHexPoint.
3338     #         @a facetNormal can be either a triple of coordinates or an edge.
3339     #  @param method  flags passing splitting method: smesh.Hex_2Prisms, smesh.Hex_4Prisms.
3340     #         smesh.Hex_2Prisms - to split the hexahedron into 2 prisms, etc.
3341     #  @param allDomains if @c False, only hexahedra adjacent to one closest
3342     #         to @a startHexPoint are split, else @a startHexPoint
3343     #         is used to find the facet to split in all domains present in @a elems.
3344     #  @ingroup l2_modif_cutquadr
3345     def SplitHexahedraIntoPrisms(self, elems, startHexPoint, facetNormal,
3346                                  method=smeshBuilder.Hex_2Prisms, allDomains=False ):
3347         # IDSource
3348         unRegister = genObjUnRegister()
3349         if isinstance( elems, Mesh ):
3350             elems = elems.GetMesh()
3351         if ( isinstance( elems, list )):
3352             elems = self.editor.MakeIDSource(elems, SMESH.VOLUME)
3353             unRegister.set( elems )
3354             pass
3355         # axis
3356         if isinstance( startHexPoint, geomBuilder.GEOM._objref_GEOM_Object):
3357             startHexPoint = self.smeshpyD.GetPointStruct( startHexPoint )
3358         elif isinstance( startHexPoint, list ):
3359             startHexPoint = SMESH.PointStruct( startHexPoint[0],
3360                                                startHexPoint[1],
3361                                                startHexPoint[2])
3362         if isinstance( facetNormal, geomBuilder.GEOM._objref_GEOM_Object):
3363             facetNormal = self.smeshpyD.GetDirStruct( facetNormal )
3364         elif isinstance( facetNormal, list ):
3365             facetNormal = self.smeshpyD.MakeDirStruct( facetNormal[0],
3366                                                        facetNormal[1],
3367                                                        facetNormal[2])
3368         self.mesh.SetParameters( startHexPoint.parameters + facetNormal.PS.parameters )
3369
3370         self.editor.SplitHexahedraIntoPrisms(elems, startHexPoint, facetNormal, method, allDomains)
3371
3372     ## Splits quadrangle faces near triangular facets of volumes
3373     #
3374     #  @ingroup l1_auxiliary
3375     def SplitQuadsNearTriangularFacets(self):
3376         faces_array = self.GetElementsByType(SMESH.FACE)
3377         for face_id in faces_array:
3378             if self.GetElemNbNodes(face_id) == 4: # quadrangle
3379                 quad_nodes = self.mesh.GetElemNodes(face_id)
3380                 node1_elems = self.GetNodeInverseElements(quad_nodes[1 -1])
3381                 isVolumeFound = False
3382                 for node1_elem in node1_elems:
3383                     if not isVolumeFound:
3384                         if self.GetElementType(node1_elem, True) == SMESH.VOLUME:
3385                             nb_nodes = self.GetElemNbNodes(node1_elem)
3386                             if 3 < nb_nodes and nb_nodes < 7: # tetra or penta, or prism
3387                                 volume_elem = node1_elem
3388                                 volume_nodes = self.mesh.GetElemNodes(volume_elem)
3389                                 if volume_nodes.count(quad_nodes[2 -1]) > 0: # 1,2
3390                                     if volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,2,4
3391                                         isVolumeFound = True
3392                                         if volume_nodes.count(quad_nodes[3 -1]) == 0: # 1,2,4 & !3
3393                                             self.SplitQuad([face_id], False) # diagonal 2-4
3394                                     elif volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,2,3 & !4
3395                                         isVolumeFound = True
3396                                         self.SplitQuad([face_id], True) # diagonal 1-3
3397                                 elif volume_nodes.count(quad_nodes[4 -1]) > 0: # 1,4 & !2
3398                                     if volume_nodes.count(quad_nodes[3 -1]) > 0: # 1,4,3 & !2
3399                                         isVolumeFound = True
3400                                         self.SplitQuad([face_id], True) # diagonal 1-3
3401
3402     ## @brief Splits hexahedrons into tetrahedrons.
3403     #
3404     #  This operation uses pattern mapping functionality for splitting.
3405     #  @param theObject the object from which the list of hexahedrons is taken; this is mesh, submesh or group.
3406     #  @param theNode000,theNode001 within the range [0,7]; gives the orientation of the
3407     #         pattern relatively each hexahedron: the (0,0,0) key-point of the pattern
3408     #         will be mapped into <VAR>theNode000</VAR>-th node of each volume, the (0,0,1)
3409     #         key-point will be mapped into <VAR>theNode001</VAR>-th node of each volume.
3410     #         The (0,0,0) key-point of the used pattern corresponds to a non-split corner.
3411     #  @return TRUE in case of success, FALSE otherwise.
3412     #  @ingroup l1_auxiliary
3413     def SplitHexaToTetras (self, theObject, theNode000, theNode001):
3414         # Pattern:     5.---------.6
3415         #              /|#*      /|
3416         #             / | #*    / |
3417         #            /  |  # * /  |
3418         #           /   |   # /*  |
3419         # (0,0,1) 4.---------.7 * |
3420         #          |#*  |1   | # *|
3421         #          | # *.----|---#.2
3422         #          |  #/ *   |   /
3423         #          |  /#  *  |  /
3424         #          | /   # * | /
3425         #          |/      #*|/
3426         # (0,0,0) 0.---------.3
3427         pattern_tetra = "!!! Nb of points: \n 8 \n\
3428         !!! Points: \n\
3429         0 0 0  !- 0 \n\
3430         0 1 0  !- 1 \n\
3431         1 1 0  !- 2 \n\
3432         1 0 0  !- 3 \n\
3433         0 0 1  !- 4 \n\
3434         0 1 1  !- 5 \n\
3435         1 1 1  !- 6 \n\
3436         1 0 1  !- 7 \n\
3437         !!! Indices of points of 6 tetras: \n\
3438         0 3 4 1 \n\
3439         7 4 3 1 \n\
3440         4 7 5 1 \n\
3441         6 2 5 7 \n\
3442         1 5 2 7 \n\
3443         2 3 1 7 \n"
3444
3445         pattern = self.smeshpyD.GetPattern()
3446         isDone  = pattern.LoadFromFile(pattern_tetra)
3447         if not isDone:
3448             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3449             return isDone
3450
3451         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3452         isDone = pattern.MakeMesh(self.mesh, False, False)
3453         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3454
3455         # split quafrangle faces near triangular facets of volumes
3456         self.SplitQuadsNearTriangularFacets()
3457
3458         return isDone
3459
3460     ## @brief Split hexahedrons into prisms.
3461     #
3462     #  Uses the pattern mapping functionality for splitting.
3463     #  @param theObject the object (mesh, submesh or group) from where the list of hexahedrons is taken;
3464     #  @param theNode000,theNode001 (within the range [0,7]) gives the orientation of the
3465     #         pattern relatively each hexahedron: keypoint (0,0,0) of the pattern
3466     #         will be mapped into the <VAR>theNode000</VAR>-th node of each volume, keypoint (0,0,1)
3467     #         will be mapped into the <VAR>theNode001</VAR>-th node of each volume.
3468     #         Edge (0,0,0)-(0,0,1) of used pattern connects two not split corners.
3469     #  @return TRUE in case of success, FALSE otherwise.
3470     #  @ingroup l1_auxiliary
3471     def SplitHexaToPrisms (self, theObject, theNode000, theNode001):
3472         # Pattern:     5.---------.6
3473         #              /|#       /|
3474         #             / | #     / |
3475         #            /  |  #   /  |
3476         #           /   |   # /   |
3477         # (0,0,1) 4.---------.7   |
3478         #          |    |    |    |
3479         #          |   1.----|----.2
3480         #          |   / *   |   /
3481         #          |  /   *  |  /
3482         #          | /     * | /
3483         #          |/       *|/
3484         # (0,0,0) 0.---------.3
3485         pattern_prism = "!!! Nb of points: \n 8 \n\
3486         !!! Points: \n\
3487         0 0 0  !- 0 \n\
3488         0 1 0  !- 1 \n\
3489         1 1 0  !- 2 \n\
3490         1 0 0  !- 3 \n\
3491         0 0 1  !- 4 \n\
3492         0 1 1  !- 5 \n\
3493         1 1 1  !- 6 \n\
3494         1 0 1  !- 7 \n\
3495         !!! Indices of points of 2 prisms: \n\
3496         0 1 3 4 5 7 \n\
3497         2 3 1 6 7 5 \n"
3498
3499         pattern = self.smeshpyD.GetPattern()
3500         isDone  = pattern.LoadFromFile(pattern_prism)
3501         if not isDone:
3502             print 'Pattern.LoadFromFile :', pattern.GetErrorCode()
3503             return isDone
3504
3505         pattern.ApplyToHexahedrons(self.mesh, theObject.GetIDs(), theNode000, theNode001)
3506         isDone = pattern.MakeMesh(self.mesh, False, False)
3507         if not isDone: print 'Pattern.MakeMesh :', pattern.GetErrorCode()
3508
3509         # Splits quafrangle faces near triangular facets of volumes
3510         self.SplitQuadsNearTriangularFacets()
3511
3512         return isDone
3513
3514     ## Smoothes elements
3515     #  @param IDsOfElements the list if ids of elements to smooth
3516     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3517     #  Note that nodes built on edges and boundary nodes are always fixed.
3518     #  @param MaxNbOfIterations the maximum number of iterations
3519     #  @param MaxAspectRatio varies in range [1.0, inf]
3520     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3521     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3522     #  @return TRUE in case of success, FALSE otherwise.
3523     #  @ingroup l2_modif_smooth
3524     def Smooth(self, IDsOfElements, IDsOfFixedNodes,
3525                MaxNbOfIterations, MaxAspectRatio, Method):
3526         if IDsOfElements == []:
3527             IDsOfElements = self.GetElementsId()
3528         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3529         self.mesh.SetParameters(Parameters)
3530         return self.editor.Smooth(IDsOfElements, IDsOfFixedNodes,
3531                                   MaxNbOfIterations, MaxAspectRatio, Method)
3532
3533     ## Smoothes elements which belong to the given object
3534     #  @param theObject the object to smooth
3535     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3536     #  Note that nodes built on edges and boundary nodes are always fixed.
3537     #  @param MaxNbOfIterations the maximum number of iterations
3538     #  @param MaxAspectRatio varies in range [1.0, inf]
3539     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3540     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3541     #  @return TRUE in case of success, FALSE otherwise.
3542     #  @ingroup l2_modif_smooth
3543     def SmoothObject(self, theObject, IDsOfFixedNodes,
3544                      MaxNbOfIterations, MaxAspectRatio, Method):
3545         if ( isinstance( theObject, Mesh )):
3546             theObject = theObject.GetMesh()
3547         return self.editor.SmoothObject(theObject, IDsOfFixedNodes,
3548                                         MaxNbOfIterations, MaxAspectRatio, Method)
3549
3550     ## Parametrically smoothes the given elements
3551     #  @param IDsOfElements the list if ids of elements to smooth
3552     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3553     #  Note that nodes built on edges and boundary nodes are always fixed.
3554     #  @param MaxNbOfIterations the maximum number of iterations
3555     #  @param MaxAspectRatio varies in range [1.0, inf]
3556     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3557     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3558     #  @return TRUE in case of success, FALSE otherwise.
3559     #  @ingroup l2_modif_smooth
3560     def SmoothParametric(self, IDsOfElements, IDsOfFixedNodes,
3561                          MaxNbOfIterations, MaxAspectRatio, Method):
3562         if IDsOfElements == []:
3563             IDsOfElements = self.GetElementsId()
3564         MaxNbOfIterations,MaxAspectRatio,Parameters,hasVars = ParseParameters(MaxNbOfIterations,MaxAspectRatio)
3565         self.mesh.SetParameters(Parameters)
3566         return self.editor.SmoothParametric(IDsOfElements, IDsOfFixedNodes,
3567                                             MaxNbOfIterations, MaxAspectRatio, Method)
3568
3569     ## Parametrically smoothes the elements which belong to the given object
3570     #  @param theObject the object to smooth
3571     #  @param IDsOfFixedNodes the list of ids of fixed nodes.
3572     #  Note that nodes built on edges and boundary nodes are always fixed.
3573     #  @param MaxNbOfIterations the maximum number of iterations
3574     #  @param MaxAspectRatio varies in range [1.0, inf]
3575     #  @param Method is either Laplacian (smesh.LAPLACIAN_SMOOTH)
3576     #         or Centroidal (smesh.CENTROIDAL_SMOOTH)
3577     #  @return TRUE in case of success, FALSE otherwise.
3578     #  @ingroup l2_modif_smooth
3579     def SmoothParametricObject(self, theObject, IDsOfFixedNodes,
3580                                MaxNbOfIterations, MaxAspectRatio, Method):
3581         if ( isinstance( theObject, Mesh )):
3582             theObject = theObject.GetMesh()
3583         return self.editor.SmoothParametricObject(theObject, IDsOfFixedNodes,
3584                                                   MaxNbOfIterations, MaxAspectRatio, Method)
3585
3586     ## Converts the mesh to quadratic or bi-quadratic, deletes old elements, replacing
3587     #  them with quadratic with the same id.
3588     #  @param theForce3d new node creation method:
3589     #         0 - the medium node lies at the geometrical entity from which the mesh element is built
3590     #         1 - the medium node lies at the middle of the line segments connecting two nodes of a mesh element
3591     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3592     #  @param theToBiQuad If True, converts the mesh to bi-quadratic
3593     #  @ingroup l2_modif_tofromqu
3594     def ConvertToQuadratic(self, theForce3d=False, theSubMesh=None, theToBiQuad=False):
3595         if isinstance( theSubMesh, Mesh ):
3596             theSubMesh = theSubMesh.mesh
3597         if theToBiQuad:
3598             self.editor.ConvertToBiQuadratic(theForce3d,theSubMesh)
3599         else:
3600             if theSubMesh:
3601                 self.editor.ConvertToQuadraticObject(theForce3d,theSubMesh)
3602             else:
3603                 self.editor.ConvertToQuadratic(theForce3d)
3604         error = self.editor.GetLastError()
3605         if error and error.comment:
3606             print error.comment
3607             
3608     ## Converts the mesh from quadratic to ordinary,
3609     #  deletes old quadratic elements, \n replacing
3610     #  them with ordinary mesh elements with the same id.
3611     #  @param theSubMesh a group or a sub-mesh to convert; WARNING: in this case the mesh can become not conformal
3612     #  @ingroup l2_modif_tofromqu
3613     def ConvertFromQuadratic(self, theSubMesh=None):
3614         if theSubMesh:
3615             self.editor.ConvertFromQuadraticObject(theSubMesh)
3616         else:
3617             return self.editor.ConvertFromQuadratic()
3618
3619     ## Creates 2D mesh as skin on boundary faces of a 3D mesh
3620     #  @return TRUE if operation has been completed successfully, FALSE otherwise
3621     #  @ingroup l2_modif_edit
3622     def  Make2DMeshFrom3D(self):
3623         return self.editor. Make2DMeshFrom3D()
3624
3625     ## Creates missing boundary elements
3626     #  @param elements - elements whose boundary is to be checked:
3627     #                    mesh, group, sub-mesh or list of elements
3628     #   if elements is mesh, it must be the mesh whose MakeBoundaryMesh() is called
3629     #  @param dimension - defines type of boundary elements to create, either of
3630     #                     { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3631     #    SMESH.BND_1DFROM3D creates mesh edges on all borders of free facets of 3D cells
3632     #  @param groupName - a name of group to store created boundary elements in,
3633     #                     "" means not to create the group
3634     #  @param meshName - a name of new mesh to store created boundary elements in,
3635     #                     "" means not to create the new mesh
3636     #  @param toCopyElements - if true, the checked elements will be copied into
3637     #     the new mesh else only boundary elements will be copied into the new mesh
3638     #  @param toCopyExistingBondary - if true, not only new but also pre-existing
3639     #     boundary elements will be copied into the new mesh
3640     #  @return tuple (mesh, group) where boundary elements were added to
3641     #  @ingroup l2_modif_edit
3642     def MakeBoundaryMesh(self, elements, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3643                          toCopyElements=False, toCopyExistingBondary=False):
3644         unRegister = genObjUnRegister()
3645         if isinstance( elements, Mesh ):
3646             elements = elements.GetMesh()
3647         if ( isinstance( elements, list )):
3648             elemType = SMESH.ALL
3649             if elements: elemType = self.GetElementType( elements[0], iselem=True)
3650             elements = self.editor.MakeIDSource(elements, elemType)
3651             unRegister.set( elements )
3652         mesh, group = self.editor.MakeBoundaryMesh(elements,dimension,groupName,meshName,
3653                                                    toCopyElements,toCopyExistingBondary)
3654         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3655         return mesh, group
3656
3657     ##
3658     # @brief Creates missing boundary elements around either the whole mesh or 
3659     #    groups of elements
3660     #  @param dimension - defines type of boundary elements to create, either of
3661     #                     { SMESH.BND_2DFROM3D, SMESH.BND_1DFROM3D, SMESH.BND_1DFROM2D }
3662     #  @param groupName - a name of group to store all boundary elements in,
3663     #    "" means not to create the group
3664     #  @param meshName - a name of a new mesh, which is a copy of the initial 
3665     #    mesh + created boundary elements; "" means not to create the new mesh
3666     #  @param toCopyAll - if true, the whole initial mesh will be copied into
3667     #    the new mesh else only boundary elements will be copied into the new mesh
3668     #  @param groups - groups of elements to make boundary around
3669     #  @retval tuple( long, mesh, groups )
3670     #                 long - number of added boundary elements
3671     #                 mesh - the mesh where elements were added to
3672     #                 group - the group of boundary elements or None
3673     #
3674     def MakeBoundaryElements(self, dimension=SMESH.BND_2DFROM3D, groupName="", meshName="",
3675                              toCopyAll=False, groups=[]):
3676         nb, mesh, group = self.editor.MakeBoundaryElements(dimension,groupName,meshName,
3677                                                            toCopyAll,groups)
3678         if mesh: mesh = self.smeshpyD.Mesh(mesh)
3679         return nb, mesh, group
3680
3681     ## Renumber mesh nodes (Obsolete, does nothing)
3682     #  @ingroup l2_modif_renumber
3683     def RenumberNodes(self):
3684         self.editor.RenumberNodes()
3685
3686     ## Renumber mesh elements (Obsole, does nothing)
3687     #  @ingroup l2_modif_renumber
3688     def RenumberElements(self):
3689         self.editor.RenumberElements()
3690
3691     ## Private method converting \a arg into a list of SMESH_IdSource's
3692     def _getIdSourceList(self, arg, idType, unRegister):
3693         if arg and isinstance( arg, list ):
3694             if isinstance( arg[0], int ):
3695                 arg = self.GetIDSource( arg, idType )
3696                 unRegister.set( arg )
3697             elif isinstance( arg[0], Mesh ):
3698                 arg[0] = arg[0].GetMesh()
3699         elif isinstance( arg, Mesh ):
3700             arg = arg.GetMesh()
3701         if arg and isinstance( arg, SMESH._objref_SMESH_IDSource ):
3702             arg = [arg]
3703         return arg
3704
3705     ## Generates new elements by rotation of the given elements and nodes around the axis
3706     #  @param nodes - nodes to revolve: a list including ids, groups, sub-meshes or a mesh
3707     #  @param edges - edges to revolve: a list including ids, groups, sub-meshes or a mesh
3708     #  @param faces - faces to revolve: a list including ids, groups, sub-meshes or a mesh
3709     #  @param Axis the axis of rotation: AxisStruct, line (geom object) or [x,y,z,dx,dy,dz]
3710     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable
3711     #         which defines angle in degrees
3712     #  @param NbOfSteps the number of steps
3713     #  @param Tolerance tolerance
3714     #  @param MakeGroups forces the generation of new groups from existing ones
3715     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3716     #                    of all steps, else - size of each step
3717     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3718     #  @ingroup l2_modif_extrurev
3719     def RotationSweepObjects(self, nodes, edges, faces, Axis, AngleInRadians, NbOfSteps, Tolerance,
3720                              MakeGroups=False, TotalAngle=False):
3721         unRegister = genObjUnRegister()
3722         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3723         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3724         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3725
3726         if isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object):
3727             Axis = self.smeshpyD.GetAxisStruct( Axis )
3728         if isinstance( Axis, list ):
3729             Axis = SMESH.AxisStruct( *Axis )
3730
3731         AngleInRadians,AngleParameters,hasVars = ParseAngles(AngleInRadians)
3732         NbOfSteps,Tolerance,Parameters,hasVars = ParseParameters(NbOfSteps,Tolerance)
3733         Parameters = Axis.parameters + var_separator + AngleParameters + var_separator + Parameters
3734         self.mesh.SetParameters(Parameters)
3735         if TotalAngle and NbOfSteps:
3736             AngleInRadians /= NbOfSteps
3737         return self.editor.RotationSweepObjects( nodes, edges, faces,
3738                                                  Axis, AngleInRadians,
3739                                                  NbOfSteps, Tolerance, MakeGroups)
3740
3741     ## Generates new elements by rotation of the elements around the axis
3742     #  @param IDsOfElements the list of ids of elements to sweep
3743     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3744     #  @param AngleInRadians the angle of Rotation (in radians) or a name of variable which defines angle in degrees
3745     #  @param NbOfSteps the number of steps
3746     #  @param Tolerance tolerance
3747     #  @param MakeGroups forces the generation of new groups from existing ones
3748     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3749     #                    of all steps, else - size of each step
3750     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3751     #  @ingroup l2_modif_extrurev
3752     def RotationSweep(self, IDsOfElements, Axis, AngleInRadians, NbOfSteps, Tolerance,
3753                       MakeGroups=False, TotalAngle=False):
3754         return self.RotationSweepObjects([], IDsOfElements, IDsOfElements, Axis,
3755                                          AngleInRadians, NbOfSteps, Tolerance,
3756                                          MakeGroups, TotalAngle)
3757
3758     ## Generates new elements by rotation of the elements of object around the axis
3759     #  @param theObject object which elements should be sweeped.
3760     #                   It can be a mesh, a sub mesh or a group.
3761     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3762     #  @param AngleInRadians the angle of Rotation
3763     #  @param NbOfSteps number of steps
3764     #  @param Tolerance tolerance
3765     #  @param MakeGroups forces the generation of new groups from existing ones
3766     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3767     #                    of all steps, else - size of each step
3768     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3769     #  @ingroup l2_modif_extrurev
3770     def RotationSweepObject(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3771                             MakeGroups=False, TotalAngle=False):
3772         return self.RotationSweepObjects( [], theObject, theObject, Axis,
3773                                           AngleInRadians, NbOfSteps, Tolerance,
3774                                           MakeGroups, TotalAngle )
3775
3776     ## Generates new elements by rotation of the elements of object around the axis
3777     #  @param theObject object which elements should be sweeped.
3778     #                   It can be a mesh, a sub mesh or a group.
3779     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3780     #  @param AngleInRadians the angle of Rotation
3781     #  @param NbOfSteps number of steps
3782     #  @param Tolerance tolerance
3783     #  @param MakeGroups forces the generation of new groups from existing ones
3784     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3785     #                    of all steps, else - size of each step
3786     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3787     #  @ingroup l2_modif_extrurev
3788     def RotationSweepObject1D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3789                               MakeGroups=False, TotalAngle=False):
3790         return self.RotationSweepObjects([],theObject,[], Axis,
3791                                          AngleInRadians, NbOfSteps, Tolerance,
3792                                          MakeGroups, TotalAngle)
3793
3794     ## Generates new elements by rotation of the elements of object around the axis
3795     #  @param theObject object which elements should be sweeped.
3796     #                   It can be a mesh, a sub mesh or a group.
3797     #  @param Axis the axis of rotation, AxisStruct or line(geom object)
3798     #  @param AngleInRadians the angle of Rotation
3799     #  @param NbOfSteps number of steps
3800     #  @param Tolerance tolerance
3801     #  @param MakeGroups forces the generation of new groups from existing ones
3802     #  @param TotalAngle gives meaning of AngleInRadians: if True then it is an angular size
3803     #                    of all steps, else - size of each step
3804     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3805     #  @ingroup l2_modif_extrurev
3806     def RotationSweepObject2D(self, theObject, Axis, AngleInRadians, NbOfSteps, Tolerance,
3807                               MakeGroups=False, TotalAngle=False):
3808         return self.RotationSweepObjects([],[],theObject, Axis, AngleInRadians,
3809                                          NbOfSteps, Tolerance, MakeGroups, TotalAngle)
3810
3811     ## Generates new elements by extrusion of the given elements and nodes
3812     #  @param nodes - nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3813     #  @param edges - edges to extrude: a list including ids, groups, sub-meshes or a mesh
3814     #  @param faces - faces to extrude: a list including ids, groups, sub-meshes or a mesh
3815     #  @param StepVector vector or DirStruct or 3 vector components, defining
3816     #         the direction and value of extrusion for one step (the total extrusion
3817     #         length will be NbOfSteps * ||StepVector||)
3818     #  @param NbOfSteps the number of steps
3819     #  @param MakeGroups forces the generation of new groups from existing ones
3820     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3821     #  @ingroup l2_modif_extrurev
3822     def ExtrusionSweepObjects(self, nodes, edges, faces, StepVector, NbOfSteps, MakeGroups=False):
3823         unRegister = genObjUnRegister()
3824         nodes = self._getIdSourceList( nodes, SMESH.NODE, unRegister )
3825         edges = self._getIdSourceList( edges, SMESH.EDGE, unRegister )
3826         faces = self._getIdSourceList( faces, SMESH.FACE, unRegister )
3827
3828         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3829             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3830         if isinstance( StepVector, list ):
3831             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3832
3833         NbOfSteps,Parameters,hasVars = ParseParameters(NbOfSteps)
3834         Parameters = StepVector.PS.parameters + var_separator + Parameters
3835         self.mesh.SetParameters(Parameters)
3836
3837         return self.editor.ExtrusionSweepObjects( nodes, edges, faces,
3838                                                   StepVector, NbOfSteps, MakeGroups)
3839
3840
3841     ## Generates new elements by extrusion of the elements with given ids
3842     #  @param IDsOfElements the list of elements ids for extrusion
3843     #  @param StepVector vector or DirStruct or 3 vector components, defining
3844     #         the direction and value of extrusion for one step (the total extrusion
3845     #         length will be NbOfSteps * ||StepVector||)
3846     #  @param NbOfSteps the number of steps
3847     #  @param MakeGroups forces the generation of new groups from existing ones
3848     #  @param IsNodes is True if elements with given ids are nodes
3849     #  @return the list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3850     #  @ingroup l2_modif_extrurev
3851     def ExtrusionSweep(self, IDsOfElements, StepVector, NbOfSteps, MakeGroups=False, IsNodes = False):
3852         n,e,f = [],[],[]
3853         if IsNodes: n = IDsOfElements
3854         else      : e,f, = IDsOfElements,IDsOfElements
3855         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3856
3857     ## Generates new elements by extrusion along the normal to a discretized surface or wire
3858     #  @param Elements elements to extrude - a list including ids, groups, sub-meshes or a mesh
3859     #         Only faces can be extruded so far. Sub-mesh should be a sub-mesh on geom faces.
3860     #  @param StepSize length of one extrusion step (the total extrusion
3861     #         length will be \a NbOfSteps * \a StepSize ).
3862     #  @param NbOfSteps number of extrusion steps.
3863     #  @param ByAverageNormal if True each node is translated by \a StepSize
3864     #         along the average of the normal vectors to the faces sharing the node;
3865     #         else each node is translated along the same average normal till
3866     #         intersection with the plane got by translation of the face sharing
3867     #         the node along its own normal by \a StepSize.
3868     #  @param UseInputElemsOnly to use only \a Elements when computing extrusion direction
3869     #         for every node of \a Elements.
3870     #  @param MakeGroups forces generation of new groups from existing ones.
3871     #  @param Dim dimension of elements to extrude: 2 - faces or 1 - edges. Extrusion of edges
3872     #         is not yet implemented. This parameter is used if \a Elements contains
3873     #         both faces and edges, i.e. \a Elements is a Mesh.
3874     #  @return the list of created groups (SMESH_GroupBase) if \a MakeGroups=True,
3875     #          empty list otherwise.
3876     #  @ingroup l2_modif_extrurev
3877     def ExtrusionByNormal(self, Elements, StepSize, NbOfSteps,
3878                           ByAverageNormal=False, UseInputElemsOnly=True, MakeGroups=False, Dim = 2):
3879         unRegister = genObjUnRegister()
3880         if isinstance( Elements, Mesh ):
3881             Elements = [ Elements.GetMesh() ]
3882         if isinstance( Elements, list ):
3883             if not Elements:
3884                 raise RuntimeError, "Elements empty!"
3885             if isinstance( Elements[0], int ):
3886                 Elements = self.GetIDSource( Elements, SMESH.ALL )
3887                 unRegister.set( Elements )
3888         if not isinstance( Elements, list ):
3889             Elements = [ Elements ]
3890         StepSize,NbOfSteps,Parameters,hasVars = ParseParameters(StepSize,NbOfSteps)
3891         self.mesh.SetParameters(Parameters)
3892         return self.editor.ExtrusionByNormal(Elements, StepSize, NbOfSteps,
3893                                              ByAverageNormal, UseInputElemsOnly, MakeGroups, Dim)
3894
3895     ## Generates new elements by extrusion of the elements which belong to the object
3896     #  @param theObject the object which elements should be processed.
3897     #                   It can be a mesh, a sub mesh or a group.
3898     #  @param StepVector vector or DirStruct or 3 vector components, defining
3899     #         the direction and value of extrusion for one step (the total extrusion
3900     #         length will be NbOfSteps * ||StepVector||)
3901     #  @param NbOfSteps the number of steps
3902     #  @param MakeGroups forces the generation of new groups from existing ones
3903     #  @param  IsNodes is True if elements to extrude are nodes
3904     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3905     #  @ingroup l2_modif_extrurev
3906     def ExtrusionSweepObject(self, theObject, StepVector, NbOfSteps, MakeGroups=False, IsNodes=False):
3907         n,e,f = [],[],[]
3908         if IsNodes: n    = theObject
3909         else      : e,f, = theObject,theObject
3910         return self.ExtrusionSweepObjects(n,e,f, StepVector, NbOfSteps, MakeGroups)
3911
3912     ## Generates new elements by extrusion of the elements which belong to the object
3913     #  @param theObject object which elements should be processed.
3914     #                   It can be a mesh, a sub mesh or a group.
3915     #  @param StepVector vector or DirStruct or 3 vector components, defining
3916     #         the direction and value of extrusion for one step (the total extrusion
3917     #         length will be NbOfSteps * ||StepVector||)
3918     #  @param NbOfSteps the number of steps
3919     #  @param MakeGroups to generate new groups from existing ones
3920     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3921     #  @ingroup l2_modif_extrurev
3922     def ExtrusionSweepObject1D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3923         return self.ExtrusionSweepObjects([],theObject,[], StepVector, NbOfSteps, MakeGroups)
3924
3925     ## Generates new elements by extrusion of the elements which belong to the object
3926     #  @param theObject object which elements should be processed.
3927     #                   It can be a mesh, a sub mesh or a group.
3928     #  @param StepVector vector or DirStruct or 3 vector components, defining
3929     #         the direction and value of extrusion for one step (the total extrusion
3930     #         length will be NbOfSteps * ||StepVector||)
3931     #  @param NbOfSteps the number of steps
3932     #  @param MakeGroups forces the generation of new groups from existing ones
3933     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3934     #  @ingroup l2_modif_extrurev
3935     def ExtrusionSweepObject2D(self, theObject, StepVector, NbOfSteps, MakeGroups=False):
3936         return self.ExtrusionSweepObjects([],[],theObject, StepVector, NbOfSteps, MakeGroups)
3937
3938     ## Generates new elements by extrusion of the elements with given ids
3939     #  @param IDsOfElements is ids of elements
3940     #  @param StepVector vector or DirStruct or 3 vector components, defining
3941     #         the direction and value of extrusion for one step (the total extrusion
3942     #         length will be NbOfSteps * ||StepVector||)
3943     #  @param NbOfSteps the number of steps
3944     #  @param ExtrFlags sets flags for extrusion
3945     #  @param SewTolerance uses for comparing locations of nodes if flag
3946     #         EXTRUSION_FLAG_SEW is set
3947     #  @param MakeGroups forces the generation of new groups from existing ones
3948     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
3949     #  @ingroup l2_modif_extrurev
3950     def AdvancedExtrusion(self, IDsOfElements, StepVector, NbOfSteps,
3951                           ExtrFlags, SewTolerance, MakeGroups=False):
3952         if isinstance( StepVector, geomBuilder.GEOM._objref_GEOM_Object):
3953             StepVector = self.smeshpyD.GetDirStruct(StepVector)
3954         if isinstance( StepVector, list ):
3955             StepVector = self.smeshpyD.MakeDirStruct(*StepVector)
3956         return self.editor.AdvancedExtrusion(IDsOfElements, StepVector, NbOfSteps,
3957                                              ExtrFlags, SewTolerance, MakeGroups)
3958
3959     ## Generates new elements by extrusion of the given elements and nodes along the path.
3960     #  The path of extrusion must be a meshed edge.
3961     #  @param Nodes nodes to extrude: a list including ids, groups, sub-meshes or a mesh
3962     #  @param Edges edges to extrude: a list including ids, groups, sub-meshes or a mesh
3963     #  @param Faces faces to extrude: a list including ids, groups, sub-meshes or a mesh
3964     #  @param PathMesh 1D mesh or 1D sub-mesh, along which proceeds the extrusion
3965     #  @param PathShape shape (edge) defines the sub-mesh of PathMesh if PathMesh
3966     #         contains not only path segments, else it can be None
3967     #  @param NodeStart the first or the last node on the path. Defines the direction of extrusion
3968     #  @param HasAngles allows the shape to be rotated around the path
3969     #                   to get the resulting mesh in a helical fashion
3970     #  @param Angles list of angles
3971     #  @param LinearVariation forces the computation of rotation angles as linear
3972     #                         variation of the given Angles along path steps
3973     #  @param HasRefPoint allows using the reference point
3974     #  @param RefPoint the point around which the shape is rotated (the mass center of the
3975     #         shape by default). The User can specify any point as the Reference Point.
3976     #  @param MakeGroups forces the generation of new groups from existing ones
3977     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error
3978     #  @ingroup l2_modif_extrurev
3979     def ExtrusionAlongPathObjects(self, Nodes, Edges, Faces, PathMesh, PathShape=None,
3980                                   NodeStart=1, HasAngles=False, Angles=[], LinearVariation=False,
3981                                   HasRefPoint=False, RefPoint=[0,0,0], MakeGroups=False):
3982         unRegister = genObjUnRegister()
3983         Nodes = self._getIdSourceList( Nodes, SMESH.NODE, unRegister )
3984         Edges = self._getIdSourceList( Edges, SMESH.EDGE, unRegister )
3985         Faces = self._getIdSourceList( Faces, SMESH.FACE, unRegister )
3986
3987         if isinstance( RefPoint, geomBuilder.GEOM._objref_GEOM_Object):
3988             RefPoint = self.smeshpyD.GetPointStruct(RefPoint)
3989         if isinstance( RefPoint, list ):
3990             RefPoint = SMESH.PointStruct( *RefPoint )
3991         if isinstance( PathMesh, Mesh ):
3992             PathMesh = PathMesh.GetMesh()
3993         Angles,AnglesParameters,hasVars = ParseAngles(Angles)
3994         Parameters = AnglesParameters + var_separator + RefPoint.parameters
3995         self.mesh.SetParameters(Parameters)
3996         return self.editor.ExtrusionAlongPathObjects(Nodes, Edges, Faces,
3997                                                      PathMesh, PathShape, NodeStart,
3998                                                      HasAngles, Angles, LinearVariation,
3999                                                      HasRefPoint, RefPoint, MakeGroups)
4000
4001     ## Generates new elements by extrusion of the given elements
4002     #  The path of extrusion must be a meshed edge.
4003     #  @param Base mesh or group, or submesh, or list of ids of elements for extrusion
4004     #  @param Path - 1D mesh or 1D sub-mesh, along which proceeds the extrusion
4005     #  @param NodeStart the start node from Path. Defines the direction of extrusion
4006     #  @param HasAngles allows the shape to be rotated around the path
4007     #                   to get the resulting mesh in a helical fashion
4008     #  @param Angles list of angles in radians
4009     #  @param LinearVariation forces the computation of rotation angles as linear
4010     #                         variation of the given Angles along path steps
4011     #  @param HasRefPoint allows using the reference point
4012     #  @param RefPoint the point around which the elements are rotated (the mass
4013     #         center of the elements by default).
4014     #         The User can specify any point as the Reference Point.
4015     #         RefPoint can be either GEOM Vertex, [x,y,z] or SMESH.PointStruct
4016     #  @param MakeGroups forces the generation of new groups from existing ones
4017     #  @param ElemType type of elements for extrusion (if param Base is a mesh)
4018     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4019     #          only SMESH::Extrusion_Error otherwise
4020     #  @ingroup l2_modif_extrurev
4021     def ExtrusionAlongPathX(self, Base, Path, NodeStart,
4022                             HasAngles, Angles, LinearVariation,
4023                             HasRefPoint, RefPoint, MakeGroups, ElemType):
4024         n,e,f = [],[],[]
4025         if ElemType == SMESH.NODE: n = Base
4026         if ElemType == SMESH.EDGE: e = Base
4027         if ElemType == SMESH.FACE: f = Base
4028         gr,er = self.ExtrusionAlongPathObjects(n,e,f, Path, None, NodeStart,
4029                                                HasAngles, Angles, LinearVariation,
4030                                                HasRefPoint, RefPoint, MakeGroups)
4031         if MakeGroups: return gr,er
4032         return er
4033
4034     ## Generates new elements by extrusion of the given elements
4035     #  The path of extrusion must be a meshed edge.
4036     #  @param IDsOfElements ids of elements
4037     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which proceeds the extrusion
4038     #  @param PathShape shape(edge) defines the sub-mesh for the path
4039     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4040     #  @param HasAngles allows the shape to be rotated around the path
4041     #                   to get the resulting mesh in a helical fashion
4042     #  @param Angles list of angles in radians
4043     #  @param HasRefPoint allows using the reference point
4044     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4045     #         The User can specify any point as the Reference Point.
4046     #  @param MakeGroups forces the generation of new groups from existing ones
4047     #  @param LinearVariation forces the computation of rotation angles as linear
4048     #                         variation of the given Angles along path steps
4049     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4050     #          only SMESH::Extrusion_Error otherwise
4051     #  @ingroup l2_modif_extrurev
4052     def ExtrusionAlongPath(self, IDsOfElements, PathMesh, PathShape, NodeStart,
4053                            HasAngles, Angles, HasRefPoint, RefPoint,
4054                            MakeGroups=False, LinearVariation=False):
4055         n,e,f = [],IDsOfElements,IDsOfElements
4056         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape,
4057                                                NodeStart, HasAngles, Angles,
4058                                                LinearVariation,
4059                                                HasRefPoint, RefPoint, MakeGroups)
4060         if MakeGroups: return gr,er
4061         return er
4062
4063     ## Generates new elements by extrusion of the elements which belong to the object
4064     #  The path of extrusion must be a meshed edge.
4065     #  @param theObject the object which elements should be processed.
4066     #                   It can be a mesh, a sub-mesh or a group.
4067     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4068     #  @param PathShape shape(edge) defines the sub-mesh for the path
4069     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4070     #  @param HasAngles allows the shape to be rotated around the path
4071     #                   to get the resulting mesh in a helical fashion
4072     #  @param Angles list of angles
4073     #  @param HasRefPoint allows using the reference point
4074     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4075     #         The User can specify any point as the Reference Point.
4076     #  @param MakeGroups forces the generation of new groups from existing ones
4077     #  @param LinearVariation forces the computation of rotation angles as linear
4078     #                         variation of the given Angles along path steps
4079     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4080     #          only SMESH::Extrusion_Error otherwise
4081     #  @ingroup l2_modif_extrurev
4082     def ExtrusionAlongPathObject(self, theObject, PathMesh, PathShape, NodeStart,
4083                                  HasAngles, Angles, HasRefPoint, RefPoint,
4084                                  MakeGroups=False, LinearVariation=False):
4085         n,e,f = [],theObject,theObject
4086         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4087                                                HasAngles, Angles, LinearVariation,
4088                                                HasRefPoint, RefPoint, MakeGroups)
4089         if MakeGroups: return gr,er
4090         return er
4091
4092     ## Generates new elements by extrusion of the elements which belong to the object
4093     #  The path of extrusion must be a meshed edge.
4094     #  @param theObject the object which elements should be processed.
4095     #                   It can be a mesh, a sub mesh or a group.
4096     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4097     #  @param PathShape shape(edge) defines the sub-mesh for the path
4098     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4099     #  @param HasAngles allows the shape to be rotated around the path
4100     #                   to get the resulting mesh in a helical fashion
4101     #  @param Angles list of angles
4102     #  @param HasRefPoint allows using the reference point
4103     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4104     #         The User can specify any point as the Reference Point.
4105     #  @param MakeGroups forces the generation of new groups from existing ones
4106     #  @param LinearVariation forces the computation of rotation angles as linear
4107     #                         variation of the given Angles along path steps
4108     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4109     #          only SMESH::Extrusion_Error otherwise
4110     #  @ingroup l2_modif_extrurev
4111     def ExtrusionAlongPathObject1D(self, theObject, PathMesh, PathShape, NodeStart,
4112                                    HasAngles, Angles, HasRefPoint, RefPoint,
4113                                    MakeGroups=False, LinearVariation=False):
4114         n,e,f = [],theObject,[]
4115         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4116                                                HasAngles, Angles, LinearVariation,
4117                                                HasRefPoint, RefPoint, MakeGroups)
4118         if MakeGroups: return gr,er
4119         return er
4120
4121     ## Generates new elements by extrusion of the elements which belong to the object
4122     #  The path of extrusion must be a meshed edge.
4123     #  @param theObject the object which elements should be processed.
4124     #                   It can be a mesh, a sub mesh or a group.
4125     #  @param PathMesh mesh containing a 1D sub-mesh on the edge, along which the extrusion proceeds
4126     #  @param PathShape shape(edge) defines the sub-mesh for the path
4127     #  @param NodeStart the first or the last node on the edge. Defines the direction of extrusion
4128     #  @param HasAngles allows the shape to be rotated around the path
4129     #                   to get the resulting mesh in a helical fashion
4130     #  @param Angles list of angles
4131     #  @param HasRefPoint allows using the reference point
4132     #  @param RefPoint the point around which the shape is rotated (the mass center of the shape by default).
4133     #         The User can specify any point as the Reference Point.
4134     #  @param MakeGroups forces the generation of new groups from existing ones
4135     #  @param LinearVariation forces the computation of rotation angles as linear
4136     #                         variation of the given Angles along path steps
4137     #  @return list of created groups (SMESH_GroupBase) and SMESH::Extrusion_Error if MakeGroups=True,
4138     #          only SMESH::Extrusion_Error otherwise
4139     #  @ingroup l2_modif_extrurev
4140     def ExtrusionAlongPathObject2D(self, theObject, PathMesh, PathShape, NodeStart,
4141                                    HasAngles, Angles, HasRefPoint, RefPoint,
4142                                    MakeGroups=False, LinearVariation=False):
4143         n,e,f = [],[],theObject
4144         gr,er = self.ExtrusionAlongPathObjects(n,e,f, PathMesh, PathShape, NodeStart,
4145                                                HasAngles, Angles, LinearVariation,
4146                                                HasRefPoint, RefPoint, MakeGroups)
4147         if MakeGroups: return gr,er
4148         return er
4149
4150     ## Creates a symmetrical copy of mesh elements
4151     #  @param IDsOfElements list of elements ids
4152     #  @param Mirror is AxisStruct or geom object(point, line, plane)
4153     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4154     #         If the Mirror is a geom object this parameter is unnecessary
4155     #  @param Copy allows to copy element (Copy is 1) or to replace with its mirroring (Copy is 0)
4156     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4157     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4158     #  @ingroup l2_modif_trsf
4159     def Mirror(self, IDsOfElements, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4160         if IDsOfElements == []:
4161             IDsOfElements = self.GetElementsId()
4162         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4163             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4164             theMirrorType = Mirror._mirrorType
4165         else:
4166             self.mesh.SetParameters(Mirror.parameters)
4167         if Copy and MakeGroups:
4168             return self.editor.MirrorMakeGroups(IDsOfElements, Mirror, theMirrorType)
4169         self.editor.Mirror(IDsOfElements, Mirror, theMirrorType, Copy)
4170         return []
4171
4172     ## Creates a new mesh by a symmetrical copy of mesh elements
4173     #  @param IDsOfElements the list of elements ids
4174     #  @param Mirror is AxisStruct or geom object (point, line, plane)
4175     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4176     #         If the Mirror is a geom object this parameter is unnecessary
4177     #  @param MakeGroups to generate new groups from existing ones
4178     #  @param NewMeshName a name of the new mesh to create
4179     #  @return instance of Mesh class
4180     #  @ingroup l2_modif_trsf
4181     def MirrorMakeMesh(self, IDsOfElements, Mirror, theMirrorType=0, MakeGroups=0, NewMeshName=""):
4182         if IDsOfElements == []:
4183             IDsOfElements = self.GetElementsId()
4184         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4185             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4186             theMirrorType = Mirror._mirrorType
4187         else:
4188             self.mesh.SetParameters(Mirror.parameters)
4189         mesh = self.editor.MirrorMakeMesh(IDsOfElements, Mirror, theMirrorType,
4190                                           MakeGroups, NewMeshName)
4191         return Mesh(self.smeshpyD,self.geompyD,mesh)
4192
4193     ## Creates a symmetrical copy of the object
4194     #  @param theObject mesh, submesh or group
4195     #  @param Mirror AxisStruct or geom object (point, line, plane)
4196     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4197     #         If the Mirror is a geom object this parameter is unnecessary
4198     #  @param Copy allows copying the element (Copy is 1) or replacing it with its mirror (Copy is 0)
4199     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4200     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4201     #  @ingroup l2_modif_trsf
4202     def MirrorObject (self, theObject, Mirror, theMirrorType=None, Copy=0, MakeGroups=False):
4203         if ( isinstance( theObject, Mesh )):
4204             theObject = theObject.GetMesh()
4205         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4206             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4207             theMirrorType = Mirror._mirrorType
4208         else:
4209             self.mesh.SetParameters(Mirror.parameters)
4210         if Copy and MakeGroups:
4211             return self.editor.MirrorObjectMakeGroups(theObject, Mirror, theMirrorType)
4212         self.editor.MirrorObject(theObject, Mirror, theMirrorType, Copy)
4213         return []
4214
4215     ## Creates a new mesh by a symmetrical copy of the object
4216     #  @param theObject mesh, submesh or group
4217     #  @param Mirror AxisStruct or geom object (point, line, plane)
4218     #  @param theMirrorType smeshBuilder.POINT, smeshBuilder.AXIS or smeshBuilder.PLANE
4219     #         If the Mirror is a geom object this parameter is unnecessary
4220     #  @param MakeGroups forces the generation of new groups from existing ones
4221     #  @param NewMeshName the name of the new mesh to create
4222     #  @return instance of Mesh class
4223     #  @ingroup l2_modif_trsf
4224     def MirrorObjectMakeMesh (self, theObject, Mirror, theMirrorType=0,MakeGroups=0,NewMeshName=""):
4225         if ( isinstance( theObject, Mesh )):
4226             theObject = theObject.GetMesh()
4227         if ( isinstance( Mirror, geomBuilder.GEOM._objref_GEOM_Object)):
4228             Mirror        = self.smeshpyD.GetAxisStruct(Mirror)
4229             theMirrorType = Mirror._mirrorType
4230         else:
4231             self.mesh.SetParameters(Mirror.parameters)
4232         mesh = self.editor.MirrorObjectMakeMesh(theObject, Mirror, theMirrorType,
4233                                                 MakeGroups, NewMeshName)
4234         return Mesh( self.smeshpyD,self.geompyD,mesh )
4235
4236     ## Translates the elements
4237     #  @param IDsOfElements list of elements ids
4238     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4239     #  @param Copy allows copying the translated elements
4240     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4241     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4242     #  @ingroup l2_modif_trsf
4243     def Translate(self, IDsOfElements, Vector, Copy, MakeGroups=False):
4244         if IDsOfElements == []:
4245             IDsOfElements = self.GetElementsId()
4246         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4247             Vector = self.smeshpyD.GetDirStruct(Vector)
4248         if isinstance( Vector, list ):
4249             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4250         self.mesh.SetParameters(Vector.PS.parameters)
4251         if Copy and MakeGroups:
4252             return self.editor.TranslateMakeGroups(IDsOfElements, Vector)
4253         self.editor.Translate(IDsOfElements, Vector, Copy)
4254         return []
4255
4256     ## Creates a new mesh of translated elements
4257     #  @param IDsOfElements list of elements ids
4258     #  @param Vector the direction of translation (DirStruct or vector or 3 vector components)
4259     #  @param MakeGroups forces the generation of new groups from existing ones
4260     #  @param NewMeshName the name of the newly created mesh
4261     #  @return instance of Mesh class
4262     #  @ingroup l2_modif_trsf
4263     def TranslateMakeMesh(self, IDsOfElements, Vector, MakeGroups=False, NewMeshName=""):
4264         if IDsOfElements == []:
4265             IDsOfElements = self.GetElementsId()
4266         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4267             Vector = self.smeshpyD.GetDirStruct(Vector)
4268         if isinstance( Vector, list ):
4269             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4270         self.mesh.SetParameters(Vector.PS.parameters)
4271         mesh = self.editor.TranslateMakeMesh(IDsOfElements, Vector, MakeGroups, NewMeshName)
4272         return Mesh ( self.smeshpyD, self.geompyD, mesh )
4273
4274     ## Translates the object
4275     #  @param theObject the object to translate (mesh, submesh, or group)
4276     #  @param Vector direction of translation (DirStruct or geom vector or 3 vector components)
4277     #  @param Copy allows copying the translated elements
4278     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4279     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4280     #  @ingroup l2_modif_trsf
4281     def TranslateObject(self, theObject, Vector, Copy, MakeGroups=False):
4282         if ( isinstance( theObject, Mesh )):
4283             theObject = theObject.GetMesh()
4284         if ( isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object)):
4285             Vector = self.smeshpyD.GetDirStruct(Vector)
4286         if isinstance( Vector, list ):
4287             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4288         self.mesh.SetParameters(Vector.PS.parameters)
4289         if Copy and MakeGroups:
4290             return self.editor.TranslateObjectMakeGroups(theObject, Vector)
4291         self.editor.TranslateObject(theObject, Vector, Copy)
4292         return []
4293
4294     ## Creates a new mesh from the translated object
4295     #  @param theObject the object to translate (mesh, submesh, or group)
4296     #  @param Vector the direction of translation (DirStruct or geom vector or 3 vector components)
4297     #  @param MakeGroups forces the generation of new groups from existing ones
4298     #  @param NewMeshName the name of the newly created mesh
4299     #  @return instance of Mesh class
4300     #  @ingroup l2_modif_trsf
4301     def TranslateObjectMakeMesh(self, theObject, Vector, MakeGroups=False, NewMeshName=""):
4302         if isinstance( theObject, Mesh ):
4303             theObject = theObject.GetMesh()
4304         if isinstance( Vector, geomBuilder.GEOM._objref_GEOM_Object ):
4305             Vector = self.smeshpyD.GetDirStruct(Vector)
4306         if isinstance( Vector, list ):
4307             Vector = self.smeshpyD.MakeDirStruct(*Vector)
4308         self.mesh.SetParameters(Vector.PS.parameters)
4309         mesh = self.editor.TranslateObjectMakeMesh(theObject, Vector, MakeGroups, NewMeshName)
4310         return Mesh( self.smeshpyD, self.geompyD, mesh )
4311
4312
4313
4314     ## Scales the object
4315     #  @param theObject - the object to translate (mesh, submesh, or group)
4316     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4317     #  @param theScaleFact - list of 1-3 scale factors for axises
4318     #  @param Copy - allows copying the translated elements
4319     #  @param MakeGroups - forces the generation of new groups from existing
4320     #                      ones (if Copy)
4321     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True,
4322     #          empty list otherwise
4323     def Scale(self, theObject, thePoint, theScaleFact, Copy, MakeGroups=False):
4324         unRegister = genObjUnRegister()
4325         if ( isinstance( theObject, Mesh )):
4326             theObject = theObject.GetMesh()
4327         if ( isinstance( theObject, list )):
4328             theObject = self.GetIDSource(theObject, SMESH.ALL)
4329             unRegister.set( theObject )
4330         if ( isinstance( thePoint, list )):
4331             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4332         if ( isinstance( theScaleFact, float )):
4333              theScaleFact = [theScaleFact]
4334         if ( isinstance( theScaleFact, int )):
4335              theScaleFact = [ float(theScaleFact)]
4336
4337         self.mesh.SetParameters(thePoint.parameters)
4338
4339         if Copy and MakeGroups:
4340             return self.editor.ScaleMakeGroups(theObject, thePoint, theScaleFact)
4341         self.editor.Scale(theObject, thePoint, theScaleFact, Copy)
4342         return []
4343
4344     ## Creates a new mesh from the translated object
4345     #  @param theObject - the object to translate (mesh, submesh, or group)
4346     #  @param thePoint - base point for scale (SMESH.PointStruct or list of 3 coordinates)
4347     #  @param theScaleFact - list of 1-3 scale factors for axises
4348     #  @param MakeGroups - forces the generation of new groups from existing ones
4349     #  @param NewMeshName - the name of the newly created mesh
4350     #  @return instance of Mesh class
4351     def ScaleMakeMesh(self, theObject, thePoint, theScaleFact, MakeGroups=False, NewMeshName=""):
4352         unRegister = genObjUnRegister()
4353         if (isinstance(theObject, Mesh)):
4354             theObject = theObject.GetMesh()
4355         if ( isinstance( theObject, list )):
4356             theObject = self.GetIDSource(theObject,SMESH.ALL)
4357             unRegister.set( theObject )
4358         if ( isinstance( thePoint, list )):
4359             thePoint = PointStruct( thePoint[0], thePoint[1], thePoint[2] )
4360         if ( isinstance( theScaleFact, float )):
4361              theScaleFact = [theScaleFact]
4362         if ( isinstance( theScaleFact, int )):
4363              theScaleFact = [ float(theScaleFact)]
4364
4365         self.mesh.SetParameters(thePoint.parameters)
4366         mesh = self.editor.ScaleMakeMesh(theObject, thePoint, theScaleFact,
4367                                          MakeGroups, NewMeshName)
4368         return Mesh( self.smeshpyD, self.geompyD, mesh )
4369
4370
4371
4372     ## Rotates the elements
4373     #  @param IDsOfElements list of elements ids
4374     #  @param Axis the axis of rotation (AxisStruct or geom line)
4375     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4376     #  @param Copy allows copying the rotated elements
4377     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4378     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4379     #  @ingroup l2_modif_trsf
4380     def Rotate (self, IDsOfElements, Axis, AngleInRadians, Copy, MakeGroups=False):
4381         if IDsOfElements == []:
4382             IDsOfElements = self.GetElementsId()
4383         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4384             Axis = self.smeshpyD.GetAxisStruct(Axis)
4385         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4386         Parameters = Axis.parameters + var_separator + Parameters
4387         self.mesh.SetParameters(Parameters)
4388         if Copy and MakeGroups:
4389             return self.editor.RotateMakeGroups(IDsOfElements, Axis, AngleInRadians)
4390         self.editor.Rotate(IDsOfElements, Axis, AngleInRadians, Copy)
4391         return []
4392
4393     ## Creates a new mesh of rotated elements
4394     #  @param IDsOfElements list of element ids
4395     #  @param Axis the axis of rotation (AxisStruct or geom line)
4396     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4397     #  @param MakeGroups forces the generation of new groups from existing ones
4398     #  @param NewMeshName the name of the newly created mesh
4399     #  @return instance of Mesh class
4400     #  @ingroup l2_modif_trsf
4401     def RotateMakeMesh (self, IDsOfElements, Axis, AngleInRadians, MakeGroups=0, NewMeshName=""):
4402         if IDsOfElements == []:
4403             IDsOfElements = self.GetElementsId()
4404         if ( isinstance( Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4405             Axis = self.smeshpyD.GetAxisStruct(Axis)
4406         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4407         Parameters = Axis.parameters + var_separator + Parameters
4408         self.mesh.SetParameters(Parameters)
4409         mesh = self.editor.RotateMakeMesh(IDsOfElements, Axis, AngleInRadians,
4410                                           MakeGroups, NewMeshName)
4411         return Mesh( self.smeshpyD, self.geompyD, mesh )
4412
4413     ## Rotates the object
4414     #  @param theObject the object to rotate( mesh, submesh, or group)
4415     #  @param Axis the axis of rotation (AxisStruct or geom line)
4416     #  @param AngleInRadians the angle of rotation (in radians) or a name of variable which defines angle in degrees
4417     #  @param Copy allows copying the rotated elements
4418     #  @param MakeGroups forces the generation of new groups from existing ones (if Copy)
4419     #  @return list of created groups (SMESH_GroupBase) if MakeGroups=True, empty list otherwise
4420     #  @ingroup l2_modif_trsf
4421     def RotateObject (self, theObject, Axis, AngleInRadians, Copy, MakeGroups=False):
4422         if (isinstance(theObject, Mesh)):
4423             theObject = theObject.GetMesh()
4424         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4425             Axis = self.smeshpyD.GetAxisStruct(Axis)
4426         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4427         Parameters = Axis.parameters + ":" + Parameters
4428         self.mesh.SetParameters(Parameters)
4429         if Copy and MakeGroups:
4430             return self.editor.RotateObjectMakeGroups(theObject, Axis, AngleInRadians)
4431         self.editor.RotateObject(theObject, Axis, AngleInRadians, Copy)
4432         return []
4433
4434     ## Creates a new mesh from the rotated object
4435     #  @param theObject the object to rotate (mesh, submesh, or group)
4436     #  @param Axis the axis of rotation (AxisStruct or geom line)
4437     #  @param AngleInRadians the angle of rotation (in radians)  or a name of variable which defines angle in degrees
4438     #  @param MakeGroups forces the generation of new groups from existing ones
4439     #  @param NewMeshName the name of the newly created mesh
4440     #  @return instance of Mesh class
4441     #  @ingroup l2_modif_trsf
4442     def RotateObjectMakeMesh(self, theObject, Axis, AngleInRadians, MakeGroups=0,NewMeshName=""):
4443         if (isinstance( theObject, Mesh )):
4444             theObject = theObject.GetMesh()
4445         if (isinstance(Axis, geomBuilder.GEOM._objref_GEOM_Object)):
4446             Axis = self.smeshpyD.GetAxisStruct(Axis)
4447         AngleInRadians,Parameters,hasVars = ParseAngles(AngleInRadians)
4448         Parameters = Axis.parameters + ":" + Parameters
4449         mesh = self.editor.RotateObjectMakeMesh(theObject, Axis, AngleInRadians,
4450                                                        MakeGroups, NewMeshName)
4451         self.mesh.SetParameters(Parameters)
4452         return Mesh( self.smeshpyD, self.geompyD, mesh )
4453
4454     ## Finds groups of adjacent nodes within Tolerance.
4455     #  @param Tolerance the value of tolerance
4456     #  @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4457     #         corner and medium nodes in separate groups thus preventing
4458     #         their further merge.
4459     #  @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4460     #  @ingroup l2_modif_trsf
4461     def FindCoincidentNodes (self, Tolerance, SeparateCornerAndMediumNodes=False):
4462         return self.editor.FindCoincidentNodes( Tolerance, SeparateCornerAndMediumNodes )
4463
4464     ## Finds groups of ajacent nodes within Tolerance.
4465     #  @param Tolerance the value of tolerance
4466     #  @param SubMeshOrGroup SubMesh or Group
4467     #  @param exceptNodes list of either SubMeshes, Groups or node IDs to exclude from search
4468     #  @param SeparateCornerAndMediumNodes if @c True, in quadratic mesh puts
4469     #         corner and medium nodes in separate groups thus preventing
4470     #         their further merge.
4471     #  @return the list of groups of nodes IDs (e.g. [[1,12,13],[4,25]])
4472     #  @ingroup l2_modif_trsf
4473     def FindCoincidentNodesOnPart (self, SubMeshOrGroup, Tolerance,
4474                                    exceptNodes=[], SeparateCornerAndMediumNodes=False):
4475         unRegister = genObjUnRegister()
4476         if (isinstance( SubMeshOrGroup, Mesh )):
4477             SubMeshOrGroup = SubMeshOrGroup.GetMesh()
4478         if not isinstance( exceptNodes, list ):
4479             exceptNodes = [ exceptNodes ]
4480         if exceptNodes and isinstance( exceptNodes[0], int ):
4481             exceptNodes = [ self.GetIDSource( exceptNodes, SMESH.NODE )]
4482             unRegister.set( exceptNodes )
4483         return self.editor.FindCoincidentNodesOnPartBut(SubMeshOrGroup, Tolerance,
4484                                                         exceptNodes, SeparateCornerAndMediumNodes)
4485
4486     ## Merges nodes
4487     #  @param GroupsOfNodes a list of groups of nodes IDs for merging
4488     #         (e.g. [[1,12,13],[25,4]], then nodes 12, 13 and 4 will be removed and replaced
4489     #         by nodes 1 and 25 correspondingly in all elements and groups
4490     #  @param NodesToKeep nodes to keep in the mesh: a list of groups, sub-meshes or node IDs.
4491     #         If @a NodesToKeep does not include a node to keep for some group to merge,
4492     #         then the first node in the group is kept.
4493     #  @ingroup l2_modif_trsf
4494     def MergeNodes (self, GroupsOfNodes, NodesToKeep=[]):
4495         # NodesToKeep are converted to SMESH_IDSource in meshEditor.MergeNodes()
4496         self.editor.MergeNodes(GroupsOfNodes,NodesToKeep)
4497
4498     ## Finds the elements built on the same nodes.
4499     #  @param MeshOrSubMeshOrGroup Mesh or SubMesh, or Group of elements for searching
4500     #  @return the list of groups of equal elements IDs (e.g. [[1,12,13],[4,25]])
4501     #  @ingroup l2_modif_trsf
4502     def FindEqualElements (self, MeshOrSubMeshOrGroup=None):
4503         if not MeshOrSubMeshOrGroup:
4504             MeshOrSubMeshOrGroup=self.mesh
4505         elif isinstance( MeshOrSubMeshOrGroup, Mesh ):
4506             MeshOrSubMeshOrGroup = MeshOrSubMeshOrGroup.GetMesh()
4507         return self.editor.FindEqualElements( MeshOrSubMeshOrGroup )
4508
4509     ## Merges elements in each given group.
4510     #  @param GroupsOfElementsID a list of groups of elements IDs for merging
4511     #        (e.g. [[1,12,13],[25,4]], then elements 12, 13 and 4 will be removed and
4512     #        replaced by elements 1 and 25 in all groups)
4513     #  @ingroup l2_modif_trsf
4514     def MergeElements(self, GroupsOfElementsID):
4515         self.editor.MergeElements(GroupsOfElementsID)
4516
4517     ## Leaves one element and removes all other elements built on the same nodes.
4518     #  @ingroup l2_modif_trsf
4519     def MergeEqualElements(self):
4520         self.editor.MergeEqualElements()
4521
4522     ## Sews free borders
4523     #  @return SMESH::Sew_Error
4524     #  @ingroup l2_modif_trsf
4525     def SewFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4526                         FirstNodeID2, SecondNodeID2, LastNodeID2,
4527                         CreatePolygons, CreatePolyedrs):
4528         return self.editor.SewFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4529                                           FirstNodeID2, SecondNodeID2, LastNodeID2,
4530                                           CreatePolygons, CreatePolyedrs)
4531
4532     ## Sews conform free borders
4533     #  @return SMESH::Sew_Error
4534     #  @ingroup l2_modif_trsf
4535     def SewConformFreeBorders (self, FirstNodeID1, SecondNodeID1, LastNodeID1,
4536                                FirstNodeID2, SecondNodeID2):
4537         return self.editor.SewConformFreeBorders(FirstNodeID1, SecondNodeID1, LastNodeID1,
4538                                                  FirstNodeID2, SecondNodeID2)
4539
4540     ## Sews border to side
4541     #  @return SMESH::Sew_Error
4542     #  @ingroup l2_modif_trsf
4543     def SewBorderToSide (self, FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4544                          FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs):
4545         return self.editor.SewBorderToSide(FirstNodeIDOnFreeBorder, SecondNodeIDOnFreeBorder, LastNodeIDOnFreeBorder,
4546                                            FirstNodeIDOnSide, LastNodeIDOnSide, CreatePolygons, CreatePolyedrs)
4547
4548     ## Sews two sides of a mesh. The nodes belonging to Side1 are
4549     #  merged with the nodes of elements of Side2.
4550     #  The number of elements in theSide1 and in theSide2 must be
4551     #  equal and they should have similar nodal connectivity.
4552     #  The nodes to merge should belong to side borders and
4553     #  the first node should be linked to the second.
4554     #  @return SMESH::Sew_Error
4555     #  @ingroup l2_modif_trsf
4556     def SewSideElements (self, IDsOfSide1Elements, IDsOfSide2Elements,
4557                          NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4558                          NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge):
4559         return self.editor.SewSideElements(IDsOfSide1Elements, IDsOfSide2Elements,
4560                                            NodeID1OfSide1ToMerge, NodeID1OfSide2ToMerge,
4561                                            NodeID2OfSide1ToMerge, NodeID2OfSide2ToMerge)
4562
4563     ## Sets new nodes for the given element.
4564     #  @param ide the element id
4565     #  @param newIDs nodes ids
4566     #  @return If the number of nodes does not correspond to the type of element - returns false
4567     #  @ingroup l2_modif_edit
4568     def ChangeElemNodes(self, ide, newIDs):
4569         return self.editor.ChangeElemNodes(ide, newIDs)
4570
4571     ## If during the last operation of MeshEditor some nodes were
4572     #  created, this method returns the list of their IDs, \n
4573     #  if new nodes were not created - returns empty list
4574     #  @return the list of integer values (can be empty)
4575     #  @ingroup l1_auxiliary
4576     def GetLastCreatedNodes(self):
4577         return self.editor.GetLastCreatedNodes()
4578
4579     ## If during the last operation of MeshEditor some elements were
4580     #  created this method returns the list of their IDs, \n
4581     #  if new elements were not created - returns empty list
4582     #  @return the list of integer values (can be empty)
4583     #  @ingroup l1_auxiliary
4584     def GetLastCreatedElems(self):
4585         return self.editor.GetLastCreatedElems()
4586
4587     ## Clears sequences of nodes and elements created by mesh edition oparations
4588     #  @ingroup l1_auxiliary
4589     def ClearLastCreated(self):
4590         self.editor.ClearLastCreated()
4591
4592     ## Creates duplicates of given elements, i.e. creates new elements based on the 
4593     #  same nodes as the given ones.
4594     #  @param theElements - container of elements to duplicate. It can be a Mesh,
4595     #         sub-mesh, group, filter or a list of element IDs. If \a theElements is
4596     #         a Mesh, elements of highest dimension are duplicated
4597     #  @param theGroupName - a name of group to contain the generated elements.
4598     #                    If a group with such a name already exists, the new elements
4599     #                    are added to the existng group, else a new group is created.
4600     #                    If \a theGroupName is empty, new elements are not added 
4601     #                    in any group.
4602     # @return a group where the new elements are added. None if theGroupName == "".
4603     #  @ingroup l2_modif_edit
4604     def DoubleElements(self, theElements, theGroupName=""):
4605         unRegister = genObjUnRegister()
4606         if isinstance( theElements, Mesh ):
4607             theElements = theElements.mesh
4608         elif isinstance( theElements, list ):
4609             theElements = self.GetIDSource( theElements, SMESH.ALL )
4610             unRegister.set( theElements )
4611         return self.editor.DoubleElements(theElements, theGroupName)
4612
4613     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4614     #  @param theNodes identifiers of nodes to be doubled
4615     #  @param theModifiedElems identifiers of elements to be updated by the new (doubled)
4616     #         nodes. If list of element identifiers is empty then nodes are doubled but
4617     #         they not assigned to elements
4618     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4619     #  @ingroup l2_modif_edit
4620     def DoubleNodes(self, theNodes, theModifiedElems):
4621         return self.editor.DoubleNodes(theNodes, theModifiedElems)
4622
4623     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4624     #  This method provided for convenience works as DoubleNodes() described above.
4625     #  @param theNodeId identifiers of node to be doubled
4626     #  @param theModifiedElems identifiers of elements to be updated
4627     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4628     #  @ingroup l2_modif_edit
4629     def DoubleNode(self, theNodeId, theModifiedElems):
4630         return self.editor.DoubleNode(theNodeId, theModifiedElems)
4631
4632     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4633     #  This method provided for convenience works as DoubleNodes() described above.
4634     #  @param theNodes group of nodes to be doubled
4635     #  @param theModifiedElems group of elements to be updated.
4636     #  @param theMakeGroup forces the generation of a group containing new nodes.
4637     #  @return TRUE or a created group if operation has been completed successfully,
4638     #          FALSE or None otherwise
4639     #  @ingroup l2_modif_edit
4640     def DoubleNodeGroup(self, theNodes, theModifiedElems, theMakeGroup=False):
4641         if theMakeGroup:
4642             return self.editor.DoubleNodeGroupNew(theNodes, theModifiedElems)
4643         return self.editor.DoubleNodeGroup(theNodes, theModifiedElems)
4644
4645     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4646     #  This method provided for convenience works as DoubleNodes() described above.
4647     #  @param theNodes list of groups of nodes to be doubled
4648     #  @param theModifiedElems list of groups of elements to be updated.
4649     #  @param theMakeGroup forces the generation of a group containing new nodes.
4650     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4651     #  @ingroup l2_modif_edit
4652     def DoubleNodeGroups(self, theNodes, theModifiedElems, theMakeGroup=False):
4653         if theMakeGroup:
4654             return self.editor.DoubleNodeGroupsNew(theNodes, theModifiedElems)
4655         return self.editor.DoubleNodeGroups(theNodes, theModifiedElems)
4656
4657     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4658     #  @param theElems - the list of elements (edges or faces) to be replicated
4659     #         The nodes for duplication could be found from these elements
4660     #  @param theNodesNot - list of nodes to NOT replicate
4661     #  @param theAffectedElems - the list of elements (cells and edges) to which the
4662     #         replicated nodes should be associated to.
4663     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4664     #  @ingroup l2_modif_edit
4665     def DoubleNodeElem(self, theElems, theNodesNot, theAffectedElems):
4666         return self.editor.DoubleNodeElem(theElems, theNodesNot, theAffectedElems)
4667
4668     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4669     #  @param theElems - the list of elements (edges or faces) to be replicated
4670     #         The nodes for duplication could be found from these elements
4671     #  @param theNodesNot - list of nodes to NOT replicate
4672     #  @param theShape - shape to detect affected elements (element which geometric center
4673     #         located on or inside shape).
4674     #         The replicated nodes should be associated to affected elements.
4675     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4676     #  @ingroup l2_modif_edit
4677     def DoubleNodeElemInRegion(self, theElems, theNodesNot, theShape):
4678         return self.editor.DoubleNodeElemInRegion(theElems, theNodesNot, theShape)
4679
4680     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4681     #  This method provided for convenience works as DoubleNodes() described above.
4682     #  @param theElems - group of of elements (edges or faces) to be replicated
4683     #  @param theNodesNot - group of nodes not to replicated
4684     #  @param theAffectedElems - group of elements to which the replicated nodes
4685     #         should be associated to.
4686     #  @param theMakeGroup forces the generation of a group containing new elements.
4687     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4688     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4689     #          FALSE or None otherwise
4690     #  @ingroup l2_modif_edit
4691     def DoubleNodeElemGroup(self, theElems, theNodesNot, theAffectedElems,
4692                              theMakeGroup=False, theMakeNodeGroup=False):
4693         if theMakeGroup or theMakeNodeGroup:
4694             twoGroups = self.editor.DoubleNodeElemGroup2New(theElems, theNodesNot,
4695                                                             theAffectedElems,
4696                                                             theMakeGroup, theMakeNodeGroup)
4697             if theMakeGroup and theMakeNodeGroup:
4698                 return twoGroups
4699             else:
4700                 return twoGroups[ int(theMakeNodeGroup) ]
4701         return self.editor.DoubleNodeElemGroup(theElems, theNodesNot, theAffectedElems)
4702
4703     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4704     #  This method provided for convenience works as DoubleNodes() described above.
4705     #  @param theElems - group of of elements (edges or faces) to be replicated
4706     #  @param theNodesNot - group of nodes not to replicated
4707     #  @param theShape - shape to detect affected elements (element which geometric center
4708     #         located on or inside shape).
4709     #         The replicated nodes should be associated to affected elements.
4710     #  @ingroup l2_modif_edit
4711     def DoubleNodeElemGroupInRegion(self, theElems, theNodesNot, theShape):
4712         return self.editor.DoubleNodeElemGroupInRegion(theElems, theNodesNot, theShape)
4713
4714     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4715     #  This method provided for convenience works as DoubleNodes() described above.
4716     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4717     #  @param theNodesNot - list of groups of nodes not to replicated
4718     #  @param theAffectedElems - group of elements to which the replicated nodes
4719     #         should be associated to.
4720     #  @param theMakeGroup forces the generation of a group containing new elements.
4721     #  @param theMakeNodeGroup forces the generation of a group containing new nodes.
4722     #  @return TRUE or created groups (one or two) if operation has been completed successfully,
4723     #          FALSE or None otherwise
4724     #  @ingroup l2_modif_edit
4725     def DoubleNodeElemGroups(self, theElems, theNodesNot, theAffectedElems,
4726                              theMakeGroup=False, theMakeNodeGroup=False):
4727         if theMakeGroup or theMakeNodeGroup:
4728             twoGroups = self.editor.DoubleNodeElemGroups2New(theElems, theNodesNot,
4729                                                              theAffectedElems,
4730                                                              theMakeGroup, theMakeNodeGroup)
4731             if theMakeGroup and theMakeNodeGroup:
4732                 return twoGroups
4733             else:
4734                 return twoGroups[ int(theMakeNodeGroup) ]
4735         return self.editor.DoubleNodeElemGroups(theElems, theNodesNot, theAffectedElems)
4736
4737     ## Creates a hole in a mesh by doubling the nodes of some particular elements
4738     #  This method provided for convenience works as DoubleNodes() described above.
4739     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4740     #  @param theNodesNot - list of groups of nodes not to replicated
4741     #  @param theShape - shape to detect affected elements (element which geometric center
4742     #         located on or inside shape).
4743     #         The replicated nodes should be associated to affected elements.
4744     #  @return TRUE if operation has been completed successfully, FALSE otherwise
4745     #  @ingroup l2_modif_edit
4746     def DoubleNodeElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4747         return self.editor.DoubleNodeElemGroupsInRegion(theElems, theNodesNot, theShape)
4748
4749     ## Identify the elements that will be affected by node duplication (actual duplication is not performed.
4750     #  This method is the first step of DoubleNodeElemGroupsInRegion.
4751     #  @param theElems - list of groups of elements (edges or faces) to be replicated
4752     #  @param theNodesNot - list of groups of nodes not to replicated
4753     #  @param theShape - shape to detect affected elements (element which geometric center
4754     #         located on or inside shape).
4755     #         The replicated nodes should be associated to affected elements.
4756     #  @return groups of affected elements
4757     #  @ingroup l2_modif_edit
4758     def AffectedElemGroupsInRegion(self, theElems, theNodesNot, theShape):
4759         return self.editor.AffectedElemGroupsInRegion(theElems, theNodesNot, theShape)
4760
4761     ## Double nodes on shared faces between groups of volumes and create flat elements on demand.
4762     # The list of groups must describe a partition of the mesh volumes.
4763     # The nodes of the internal faces at the boundaries of the groups are doubled.
4764     # In option, the internal faces are replaced by flat elements.
4765     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4766     # @param theDomains - list of groups of volumes
4767     # @param createJointElems - if TRUE, create the elements
4768     # @param onAllBoundaries - if TRUE, the nodes and elements are also created on
4769     #        the boundary between \a theDomains and the rest mesh
4770     # @return TRUE if operation has been completed successfully, FALSE otherwise
4771     def DoubleNodesOnGroupBoundaries(self, theDomains, createJointElems, onAllBoundaries=False ):
4772        return self.editor.DoubleNodesOnGroupBoundaries( theDomains, createJointElems, onAllBoundaries )
4773
4774     ## Double nodes on some external faces and create flat elements.
4775     # Flat elements are mainly used by some types of mechanic calculations.
4776     #
4777     # Each group of the list must be constituted of faces.
4778     # Triangles are transformed in prisms, and quadrangles in hexahedrons.
4779     # @param theGroupsOfFaces - list of groups of faces
4780     # @return TRUE if operation has been completed successfully, FALSE otherwise
4781     def CreateFlatElementsOnFacesGroups(self, theGroupsOfFaces ):
4782         return self.editor.CreateFlatElementsOnFacesGroups( theGroupsOfFaces )
4783     
4784     ## identify all the elements around a geom shape, get the faces delimiting the hole
4785     #
4786     def CreateHoleSkin(self, radius, theShape, groupName, theNodesCoords):
4787         return self.editor.CreateHoleSkin( radius, theShape, groupName, theNodesCoords )
4788
4789     def _getFunctor(self, funcType ):
4790         fn = self.functors[ funcType._v ]
4791         if not fn:
4792             fn = self.smeshpyD.GetFunctor(funcType)
4793             fn.SetMesh(self.mesh)
4794             self.functors[ funcType._v ] = fn
4795         return fn
4796
4797     ## Returns value of a functor for a given element
4798     #  @param funcType an item of SMESH.FunctorType enum
4799     #         Type "SMESH.FunctorType._items" in the Python Console to see all items.
4800     #  @param elemId element or node ID
4801     #  @param isElem @a elemId is ID of element or node
4802     #  @return the functor value or zero in case of invalid arguments
4803     def FunctorValue(self, funcType, elemId, isElem=True):
4804         fn = self._getFunctor( funcType )
4805         if fn.GetElementType() == self.GetElementType(elemId, isElem):
4806             val = fn.GetValue(elemId)
4807         else:
4808             val = 0
4809         return val
4810
4811     ## Get length of 1D element or sum of lengths of all 1D mesh elements
4812     #  @param elemId mesh element ID (if not defined - sum of length of all 1D elements will be calculated)
4813     #  @return element's length value if \a elemId is specified or sum of all 1D mesh elements' lengths otherwise
4814     #  @ingroup l1_measurements
4815     def GetLength(self, elemId=None):
4816         length = 0
4817         if elemId == None:
4818             length = self.smeshpyD.GetLength(self)
4819         else:
4820             length = self.FunctorValue(SMESH.FT_Length, elemId)
4821         return length
4822
4823     ## Get area of 2D element or sum of areas of all 2D mesh elements
4824     #  @param elemId mesh element ID (if not defined - sum of areas of all 2D elements will be calculated)
4825     #  @return element's area value if \a elemId is specified or sum of all 2D mesh elements' areas otherwise
4826     #  @ingroup l1_measurements
4827     def GetArea(self, elemId=None):
4828         area = 0
4829         if elemId == None:
4830             area = self.smeshpyD.GetArea(self)
4831         else:
4832             area = self.FunctorValue(SMESH.FT_Area, elemId)
4833         return area
4834
4835     ## Get volume of 3D element or sum of volumes of all 3D mesh elements
4836     #  @param elemId mesh element ID (if not defined - sum of volumes of all 3D elements will be calculated)
4837     #  @return element's volume value if \a elemId is specified or sum of all 3D mesh elements' volumes otherwise
4838     #  @ingroup l1_measurements
4839     def GetVolume(self, elemId=None):
4840         volume = 0
4841         if elemId == None:
4842             volume = self.smeshpyD.GetVolume(self)
4843         else:
4844             volume = self.FunctorValue(SMESH.FT_Volume3D, elemId)
4845         return volume
4846
4847     ## Get maximum element length.
4848     #  @param elemId mesh element ID
4849     #  @return element's maximum length value
4850     #  @ingroup l1_measurements
4851     def GetMaxElementLength(self, elemId):
4852         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4853             ftype = SMESH.FT_MaxElementLength3D
4854         else:
4855             ftype = SMESH.FT_MaxElementLength2D
4856         return self.FunctorValue(ftype, elemId)
4857
4858     ## Get aspect ratio of 2D or 3D element.
4859     #  @param elemId mesh element ID
4860     #  @return element's aspect ratio value
4861     #  @ingroup l1_measurements
4862     def GetAspectRatio(self, elemId):
4863         if self.GetElementType(elemId, True) == SMESH.VOLUME:
4864             ftype = SMESH.FT_AspectRatio3D
4865         else:
4866             ftype = SMESH.FT_AspectRatio
4867         return self.FunctorValue(ftype, elemId)
4868
4869     ## Get warping angle of 2D element.
4870     #  @param elemId mesh element ID
4871     #  @return element's warping angle value
4872     #  @ingroup l1_measurements
4873     def GetWarping(self, elemId):
4874         return self.FunctorValue(SMESH.FT_Warping, elemId)
4875
4876     ## Get minimum angle of 2D element.
4877     #  @param elemId mesh element ID
4878     #  @return element's minimum angle value
4879     #  @ingroup l1_measurements
4880     def GetMinimumAngle(self, elemId):
4881         return self.FunctorValue(SMESH.FT_MinimumAngle, elemId)
4882
4883     ## Get taper of 2D element.
4884     #  @param elemId mesh element ID
4885     #  @return element's taper value
4886     #  @ingroup l1_measurements
4887     def GetTaper(self, elemId):
4888         return self.FunctorValue(SMESH.FT_Taper, elemId)
4889
4890     ## Get skew of 2D element.
4891     #  @param elemId mesh element ID
4892     #  @return element's skew value
4893     #  @ingroup l1_measurements
4894     def GetSkew(self, elemId):
4895         return self.FunctorValue(SMESH.FT_Skew, elemId)
4896
4897     ## Return minimal and maximal value of a given functor.
4898     #  @param funType a functor type, an item of SMESH.FunctorType enum
4899     #         (one of SMESH.FunctorType._items)
4900     #  @param meshPart a part of mesh (group, sub-mesh) to treat
4901     #  @return tuple (min,max)
4902     #  @ingroup l1_measurements
4903     def GetMinMax(self, funType, meshPart=None):
4904         unRegister = genObjUnRegister()
4905         if isinstance( meshPart, list ):
4906             meshPart = self.GetIDSource( meshPart, SMESH.ALL )
4907             unRegister.set( meshPart )
4908         if isinstance( meshPart, Mesh ):
4909             meshPart = meshPart.mesh
4910         fun = self._getFunctor( funType )
4911         if fun:
4912             if meshPart:
4913                 hist = fun.GetLocalHistogram( 1, False, meshPart )
4914             else:
4915                 hist = fun.GetHistogram( 1, False )
4916             if hist:
4917                 return hist[0].min, hist[0].max
4918         return None
4919
4920     pass # end of Mesh class
4921
4922
4923 ## class used to compensate change of CORBA API of SMESH_Mesh for backward compatibility
4924 #  with old dump scripts which call SMESH_Mesh directly and not via smeshBuilder.Mesh
4925 #
4926 class meshProxy(SMESH._objref_SMESH_Mesh):
4927     def __init__(self):
4928         SMESH._objref_SMESH_Mesh.__init__(self)
4929     def __deepcopy__(self, memo=None):
4930         new = self.__class__()
4931         return new
4932     def CreateDimGroup(self,*args): # 2 args added: nbCommonNodes, underlyingOnly
4933         if len( args ) == 3:
4934             args += SMESH.ALL_NODES, True
4935         return SMESH._objref_SMESH_Mesh.CreateDimGroup( self, *args )
4936     pass
4937 omniORB.registerObjref(SMESH._objref_SMESH_Mesh._NP_RepositoryId, meshProxy)
4938
4939 ## class used to compensate change of CORBA API of SMESH_MeshEditor for backward compatibility
4940 #  with old dump scripts which call SMESH_MeshEditor directly and not via smeshBuilder.Mesh
4941 #
4942 class meshEditor(SMESH._objref_SMESH_MeshEditor):
4943     def __init__(self):
4944         SMESH._objref_SMESH_MeshEditor.__init__(self)
4945         self.mesh = None
4946     def __getattr__(self, name ): # method called if an attribute not found
4947         if not self.mesh:         # look for name() method in Mesh class
4948             self.mesh = Mesh( None, None, SMESH._objref_SMESH_MeshEditor.GetMesh(self))
4949         if hasattr( self.mesh, name ):
4950             return getattr( self.mesh, name )
4951         if name == "ExtrusionAlongPathObjX":
4952             return getattr( self.mesh, "ExtrusionAlongPathX" ) # other method name
4953         print "meshEditor: attribute '%s' NOT FOUND" % name
4954         return None
4955     def __deepcopy__(self, memo=None):
4956         new = self.__class__()
4957         return new
4958     def FindCoincidentNodes(self,*args): # a 2nd arg added (SeparateCornerAndMediumNodes)
4959         if len( args ) == 1: args += False,
4960         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodes( self, *args )
4961     def FindCoincidentNodesOnPart(self,*args): # a 3d arg added (SeparateCornerAndMediumNodes)
4962         if len( args ) == 2: args += False,
4963         return SMESH._objref_SMESH_MeshEditor.FindCoincidentNodesOnPart( self, *args )
4964     def MergeNodes(self,*args): # a 2nd arg added (NodesToKeep)
4965         if len( args ) == 1:
4966             return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], [] )
4967         NodesToKeep = args[1]
4968         unRegister  = genObjUnRegister()
4969         if NodesToKeep:
4970             if isinstance( NodesToKeep, list ) and isinstance( NodesToKeep[0], int ):
4971                 NodesToKeep = self.MakeIDSource( NodesToKeep, SMESH.NODE )
4972             if not isinstance( NodesToKeep, list ):
4973                 NodesToKeep = [ NodesToKeep ]
4974         return SMESH._objref_SMESH_MeshEditor.MergeNodes( self, args[0], NodesToKeep )
4975     pass
4976 omniORB.registerObjref(SMESH._objref_SMESH_MeshEditor._NP_RepositoryId, meshEditor)
4977
4978 ## Helper class for wrapping of SMESH.SMESH_Pattern CORBA class
4979 #
4980 class Pattern(SMESH._objref_SMESH_Pattern):
4981
4982     def ApplyToMeshFaces(self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse):
4983         decrFun = lambda i: i-1
4984         theNodeIndexOnKeyPoint1,Parameters,hasVars = ParseParameters(theNodeIndexOnKeyPoint1, decrFun)
4985         theMesh.SetParameters(Parameters)
4986         return SMESH._objref_SMESH_Pattern.ApplyToMeshFaces( self, theMesh, theFacesIDs, theNodeIndexOnKeyPoint1, theReverse )
4987
4988     def ApplyToHexahedrons(self, theMesh, theVolumesIDs, theNode000Index, theNode001Index):
4989         decrFun = lambda i: i-1
4990         theNode000Index,theNode001Index,Parameters,hasVars = ParseParameters(theNode000Index,theNode001Index, decrFun)
4991         theMesh.SetParameters(Parameters)
4992         return SMESH._objref_SMESH_Pattern.ApplyToHexahedrons( self, theMesh, theVolumesIDs, theNode000Index, theNode001Index )
4993
4994 # Registering the new proxy for Pattern
4995 omniORB.registerObjref(SMESH._objref_SMESH_Pattern._NP_RepositoryId, Pattern)
4996
4997 ## Private class used to bind methods creating algorithms to the class Mesh
4998 #
4999 class algoCreator:
5000     def __init__(self):
5001         self.mesh = None
5002         self.defaultAlgoType = ""
5003         self.algoTypeToClass = {}
5004
5005     # Stores a python class of algorithm
5006     def add(self, algoClass):
5007         if type( algoClass ).__name__ == 'classobj' and \
5008            hasattr( algoClass, "algoType"):
5009             self.algoTypeToClass[ algoClass.algoType ] = algoClass
5010             if not self.defaultAlgoType and \
5011                hasattr( algoClass, "isDefault") and algoClass.isDefault:
5012                 self.defaultAlgoType = algoClass.algoType
5013             #print "Add",algoClass.algoType, "dflt",self.defaultAlgoType
5014
5015     # creates a copy of self and assign mesh to the copy
5016     def copy(self, mesh):
5017         other = algoCreator()
5018         other.defaultAlgoType = self.defaultAlgoType
5019         other.algoTypeToClass  = self.algoTypeToClass
5020         other.mesh = mesh
5021         return other
5022
5023     # creates an instance of algorithm
5024     def __call__(self,algo="",geom=0,*args):
5025         algoType = self.defaultAlgoType
5026         for arg in args + (algo,geom):
5027             if isinstance( arg, geomBuilder.GEOM._objref_GEOM_Object ):
5028                 geom = arg
5029             if isinstance( arg, str ) and arg:
5030                 algoType = arg
5031         if not algoType and self.algoTypeToClass:
5032             algoType = self.algoTypeToClass.keys()[0]
5033         if self.algoTypeToClass.has_key( algoType ):
5034             #print "Create algo",algoType
5035             return self.algoTypeToClass[ algoType ]( self.mesh, geom )
5036         raise RuntimeError, "No class found for algo type %s" % algoType
5037         return None
5038
5039 # Private class used to substitute and store variable parameters of hypotheses.
5040 #
5041 class hypMethodWrapper:
5042     def __init__(self, hyp, method):
5043         self.hyp    = hyp
5044         self.method = method
5045         #print "REBIND:", method.__name__
5046         return
5047
5048     # call a method of hypothesis with calling SetVarParameter() before
5049     def __call__(self,*args):
5050         if not args:
5051             return self.method( self.hyp, *args ) # hypothesis method with no args
5052
5053         #print "MethWrapper.__call__",self.method.__name__, args
5054         try:
5055             parsed = ParseParameters(*args)     # replace variables with their values
5056             self.hyp.SetVarParameter( parsed[-2], self.method.__name__ )
5057             result = self.method( self.hyp, *parsed[:-2] ) # call hypothesis method
5058         except omniORB.CORBA.BAD_PARAM: # raised by hypothesis method call
5059             # maybe there is a replaced string arg which is not variable
5060             result = self.method( self.hyp, *args )
5061         except ValueError, detail: # raised by ParseParameters()
5062             try:
5063                 result = self.method( self.hyp, *args )
5064             except omniORB.CORBA.BAD_PARAM:
5065                 raise ValueError, detail # wrong variable name
5066
5067         return result
5068     pass
5069
5070 # A helper class that call UnRegister() of SALOME.GenericObj'es stored in it
5071 class genObjUnRegister:
5072
5073     def __init__(self, genObj=None):
5074         self.genObjList = []
5075         self.set( genObj )
5076         return
5077
5078     def set(self, genObj):
5079         "Store one or a list of of SALOME.GenericObj'es"
5080         if isinstance( genObj, list ):
5081             self.genObjList.extend( genObj )
5082         else:
5083             self.genObjList.append( genObj )
5084         return
5085
5086     def __del__(self):
5087         for genObj in self.genObjList:
5088             if genObj and hasattr( genObj, "UnRegister" ):
5089                 genObj.UnRegister()
5090
5091 for pluginName in os.environ[ "SMESH_MeshersList" ].split( ":" ):
5092     #
5093     #print "pluginName: ", pluginName
5094     pluginBuilderName = pluginName + "Builder"
5095     try:
5096         exec( "from salome.%s.%s import *" % (pluginName, pluginBuilderName))
5097     except Exception, e:
5098         from salome_utils import verbose
5099         if verbose(): print "Exception while loading %s: %s" % ( pluginBuilderName, e )
5100         continue
5101     exec( "from salome.%s import %s" % (pluginName, pluginBuilderName))
5102     plugin = eval( pluginBuilderName )
5103     #print "  plugin:" , str(plugin)
5104
5105     # add methods creating algorithms to Mesh
5106     for k in dir( plugin ):
5107         if k[0] == '_': continue
5108         algo = getattr( plugin, k )
5109         #print "             algo:", str(algo)
5110         if type( algo ).__name__ == 'classobj' and hasattr( algo, "meshMethod" ):
5111             #print "                     meshMethod:" , str(algo.meshMethod)
5112             if not hasattr( Mesh, algo.meshMethod ):
5113                 setattr( Mesh, algo.meshMethod, algoCreator() )
5114                 pass
5115             getattr( Mesh, algo.meshMethod ).add( algo )
5116             pass
5117         pass
5118     pass
5119 del pluginName