Salome HOME
Creating Remote and SA NETGEN_3D plugins
[plugins/netgenplugin.git] / src / NETGENPlugin / NETGENPlugin_NETGEN_3D_Remote.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //=============================================================================
24 // File      : NETGENPlugin_NETGEN_3D_Remote.cxx
25 // Created   : lundi 19 Septembre 2022
26 // Author    : Yoann AUDOUIN (CEA)
27 // Project   : SALOME
28 //=============================================================================
29 //
30 //
31 #include "NETGENPlugin_NETGEN_3D_Remote.hxx"
32
33 #include "NETGENPlugin_NETGEN_3D.hxx"
34
35 #include "NETGENPlugin_DriverParam.hxx"
36 #include "NETGENPlugin_Hypothesis.hxx"
37
38 #include <SMESH_Gen.hxx>
39 #include <SMESH_Mesh.hxx>
40 #include <SMESH_MesherHelper.hxx>
41 #include <SMESH_DriverShape.hxx>
42 #include <SMESH_DriverMesh.hxx>
43 #include <SMESHDS_Mesh.hxx>
44
45 #include <QString>
46 #include <QProcess>
47
48 #include <boost/filesystem.hpp>
49 namespace fs = boost::filesystem;
50
51 /*
52   Netgen include files
53 */
54
55 #ifndef OCCGEOMETRY
56 #define OCCGEOMETRY
57 #endif
58 #include <occgeom.hpp>
59
60 #ifdef NETGEN_V5
61 #include <ngexception.hpp>
62 #endif
63 #ifdef NETGEN_V6
64 #include <core/exception.hpp>
65 #endif
66
67 namespace nglib {
68 #include <nglib.h>
69 }
70 namespace netgen {
71
72   NETGENPLUGIN_DLL_HEADER
73   extern MeshingParameters mparam;
74
75   NETGENPLUGIN_DLL_HEADER
76   extern volatile multithreadt multithread;
77 }
78 using namespace nglib;
79
80 //=============================================================================
81 /*!
82  *
83  */
84 //=============================================================================
85
86 NETGENPlugin_NETGEN_3D_Remote::NETGENPlugin_NETGEN_3D_Remote(int hypId, SMESH_Gen * gen)
87   : NETGENPlugin_NETGEN_3D(hypId, gen)
88 {
89   _name = "NETGEN_3D_Remote";
90 }
91
92 //=============================================================================
93 /*!
94  *
95  */
96 //=============================================================================
97
98 NETGENPlugin_NETGEN_3D_Remote::~NETGENPlugin_NETGEN_3D_Remote()
99 {
100 }
101
102
103 void NETGENPlugin_NETGEN_3D_Remote::fillParameters(const NETGENPlugin_Hypothesis* hyp, netgen_params &aParams)
104 {
105   aParams.maxh               = hyp->GetMaxSize();
106   aParams.minh               = hyp->GetMinSize();
107   aParams.segmentsperedge    = hyp->GetNbSegPerEdge();
108   aParams.grading            = hyp->GetGrowthRate();
109   aParams.curvaturesafety    = hyp->GetNbSegPerRadius();
110   aParams.secondorder        = hyp->GetSecondOrder() ? 1 : 0;
111   aParams.quad               = hyp->GetQuadAllowed() ? 1 : 0;
112   aParams.optimize           = hyp->GetOptimize();
113   aParams.fineness           = hyp->GetFineness();
114   aParams.uselocalh          = hyp->GetSurfaceCurvature();
115   aParams.merge_solids       = hyp->GetFuseEdges();
116   aParams.chordalError       = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
117   aParams.optsteps2d         = aParams.optimize ? hyp->GetNbSurfOptSteps() : 0;
118   aParams.optsteps3d         = aParams.optimize ? hyp->GetNbVolOptSteps()  : 0;
119   aParams.elsizeweight       = hyp->GetElemSizeWeight();
120   aParams.opterrpow          = hyp->GetWorstElemMeasure();
121   aParams.delaunay           = hyp->GetUseDelauney();
122   aParams.checkoverlap       = hyp->GetCheckOverlapping();
123   aParams.checkchartboundary = hyp->GetCheckChartBoundary();
124 #ifdef NETGEN_V6
125   // std::string
126   aParams.meshsizefilename = hyp->GetMeshSizeFile();
127 #else
128   // const char*
129   aParams.meshsizefilename = hyp->GetMeshSizeFile();
130 #endif
131 #ifdef NETGEN_V6
132   aParams.closeedgefac = 2;
133 #else
134   aParams.closeedgefac = 0;
135 #endif
136 }
137
138 // write in a binary file the orientation for each 2D element of the mesh
139 void NETGENPlugin_NETGEN_3D_Remote::exportElementOrientation(SMESH_Mesh& aMesh,
140                                                       const TopoDS_Shape& aShape,
141                                                       netgen_params& aParams,
142                                                       const std::string output_file)
143 {
144   SMESH_MesherHelper helper(aMesh);
145   NETGENPlugin_Internals internals( aMesh, aShape, /*is3D=*/true );
146   SMESH_ProxyMesh::Ptr proxyMesh( new SMESH_ProxyMesh( aMesh ));
147   std::map<vtkIdType, bool> elemOrientation;
148
149   for ( TopExp_Explorer exFa( aShape, TopAbs_FACE ); exFa.More(); exFa.Next())
150   {
151     const TopoDS_Shape& aShapeFace = exFa.Current();
152     int faceID = aMesh.GetMeshDS()->ShapeToIndex( aShapeFace );
153     bool isInternalFace = internals.isInternalShape( faceID );
154     bool isRev = false;
155     if ( !isInternalFace &&
156           helper.NbAncestors(aShapeFace, aMesh, aShape.ShapeType()) > 1 )
157       // IsReversedSubMesh() can work wrong on strongly curved faces,
158       // so we use it as less as possible
159       isRev = helper.IsReversedSubMesh( TopoDS::Face( aShapeFace ));
160
161     const SMESHDS_SubMesh * aSubMeshDSFace = proxyMesh->GetSubMesh( aShapeFace );
162     if ( !aSubMeshDSFace ) continue;
163
164     SMDS_ElemIteratorPtr iteratorElem = aSubMeshDSFace->GetElements();
165     if ( aParams._quadraticMesh &&
166           dynamic_cast< const SMESH_ProxyMesh::SubMesh*>( aSubMeshDSFace ))
167     {
168       // add medium nodes of proxy triangles to helper (#16843)
169       while ( iteratorElem->more() )
170         helper.AddTLinks( static_cast< const SMDS_MeshFace* >( iteratorElem->next() ));
171
172       iteratorElem = aSubMeshDSFace->GetElements();
173     }
174     while ( iteratorElem->more() ) // loop on elements on a geom face
175     {
176       // check mesh face
177       const SMDS_MeshElement* elem = iteratorElem->next();
178       if ( !elem )
179         error( COMPERR_BAD_INPUT_MESH, "Null element encounters");
180       if ( elem->NbCornerNodes() != 3 )
181         error( COMPERR_BAD_INPUT_MESH, "Not triangle element encounters");
182       elemOrientation[elem->GetID()] = isRev;
183     } // loop on elements on a face
184   } // loop on faces of a SOLID or SHELL
185
186   {
187     std::ofstream df(output_file, ios::out|ios::binary);
188     int size=elemOrientation.size();
189
190     df.write((char*)&size, sizeof(int));
191     for(auto const& [id, orient]:elemOrientation){
192       df.write((char*)&id, sizeof(vtkIdType));
193       df.write((char*)&orient, sizeof(bool));
194     }
195   }
196 }
197
198
199 bool NETGENPlugin_NETGEN_3D_Remote::Compute(SMESH_Mesh&         aMesh,
200                                            const TopoDS_Shape& aShape)
201 {
202   aMesh.Lock();
203   SMESH_Hypothesis::Hypothesis_Status hypStatus;
204   NETGENPlugin_NETGEN_3D::CheckHypothesis(aMesh, aShape, hypStatus);
205
206
207   // Temporary folder for run
208   fs::path tmp_folder = aMesh.tmp_folder / fs::unique_path(fs::path("Volume-%%%%-%%%%"));
209   fs::create_directories(tmp_folder);
210   // Using MESH2D generated after all triangles where created.
211   fs::path mesh_file=aMesh.tmp_folder / fs::path("Mesh2D.med");
212   fs::path element_orientation_file=tmp_folder / fs::path("element_orientation.dat");
213   fs::path new_element_file=tmp_folder / fs::path("new_elements.dat");
214   fs::path tmp_mesh_file=tmp_folder / fs::path("tmp_mesh.med");
215   // Not used kept for debug
216   //fs::path output_mesh_file=tmp_folder / fs::path("output_mesh.med");
217   fs::path shape_file=tmp_folder / fs::path("shape.brep");
218   fs::path param_file=tmp_folder / fs::path("netgen3d_param.txt");
219   fs::path log_file=tmp_folder / fs::path("run.log");
220   fs::path cmd_file=tmp_folder / fs::path("cmd.log");
221   //TODO: Handle variable mesh_name
222   std::string mesh_name = "Maillage_1";
223
224   //Writing Shape
225   exportShape(shape_file.string(), aShape);
226
227   //Writing hypo
228   netgen_params aParams;
229   std::cout << _hypParameters << std::endl;
230   fillParameters(_hypParameters, aParams);
231
232   exportNetgenParams(param_file.string(), aParams);
233
234   // Exporting element orientation
235   exportElementOrientation(aMesh, aShape, aParams, element_orientation_file.string());
236
237   aMesh.Unlock();
238   // Calling run_mesher
239   // TODO: check if we need to handle the .exe for windows
240   std::string cmd;
241   fs::path run_mesher_exe =
242     fs::path(std::getenv("NETGENPLUGIN_ROOT_DIR"))/
243     fs::path("bin")/
244     fs::path("salome")/
245     fs::path("NETGENPlugin_Runner");
246
247   cmd = run_mesher_exe.string() +
248                   " NETGEN3D " + mesh_file.string() + " "
249                                + shape_file.string() + " "
250                                + param_file.string() + " "
251                                + element_orientation_file.string() + " "
252                                + std::to_string(aMesh.GetMesherNbThreads()) + " "
253                                + new_element_file.string() + " "
254                                + "NONE";
255   // Writing command in log
256   {
257     std::ofstream flog(cmd_file.string());
258     flog << cmd << endl;
259     flog << endl;
260   }
261   //std::cout << "Running command: " << std::endl;
262   //std::cout << cmd << std::endl;
263
264
265   // Building arguments for QProcess
266   QString program = run_mesher_exe.c_str();
267   QStringList arguments;
268   arguments << "NETGEN3D";
269   arguments << mesh_file.c_str();
270   arguments << shape_file.c_str();
271   arguments << param_file.c_str();
272   arguments << element_orientation_file.c_str();
273   arguments << std::to_string(aMesh.GetMesherNbThreads()).c_str();
274   arguments << new_element_file.c_str();
275   arguments << "NONE";
276   QString out_file = log_file.c_str();
277   QProcess myProcess;
278   myProcess.setStandardOutputFile(out_file);
279
280   myProcess.start(program, arguments);
281   myProcess.waitForFinished();
282   int ret = myProcess.exitStatus();
283
284   if(ret != 0){
285     // Run crahed
286     std::cout << "Issue with command: " << std::endl;
287     std::cout << "See log for more details: " << log_file.string() << std::endl;
288     std::cout << cmd << std::endl;
289     return false;
290   }
291
292   aMesh.Lock();
293   {
294     std::ifstream df(new_element_file.string(), ios::binary);
295
296     int Netgen_NbOfNodes;
297     int Netgen_NbOfNodesNew;
298     int Netgen_NbOfTetra;
299     double Netgen_point[3];
300     int    Netgen_tetrahedron[4];
301     int nodeID;
302
303     SMESH_MesherHelper helper(aMesh);
304     // This function is mandatory for setElementsOnShape to work
305     helper.IsQuadraticSubMesh(aShape);
306     helper.SetElementsOnShape( true );
307
308     // Number of nodes in intial mesh
309     df.read((char*) &Netgen_NbOfNodes, sizeof(int));
310     // Number of nodes added by netgen
311     df.read((char*) &Netgen_NbOfNodesNew, sizeof(int));
312
313     // Filling nodevec (correspondence netgen numbering mesh numbering)
314     vector< const SMDS_MeshNode* > nodeVec ( Netgen_NbOfNodesNew + 1 );
315     //vector<int> nodeTmpVec ( Netgen_NbOfNodesNew + 1 );
316     SMESHDS_Mesh * meshDS = helper.GetMeshDS();
317     for (int nodeIndex = 1 ; nodeIndex <= Netgen_NbOfNodes; ++nodeIndex )
318     {
319       //Id of the point
320       df.read((char*) &nodeID, sizeof(int));
321       nodeVec.at(nodeIndex) = meshDS->FindNode(nodeID);
322     }
323
324     // Add new points and update nodeVec
325     for (int nodeIndex = Netgen_NbOfNodes +1 ; nodeIndex <= Netgen_NbOfNodesNew; ++nodeIndex )
326     {
327       df.read((char *) &Netgen_point, sizeof(double)*3);
328
329       nodeVec.at(nodeIndex) = helper.AddNode(Netgen_point[0],
330                                  Netgen_point[1],
331                                  Netgen_point[2]);
332     }
333
334     // Add tetrahedrons
335     df.read((char*) &Netgen_NbOfTetra, sizeof(int));
336
337     for ( int elemIndex = 1; elemIndex <= Netgen_NbOfTetra; ++elemIndex )
338     {
339       df.read((char*) &Netgen_tetrahedron, sizeof(int)*4);
340       helper.AddVolume(
341                     nodeVec.at( Netgen_tetrahedron[0] ),
342                     nodeVec.at( Netgen_tetrahedron[1] ),
343                     nodeVec.at( Netgen_tetrahedron[2] ),
344                     nodeVec.at( Netgen_tetrahedron[3] ));
345     }
346   }
347
348   aMesh.Unlock();
349
350   return true;
351 }