Salome HOME
Porting to MeshGems 2.10: additional correction to avoid crash
[plugins/blsurfplugin.git] / src / BLSURFPlugin / BLSURFPluginBuilder.py
index 3b443a95783717ff7e7cb72cab50b61b1c98b181..1571de3eb6b092d71a4b15bbcd66fcda97b9baeb 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (C) 2007-2016  CEA/DEN, EDF R&D
+# Copyright (C) 2007-2019  CEA/DEN, EDF R&D
 #
 # This library is free software; you can redistribute it and/or
 # modify it under the terms of the GNU Lesser General Public
 # Python API for the MG-CADSurf meshing plug-in module.
 
 from salome.smesh.smesh_algorithm import Mesh_Algorithm
+import GEOM
 
 LIBRARY = "libBLSURFEngine.so"
 
+# ElementType enum
+Triangles, QuadrangleDominant, Quadrangles = 0, 1, 2
+
 # Topology treatment way of MG-CADSurf
 FromCAD, PreProcess, PreProcessPlus, PreCAD = 0,1,2,3
 
@@ -74,6 +78,7 @@ class BLSURF_Algorithm(Mesh_Algorithm):
   _bad_surface_element_aspect_ratio = 1000
   _geometric_approximation = 22
   _gradation  = 1.3
+  _volume_gradation  = 2
   _metric = "isotropic"
   _remove_tiny_edges = 0
 
@@ -84,8 +89,12 @@ class BLSURF_Algorithm(Mesh_Algorithm):
   def __init__(self, mesh, geom=0):
     Mesh_Algorithm.__init__(self)
     if noBLSURFPlugin:
-      print "Warning: BLSURFPlugin module unavailable"
-    self.Create(mesh, geom, BLSURF, LIBRARY)
+      print("Warning: BLSURFPlugin module unavailable")
+    if mesh.GetMesh().HasShapeToMesh():
+      self.Create(mesh, geom, self.algoType, LIBRARY)
+    else:
+      self.Create(mesh, geom, self.algoType+"_NOGEOM", LIBRARY)
+      mesh.smeshpyD.SetName( self.algo, self.algoType )
     self.params=None
     self.geompyD = mesh.geompyD
     #self.SetPhysicalMesh() - PAL19680
@@ -158,12 +167,25 @@ class BLSURF_Algorithm(Mesh_Algorithm):
     pass
 
   ## Sets maximal allowed ratio between the lengths of two adjacent edges.
+  #  @param toUseGradation to use gradation
   #  @param theVal value of maximal length ratio
-  def SetGradation(self, theVal=_gradation):
+  def SetGradation(self, toUseGradation=True, theVal=_gradation):
+    if isinstance( toUseGradation, float ): ## backward compatibility
+      toUseGradation, theVal = True, toUseGradation
     if self.Parameters().GetGeometricMesh() == 0: theVal = self._gradation
+    self.Parameters().SetUseGradation(toUseGradation)
     self.Parameters().SetGradation(theVal)
     pass
 
+  ## Sets maximal allowed ratio between the lengths of two adjacent edges in 3D mesh.
+  #  @param toUseGradation to use gradation
+  #  @param theVal value of maximal length ratio
+  def SetVolumeGradation(self, toUseGradation=True, theVal=_gradation):
+    if self.Parameters().GetGeometricMesh() == 0: theVal = self._volume_gradation
+    self.Parameters().SetUseVolumeGradation(toUseGradation)
+    self.Parameters().SetVolumeGradation(theVal)
+    pass
+
   ## Sets topology usage way.
   # @param way defines how mesh conformity is assured <ul>
   # <li>FromCAD - mesh conformity is assured by conformity of a shape</li>
@@ -171,19 +193,53 @@ class BLSURF_Algorithm(Mesh_Algorithm):
   # <li>PreCAD - by pre-processing with PreCAD a CAD model</li></ul>
   def SetTopology(self, way):
     if way != PreCAD and way != FromCAD:
-      print "Warning: topology mode %d is no longer supported. Mode FromCAD is used."%way
+      print("Warning: topology mode %d is no longer supported. Mode FromCAD is used."%way)
       way = FromCAD
     self.Parameters().SetTopology(way)
     pass
 
-  ## To respect geometrical edges or not.
-  #  @param toIgnoreEdges "ignore edges" flag value
-  def SetDecimesh(self, toIgnoreEdges=False):
-    if toIgnoreEdges:
-      self.SetOptionValue("respect_geometry","0")
-    else:
-      self.SetOptionValue("respect_geometry","1")
-    pass
+  ## Activate/deactivate surface proximity computation
+  # @param toUse boolean flag
+  #
+  def SetSurfaceProximity(self, toUse ):
+    self.Parameters().SetSurfaceProximity(toUse)
+    return
+
+  ## Set number of surface element layers to be generated due to surface proximity
+  # @param nbLayers number of layers
+  #
+  def SetNbSurfaceProximityLayers(self, nbLayers ):
+    self.Parameters().SetNbSurfaceProximityLayers( nbLayers )
+    return
+
+  ## Set coefficient by which size of element refined due to surface proximity is increased
+  # @param ratio proximity coefficient
+  #
+  def SetSurfaceProximityRatio(self, ratio ):
+    self.Parameters().SetSurfaceProximityRatio(ratio)
+    return
+  
+  ## Activate/deactivate volume proximity computation
+  # @param toUse boolean flag
+  #
+  def SetVolumeProximity(self, toUse ):
+    self.Parameters().SetVolumeProximity(toUse)
+    return
+  
+  ## Set number of surface element layers to be generated due to volume proximity
+  # @param nbLayers number of layers
+  #
+  def SetNbVolumeProximityLayers(self, nbLayers ):
+    self.Parameters().SetNbVolumeProximityLayers(nbLayers)
+    return
+
+  ## Set coefficient by which size of element refined due to volume proximity is increased
+  # @param ratio proximity coefficient
+  #
+  def SetVolumeProximityRatio(self, ratio ):
+    self.Parameters().SetVolumeProximityRatio(ratio)
+    return
+
 
   ## Sets verbosity level in the range 0 to 100.
   #  @param level verbosity level
@@ -191,18 +247,185 @@ class BLSURF_Algorithm(Mesh_Algorithm):
     self.Parameters().SetVerbosity(level)
     pass
 
+  ## Set enforce_cad_edge_sizes parameter
+  #  
+  #  Relaxes the given sizemap constraint around CAD edges to allow a better
+  #  element quality and a better geometric approximation. It is only useful in 
+  #  combination with the gradation option.
+  #  
+  def SetEnforceCadEdgesSize( self, toEnforce ):
+    self.Parameters().SetEnforceCadEdgesSize( toEnforce )
+
+  ## Set jacobian_rectification_respect_geometry parameter
+  #  
+  #  While making the mesh quadratic, allows to lose the CAD-mesh associativity in order
+  #  to correct elements with nagative Jacobian
+  #  
+  def SetJacobianRectificationRespectGeometry( self, allowRectification ):
+    self.Parameters().SetJacobianRectificationRespectGeometry( allowRectification )
+    
+  ## Set rectify_jacobian parameter
+  #  
+  #  While making the mesh quadratic, allow to fix nagative Jacobian surface elements
+  #  
+  def SetJacobianRectification( self, allowRectification ):
+    self.Parameters().SetJacobianRectification( allowRectification )
+
+  ## Set use_deprecated_patch_mesher parameter (compatibility with older versions of Meshgems)
+  #  
+  # the use_deprecated_patch_mesher parameter allows to keep the same behaviour than
+  # in salome < 8.3 (meshgems 2.1.11 instead of meshgems >= 2.4.5)
+  #  
+  def SetUseDeprecatedPatchMesher( self, useDeprecatedPatchMesher ):
+    self.Parameters().SetUseDeprecatedPatchMesher( useDeprecatedPatchMesher )
+
+  ## Set respect_geometry parameter
+  #  
+  #  This patch independent option can be deactivated to allow MeshGems-CADSurf
+  #  to lower the geometry accuracy in its patch independent process.
+  #  
+  def SetRespectGeometry( self, toRespect ):
+    self.Parameters().SetRespectGeometry( toRespect )
+
+  ## Set max_number_of_points_per_patch parameter
+  #  
+  #  This parameter controls the maximum amount of points MeshGems-CADSurf is allowed
+  #  to generate on a single CAD patch. For an automatic gestion of the memory, one
+  #  can set this parameter to 0
+  #  
+  def SetMaxNumberOfPointsPerPatch( self, nb ):
+    print("Warning: method SetMaxNumberOfPointsPerPatch() is deprecated")
+    self.Parameters().SetMaxNumberOfPointsPerPatch( nb )
+
+  ## Set max_number_of_threads parameter
+  #
+  #  Set the maximum of threads to use for multithreading mesh computation
+  #
+  def SetMaxNumberOfThreads( self, nb ):
+    self.Parameters().SetMaxNumberOfThreads( nb )
+
+  ## Set respect_geometry parameter
+  #  
+  #  This patch independent option can be deactivated to allow MeshGems-CADSurf
+  #  to lower the geometry accuracy in its patch independent process.
+  #  
+  def SetRespectGeometry( self, toRespect ):
+    self.Parameters().SetRespectGeometry( toRespect )
+
+  ## Set tiny_edges_avoid_surface_intersections parameter
+  #  
+  #  This option defines the priority between the tiny feature
+  #  suppression and the surface intersection prevention. 
+  #  
+  def SetTinyEdgesAvoidSurfaceIntersections( self, toAvoidIntersection ):
+    self.Parameters().SetTinyEdgesAvoidSurfaceIntersections( toAvoidIntersection )
+
+  ## Set closed_geometry parameter parameter
+  #  
+  #  Describes whether the geometry is expected to be closed or not. 
+  #  When activated, this option helps MeshGems-PreCAD to treat the dirtiest geometries.
+  #  
+  def SetClosedGeometry( self, isClosed ):
+    self.Parameters().SetClosedGeometry( isClosed )
+
+  ## Set debug parameter
+  #  
+  #  Make MeshGems-CADSurf will be very verbose and will output some intermediate
+  #  files in the working directory. This option is mainly meant for Distene support issues.
+  #  
+  def SetDebug( self, isDebug ):
+    self.Parameters().SetDebug( isDebug )
+
+  ## Set periodic_tolerance parameter
+  #  
+  #  This parameter defines the maximum size difference between two periodic edges
+  #  and also the maximum distance error between two periodic entities.
+  #  
+  def SetPeriodicTolerance( self, tol ):
+    self.Parameters().SetPeriodicTolerance( tol )
+
+  ## Set required_entities parameter
+  #  
+  #  The required entities control the correction operations. 
+  #  Accepted values for this parameter are :
+  #  - "respect" : MeshGems-CADSurf is not allowed to alter any required entity, 
+  #                even for correction purposes,
+  #  - "ignore" : MeshGems-CADSurf will ignore the required entities in its processing,
+  #  - "clear" : MeshGems-CADSurf will clear any required status for the entities. 
+  #              There will not be any entity marked as required in the generated mesh.
+  #  
+  def SetRequiredEntities( self, howToTreat ):
+    self.Parameters().SetRequiredEntities( howToTreat )
+
+  ## Set sewing_tolerance parameter
+  #  
+  #  This parameter is the tolerance of the assembly.
+  #  
+  def SetSewingTolerance( self, tol ):
+    self.Parameters().SetSewingTolerance( tol )
+
+  ## Set tags parameter
+  #  
+  #  The tag (attribute) system controls the optimisation process. 
+  #  Accepted values for this parameter are :
+  #  - "respect"  : the CAD tags will be preserved and unaltered by the optimisation operations,
+  #  - "ignore" : the CAD tags will be ignored by the optimisation operations 
+  #               but they will still be present in the output mesh,
+  #  - "clear" : MeshGems-CADSurf will clear any tag on any entity and optimise accordingly. 
+  #              There will not be any tag in the generated mesh.
+  #  
+  def SetTags( self, howToTreat ):
+    self.Parameters().SetTags( howToTreat )
+
+  ## Activate/deactivate fully patch independent meshing
+  #   @param isIndependent boolean flag
+  #
+  # This feature can only be used if the @a tags parameter is set to "respect".
+  # By default this option deactivated.
+  #
+  def SetPatchIndependent( self, isIndependent ):
+    self.SetOptionValue( "allow_patch_independent", "yes" if isIndependent else "no" )
+
+  ## Set to preserve lines defined by a sharp angle in the input discrete geometry
+  #   @param toCompute boolean flag
+  #
+  # If this option is deactivated, MeshGems-CADSurf will not try to preserve lines
+  # defined by a sharp angle in the input discrete geometry. Only input ridges, free
+  # edges, non manifold edges and separation betwen zones with different attributes
+  # will be respected (if tags is set to respect).
+  # By default this option activated.
+  #
+  def SetComputeRidges( self, toCompute ):
+    self.SetOptionValue( "compute_ridges", "yes" if toCompute else "no" )
+
+
+  ## Activate removal of the tiny edges from the generated
+  # mesh when it improves the local mesh quality, without taking into account the
+  # tags (attributes) specifications.
+  #  @param toOptimise "to optimize" flag value
+  #  @param length minimal length under which an edge is considered to be a tiny
+  def SetOptimiseTinyEdges(self, toOptimise, length=-1):
+    self.Parameters().SetOptimiseTinyEdges( toOptimise )
+    if toOptimise:
+      self.Parameters().SetTinyEdgeOptimisationLength( length )
+
+  ## Activate correction of all surface intersections
+  #  @param toCorrect "to correct" flag value
+  #  @param maxCost  the time the user is ready to spend in the intersection prevention process
+  #         For example, maxCost = 3 means that MeshGems-CADSurf will not spend more time
+  #         in the intersection removal process than 3 times the time required to mesh
+  #         without processing the intersections.
+  def SetCorrectSurfaceIntersection(self, toCorrect, maxCost ):
+    self.Parameters().SetCorrectSurfaceIntersection( toCorrect )
+    if toCorrect:
+      self.Parameters().SetCorrectSurfaceIntersectionMaxCost( maxCost )
+
   ## To optimize merges edges.
   #  @param toMergeEdges "merge edges" flag value
   def SetPreCADMergeEdges(self, toMergeEdges=False):
     self.Parameters().SetPreCADMergeEdges(toMergeEdges)
     pass
 
-  ## To remove tiny UV edges.
-  #  @param toRemoveTinyUVEdges "remove_tiny_uv_edges" flag value
-  def SetPreCADRemoveTinyUVEdges(self, toRemoveTinyUVEdges=False):
-    self.Parameters().SetPreCADRemoveTinyUVEdges(toRemoveTinyUVEdges)
-    pass
-
   ## To remove duplicate CAD Faces
   #  @param toRemoveDuplicateCADFaces "remove_duplicate_cad_faces" flag value
   def SetPreCADRemoveDuplicateCADFaces(self, toRemoveDuplicateCADFaces=False):
@@ -251,6 +474,12 @@ class BLSURF_Algorithm(Mesh_Algorithm):
     self.Parameters().SetPreCADOptionValue(optionName,optionValue)
     pass
   
+  ## Adds custom advanced option values
+  #  @param optionsAndValues options and values in a form "option_1 v1 option_2 v2'"
+  def SetAdvancedOption(self, optionsAndValues):
+    self.Parameters().SetAdvancedOption(optionsAndValues)
+    pass
+
   ## Adds custom advanced option value.
   #  @param optionName custom advanced option name
   #  @param level custom advanced option value
@@ -340,6 +569,42 @@ class BLSURF_Algorithm(Mesh_Algorithm):
       return self.Parameters().SetEnforcedVertexGeomWithGroup(theFace, theVertex,groupName)
     pass
 
+  ## Set an enforced vertex on a face given the coordinates of a point.
+  #  The face if found by the application.
+  #  @param x            : x coordinate
+  #  @param y            : y coordinate
+  #  @param z            : z coordinate
+  #  @param vertexName   : name of the enforced vertex
+  #  @param groupName    : name of the group
+  def AddEnforcedVertex(self, x, y, z, vertexName = "", groupName = ""):
+    from salome.smesh.smeshBuilder import AssureGeomPublished
+    if vertexName == "":
+      if groupName == "":
+        return self.Parameters().AddEnforcedVertex(x, y, z)
+      else:
+        return self.Parameters().AddEnforcedVertexWithGroup(x, y, z, groupName)
+      pass
+    else:
+      if groupName == "":
+        return self.Parameters().AddEnforcedVertexNamed(x, y, z, vertexName)
+      else:
+        return self.Parameters().AddEnforcedVertexNamedWithGroup( x, y, z, vertexName, groupName)
+      pass
+    pass
+
+  ## To set an enforced vertex on a face given a GEOM vertex, group or compound.
+  #  The face if found by the application.
+  #  @param theVertex    : GEOM vertex (or group, compound).
+  #  @param groupName    : name of the group
+  def AddEnforcedVertexGeom(self, theVertex, groupName = ""):
+    from salome.smesh.smeshBuilder import AssureGeomPublished
+    AssureGeomPublished( self.mesh, theVertex )
+    if groupName == "":
+      return self.Parameters().AddEnforcedVertexGeom(theVertex)
+    else:
+      return self.Parameters().AddEnforcedVertexGeomWithGroup(theVertex,groupName)
+    pass
+
   ## To remove an enforced vertex on a given GEOM face (or group, compound) given the coordinates.
   #  @param theFace      : GEOM face (or group, compound) on which to remove the enforced vertex
   #  @param x            : x coordinate
@@ -447,18 +712,30 @@ class BLSURF_Algorithm(Mesh_Algorithm):
     self.Parameters().ClearSizeMaps()
     pass
 
-  ## Sets QuadAllowed flag.
+  ## Sets QuadAllowed flag (DEPRECATED: use SetElementType)
   #  @param toAllow "allow quadrangles" flag value
+  # TODO: to remove in Salome 9
   def SetQuadAllowed(self, toAllow=True):
     self.Parameters().SetQuadAllowed(toAllow)
     pass
 
+  ## Sets elements type
+  #  @param theElementType: 0 (Triangles), 1 (QuadrangleDominant), 2 (Quadrangles)
+  def SetElementType(self, theElementType=Triangles):
+    self.Parameters().SetElementType(theElementType)
+    pass
+
   ## Defines hypothesis having several parameters
   #  @return hypothesis object
   def Parameters(self):
     if not self.params:
-      self.params = self.Hypothesis("MG-CADSurf Parameters", [],
-                                    LIBRARY, UseExisting=0)
+      hypType = "MG-CADSurf Parameters"
+      hasGeom = self.mesh.GetMesh().HasShapeToMesh()
+      if hasGeom:
+        self.params = self.Hypothesis(hypType, [], LIBRARY, UseExisting=0)
+      else:
+        self.params = self.Hypothesis(hypType + "_NOGEOM", [], LIBRARY, UseExisting=0)
+        self.mesh.smeshpyD.SetName( self.params, hypType )
       pass
     return self.params
 
@@ -504,66 +781,34 @@ class BLSURF_Algorithm(Mesh_Algorithm):
         self.Parameters().AddPreCadEdgesPeriodicity(theEdge1, theEdge2)
     pass
 
-  #=====================
-  # Obsolete methods
-  #=====================
-  #
-  # SALOME 6.6.0
-  #
-
-  ## Sets lower boundary of mesh element size (PhySize).
-  def SetPhyMin(self, theVal=-1):
-    """
-    Obsolete function. Use SetMinSize.
-    """
-    print "Warning: SetPhyMin is obsolete. Please use SetMinSize"
-    self.SetMinSize(theVal)
-    pass
-
-  ## Sets upper boundary of mesh element size (PhySize).
-  def SetPhyMax(self, theVal=-1):
-    """
-    Obsolete function. Use SetMaxSize.
-    """
-    print "Warning: SetPhyMax is obsolete. Please use SetMaxSize"
-    self.SetMaxSize(theVal)
-    pass
-
-  ## Sets angular deflection (in degrees) of a mesh face from CAD surface.
-  def SetAngleMeshS(self, theVal=_geometric_approximation):
-    """
-    Obsolete function. Use SetAngleMesh.
-    """
-    print "Warning: SetAngleMeshS is obsolete. Please use SetAngleMesh"
-    self.SetAngleMesh(theVal)
-    pass
-
-  ## Sets angular deflection (in degrees) of a mesh edge from CAD curve.
-  def SetAngleMeshC(self, theVal=_geometric_approximation):
-    """
-    Obsolete function. Use SetAngleMesh.
-    """
-    print "Warning: SetAngleMeshC is obsolete. Please use SetAngleMesh"
-    self.SetAngleMesh(theVal)
-    pass
-
-  ## Sets lower boundary of mesh element size computed to respect angular deflection.
-  def SetGeoMin(self, theVal=-1):
-    """
-    Obsolete function. Use SetMinSize.
-    """
-    print "Warning: SetGeoMin is obsolete. Please use SetMinSize"
-    self.SetMinSize(theVal)
-    pass
-
-  ## Sets upper boundary of mesh element size computed to respect angular deflection.
-  def SetGeoMax(self, theVal=-1):
-    """
-    Obsolete function. Use SetMaxSize.
-    """
-    print "Warning: SetGeoMax is obsolete. Please use SetMaxSize"
-    self.SetMaxSize(theVal)
-    pass
-
+  #-----------------------------------------
+  # Hyper-Patches
+  #-----------------------------------------
+  
+  ## Defines hyper-patches. A hyper-patch is a set of adjacent faces meshed as a whole,
+  #  ignoring edges between them
+  #  @param hyperPatchList : list of hyper-patches. A hyper-patch is defined as a list of
+  #         faces or groups of faces. A face can be identified either as a GEOM object or
+  #         a face ID (returned e.g. by geompy.GetSubShapeID( mainShape, subShape )).
+  #         
+  #  Example: cadsurf.SetHyperPatches([[ Face_1, Group_2 ],[ 13, 23 ]])
+  def SetHyperPatches(self, hyperPatchList):
+    hpl = []
+    for patch in hyperPatchList:
+      ids = []
+      for face in patch:
+        if isinstance( face, int ):
+          ids.append( face )
+        elif isinstance( face, GEOM._objref_GEOM_Object):
+          faces = self.mesh.geompyD.SubShapeAll( face, self.mesh.geompyD.ShapeType["FACE"] )
+          for f in faces:
+            ids.append( self.mesh.geompyD.GetSubShapeID( self.mesh.geom, f ))
+        else:
+          raise TypeError("Face of hyper-patch should be either ID or GEOM_Object, not %s" % type(face))
+        pass
+      hpl.append( ids )
+      pass
+    self.Parameters().SetHyperPatches( hpl )
+    return
 
   pass # end of BLSURF_Algorithm class