]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_binobj.cxx
86c0fba2b13d1d257c1602b4fcf443d2c041a456
[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 calender time
350     unsigned int foo_calendar_time;
351     sgReadUInt( fp, &foo_calendar_time );
352
353 #if 0
354     time_t calendar_time = foo_calendar_time;
355     // The following code has a global effect on the host application
356     // and can screws up the time elsewhere.  It should be avoided
357     // unless you need this for debugging in which case you should
358     // disable it again once the debugging task is finished.
359     struct tm *local_tm;
360     local_tm = localtime( &calendar_time );
361     char time_str[256];
362     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
363     cout << "File created on " << time_str << endl;
364 #endif
365
366     // read number of top level objects
367     short nobjects;
368     sgReadShort( fp, &nobjects );
369     // cout << "Total objects to read = " << nobjects << endl;
370
371     // read in objects
372     for ( i = 0; i < nobjects; ++i ) {
373         // read object header
374         char obj_type;
375         short nproperties, nelements;
376         sgReadChar( fp, &obj_type );
377         sgReadShort( fp, &nproperties );
378         sgReadShort( fp, &nelements );
379
380         // cout << "object " << i << " = " << (int)obj_type << " props = "
381         //      << nproperties << " elements = " << nelements << endl;
382             
383         if ( obj_type == SG_BOUNDING_SPHERE ) {
384             // read bounding sphere properties
385             for ( j = 0; j < nproperties; ++j ) {
386                 char prop_type;
387                 sgReadChar( fp, &prop_type );
388
389                 sgReadUInt( fp, &nbytes );
390                 // cout << "property size = " << nbytes << endl;
391                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
392                 char *ptr = buf.get_ptr();
393                 sgReadBytes( fp, nbytes, ptr );
394             }
395
396             // read bounding sphere elements
397             for ( j = 0; j < nelements; ++j ) {
398                 sgReadUInt( fp, &nbytes );
399                 // cout << "element size = " << nbytes << endl;
400                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
401                 char *ptr = buf.get_ptr();
402                 sgReadBytes( fp, nbytes, ptr );
403
404                 double *dptr = (double *)ptr;
405                 if ( sgIsBigEndian() ) {
406                     sgEndianSwap( (uint64 *)&(dptr[0]) );
407                     sgEndianSwap( (uint64 *)&(dptr[1]) );
408                     sgEndianSwap( (uint64 *)&(dptr[2]) );
409                 }
410                 gbs_center = Point3D( dptr[0], dptr[1], dptr[2] );
411                 // cout << "Center = " << gbs_center << endl;
412                 ptr += sizeof(double) * 3;
413                 
414                 float *fptr = (float *)ptr;
415                 if ( sgIsBigEndian() ) {
416                     sgEndianSwap( (unsigned int *)fptr );
417                 }
418                 gbs_radius = fptr[0];
419                 // cout << "Bounding radius = " << gbs_radius << endl;
420             }
421         } else if ( obj_type == SG_VERTEX_LIST ) {
422             // read vertex list properties
423             for ( j = 0; j < nproperties; ++j ) {
424                 char prop_type;
425                 sgReadChar( fp, &prop_type );
426
427                 sgReadUInt( fp, &nbytes );
428                 // cout << "property size = " << nbytes << endl;
429                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
430                 char *ptr = buf.get_ptr();
431                 sgReadBytes( fp, nbytes, ptr );
432             }
433
434             // read vertex list elements
435             for ( j = 0; j < nelements; ++j ) {
436                 sgReadUInt( fp, &nbytes );
437                 // cout << "element size = " << nbytes << endl;
438                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
439                 char *ptr = buf.get_ptr();
440                 sgReadBytes( fp, nbytes, ptr );
441                 int count = nbytes / (sizeof(float) * 3);
442                 float *fptr = (float *)ptr;
443                 for ( k = 0; k < count; ++k ) {
444                     if ( sgIsBigEndian() ) {
445                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
446                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
447                         sgEndianSwap( (unsigned int *)&(fptr[2]) );
448                     }
449                     p = Point3D( fptr[0], fptr[1], fptr[2] );
450                     // cout << "node = " << p << endl;
451                     wgs84_nodes.push_back( p );
452                     fptr += 3;
453                 }
454             }
455         } else if ( obj_type == SG_COLOR_LIST ) {
456             // read color list properties
457             for ( j = 0; j < nproperties; ++j ) {
458                 char prop_type;
459                 sgReadChar( fp, &prop_type );
460
461                 sgReadUInt( fp, &nbytes );
462                 // cout << "property size = " << nbytes << endl;
463                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
464                 char *ptr = buf.get_ptr();
465                 sgReadBytes( fp, nbytes, ptr );
466             }
467
468             // read color list elements
469             for ( j = 0; j < nelements; ++j ) {
470                 sgReadUInt( fp, &nbytes );
471                 // cout << "element size = " << nbytes << endl;
472                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
473                 char *ptr = buf.get_ptr();
474                 sgReadBytes( fp, nbytes, ptr );
475                 int count = nbytes / (sizeof(float) * 4);
476                 float *fptr = (float *)ptr;
477                 for ( k = 0; k < count; ++k ) {
478                     if ( sgIsBigEndian() ) {
479                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
480                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
481                         sgEndianSwap( (unsigned int *)&(fptr[2]) );
482                         sgEndianSwap( (unsigned int *)&(fptr[3]) );
483                     }
484                     p = Point3D( fptr[0], fptr[1], fptr[2] );
485                     // cout << "node = " << p << endl;
486                     colors.push_back( p );
487                     fptr += 4;
488                 }
489             }
490         } else if ( obj_type == SG_NORMAL_LIST ) {
491             // read normal list properties
492             for ( j = 0; j < nproperties; ++j ) {
493                 char prop_type;
494                 sgReadChar( fp, &prop_type );
495
496                 sgReadUInt( fp, &nbytes );
497                 // cout << "property size = " << nbytes << endl;
498                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
499                 char *ptr = buf.get_ptr();
500                 sgReadBytes( fp, nbytes, ptr );
501             }
502
503             // read normal list elements
504             for ( j = 0; j < nelements; ++j ) {
505                 sgReadUInt( fp, &nbytes );
506                 // cout << "element size = " << nbytes << endl;
507                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
508                 unsigned char *ptr = (unsigned char *)(buf.get_ptr());
509                 sgReadBytes( fp, nbytes, ptr );
510                 int count = nbytes / 3;
511                 for ( k = 0; k < count; ++k ) {
512                     sgdVec3 normal;
513                     sgdSetVec3( normal,
514                                (ptr[0]) / 127.5 - 1.0,
515                                (ptr[1]) / 127.5 - 1.0,
516                                (ptr[2]) / 127.5 - 1.0 );
517                     sgdNormalizeVec3( normal );
518
519                     p = Point3D( normal[0], normal[1], normal[2] );
520                     // cout << "normal = " << p << endl;
521                     normals.push_back( p );
522                     ptr += 3;
523                 }
524             }
525         } else if ( obj_type == SG_TEXCOORD_LIST ) {
526             // read texcoord list properties
527             for ( j = 0; j < nproperties; ++j ) {
528                 char prop_type;
529                 sgReadChar( fp, &prop_type );
530
531                 sgReadUInt( fp, &nbytes );
532                 // cout << "property size = " << nbytes << endl;
533                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
534                 char *ptr = buf.get_ptr();
535                 sgReadBytes( fp, nbytes, ptr );
536             }
537
538             // read texcoord list elements
539             for ( j = 0; j < nelements; ++j ) {
540                 sgReadUInt( fp, &nbytes );
541                 // cout << "element size = " << nbytes << endl;
542                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
543                 char *ptr = buf.get_ptr();
544                 sgReadBytes( fp, nbytes, ptr );
545                 int count = nbytes / (sizeof(float) * 2);
546                 float *fptr = (float *)ptr;
547                 for ( k = 0; k < count; ++k ) {
548                     if ( sgIsBigEndian() ) {
549                         sgEndianSwap( (unsigned int *)&(fptr[0]) );
550                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
551                     }
552                     p = Point3D( fptr[0], fptr[1], 0 );
553                     // cout << "texcoord = " << p << endl;
554                     texcoords.push_back( p );
555                     fptr += 2;
556                 }
557             }
558         } else if ( obj_type == SG_POINTS ) {
559             // read point elements
560             read_object( fp, SG_POINTS, nproperties, nelements,
561                          &pts_v, &pts_n, &pts_c, &pts_tc, &pt_materials );
562         } else if ( obj_type == SG_TRIANGLE_FACES ) {
563             // read triangle face properties
564             read_object( fp, SG_TRIANGLE_FACES, nproperties, nelements,
565                          &tris_v, &tris_n, &tris_c, &tris_tc, &tri_materials );
566         } else if ( obj_type == SG_TRIANGLE_STRIPS ) {
567             // read triangle strip properties
568             read_object( fp, SG_TRIANGLE_STRIPS, nproperties, nelements,
569                          &strips_v, &strips_n, &strips_c, &strips_tc,
570                          &strip_materials );
571         } else if ( obj_type == SG_TRIANGLE_FANS ) {
572             // read triangle fan properties
573             read_object( fp, SG_TRIANGLE_FANS, nproperties, nelements,
574                          &fans_v, &fans_n, &fans_c, &fans_tc, &fan_materials );
575         } else {
576             // unknown object type, just skip
577
578             // read properties
579             for ( j = 0; j < nproperties; ++j ) {
580                 char prop_type;
581                 sgReadChar( fp, &prop_type );
582
583                 sgReadUInt( fp, &nbytes );
584                 // cout << "property size = " << nbytes << endl;
585                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
586                 char *ptr = buf.get_ptr();
587                 sgReadBytes( fp, nbytes, ptr );
588             }
589
590             // read elements
591             for ( j = 0; j < nelements; ++j ) {
592                 sgReadUInt( fp, &nbytes );
593                 // cout << "element size = " << nbytes << endl;
594                 if ( nbytes > buf.get_size() ) { buf.resize( nbytes ); }
595                 char *ptr = buf.get_ptr();
596                 sgReadBytes( fp, nbytes, ptr );
597             }
598         }
599     }
600
601     // close the file
602     gzclose(fp);
603
604     if ( sgReadError() ) {
605         cout << "We detected an error while reading the file." << endl;
606         return false;
607     }
608
609     return true;
610 }
611
612
613 // write out the structures to a binary file.  We assume that the
614 // groups come to us sorted by material property.  If not, things
615 // don't break, but the result won't be as optimal.
616 bool SGBinObject::write_bin( const string& base, const string& name,
617                              const SGBucket& b )
618 {
619     Point3D p;
620     sgVec2 t;
621     sgVec3 pt;
622     sgVec4 color;
623     int i, j;
624     unsigned char idx_mask;
625     int idx_size;
626
627     string dir = base + "/" + b.gen_base_path();
628     string command = "mkdir -p " + dir;
629 #if defined(_MSC_VER) || defined(__MINGW32__)
630     system( (string("mkdir ") + dir).c_str() );
631 #else
632     system(command.c_str());
633 #endif
634
635     string file = dir + "/" + name + ".gz";
636     cout << "Output file = " << file << endl;
637
638     gzFile fp;
639     if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
640         cout << "ERROR: opening " << file << " for writing!" << endl;
641         return false;
642     }
643
644     sgClearWriteError();
645
646     cout << "points size = " << pts_v.size() << "  pt_materials = " 
647          << pt_materials.size() << endl;
648     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
649          << tri_materials.size() << endl;
650     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
651          << strip_materials.size() << endl;
652     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
653          << fan_materials.size() << endl;
654
655     cout << "nodes = " << wgs84_nodes.size() << endl;
656     cout << "colors = " << colors.size() << endl;
657     cout << "normals = " << normals.size() << endl;
658     cout << "tex coords = " << texcoords.size() << endl;
659
660     // write header magic
661     sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
662     time_t calendar_time = time(NULL);
663     sgWriteLong( fp, (long int)calendar_time );
664
665     // calculate and write number of top level objects
666     string material;
667     int start;
668     int end;
669     short nobjects = 0;
670     nobjects++;                 // for gbs
671     nobjects++;                 // for vertices
672     nobjects++;                 // for colors
673     nobjects++;                 // for normals
674     nobjects++;                 // for texcoords
675
676     // points
677     short npts = 0;
678     start = 0; end = 1;
679     while ( start < (int)pt_materials.size() ) {
680         material = pt_materials[start];
681         while ( (end < (int)pt_materials.size()) &&
682                 (material == pt_materials[end]) ) {
683             end++;
684         }
685         npts++;
686         start = end; end = start + 1;
687     }
688     nobjects += npts;
689
690     // tris
691     short ntris = 0;
692     start = 0; end = 1;
693     while ( start < (int)tri_materials.size() ) {
694         material = tri_materials[start];
695         while ( (end < (int)tri_materials.size()) &&
696                 (material == tri_materials[end]) ) {
697             end++;
698         }
699         ntris++;
700         start = end; end = start + 1;
701     }
702     nobjects += ntris;
703
704     // strips
705     short nstrips = 0;
706     start = 0; end = 1;
707     while ( start < (int)strip_materials.size() ) {
708         material = strip_materials[start];
709         while ( (end < (int)strip_materials.size()) &&
710                 (material == strip_materials[end]) ) {
711             end++;
712         }
713         nstrips++;
714         start = end; end = start + 1;
715     }
716     nobjects += nstrips;
717
718     // fans
719     short nfans = 0;
720     start = 0; end = 1;
721     while ( start < (int)fan_materials.size() ) {
722         material = fan_materials[start];
723         while ( (end < (int)fan_materials.size()) &&
724                 (material == fan_materials[end]) ) {
725             end++;
726         }
727         nfans++;
728         start = end; end = start + 1;
729     }
730     nobjects += nfans;
731
732     cout << "total top level objects = " << nobjects << endl;
733     sgWriteShort( fp, nobjects );
734
735     // write bounding sphere
736     sgWriteChar( fp, (char)SG_BOUNDING_SPHERE );        // type
737     sgWriteShort( fp, 0 );                              // nproperties
738     sgWriteShort( fp, 1 );                              // nelements
739
740     sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
741     sgdVec3 center;
742     sgdSetVec3( center, gbs_center.x(), gbs_center.y(), gbs_center.z() );
743     sgWritedVec3( fp, center );
744     sgWriteFloat( fp, gbs_radius );
745
746     // dump vertex list
747     sgWriteChar( fp, (char)SG_VERTEX_LIST );             // type
748     sgWriteShort( fp, 0 );                               // nproperties
749     sgWriteShort( fp, 1 );                               // nelements
750     sgWriteUInt( fp, wgs84_nodes.size() * sizeof(float) * 3 ); // nbytes
751     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
752         p = wgs84_nodes[i] - gbs_center;
753         sgSetVec3( pt, p.x(), p.y(), p.z() );
754         sgWriteVec3( fp, pt );
755     }
756
757     // dump vertex color list
758     sgWriteChar( fp, (char)SG_COLOR_LIST );             // type
759     sgWriteShort( fp, 0 );                               // nproperties
760     sgWriteShort( fp, 1 );                               // nelements
761     sgWriteUInt( fp, colors.size() * sizeof(float) * 4 ); // nbytes
762     for ( i = 0; i < (int)colors.size(); ++i ) {
763         p = colors[i];
764         // Right now we have a place holder for color alpha but we
765         // need to update the interface so the calling program can
766         // provide the info.
767         sgSetVec4( color, p.x(), p.y(), p.z(), 1.0 );
768         sgWriteVec4( fp, color );
769     }
770
771     // dump vertex normal list
772     sgWriteChar( fp, (char)SG_NORMAL_LIST );            // type
773     sgWriteShort( fp, 0 );                              // nproperties
774     sgWriteShort( fp, 1 );                              // nelements
775     sgWriteUInt( fp, normals.size() * 3 );              // nbytes
776     char normal[3];
777     for ( i = 0; i < (int)normals.size(); ++i ) {
778         p = normals[i];
779         normal[0] = (unsigned char)((p.x() + 1.0) * 127.5);
780         normal[1] = (unsigned char)((p.y() + 1.0) * 127.5);
781         normal[2] = (unsigned char)((p.z() + 1.0) * 127.5);
782         sgWriteBytes( fp, 3, normal );
783     }
784
785     // dump texture coordinates
786     sgWriteChar( fp, (char)SG_TEXCOORD_LIST );          // type
787     sgWriteShort( fp, 0 );                              // nproperties
788     sgWriteShort( fp, 1 );                              // nelements
789     sgWriteUInt( fp, texcoords.size() * sizeof(float) * 2 ); // nbytes
790     for ( i = 0; i < (int)texcoords.size(); ++i ) {
791         p = texcoords[i];
792         sgSetVec2( t, p.x(), p.y() );
793         sgWriteVec2( fp, t );
794     }
795
796     // dump point groups if they exist
797     if ( pts_v.size() > 0 ) {
798         int start = 0;
799         int end = 1;
800         string material;
801         while ( start < (int)pt_materials.size() ) {
802             // find next group
803             material = pt_materials[start];
804             while ( (end < (int)pt_materials.size()) && 
805                     (material == pt_materials[end]) )
806                 {
807                     // cout << "end = " << end << endl;
808                     end++;
809                 }
810             // cout << "group = " << start << " to " << end - 1 << endl;
811
812             // write group headers
813             sgWriteChar( fp, (char)SG_POINTS );          // type
814             sgWriteShort( fp, 2 );                       // nproperties
815             sgWriteShort( fp, end - start );             // nelements
816
817             sgWriteChar( fp, (char)SG_MATERIAL );        // property
818             sgWriteUInt( fp, material.length() );        // nbytes
819             sgWriteBytes( fp, material.length(), material.c_str() );
820
821             idx_mask = 0;
822             idx_size = 0;
823             if ( pts_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
824             if ( pts_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
825             if ( pts_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
826             if ( pts_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
827             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
828             sgWriteUInt( fp, 1 );                        // nbytes
829             sgWriteChar( fp, idx_mask );
830
831             // write strips
832             for ( i = start; i < end; ++i ) {
833                 // nbytes
834                 sgWriteUInt( fp, pts_v[i].size() * idx_size * sizeof(short) );
835                 for ( j = 0; j < (int)pts_v[i].size(); ++j ) {
836                     if ( pts_v.size() ) { 
837                         sgWriteShort( fp, (short)pts_v[i][j] );
838                     }
839                     if ( pts_n.size() ) { 
840                         sgWriteShort( fp, (short)pts_n[i][j] );
841                     }
842                     if ( pts_c.size() ) { 
843                         sgWriteShort( fp, (short)pts_c[i][j] );
844                     }
845                     if ( pts_tc.size() ) { 
846                         sgWriteShort( fp, (short)pts_tc[i][j] );
847                     }
848                 }
849             }
850             
851             start = end;
852             end = start + 1;
853         }
854     }
855
856     // dump individual triangles if they exist
857     if ( tris_v.size() > 0 ) {
858         int start = 0;
859         int end = 1;
860         string material;
861         while ( start < (int)tri_materials.size() ) {
862             // find next group
863             material = tri_materials[start];
864             while ( (end < (int)tri_materials.size()) && 
865                     (material == tri_materials[end]) )
866             {
867                 // cout << "end = " << end << endl;
868                 end++;
869             }
870             // cout << "group = " << start << " to " << end - 1 << endl;
871
872             // write group headers
873             sgWriteChar( fp, (char)SG_TRIANGLE_FACES ); // type
874             sgWriteShort( fp, 2 );                      // nproperties
875             sgWriteShort( fp, 1 );                      // nelements
876
877             sgWriteChar( fp, (char)SG_MATERIAL );       // property
878             sgWriteUInt( fp, material.length() );        // nbytes
879             sgWriteBytes( fp, material.length(), material.c_str() );
880
881             idx_mask = 0;
882             idx_size = 0;
883             if ( tris_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
884             if ( tris_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
885             if ( tris_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
886             if ( tris_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
887             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
888             sgWriteUInt( fp, 1 );                        // nbytes
889             sgWriteChar( fp, idx_mask );
890
891             // nbytes
892             sgWriteUInt( fp, (end - start) * 3 * idx_size * sizeof(short) );
893
894             // write group
895             for ( i = start; i < end; ++i ) {
896                 for ( j = 0; j < 3; ++j ) {
897                     if ( tris_v.size() ) {
898                         sgWriteShort( fp, (short)tris_v[i][j] );
899                     }
900                     if ( tris_n.size() ) {
901                         sgWriteShort( fp, (short)tris_n[i][j] );
902                     }
903                     if ( tris_c.size() ) {
904                         sgWriteShort( fp, (short)tris_c[i][j] );
905                     }
906                     if ( tris_tc.size() ) {
907                         sgWriteShort( fp, (short)tris_tc[i][j] );
908                     }
909                 }
910             }
911
912             start = end;
913             end = start + 1;
914         }
915     }
916
917     // dump triangle strips
918     if ( strips_v.size() > 0 ) {
919         int start = 0;
920         int end = 1;
921         string material;
922         while ( start < (int)strip_materials.size() ) {
923             // find next group
924             material = strip_materials[start];
925             while ( (end < (int)strip_materials.size()) && 
926                     (material == strip_materials[end]) )
927                 {
928                     // cout << "end = " << end << endl;
929                     end++;
930                 }
931             // cout << "group = " << start << " to " << end - 1 << endl;
932
933             // write group headers
934             sgWriteChar( fp, (char)SG_TRIANGLE_STRIPS ); // type
935             sgWriteShort( fp, 2 );                       // nproperties
936             sgWriteShort( fp, end - start );             // nelements
937
938             sgWriteChar( fp, (char)SG_MATERIAL );        // property
939             sgWriteUInt( fp, material.length() );        // nbytes
940             sgWriteBytes( fp, material.length(), material.c_str() );
941
942             idx_mask = 0;
943             idx_size = 0;
944             if ( strips_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
945             if ( strips_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
946             if ( strips_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
947             if ( strips_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size;}
948             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
949             sgWriteUInt( fp, 1 );                        // nbytes
950             sgWriteChar( fp, idx_mask );
951
952             // write strips
953             for ( i = start; i < end; ++i ) {
954                 // nbytes
955                 sgWriteUInt( fp, strips_v[i].size() * idx_size * sizeof(short));
956                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
957                     if ( strips_v.size() ) { 
958                         sgWriteShort( fp, (short)strips_v[i][j] );
959                     }
960                     if ( strips_n.size() ) { 
961                         sgWriteShort( fp, (short)strips_n[i][j] );
962                     }
963                     if ( strips_c.size() ) { 
964                         sgWriteShort( fp, (short)strips_c[i][j] );
965                     }
966                     if ( strips_tc.size() ) { 
967                         sgWriteShort( fp, (short)strips_tc[i][j] );
968                     }
969                 }
970             }
971             
972             start = end;
973             end = start + 1;
974         }
975     }
976
977     // dump triangle fans
978     if ( fans_v.size() > 0 ) {
979         int start = 0;
980         int end = 1;
981         string material;
982         while ( start < (int)fan_materials.size() ) {
983             // find next group
984             material = fan_materials[start];
985             while ( (end < (int)fan_materials.size()) && 
986                     (material == fan_materials[end]) )
987                 {
988                     // cout << "end = " << end << endl;
989                     end++;
990                 }
991             // cout << "group = " << start << " to " << end - 1 << endl;
992
993             // write group headers
994             sgWriteChar( fp, (char)SG_TRIANGLE_FANS );   // type
995             sgWriteShort( fp, 2 );                       // nproperties
996             sgWriteShort( fp, end - start );             // nelements
997
998             sgWriteChar( fp, (char)SG_MATERIAL );       // property
999             sgWriteUInt( fp, material.length() );        // nbytes
1000             sgWriteBytes( fp, material.length(), material.c_str() );
1001
1002             idx_mask = 0;
1003             idx_size = 0;
1004             if ( fans_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
1005             if ( fans_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
1006             if ( fans_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
1007             if ( fans_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
1008             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
1009             sgWriteUInt( fp, 1 );                        // nbytes
1010             sgWriteChar( fp, idx_mask );
1011
1012             // write fans
1013             for ( i = start; i < end; ++i ) {
1014                 // nbytes
1015                 sgWriteUInt( fp, fans_v[i].size() * idx_size * sizeof(short) );
1016                 for ( j = 0; j < (int)fans_v[i].size(); ++j ) {
1017                     if ( fans_v.size() ) {
1018                         sgWriteShort( fp, (short)fans_v[i][j] );
1019                     }
1020                     if ( fans_n.size() ) {
1021                         sgWriteShort( fp, (short)fans_n[i][j] );
1022                     }
1023                     if ( fans_c.size() ) {
1024                         sgWriteShort( fp, (short)fans_c[i][j] );
1025                     }
1026                     if ( fans_tc.size() ) {
1027                         sgWriteShort( fp, (short)fans_tc[i][j] );
1028                     }
1029                 }
1030             }
1031             
1032             start = end;
1033             end = start + 1;
1034         }
1035     }
1036
1037     // close the file
1038     gzclose(fp);
1039
1040     if ( sgWriteError() ) {
1041         cout << "We detected an error while writing the file." << endl;
1042         return false;
1043     }
1044
1045     return true;
1046 }
1047
1048
1049 // write out the structures to an ASCII file.  We assume that the
1050 // groups come to us sorted by material property.  If not, things
1051 // don't break, but the result won't be as optimal.
1052 bool SGBinObject::write_ascii( const string& base, const string& name,
1053                                const SGBucket& b )
1054 {
1055     Point3D p;
1056     int i, j;
1057
1058     string dir = base + "/" + b.gen_base_path();
1059     string command = "mkdir -p " + dir;
1060 #if defined(_MSC_VER) || defined(__MINGW32__)
1061     system( (string("mkdir ") + dir).c_str() );
1062 #else
1063     system(command.c_str());
1064 #endif
1065
1066     // string file = dir + "/" + b.gen_index_str();
1067     string file = dir + "/" + name;
1068     cout << "Output file = " << file << endl;
1069
1070     FILE *fp;
1071     if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
1072         cout << "ERROR: opening " << file << " for writing!" << endl;
1073         return false;
1074     }
1075
1076     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
1077          << tri_materials.size() << endl;
1078     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
1079          << strip_materials.size() << endl;
1080     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
1081          << fan_materials.size() << endl;
1082
1083     cout << "points = " << wgs84_nodes.size() << endl;
1084     cout << "tex coords = " << texcoords.size() << endl;
1085     // write headers
1086     fprintf(fp, "# FGFS Scenery\n");
1087     fprintf(fp, "# Version %s\n", SG_SCENERY_FILE_FORMAT);
1088
1089     time_t calendar_time = time(NULL);
1090     struct tm *local_tm;
1091     local_tm = localtime( &calendar_time );
1092     char time_str[256];
1093     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
1094     fprintf(fp, "# Created %s\n", time_str );
1095     fprintf(fp, "\n");
1096
1097     // write bounding sphere
1098     fprintf(fp, "# gbs %.5f %.5f %.5f %.2f\n",
1099             gbs_center.x(), gbs_center.y(), gbs_center.z(), gbs_radius);
1100     fprintf(fp, "\n");
1101
1102     // dump vertex list
1103     fprintf(fp, "# vertex list\n");
1104     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
1105         p = wgs84_nodes[i] - gbs_center;
1106         
1107         fprintf(fp,  "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1108     }
1109     fprintf(fp, "\n");
1110
1111     fprintf(fp, "# vertex normal list\n");
1112     for ( i = 0; i < (int)normals.size(); ++i ) {
1113         p = normals[i];
1114         fprintf(fp,  "vn %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1115     }
1116     fprintf(fp, "\n");
1117
1118     // dump texture coordinates
1119     fprintf(fp, "# texture coordinate list\n");
1120     for ( i = 0; i < (int)texcoords.size(); ++i ) {
1121         p = texcoords[i];
1122         fprintf(fp,  "vt %.5f %.5f\n", p.x(), p.y() );
1123     }
1124     fprintf(fp, "\n");
1125
1126     // dump individual triangles if they exist
1127     if ( tris_v.size() > 0 ) {
1128         fprintf(fp, "# triangle groups\n");
1129
1130         int start = 0;
1131         int end = 1;
1132         string material;
1133         while ( start < (int)tri_materials.size() ) {
1134             // find next group
1135             material = tri_materials[start];
1136             while ( (end < (int)tri_materials.size()) && 
1137                     (material == tri_materials[end]) )
1138             {
1139                 // cout << "end = " << end << endl;
1140                 end++;
1141             }
1142             // cout << "group = " << start << " to " << end - 1 << endl;
1143
1144             // make a list of points for the group
1145             point_list group_nodes;
1146             group_nodes.clear();
1147             Point3D bs_center;
1148             double bs_radius = 0;
1149             for ( i = start; i < end; ++i ) {
1150                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1151                     group_nodes.push_back( wgs84_nodes[ tris_v[i][j] ] );
1152                     bs_center = calc_center( group_nodes );
1153                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1154                 }
1155             }
1156
1157             // write group headers
1158             fprintf(fp, "\n");
1159             fprintf(fp, "# usemtl %s\n", material.c_str());
1160             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1161                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1162
1163             // write groups
1164             for ( i = start; i < end; ++i ) {
1165                 fprintf(fp, "f");
1166                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1167                     fprintf(fp, " %d/%d", tris_v[i][j], tris_tc[i][j] );
1168                 }
1169                 fprintf(fp, "\n");
1170             }
1171
1172             start = end;
1173             end = start + 1;
1174         }
1175     }
1176
1177     // dump triangle groups
1178     if ( strips_v.size() > 0 ) {
1179         fprintf(fp, "# triangle strips\n");
1180
1181         int start = 0;
1182         int end = 1;
1183         string material;
1184         while ( start < (int)strip_materials.size() ) {
1185             // find next group
1186             material = strip_materials[start];
1187             while ( (end < (int)strip_materials.size()) && 
1188                     (material == strip_materials[end]) )
1189                 {
1190                     // cout << "end = " << end << endl;
1191                     end++;
1192                 }
1193             // cout << "group = " << start << " to " << end - 1 << endl;
1194
1195             // make a list of points for the group
1196             point_list group_nodes;
1197             group_nodes.clear();
1198             Point3D bs_center;
1199             double bs_radius = 0;
1200             for ( i = start; i < end; ++i ) {
1201                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1202                     group_nodes.push_back( wgs84_nodes[ strips_v[i][j] ] );
1203                     bs_center = calc_center( group_nodes );
1204                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1205                 }
1206             }
1207
1208             // write group headers
1209             fprintf(fp, "\n");
1210             fprintf(fp, "# usemtl %s\n", material.c_str());
1211             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1212                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1213
1214             // write groups
1215             for ( i = start; i < end; ++i ) {
1216                 fprintf(fp, "ts");
1217                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1218                     fprintf(fp, " %d/%d", strips_v[i][j], strips_tc[i][j] );
1219                 }
1220                 fprintf(fp, "\n");
1221             }
1222             
1223             start = end;
1224             end = start + 1;
1225         }
1226     }
1227
1228     // close the file
1229     fclose(fp);
1230
1231     command = "gzip --force --best " + file;
1232     system(command.c_str());
1233
1234     return true;
1235 }