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