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