Salome HOME
Merge from V6_main 01/04/2013
[modules/smesh.git] / src / DriverSTL / DriverSTL_W_SMDS_Mesh.cxx
1 // Copyright (C) 2007-2013  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.
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 #include <stdio.h>
24 #include <limits>
25
26 #include "DriverSTL_W_SMDS_Mesh.h"
27
28 #include "SMDS_FaceOfNodes.hxx"
29 #include "SMDS_IteratorOnIterators.hxx"
30 #include "SMDS_Mesh.hxx"
31 #include "SMDS_MeshElement.hxx"
32 #include "SMDS_MeshNode.hxx"
33 #include "SMDS_SetIterator.hxx"
34 #include "SMDS_VolumeTool.hxx"
35 #include "SMESH_TypeDefs.hxx"
36
37 #include <OSD_File.hxx>
38 #include <OSD_Path.hxx>
39 #include <OSD_Protection.hxx>
40 #include <TCollection_AsciiString.hxx>
41 #include <gp_XYZ.hxx>
42 #include <Basics_Utils.hxx>
43
44 #include "utilities.h"
45
46 // definition des constantes 
47 static const int LABEL_SIZE = 80;
48
49 DriverSTL_W_SMDS_Mesh::DriverSTL_W_SMDS_Mesh()
50 {
51   myIsAscii = false;
52 }
53
54 void DriverSTL_W_SMDS_Mesh::SetIsAscii( const bool theIsAscii )
55 {
56   myIsAscii = theIsAscii;
57 }
58
59 Driver_Mesh::Status DriverSTL_W_SMDS_Mesh::Perform()
60 {
61   Kernel_Utils::Localizer loc;
62
63   Status aResult = DRS_OK;
64
65   if ( !myMesh ) {
66     fprintf(stderr, ">> ERROR : Mesh is null \n");
67     return DRS_FAIL;
68   }
69   findVolumeTriangles();
70   if ( myIsAscii )
71     aResult = writeAscii();
72   else
73     aResult = writeBinary();
74
75   return aResult;
76 }
77 //================================================================================
78 /*!
79  * \brief Destructor deletes temporary faces
80  */
81 //================================================================================
82
83 DriverSTL_W_SMDS_Mesh::~DriverSTL_W_SMDS_Mesh()
84 {
85   for ( unsigned i = 0; i < myVolumeTrias.size(); ++i )
86     delete myVolumeTrias[i];
87 }
88
89 //================================================================================
90 /*!
91  * \brief Finds free facets of volumes for which faces are missing in the mesh
92  */
93 //================================================================================
94
95 void DriverSTL_W_SMDS_Mesh::findVolumeTriangles()
96 {
97   SMDS_VolumeTool myTool;
98   SMDS_VolumeIteratorPtr vIt = myMesh->volumesIterator();
99   while ( vIt->more() )
100   {
101     myTool.Set( vIt->next() );
102     for ( int iF = 0; iF < myTool.NbFaces(); ++iF )
103       if ( myTool.IsFreeFace( iF ))
104       {
105         const SMDS_MeshNode** n = myTool.GetFaceNodes(iF);
106         int                 nbN = myTool.NbFaceNodes(iF);
107         std::vector< const SMDS_MeshNode*> nodes( n, n+nbN );
108         if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false))
109         {
110           int nbTria = nbN - 2;
111           for ( int iT = 0; iT < nbTria; ++iT )
112           {
113             myVolumeTrias.push_back( new SMDS_FaceOfNodes( n[0], n[1+iT], n[2+iT] ));
114           }
115         }
116       }
117   }
118 }
119
120 //================================================================================
121 /*!
122  * \brief Return iterator on both faces in the mesh and on temporary faces
123  */
124 //================================================================================
125
126 SMDS_ElemIteratorPtr DriverSTL_W_SMDS_Mesh::getFaces() const
127 {
128   SMDS_ElemIteratorPtr facesIter = myMesh->elementsIterator(SMDSAbs_Face);
129   SMDS_ElemIteratorPtr tmpTriaIter( new SMDS_ElementVectorIterator( myVolumeTrias.begin(),
130                                                                     myVolumeTrias.end()));
131   typedef std::vector< SMDS_ElemIteratorPtr > TElemIterVector;
132   TElemIterVector iters(2);
133   iters[0] = facesIter;
134   iters[1] = tmpTriaIter;
135   
136   typedef SMDS_IteratorOnIterators<const SMDS_MeshElement *, TElemIterVector> TItersIter;
137   return SMDS_ElemIteratorPtr( new TItersIter( iters ));
138 }
139
140 // static methods
141
142 static void writeInteger( const Standard_Integer& theVal,
143                          OSD_File& ofile )
144 {
145   union {
146     Standard_Integer i;
147     char c[4];
148   }u;
149
150   u.i = theVal;
151
152   Standard_Integer entier;
153   entier  =  u.c[0] & 0xFF;
154   entier |= (u.c[1] & 0xFF) << 0x08;
155   entier |= (u.c[2] & 0xFF) << 0x10;
156   entier |= (u.c[3] & 0xFF) << 0x18;
157
158   ofile.Write((char *)&entier,sizeof(u.c));
159 }
160
161 static void writeFloat  ( const Standard_ShortReal& theVal,
162                          OSD_File& ofile)
163 {
164   union {
165     Standard_ShortReal f;
166     char c[4]; 
167   }u;
168
169   u.f = theVal;
170
171   Standard_Integer entier;
172
173   entier  =  u.c[0] & 0xFF;
174   entier |= (u.c[1] & 0xFF) << 0x08;
175   entier |= (u.c[2] & 0xFF) << 0x10;
176   entier |= (u.c[3] & 0xFF) << 0x18;
177
178   ofile.Write((char *)&entier,sizeof(u.c));
179 }
180
181 static gp_XYZ getNormale( const SMDS_MeshNode* n1,
182                           const SMDS_MeshNode* n2,
183                           const SMDS_MeshNode* n3)
184 {
185   SMESH_TNodeXYZ xyz1( n1 );
186   SMESH_TNodeXYZ xyz2( n2 );
187   SMESH_TNodeXYZ xyz3( n3 );
188   gp_XYZ q1 = xyz2 - xyz1;
189   gp_XYZ q2 = xyz3 - xyz1;
190   gp_XYZ n  = q1 ^ q2;
191   double len = n.Modulus();
192   if ( len > std::numeric_limits<double>::min() )
193     n /= len;
194
195   return n;
196 }
197
198 //================================================================================
199 /*!
200  * \brief Decompose a mesh face into triangles
201  *  \retval int - number of triangles
202  */
203 //================================================================================
204
205 static int getTriangles( const SMDS_MeshElement* face,
206                          const SMDS_MeshNode**   nodes)
207 {
208   // WARNING: implementation must be coherent with counting triangles in writeBinary()
209   int nbN = face->NbCornerNodes();
210   const int nbTria = nbN-2;
211   for ( int i = 0; nbN > 1; --nbN )
212   {
213     nodes[ i++ ] = face->GetNode( 0 );
214     nodes[ i++ ] = face->GetNode( nbN-2 );
215     nodes[ i++ ] = face->GetNode( nbN-1 );
216   }
217   return nbTria;
218 }
219
220 // private methods
221
222 Driver_Mesh::Status DriverSTL_W_SMDS_Mesh::writeAscii() const
223 {
224   Status aResult = DRS_OK;
225   TCollection_AsciiString aFileName( (char *)myFile.c_str() );
226   if ( aFileName.IsEmpty() ) {
227     fprintf(stderr, ">> ERREOR : invalid file name \n");
228     return DRS_FAIL;
229   }
230
231   OSD_File aFile = OSD_File(OSD_Path(aFileName));
232   aFile.Build(OSD_WriteOnly,OSD_Protection());
233
234   char sval[16];
235   TCollection_AsciiString buf = TCollection_AsciiString ("solid\n");
236   aFile.Write (buf,buf.Length());buf.Clear();
237
238   const SMDS_MeshNode* triaNodes[2048];
239
240   SMDS_ElemIteratorPtr itFaces = getFaces();
241   while ( itFaces->more() )
242   {
243     const SMDS_MeshElement* aFace = itFaces->next();
244     int nbTria = getTriangles( aFace, triaNodes );
245     
246     for ( int iT = 0, iN = 0; iT < nbTria; ++iT )
247     {
248       gp_XYZ normale = getNormale( triaNodes[iN],
249                                    triaNodes[iN+1],
250                                    triaNodes[iN+2] );
251
252       buf += " facet normal "; 
253       sprintf (sval,"% 12e",normale.X());
254       buf += sval;
255       buf += " "; 
256       sprintf (sval,"% 12e",normale.Y());
257       buf += sval;
258       buf += " "; 
259       sprintf (sval,"% 12e",normale.Z());
260       buf += sval;
261       buf += '\n';
262       aFile.Write (buf,buf.Length());buf.Clear();
263       buf += "   outer loop\n"; 
264       aFile.Write (buf,buf.Length());buf.Clear();
265       
266       for ( int jN = 0; jN < 3; ++jN, ++iN ) {
267         const SMDS_MeshNode* node = triaNodes[iN];
268         buf += "     vertex "; 
269         sprintf (sval,"% 12e",node->X());
270         buf += sval;
271         buf += " "; 
272         sprintf (sval,"% 12e",node->Y());
273         buf += sval;
274         buf += " "; 
275         sprintf (sval,"% 12e",node->Z());
276         buf += sval;
277         buf += '\n';
278         aFile.Write (buf,buf.Length());buf.Clear();
279       }
280       buf += "   endloop\n"; 
281       aFile.Write (buf,buf.Length());buf.Clear();
282       buf += " endfacet\n"; 
283       aFile.Write (buf,buf.Length());buf.Clear();
284     } 
285   }
286   buf += "endsolid\n";
287   aFile.Write (buf,buf.Length());buf.Clear();
288   
289   aFile.Close ();
290
291   return aResult;
292 }
293
294 Driver_Mesh::Status DriverSTL_W_SMDS_Mesh::writeBinary() const
295 {
296   Status aResult = DRS_OK;
297   TCollection_AsciiString aFileName( (char *)myFile.c_str() );
298   if ( aFileName.IsEmpty() ) {
299     fprintf(stderr, ">> ERREOR : invalid filename \n");
300     return DRS_FAIL;
301   }
302
303   OSD_File aFile = OSD_File(OSD_Path(aFileName));
304   aFile.Build(OSD_WriteOnly,OSD_Protection());
305
306   // we first count the number of triangles
307   // WARNING: counting triangles must be coherent with getTriangles()
308   int nbTri = 0;
309   const SMDS_MeshInfo& info = myMesh->GetMeshInfo();
310   nbTri += info.NbTriangles();
311   nbTri += info.NbQuadrangles() * 2;
312   nbTri += myVolumeTrias.size();
313   if ( info.NbPolygons() > 0 )
314   {
315     SMDS_FaceIteratorPtr itFaces = myMesh->facesIterator();
316     while ( itFaces->more() )
317     {
318       const SMDS_MeshElement* aFace = itFaces->next();
319       if ( aFace->IsPoly() )
320         nbTri += aFace->NbNodes() - 2;
321     }
322   }
323
324   // char sval[80]; -- avoid writing not initialized memory
325   TCollection_AsciiString sval(LABEL_SIZE-1,' ');
326   aFile.Write((Standard_Address)sval.ToCString(),LABEL_SIZE);
327
328   // write number of triangles
329   writeInteger(nbTri,aFile);  
330
331   // Loop writing nodes
332
333   int dum=0;
334
335   const SMDS_MeshNode* triaNodes[2048];
336
337   SMDS_ElemIteratorPtr itFaces = getFaces();
338   while ( itFaces->more() )
339   {
340     const SMDS_MeshElement* aFace = itFaces->next();
341     int nbTria = getTriangles( aFace, triaNodes );
342     
343     for ( int iT = 0, iN = 0; iT < nbTria; ++iT )
344     {
345       gp_XYZ normale = getNormale( triaNodes[iN],
346                                    triaNodes[iN+1],
347                                    triaNodes[iN+2] );
348       writeFloat(normale.X(),aFile);
349       writeFloat(normale.Y(),aFile);
350       writeFloat(normale.Z(),aFile);
351
352       for ( int jN = 0; jN < 3; ++jN, ++iN )
353       {
354         const SMDS_MeshNode* node = triaNodes[iN];
355         writeFloat(node->X(),aFile);
356         writeFloat(node->Y(),aFile);
357         writeFloat(node->Z(),aFile);
358       }
359       aFile.Write (&dum,2);
360     } 
361   }
362   aFile.Close ();
363
364   return aResult;
365 }