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