Salome HOME
Copyright update 2020
[modules/smesh.git] / src / Tools / MacMesh / MacMesh / PublishGroups.py
1 # Copyright (C) 2014-2020  EDF R&D
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
20 #
21 import SMESH
22 import math
23 import Config
24
25 from salome.geom import geomBuilder
26 geompy = geomBuilder.New()
27
28 from salome.smesh import smeshBuilder
29 smesh = smeshBuilder.New()
30
31 ##########################################################################################################
32
33 def PublishGroups ():
34     aFilterManager = smesh.CreateFilterManager()
35
36     # Building geometric and mesh compounds and  groups ##############################################
37     if Config.debug : print("Searching for geometric groups and publishing final compound")
38
39     TempGEOList = []
40     TempMESHList = []
41
42     for MacroObj in Config.ListObj :
43         TempGEOList += MacroObj.GeoChildren
44         TempMESHList += MacroObj.Mesh
45
46     FinalCompound = geompy.MakeCompound(TempGEOList)
47     geompy.addToStudy (FinalCompound,Config.StudyName)
48     MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
49     MeshCompound.SetName(Config.StudyName)
50
51     GroupGEO = []
52     for group in Config.Groups :
53
54         # Geometric groups definition
55         TempGEOList = []
56         aFilterManager = smesh.CreateFilterManager()
57
58         # Building geometric and mesh compounds and  groups ##############################################
59         if Config.debug : print("Searching for geometric groups and publishing final compound")
60         
61         TempGEOList = []
62         TempMESHList = []
63         
64         for MacroObj in Config.ListObj : 
65                 TempGEOList += MacroObj.GeoChildren
66                 TempMESHList += MacroObj.Mesh
67                 
68         FinalCompound = geompy.MakeCompound(TempGEOList)
69         geompy.addToStudy (FinalCompound,Config.StudyName)
70         MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
71         MeshCompound.SetName(Config.StudyName)
72         
73         GroupGEO = []
74         for group in Config.Groups :
75         
76                 # Geometric groups definition
77                 TempGEOList = []
78                 TempNames = []
79                 for MacroObj in Config.ListObj :
80                         if group in MacroObj.GroupNames :
81                                 Occurrences = IndexMultiOcc(MacroObj.GroupNames, group)
82                                 for Occ in Occurrences :
83                                         TempGEOList += MacroObj.GetBorder(Occ)
84                 GroupGEO.append(geompy.MakeCompound(TempGEOList))
85                 geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
86                 
87                 # Mesh groups definition
88                 Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
89                 #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
90                 MeshCompound.MakeGroupByCriterion(group,Criterion)
91         
92         StudyBuilder = Config.theStudy.NewBuilder()
93         for MeshObj in TempMESHList:
94                 SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
95                 if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
96         
97         return MeshCompound        
98                 
99
100 def IndexMultiOcc (Array,Element) :
101     """
102     This function returns the occurrences indices of Element in Array.
103     As opposed to Array.index(Element) method, this allows determining
104     multiple entries rather than just the first one!
105     """
106     Output = []
107     try : Array.index(Element)
108     except ValueError : print("No more occurrences")
109     else : Output.append(Array.index(Element))
110
111     if not(Output == [-1]) and len(Array) > 1 :
112         for index, ArrElem in enumerate(Array[Output[0]+1:]) :
113             if ArrElem is Element : Output.append(index+Output[0]+1)
114
115     return Output
116
117 def Publish (ObjToPublish):
118     for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i))
119
120 def RevolveMesh(MainMesh,**args):
121         """
122         This function permits to revolute and scale a 2D mesh while transforming the edge
123         groups into face groups. Moreover, the function automatically creates the face groups 
124         corresponding to the symmetry lower and upper faces
125         Facultatif arguments are : 
126                 - Center [X,Y,Z], origin being the default
127                 - Direction [VX,VY,VZ], x-axis being the default
128                 - AngleDeg or AngleRad : ALPHA, 10 degrees being the default
129                 - Scale : BETA, no scaling being default
130         """
131         ################################################################################
132         # Reading input arguments and proceeding to defaults if necessary
133         ################################################################################       
134         if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']]
135         else : 
136                 print("\nThe coordinates of the center of revolution were not given\nThe origin is used by default.")
137                 CenterCoor = [0.,0.,0.]
138         
139         if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']]
140         else :
141                 print("\nThe axis vector of revolution was not given\nThe x-axis is used by default.")
142                 Direction = [1.,0.,0.]
143         
144         if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180.
145         elif 'AngleRad' in args : Angle = float(args['AngleRad'])
146         else :
147                 print("\nThe revolution angle was not given\nAn angle of 10 degrees is used by default.")
148                 Angle = 10.*math.pi/180.
149                 
150         if 'Scale' in args : Scale = float(args['Scale'])
151         else : Scale = 1.
152         
153
154         # Creating the lower face group LOFAC
155         LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
156         LOFAC.AddFrom(MainMesh.GetMesh())
157
158         GR_Names = MainMesh.GetGroupNames()
159         GRs = MainMesh.GetGroups()
160         Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True)
161
162         # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
163         for GR in GRs:
164                 CurrentName = GR.GetName()
165                 if CurrentName in GR_Names and not(CurrentName=='LOFAC'):  # Meaning that this is an old edge group
166                         GR.SetName(CurrentName+'_EDGE')
167
168         # Removing the _rotated prefix from the rotated FACE groups
169         for GR in Rev3DMeshGroups:
170                 CurrentName = GR.GetName()
171                 if CurrentName.endswith( "_rotated"):
172                         if CurrentName.startswith( 'LOFAC_' ):
173                                 GR.SetName('VOL')
174                         else:
175                                 GR.SetName(CurrentName[:-8])
176                 elif CurrentName == 'LOFAC_top':
177                         GR.SetName('HIFAC')
178                         #Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True)
179                         #GR.SetName(GR_Names[Index])
180
181         # Creating the upper face group HIFAC
182         ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
183         ALLFAC.AddFrom(MainMesh.GetMesh())
184
185         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
186         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' )
187
188         # Scaling down the mesh to meter units
189         if not(Scale==1.):
190                 MeshEditor = MainMesh.GetMeshEditor()
191                 MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
192      
193                 
194 def ExtrudeMesh(MainMesh,**args):
195         """
196         This function permits to extrude and scale a 2D mesh while transforming the edge
197         groups into face groups. Moreover, the function automatically creates the face groups 
198         corresponding to the symmetry lower and upper faces
199         Facultatif arguments are : 
200                 - Direction [VX,VY,VZ], z-axis being default
201                 - Distance : D, default is 1
202                 - NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1
203                 - Scale : BETA, no scaling being default
204         """
205         ################################################################################
206         # Reading input arguments and proceeding to defaults if necessary
207         ################################################################################              
208         if 'Distance' in args : Distance = float(args['Distance'])
209         else :
210                 print("\nThe extrusion distance was not given\nA default value of 1 is used.")
211                 Distance = 1.
212                 
213         if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance)
214         else :
215                 print("\nThe extrusion vector of revolution was not given\nThe z-axis is used by default.")
216                 Direction = NormalizeVector([0.,0.,1.],Distance)
217                                 
218         if 'Scale' in args : Scale = float(args['Scale'])
219         else : Scale = 1.
220         
221         if 'NSteps' in args : NSteps = int(args['NSteps'])
222         else : NSteps = 1
223         
224         # Creating the lower face group LOFAC
225         LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
226         LOFAC.AddFrom(MainMesh.GetMesh())
227
228         GR_Names = MainMesh.GetGroupNames()
229         GRs = MainMesh.GetGroups()
230         Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True)
231
232         # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
233         for GR in GRs:
234                 CurrentName = GR.GetName()
235                 if CurrentName in GR_Names and not(CurrentName=='LOFAC'):  # Meaning that this is an old edge group
236                         GR.SetName(CurrentName+'_EDGE')
237
238         # Removing the _extruded suffix from the extruded FACE groups
239         for GR in Ext3DMeshGroups:
240                 CurrentName = GR.GetName()
241                 if CurrentName.endswith( "_extruded"):
242                         if CurrentName.startswith( 'LOFAC_' ):
243                                 GR.SetName('VOL')
244                         else:
245                                 GR.SetName(CurrentName[:-9])
246                 elif CurrentName == 'LOFAC_top':
247                         GR.SetName('HIFAC')
248
249         # Creating the upper face group HIFAC
250         ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
251         ALLFAC.AddFrom(MainMesh.GetMesh())
252
253         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
254
255         # Scaling down the mesh to meter units
256         if not(Scale==1.):
257                 MeshEditor = MainMesh.GetMeshEditor()
258                 MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
259      
260                
261 def NormalizeVector (V,Norm):
262     """
263     This function returns a normalized vector (magnitude = Norm), parallel to the entered one
264     """
265     V = [float(Coor) for Coor in V]
266     Norm = float(Norm)
267     MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2])
268     return [Coor*Norm/MagV for Coor in V]