]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_binobj.cxx
Patch from Melchior Franz:
[simgear.git] / simgear / io / sg_binobj.cxx
1 // sg_binobj.cxx -- routines to read and write low level flightgear 3d objects
2 //
3 // Written by Curtis Olson, started January 2000.
4 //
5 // Copyright (C) 2000  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or modify
8 // it under the terms of the GNU General Public License as published by
9 // the Free Software Foundation; either version 2 of the License, or
10 // (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 // GNU General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22 //
23
24
25 #include <simgear/compiler.h>
26
27 #include <stdio.h>
28 #include <time.h>
29
30 #include <vector>
31 #include STL_STRING
32
33 #include <simgear/bucket/newbucket.hxx>
34
35 #include "lowlevel.hxx"
36 #include "sg_binobj.hxx"
37
38
39 SG_USING_STD( string );
40 SG_USING_STD( vector );
41
42 #if !defined (SG_HAVE_NATIVE_SGI_COMPILERS)
43 SG_USING_STD( cout );
44 SG_USING_STD( endl );
45 #endif
46
47
48 enum {
49     SG_BOUNDING_SPHERE = 0,
50
51     SG_VERTEX_LIST = 1,
52     SG_COLOR_LIST = 4,
53     SG_NORMAL_LIST = 2,
54     SG_TEXCOORD_LIST = 3,
55
56     SG_POINTS = 9,
57
58     SG_TRIANGLE_FACES = 10,
59     SG_TRIANGLE_STRIPS = 11,
60     SG_TRIANGLE_FANS = 12
61 } sgObjectTypes;
62
63 enum {
64     SG_IDX_VERTICES =  0x01,
65     SG_IDX_NORMALS =   0x02,
66     SG_IDX_COLORS =    0x04,
67     SG_IDX_TEXCOORDS = 0x08
68 } sgIndexTypes;
69
70 enum {
71     SG_MATERIAL = 0,
72     SG_INDEX_TYPES = 1
73 } sgPropertyTypes;
74
75
76
77 class sgSimpleBuffer {
78
79 private:
80
81     char *ptr;
82     unsigned int size;
83
84 public:
85
86     inline sgSimpleBuffer( unsigned int s )
87     {
88         size = 1;
89         while ( size < s ) {
90             size *= 2;
91         }
92         cout << "Creating a new buffer of size = " << size << endl;
93         ptr = new char[size];
94     }
95
96     inline ~sgSimpleBuffer() {
97         delete [] ptr;
98     }
99
100     inline unsigned int get_size() const { return size; }
101     inline char *get_ptr() const { return ptr; }
102     inline void resize( unsigned int s ) {
103         if ( s > size ) {
104             if ( ptr != NULL ) {
105                 delete [] ptr;
106             }
107             while ( size < s ) {
108                 size *= 2;
109             }
110             cout << "resizing buffer to size = " << size << endl;
111             ptr = new char[size];
112         }
113     }
114 };
115
116
117 // calculate the center of a list of points, by taking the halfway
118 // point between the min and max points.
119 static Point3D calc_center( point_list& wgs84_nodes ) {
120     Point3D p, min, max;
121
122     if ( wgs84_nodes.size() ) {
123         min = max = wgs84_nodes[0];
124     } else {
125         min = max = Point3D( 0 );
126     }
127
128     for ( int i = 0; i < (int)wgs84_nodes.size(); ++i ) {
129         p = wgs84_nodes[i];
130
131         if ( p.x() < min.x() ) { min.setx( p.x() ); }
132         if ( p.y() < min.y() ) { min.sety( p.y() ); }
133         if ( p.z() < min.z() ) { min.setz( p.z() ); }
134
135         if ( p.x() > max.x() ) { max.setx( p.x() ); }
136         if ( p.y() > max.y() ) { max.sety( p.y() ); }
137         if ( p.z() > max.z() ) { max.setz( p.z() ); }
138     }
139
140     return ( min + max ) / 2.0;
141 }
142
143 // calculate the bounding sphere.  Center is the center of the
144 // tile and zero elevation
145 double sgCalcBoundingRadius( Point3D center, point_list& wgs84_nodes ) {
146     double dist_squared;
147     double radius_squared = 0;
148     
149     for ( int i = 0; i < (int)wgs84_nodes.size(); ++i ) {
150         dist_squared = center.distance3Dsquared( wgs84_nodes[i] );
151         if ( dist_squared > radius_squared ) {
152             radius_squared = dist_squared;
153         }
154     }
155
156     return sqrt(radius_squared);
157 }
158
159
160
161 // read object properties
162 static void read_object( gzFile fp,
163                          int obj_type,
164                          int nproperties,
165                          int nelements,
166                          group_list *vertices,
167                          group_list *normals,
168                          group_list *colors,
169                          group_list *texcoords,
170                          string_list *materials )
171 {
172     unsigned int nbytes;
173     unsigned char idx_mask;
174     int idx_size;
175     bool do_vertices, do_normals, do_colors, do_texcoords;
176     int j, k, idx;
177     static sgSimpleBuffer buf( 32768 );  // 32 Kb
178     char material[256];
179
180     // default values
181     if ( obj_type == SG_POINTS ) {
182         idx_size = 1;
183         idx_mask = SG_IDX_VERTICES;
184         do_vertices = true;
185         do_normals = false;
186         do_colors = false;
187         do_texcoords = false;
188     } else {
189         idx_size = 2;
190         idx_mask = (char)(SG_IDX_VERTICES | SG_IDX_TEXCOORDS);
191         do_vertices = true;
192         do_normals = false;
193         do_colors = false;
194         do_texcoords = true;
195     }
196
197     for ( j = 0; j < nproperties; ++j ) {
198         char prop_type;
199         sgReadChar( fp, &prop_type );
200
201         sgReadUInt( fp, &nbytes );
202         // cout << "property size = " << nbytes << endl;
203         if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
204         char *ptr = buf.get_ptr();
205         sgReadBytes( fp, nbytes, ptr );
206         if ( prop_type == SG_MATERIAL ) {
207             strncpy( material, ptr, nbytes );
208             material[nbytes] = '\0';
209             // cout << "material type = " << material << endl;
210         } else if ( prop_type == SG_INDEX_TYPES ) {
211             idx_mask = ptr[0];
212             // cout << "idx_mask = " << (int)idx_mask << endl;
213             idx_size = 0;
214             do_vertices = false;
215             do_normals = false;
216             do_colors = false;
217             do_texcoords = false;
218             if ( idx_mask & SG_IDX_VERTICES ) {
219                 do_vertices = true;
220                 ++idx_size;
221             }
222             if ( idx_mask & SG_IDX_NORMALS ) {
223                 do_normals = true;
224                 ++idx_size;
225             }
226             if ( idx_mask & SG_IDX_COLORS ) {
227                 do_colors = true;
228                 ++idx_size;
229             }
230             if ( idx_mask & SG_IDX_TEXCOORDS ) {
231                 do_texcoords = true;
232                 ++idx_size;
233             }
234         }
235     }
236
237     for ( j = 0; j < nelements; ++j ) {
238         sgReadUInt( fp, &nbytes );
239         // cout << "element size = " << nbytes << endl;
240         if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
241         char *ptr = buf.get_ptr();
242         sgReadBytes( fp, nbytes, ptr );
243         int count = nbytes / (idx_size * sizeof(short));
244         short *sptr = (short *)ptr;
245         int_list vs; vs.clear();
246         int_list ns; ns.clear();
247         int_list cs; cs.clear();
248         int_list tcs; tcs.clear();
249         for ( k = 0; k < count; ++k ) {
250             if ( sgIsBigEndian() ) {
251                 for ( idx = 0; idx < idx_size; ++idx ) {
252                     sgEndianSwap( (unsigned short *)&(sptr[idx]) );
253                 }
254             }
255             idx = 0;
256             if ( do_vertices ) {
257                 vs.push_back( sptr[idx++] );
258             }
259             if ( do_normals ) {
260                 ns.push_back( sptr[idx++] );
261                     }
262             if ( do_colors ) {
263                 cs.push_back( sptr[idx++] );
264             }
265             if ( do_texcoords ) {
266                 tcs.push_back( sptr[idx++] );
267             }
268             // cout << sptr[0] << " ";
269             sptr += idx_size;
270         }
271         // cout << endl;
272         vertices->push_back( vs );
273         normals->push_back( ns );
274         colors->push_back( cs );
275         texcoords->push_back( tcs );
276         materials->push_back( material );
277     }
278 }
279
280
281 // read a binary file and populate the provided structures.
282 bool SGBinObject::read_bin( const string& file ) {
283     Point3D p;
284     int i, j, k;
285     unsigned int nbytes;
286     static sgSimpleBuffer buf( 32768 );  // 32 Kb
287
288     // zero out structures
289     gbs_center = Point3D( 0 );
290     gbs_radius = 0.0;
291
292     wgs84_nodes.clear();
293     normals.clear();
294     texcoords.clear();
295
296     pts_v.clear();
297     pts_n.clear();
298     pts_c.clear();
299     pts_tc.clear();
300     pt_materials.clear();
301
302     tris_v.clear();
303     tris_n.clear();
304     tris_c.clear();
305     tris_tc.clear();
306     tri_materials.clear();
307
308     strips_v.clear();
309     strips_n.clear();
310     strips_c.clear();
311     strips_tc.clear();
312     strip_materials.clear();
313
314     fans_v.clear();
315     fans_n.clear();
316     fans_c.clear();
317     fans_tc.clear();
318     fan_materials.clear();
319    
320     gzFile fp;
321     if ( (fp = gzopen( file.c_str(), "rb" )) == NULL ) {
322         string filegz = file + ".gz";
323         if ( (fp = gzopen( filegz.c_str(), "rb" )) == NULL ) {
324             cout << "ERROR: opening " << file << " or " << filegz
325                  << "for reading!" << endl;
326
327             return false;
328         }
329     }
330
331     sgClearReadError();
332
333     // read headers
334     unsigned int header;
335     sgReadUInt( fp, &header );
336     if ( ((header & 0xFF000000) >> 24) == 'S' &&
337          ((header & 0x00FF0000) >> 16) == 'G' ) {
338         // cout << "Good header" << endl;
339         // read file version
340         version = (header & 0x0000FFFF);
341         // cout << "File version = " << version << endl;
342     } else {
343         // close the file before we return
344         gzclose(fp);
345
346         return false;
347     }
348
349     // read creation time
350     time_t calendar_time;
351     sgReadLong( fp, &calendar_time );
352
353 #if 0
354     // The following code has a global effect on the host application
355     // and can screws up the time elsewhere.  It should be avoided
356     // unless you need this for debugging in which case you should
357     // disable it again once the debugging task is finished.
358     struct tm *local_tm;
359     local_tm = localtime( &calendar_time );
360     char time_str[256];
361     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
362     cout << "File created on " << time_str << endl;
363 #endif
364
365     // read number of top level objects
366     short nobjects;
367     sgReadShort( fp, &nobjects );
368     // cout << "Total objects to read = " << nobjects << endl;
369
370     // read in objects
371     for ( i = 0; i < nobjects; ++i ) {
372         // read object header
373         char obj_type;
374         short nproperties, nelements;
375         sgReadChar( fp, &obj_type );
376         sgReadShort( fp, &nproperties );
377         sgReadShort( fp, &nelements );
378
379         // cout << "object " << i << " = " << (int)obj_type << " props = "
380         //      << nproperties << " elements = " << nelements << endl;
381             
382         if ( obj_type == SG_BOUNDING_SPHERE ) {
383             // read bounding sphere properties
384             for ( j = 0; j < nproperties; ++j ) {
385                 char prop_type;
386                 sgReadChar( fp, &prop_type );
387
388                 sgReadUInt( fp, &nbytes );
389                 // cout << "property size = " << nbytes << endl;
390                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
391                 char *ptr = buf.get_ptr();
392                 sgReadBytes( fp, nbytes, ptr );
393             }
394
395             // read bounding sphere elements
396             for ( j = 0; j < nelements; ++j ) {
397                 sgReadUInt( fp, &nbytes );
398                 // cout << "element size = " << nbytes << endl;
399                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
400                 char *ptr = buf.get_ptr();
401                 sgReadBytes( fp, nbytes, ptr );
402
403                 double *dptr = (double *)ptr;
404                 if ( sgIsBigEndian() ) {
405                     sgEndianSwap( (uint64 *)&(dptr[0]) );
406                     sgEndianSwap( (uint64 *)&(dptr[1]) );
407                     sgEndianSwap( (uint64 *)&(dptr[2]) );
408                 }
409                 gbs_center = Point3D( dptr[0], dptr[1], dptr[2] );
410                 // cout << "Center = " << gbs_center << endl;
411                 ptr += sizeof(double) * 3;
412                 
413                 float *fptr = (float *)ptr;
414                 if ( sgIsBigEndian() ) {
415                     sgEndianSwap( (unsigned int *)fptr );
416                 }
417                 gbs_radius = fptr[0];
418                 // cout << "Bounding radius = " << gbs_radius << endl;
419             }
420         } else if ( obj_type == SG_VERTEX_LIST ) {
421             // read vertex list properties
422             for ( j = 0; j < nproperties; ++j ) {
423                 char prop_type;
424                 sgReadChar( fp, &prop_type );
425
426                 sgReadUInt( fp, &nbytes );
427                 // cout << "property size = " << nbytes << endl;
428                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
429                 char *ptr = buf.get_ptr();
430                 sgReadBytes( fp, nbytes, ptr );
431             }
432
433             // read vertex list elements
434             for ( j = 0; j < nelements; ++j ) {
435                 sgReadUInt( fp, &nbytes );
436                 // cout << "element size = " << nbytes << endl;
437                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
438                 char *ptr = buf.get_ptr();
439                 sgReadBytes( fp, nbytes, ptr );
440                 int count = nbytes / (sizeof(float) * 3);
441                 float *fptr = (float *)ptr;
442                 for ( k = 0; k < count; ++k ) {
443                     if ( sgIsBigEndian() ) {
444                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
445                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
446                         sgEndianSwap( (unsigned int *)&(fptr[2]) );
447                     }
448                     p = Point3D( fptr[0], fptr[1], fptr[2] );
449                     // cout << "node = " << p << endl;
450                     wgs84_nodes.push_back( p );
451                     fptr += 3;
452                 }
453             }
454         } else if ( obj_type == SG_COLOR_LIST ) {
455             // read color list properties
456             for ( j = 0; j < nproperties; ++j ) {
457                 char prop_type;
458                 sgReadChar( fp, &prop_type );
459
460                 sgReadUInt( fp, &nbytes );
461                 // cout << "property size = " << nbytes << endl;
462                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
463                 char *ptr = buf.get_ptr();
464                 sgReadBytes( fp, nbytes, ptr );
465             }
466
467             // read color list elements
468             for ( j = 0; j < nelements; ++j ) {
469                 sgReadUInt( fp, &nbytes );
470                 // cout << "element size = " << nbytes << endl;
471                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
472                 char *ptr = buf.get_ptr();
473                 sgReadBytes( fp, nbytes, ptr );
474                 int count = nbytes / (sizeof(float) * 4);
475                 float *fptr = (float *)ptr;
476                 for ( k = 0; k < count; ++k ) {
477                     if ( sgIsBigEndian() ) {
478                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
479                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
480                         sgEndianSwap( (unsigned int *)&(fptr[2]) );
481                         sgEndianSwap( (unsigned int *)&(fptr[3]) );
482                     }
483                     p = Point3D( fptr[0], fptr[1], fptr[2] );
484                     // cout << "node = " << p << endl;
485                     colors.push_back( p );
486                     fptr += 4;
487                 }
488             }
489         } else if ( obj_type == SG_NORMAL_LIST ) {
490             // read normal list properties
491             for ( j = 0; j < nproperties; ++j ) {
492                 char prop_type;
493                 sgReadChar( fp, &prop_type );
494
495                 sgReadUInt( fp, &nbytes );
496                 // cout << "property size = " << nbytes << endl;
497                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
498                 char *ptr = buf.get_ptr();
499                 sgReadBytes( fp, nbytes, ptr );
500             }
501
502             // read normal list elements
503             for ( j = 0; j < nelements; ++j ) {
504                 sgReadUInt( fp, &nbytes );
505                 // cout << "element size = " << nbytes << endl;
506                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
507                 unsigned char *ptr = (unsigned char *)(buf.get_ptr());
508                 sgReadBytes( fp, nbytes, ptr );
509                 int count = nbytes / 3;
510                 for ( k = 0; k < count; ++k ) {
511                     sgdVec3 normal;
512                     sgdSetVec3( normal,
513                                (ptr[0]) / 127.5 - 1.0,
514                                (ptr[1]) / 127.5 - 1.0,
515                                (ptr[2]) / 127.5 - 1.0 );
516                     sgdNormalizeVec3( normal );
517
518                     p = Point3D( normal[0], normal[1], normal[2] );
519                     // cout << "normal = " << p << endl;
520                     normals.push_back( p );
521                     ptr += 3;
522                 }
523             }
524         } else if ( obj_type == SG_TEXCOORD_LIST ) {
525             // read texcoord list properties
526             for ( j = 0; j < nproperties; ++j ) {
527                 char prop_type;
528                 sgReadChar( fp, &prop_type );
529
530                 sgReadUInt( fp, &nbytes );
531                 // cout << "property size = " << nbytes << endl;
532                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
533                 char *ptr = buf.get_ptr();
534                 sgReadBytes( fp, nbytes, ptr );
535             }
536
537             // read texcoord list elements
538             for ( j = 0; j < nelements; ++j ) {
539                 sgReadUInt( fp, &nbytes );
540                 // cout << "element size = " << nbytes << endl;
541                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
542                 char *ptr = buf.get_ptr();
543                 sgReadBytes( fp, nbytes, ptr );
544                 int count = nbytes / (sizeof(float) * 2);
545                 float *fptr = (float *)ptr;
546                 for ( k = 0; k < count; ++k ) {
547                     if ( sgIsBigEndian() ) {
548                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
549                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
550                     }
551                     p = Point3D( fptr[0], fptr[1], 0 );
552                     // cout << "texcoord = " << p << endl;
553                     texcoords.push_back( p );
554                     fptr += 2;
555                 }
556             }
557         } else if ( obj_type == SG_POINTS ) {
558             // read point elements
559             read_object( fp, SG_POINTS, nproperties, nelements,
560                          &pts_v, &pts_n, &pts_c, &pts_tc, &pt_materials );
561         } else if ( obj_type == SG_TRIANGLE_FACES ) {
562             // read triangle face properties
563             read_object( fp, SG_TRIANGLE_FACES, nproperties, nelements,
564                          &tris_v, &tris_n, &tris_c, &tris_tc, &tri_materials );
565         } else if ( obj_type == SG_TRIANGLE_STRIPS ) {
566             // read triangle strip properties
567             read_object( fp, SG_TRIANGLE_STRIPS, nproperties, nelements,
568                          &strips_v, &strips_n, &strips_c, &strips_tc,
569                          &strip_materials );
570         } else if ( obj_type == SG_TRIANGLE_FANS ) {
571             // read triangle fan properties
572             read_object( fp, SG_TRIANGLE_FANS, nproperties, nelements,
573                          &fans_v, &fans_n, &fans_c, &fans_tc, &fan_materials );
574         } else {
575             // unknown object type, just skip
576
577             // read properties
578             for ( j = 0; j < nproperties; ++j ) {
579                 char prop_type;
580                 sgReadChar( fp, &prop_type );
581
582                 sgReadUInt( fp, &nbytes );
583                 // cout << "property size = " << nbytes << endl;
584                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
585                 char *ptr = buf.get_ptr();
586                 sgReadBytes( fp, nbytes, ptr );
587             }
588
589             // read elements
590             for ( j = 0; j < nelements; ++j ) {
591                 sgReadUInt( fp, &nbytes );
592                 // cout << "element size = " << nbytes << endl;
593                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
594                 char *ptr = buf.get_ptr();
595                 sgReadBytes( fp, nbytes, ptr );
596             }
597         }
598     }
599
600     // close the file
601     gzclose(fp);
602
603     if ( sgReadError() ) {
604         cout << "We detected an error while reading the file." << endl;
605         return false;
606     }
607
608     return true;
609 }
610
611
612 // write out the structures to a binary file.  We assume that the
613 // groups come to us sorted by material property.  If not, things
614 // don't break, but the result won't be as optimal.
615 bool SGBinObject::write_bin( const string& base, const string& name,
616                              const SGBucket& b )
617 {
618     Point3D p;
619     sgVec2 t;
620     sgVec3 pt;
621     sgVec4 color;
622     int i, j;
623     unsigned char idx_mask;
624     int idx_size;
625
626     string dir = base + "/" + b.gen_base_path();
627     string command = "mkdir -p " + dir;
628 #if defined(_MSC_VER) || defined(__MINGW32__)
629     system( (string("mkdir ") + dir).c_str() );
630 #else
631     system(command.c_str());
632 #endif
633
634     string file = dir + "/" + name + ".gz";
635     cout << "Output file = " << file << endl;
636
637     gzFile fp;
638     if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
639         cout << "ERROR: opening " << file << " for writing!" << endl;
640         return false;
641     }
642
643     sgClearWriteError();
644
645     cout << "points size = " << pts_v.size() << "  pt_materials = " 
646          << pt_materials.size() << endl;
647     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
648          << tri_materials.size() << endl;
649     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
650          << strip_materials.size() << endl;
651     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
652          << fan_materials.size() << endl;
653
654     cout << "nodes = " << wgs84_nodes.size() << endl;
655     cout << "colors = " << colors.size() << endl;
656     cout << "normals = " << normals.size() << endl;
657     cout << "tex coords = " << texcoords.size() << endl;
658
659     // write header magic
660     sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
661     time_t calendar_time = time(NULL);
662     sgWriteLong( fp, (long int)calendar_time );
663
664     // calculate and write number of top level objects
665     string material;
666     int start;
667     int end;
668     short nobjects = 0;
669     nobjects++;                 // for gbs
670     nobjects++;                 // for vertices
671     nobjects++;                 // for colors
672     nobjects++;                 // for normals
673     nobjects++;                 // for texcoords
674
675     // points
676     short npts = 0;
677     start = 0; end = 1;
678     while ( start < (int)pt_materials.size() ) {
679         material = pt_materials[start];
680         while ( (end < (int)pt_materials.size()) &&
681                 (material == pt_materials[end]) ) {
682             end++;
683         }
684         npts++;
685         start = end; end = start + 1;
686     }
687     nobjects += npts;
688
689     // tris
690     short ntris = 0;
691     start = 0; end = 1;
692     while ( start < (int)tri_materials.size() ) {
693         material = tri_materials[start];
694         while ( (end < (int)tri_materials.size()) &&
695                 (material == tri_materials[end]) ) {
696             end++;
697         }
698         ntris++;
699         start = end; end = start + 1;
700     }
701     nobjects += ntris;
702
703     // strips
704     short nstrips = 0;
705     start = 0; end = 1;
706     while ( start < (int)strip_materials.size() ) {
707         material = strip_materials[start];
708         while ( (end < (int)strip_materials.size()) &&
709                 (material == strip_materials[end]) ) {
710             end++;
711         }
712         nstrips++;
713         start = end; end = start + 1;
714     }
715     nobjects += nstrips;
716
717     // fans
718     short nfans = 0;
719     start = 0; end = 1;
720     while ( start < (int)fan_materials.size() ) {
721         material = fan_materials[start];
722         while ( (end < (int)fan_materials.size()) &&
723                 (material == fan_materials[end]) ) {
724             end++;
725         }
726         nfans++;
727         start = end; end = start + 1;
728     }
729     nobjects += nfans;
730
731     cout << "total top level objects = " << nobjects << endl;
732     sgWriteShort( fp, nobjects );
733
734     // write bounding sphere
735     sgWriteChar( fp, (char)SG_BOUNDING_SPHERE );        // type
736     sgWriteShort( fp, 0 );                              // nproperties
737     sgWriteShort( fp, 1 );                              // nelements
738
739     sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
740     sgdVec3 center;
741     sgdSetVec3( center, gbs_center.x(), gbs_center.y(), gbs_center.z() );
742     sgWritedVec3( fp, center );
743     sgWriteFloat( fp, gbs_radius );
744
745     // dump vertex list
746     sgWriteChar( fp, (char)SG_VERTEX_LIST );             // type
747     sgWriteShort( fp, 0 );                               // nproperties
748     sgWriteShort( fp, 1 );                               // nelements
749     sgWriteUInt( fp, wgs84_nodes.size() * sizeof(float) * 3 ); // nbytes
750     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
751         p = wgs84_nodes[i] - gbs_center;
752         sgSetVec3( pt, p.x(), p.y(), p.z() );
753         sgWriteVec3( fp, pt );
754     }
755
756     // dump vertex color list
757     sgWriteChar( fp, (char)SG_COLOR_LIST );             // type
758     sgWriteShort( fp, 0 );                               // nproperties
759     sgWriteShort( fp, 1 );                               // nelements
760     sgWriteUInt( fp, colors.size() * sizeof(float) * 4 ); // nbytes
761     for ( i = 0; i < (int)colors.size(); ++i ) {
762         p = colors[i];
763         // Right now we have a place holder for color alpha but we
764         // need to update the interface so the calling program can
765         // provide the info.
766         sgSetVec4( color, p.x(), p.y(), p.z(), 1.0 );
767         sgWriteVec4( fp, color );
768     }
769
770     // dump vertex normal list
771     sgWriteChar( fp, (char)SG_NORMAL_LIST );            // type
772     sgWriteShort( fp, 0 );                              // nproperties
773     sgWriteShort( fp, 1 );                              // nelements
774     sgWriteUInt( fp, normals.size() * 3 );              // nbytes
775     char normal[3];
776     for ( i = 0; i < (int)normals.size(); ++i ) {
777         p = normals[i];
778         normal[0] = (unsigned char)((p.x() + 1.0) * 127.5);
779         normal[1] = (unsigned char)((p.y() + 1.0) * 127.5);
780         normal[2] = (unsigned char)((p.z() + 1.0) * 127.5);
781         sgWriteBytes( fp, 3, normal );
782     }
783
784     // dump texture coordinates
785     sgWriteChar( fp, (char)SG_TEXCOORD_LIST );          // type
786     sgWriteShort( fp, 0 );                              // nproperties
787     sgWriteShort( fp, 1 );                              // nelements
788     sgWriteUInt( fp, texcoords.size() * sizeof(float) * 2 ); // nbytes
789     for ( i = 0; i < (int)texcoords.size(); ++i ) {
790         p = texcoords[i];
791         sgSetVec2( t, p.x(), p.y() );
792         sgWriteVec2( fp, t );
793     }
794
795     // dump point groups if they exist
796     if ( pts_v.size() > 0 ) {
797         int start = 0;
798         int end = 1;
799         string material;
800         while ( start < (int)pt_materials.size() ) {
801             // find next group
802             material = pt_materials[start];
803             while ( (end < (int)pt_materials.size()) && 
804                     (material == pt_materials[end]) )
805                 {
806                     // cout << "end = " << end << endl;
807                     end++;
808                 }
809             // cout << "group = " << start << " to " << end - 1 << endl;
810
811             // write group headers
812             sgWriteChar( fp, (char)SG_POINTS );          // type
813             sgWriteShort( fp, 2 );                       // nproperties
814             sgWriteShort( fp, end - start );             // nelements
815
816             sgWriteChar( fp, (char)SG_MATERIAL );        // property
817             sgWriteUInt( fp, material.length() );        // nbytes
818             sgWriteBytes( fp, material.length(), material.c_str() );
819
820             idx_mask = 0;
821             idx_size = 0;
822             if ( pts_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
823             if ( pts_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
824             if ( pts_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
825             if ( pts_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
826             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
827             sgWriteUInt( fp, 1 );                        // nbytes
828             sgWriteChar( fp, idx_mask );
829
830             // write strips
831             for ( i = start; i < end; ++i ) {
832                 // nbytes
833                 sgWriteUInt( fp, pts_v[i].size() * idx_size * sizeof(short) );
834                 for ( j = 0; j < (int)pts_v[i].size(); ++j ) {
835                     if ( pts_v.size() ) { 
836                         sgWriteShort( fp, (short)pts_v[i][j] );
837                     }
838                     if ( pts_n.size() ) { 
839                         sgWriteShort( fp, (short)pts_n[i][j] );
840                     }
841                     if ( pts_c.size() ) { 
842                         sgWriteShort( fp, (short)pts_c[i][j] );
843                     }
844                     if ( pts_tc.size() ) { 
845                         sgWriteShort( fp, (short)pts_tc[i][j] );
846                     }
847                 }
848             }
849             
850             start = end;
851             end = start + 1;
852         }
853     }
854
855     // dump individual triangles if they exist
856     if ( tris_v.size() > 0 ) {
857         int start = 0;
858         int end = 1;
859         string material;
860         while ( start < (int)tri_materials.size() ) {
861             // find next group
862             material = tri_materials[start];
863             while ( (end < (int)tri_materials.size()) && 
864                     (material == tri_materials[end]) )
865             {
866                 // cout << "end = " << end << endl;
867                 end++;
868             }
869             // cout << "group = " << start << " to " << end - 1 << endl;
870
871             // write group headers
872             sgWriteChar( fp, (char)SG_TRIANGLE_FACES ); // type
873             sgWriteShort( fp, 2 );                      // nproperties
874             sgWriteShort( fp, 1 );                      // nelements
875
876             sgWriteChar( fp, (char)SG_MATERIAL );       // property
877             sgWriteUInt( fp, material.length() );        // nbytes
878             sgWriteBytes( fp, material.length(), material.c_str() );
879
880             idx_mask = 0;
881             idx_size = 0;
882             if ( tris_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
883             if ( tris_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
884             if ( tris_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
885             if ( tris_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
886             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
887             sgWriteUInt( fp, 1 );                        // nbytes
888             sgWriteChar( fp, idx_mask );
889
890             // nbytes
891             sgWriteUInt( fp, (end - start) * 3 * idx_size * sizeof(short) );
892
893             // write group
894             for ( i = start; i < end; ++i ) {
895                 for ( j = 0; j < 3; ++j ) {
896                     if ( tris_v.size() ) {
897                         sgWriteShort( fp, (short)tris_v[i][j] );
898                     }
899                     if ( tris_n.size() ) {
900                         sgWriteShort( fp, (short)tris_n[i][j] );
901                     }
902                     if ( tris_c.size() ) {
903                         sgWriteShort( fp, (short)tris_c[i][j] );
904                     }
905                     if ( tris_tc.size() ) {
906                         sgWriteShort( fp, (short)tris_tc[i][j] );
907                     }
908                 }
909             }
910
911             start = end;
912             end = start + 1;
913         }
914     }
915
916     // dump triangle strips
917     if ( strips_v.size() > 0 ) {
918         int start = 0;
919         int end = 1;
920         string material;
921         while ( start < (int)strip_materials.size() ) {
922             // find next group
923             material = strip_materials[start];
924             while ( (end < (int)strip_materials.size()) && 
925                     (material == strip_materials[end]) )
926                 {
927                     // cout << "end = " << end << endl;
928                     end++;
929                 }
930             // cout << "group = " << start << " to " << end - 1 << endl;
931
932             // write group headers
933             sgWriteChar( fp, (char)SG_TRIANGLE_STRIPS ); // type
934             sgWriteShort( fp, 2 );                       // nproperties
935             sgWriteShort( fp, end - start );             // nelements
936
937             sgWriteChar( fp, (char)SG_MATERIAL );        // property
938             sgWriteUInt( fp, material.length() );        // nbytes
939             sgWriteBytes( fp, material.length(), material.c_str() );
940
941             idx_mask = 0;
942             idx_size = 0;
943             if ( strips_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
944             if ( strips_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
945             if ( strips_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
946             if ( strips_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size;}
947             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
948             sgWriteUInt( fp, 1 );                        // nbytes
949             sgWriteChar( fp, idx_mask );
950
951             // write strips
952             for ( i = start; i < end; ++i ) {
953                 // nbytes
954                 sgWriteUInt( fp, strips_v[i].size() * idx_size * sizeof(short));
955                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
956                     if ( strips_v.size() ) { 
957                         sgWriteShort( fp, (short)strips_v[i][j] );
958                     }
959                     if ( strips_n.size() ) { 
960                         sgWriteShort( fp, (short)strips_n[i][j] );
961                     }
962                     if ( strips_c.size() ) { 
963                         sgWriteShort( fp, (short)strips_c[i][j] );
964                     }
965                     if ( strips_tc.size() ) { 
966                         sgWriteShort( fp, (short)strips_tc[i][j] );
967                     }
968                 }
969             }
970             
971             start = end;
972             end = start + 1;
973         }
974     }
975
976     // dump triangle fans
977     if ( fans_v.size() > 0 ) {
978         int start = 0;
979         int end = 1;
980         string material;
981         while ( start < (int)fan_materials.size() ) {
982             // find next group
983             material = fan_materials[start];
984             while ( (end < (int)fan_materials.size()) && 
985                     (material == fan_materials[end]) )
986                 {
987                     // cout << "end = " << end << endl;
988                     end++;
989                 }
990             // cout << "group = " << start << " to " << end - 1 << endl;
991
992             // write group headers
993             sgWriteChar( fp, (char)SG_TRIANGLE_FANS );   // type
994             sgWriteShort( fp, 2 );                       // nproperties
995             sgWriteShort( fp, end - start );             // nelements
996
997             sgWriteChar( fp, (char)SG_MATERIAL );       // property
998             sgWriteUInt( fp, material.length() );        // nbytes
999             sgWriteBytes( fp, material.length(), material.c_str() );
1000
1001             idx_mask = 0;
1002             idx_size = 0;
1003             if ( fans_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
1004             if ( fans_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
1005             if ( fans_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
1006             if ( fans_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
1007             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
1008             sgWriteUInt( fp, 1 );                        // nbytes
1009             sgWriteChar( fp, idx_mask );
1010
1011             // write fans
1012             for ( i = start; i < end; ++i ) {
1013                 // nbytes
1014                 sgWriteUInt( fp, fans_v[i].size() * idx_size * sizeof(short) );
1015                 for ( j = 0; j < (int)fans_v[i].size(); ++j ) {
1016                     if ( fans_v.size() ) {
1017                         sgWriteShort( fp, (short)fans_v[i][j] );
1018                     }
1019                     if ( fans_n.size() ) {
1020                         sgWriteShort( fp, (short)fans_n[i][j] );
1021                     }
1022                     if ( fans_c.size() ) {
1023                         sgWriteShort( fp, (short)fans_c[i][j] );
1024                     }
1025                     if ( fans_tc.size() ) {
1026                         sgWriteShort( fp, (short)fans_tc[i][j] );
1027                     }
1028                 }
1029             }
1030             
1031             start = end;
1032             end = start + 1;
1033         }
1034     }
1035
1036     // close the file
1037     gzclose(fp);
1038
1039     if ( sgWriteError() ) {
1040         cout << "We detected an error while writing the file." << endl;
1041         return false;
1042     }
1043
1044     return true;
1045 }
1046
1047
1048 // write out the structures to an ASCII file.  We assume that the
1049 // groups come to us sorted by material property.  If not, things
1050 // don't break, but the result won't be as optimal.
1051 bool SGBinObject::write_ascii( const string& base, const string& name,
1052                                const SGBucket& b )
1053 {
1054     Point3D p;
1055     int i, j;
1056
1057     string dir = base + "/" + b.gen_base_path();
1058     string command = "mkdir -p " + dir;
1059 #if defined(_MSC_VER) || defined(__MINGW32__)
1060     system( (string("mkdir ") + dir).c_str() );
1061 #else
1062     system(command.c_str());
1063 #endif
1064
1065     // string file = dir + "/" + b.gen_index_str();
1066     string file = dir + "/" + name;
1067     cout << "Output file = " << file << endl;
1068
1069     FILE *fp;
1070     if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
1071         cout << "ERROR: opening " << file << " for writing!" << endl;
1072         return false;
1073     }
1074
1075     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
1076          << tri_materials.size() << endl;
1077     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
1078          << strip_materials.size() << endl;
1079     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
1080          << fan_materials.size() << endl;
1081
1082     cout << "points = " << wgs84_nodes.size() << endl;
1083     cout << "tex coords = " << texcoords.size() << endl;
1084     // write headers
1085     fprintf(fp, "# FGFS Scenery\n");
1086     fprintf(fp, "# Version %s\n", SG_SCENERY_FILE_FORMAT);
1087
1088     time_t calendar_time = time(NULL);
1089     struct tm *local_tm;
1090     local_tm = localtime( &calendar_time );
1091     char time_str[256];
1092     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
1093     fprintf(fp, "# Created %s\n", time_str );
1094     fprintf(fp, "\n");
1095
1096     // write bounding sphere
1097     fprintf(fp, "# gbs %.5f %.5f %.5f %.2f\n",
1098             gbs_center.x(), gbs_center.y(), gbs_center.z(), gbs_radius);
1099     fprintf(fp, "\n");
1100
1101     // dump vertex list
1102     fprintf(fp, "# vertex list\n");
1103     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
1104         p = wgs84_nodes[i] - gbs_center;
1105         
1106         fprintf(fp,  "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1107     }
1108     fprintf(fp, "\n");
1109
1110     fprintf(fp, "# vertex normal list\n");
1111     for ( i = 0; i < (int)normals.size(); ++i ) {
1112         p = normals[i];
1113         fprintf(fp,  "vn %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1114     }
1115     fprintf(fp, "\n");
1116
1117     // dump texture coordinates
1118     fprintf(fp, "# texture coordinate list\n");
1119     for ( i = 0; i < (int)texcoords.size(); ++i ) {
1120         p = texcoords[i];
1121         fprintf(fp,  "vt %.5f %.5f\n", p.x(), p.y() );
1122     }
1123     fprintf(fp, "\n");
1124
1125     // dump individual triangles if they exist
1126     if ( tris_v.size() > 0 ) {
1127         fprintf(fp, "# triangle groups\n");
1128
1129         int start = 0;
1130         int end = 1;
1131         string material;
1132         while ( start < (int)tri_materials.size() ) {
1133             // find next group
1134             material = tri_materials[start];
1135             while ( (end < (int)tri_materials.size()) && 
1136                     (material == tri_materials[end]) )
1137             {
1138                 // cout << "end = " << end << endl;
1139                 end++;
1140             }
1141             // cout << "group = " << start << " to " << end - 1 << endl;
1142
1143             // make a list of points for the group
1144             point_list group_nodes;
1145             group_nodes.clear();
1146             Point3D bs_center;
1147             double bs_radius = 0;
1148             for ( i = start; i < end; ++i ) {
1149                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1150                     group_nodes.push_back( wgs84_nodes[ tris_v[i][j] ] );
1151                     bs_center = calc_center( group_nodes );
1152                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1153                 }
1154             }
1155
1156             // write group headers
1157             fprintf(fp, "\n");
1158             fprintf(fp, "# usemtl %s\n", material.c_str());
1159             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1160                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1161
1162             // write groups
1163             for ( i = start; i < end; ++i ) {
1164                 fprintf(fp, "f");
1165                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1166                     fprintf(fp, " %d/%d", tris_v[i][j], tris_tc[i][j] );
1167                 }
1168                 fprintf(fp, "\n");
1169             }
1170
1171             start = end;
1172             end = start + 1;
1173         }
1174     }
1175
1176     // dump triangle groups
1177     if ( strips_v.size() > 0 ) {
1178         fprintf(fp, "# triangle strips\n");
1179
1180         int start = 0;
1181         int end = 1;
1182         string material;
1183         while ( start < (int)strip_materials.size() ) {
1184             // find next group
1185             material = strip_materials[start];
1186             while ( (end < (int)strip_materials.size()) && 
1187                     (material == strip_materials[end]) )
1188                 {
1189                     // cout << "end = " << end << endl;
1190                     end++;
1191                 }
1192             // cout << "group = " << start << " to " << end - 1 << endl;
1193
1194             // make a list of points for the group
1195             point_list group_nodes;
1196             group_nodes.clear();
1197             Point3D bs_center;
1198             double bs_radius = 0;
1199             for ( i = start; i < end; ++i ) {
1200                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1201                     group_nodes.push_back( wgs84_nodes[ strips_v[i][j] ] );
1202                     bs_center = calc_center( group_nodes );
1203                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1204                 }
1205             }
1206
1207             // write group headers
1208             fprintf(fp, "\n");
1209             fprintf(fp, "# usemtl %s\n", material.c_str());
1210             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1211                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1212
1213             // write groups
1214             for ( i = start; i < end; ++i ) {
1215                 fprintf(fp, "ts");
1216                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1217                     fprintf(fp, " %d/%d", strips_v[i][j], strips_tc[i][j] );
1218                 }
1219                 fprintf(fp, "\n");
1220             }
1221             
1222             start = end;
1223             end = start + 1;
1224         }
1225     }
1226
1227     // close the file
1228     fclose(fp);
1229
1230     command = "gzip --force --best " + file;
1231     system(command.c_str());
1232
1233     return true;
1234 }