]> git.mxchange.org Git - simgear.git/blob - simgear/io/sg_binobj.cxx
Bernie Bright:
[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 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #include <stdio.h>
32 #include <time.h>
33
34 #include <vector>
35 #include STL_STRING
36
37 #include <simgear/bucket/newbucket.hxx>
38
39 #include "lowlevel.hxx"
40 #include "sg_binobj.hxx"
41
42
43 SG_USING_STD( string );
44 SG_USING_STD( vector );
45 SG_USING_STD( cout );
46 SG_USING_STD( endl );
47
48
49 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 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 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         cout << "Creating a new buffer of size = " << size << endl;
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             cout << "resizing buffer to size = " << size << endl;
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 static Point3D calc_center( 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(short));
245         short *sptr = (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( (unsigned short *)&(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             cout << "ERROR: opening " << file << " or " << filegz
326                  << "for reading!" << endl;
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     cout << "File created on " << time_str << endl;
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 *)&(dptr[0]) );
408                     sgEndianSwap( (uint64 *)&(dptr[1]) );
409                     sgEndianSwap( (uint64 *)&(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( (unsigned int *)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( (unsigned int *)&(fptr[0]) );
448                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
449                         sgEndianSwap( (unsigned int *)&(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( (unsigned int *)&(fptr[0]) );
481                         sgEndianSwap( (unsigned int *)&(fptr[1]) );
482                         sgEndianSwap( (unsigned int *)&(fptr[2]) );
483                         sgEndianSwap( (unsigned int *)&(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( (unsigned int *)&(fptr[0]) );
549                         sgEndianSwap( (unsigned int *)&(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     string dir = base + "/" + b.gen_base_path();
625     string command = "mkdir -p " + dir;
626 #if defined(_MSC_VER) || defined(__MINGW32__)
627     system( (string("mkdir ") + dir).c_str() );
628 #else
629     system(command.c_str());
630 #endif
631
632     string file = dir + "/" + name + ".gz";
633     cout << "Output file = " << file << endl;
634
635     gzFile fp;
636     if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
637         cout << "ERROR: opening " << file << " for writing!" << endl;
638         return false;
639     }
640
641     sgClearWriteError();
642
643     cout << "points size = " << pts_v.size() << "  pt_materials = " 
644          << pt_materials.size() << endl;
645     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
646          << tri_materials.size() << endl;
647     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
648          << strip_materials.size() << endl;
649     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
650          << fan_materials.size() << endl;
651
652     cout << "nodes = " << wgs84_nodes.size() << endl;
653     cout << "colors = " << colors.size() << endl;
654     cout << "normals = " << normals.size() << endl;
655     cout << "tex coords = " << texcoords.size() << endl;
656
657     // write header magic
658     sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
659     time_t calendar_time = time(NULL);
660     sgWriteLong( fp, (long int)calendar_time );
661
662     // calculate and write number of top level objects
663     string material;
664     int start;
665     int end;
666     short nobjects = 0;
667     nobjects++;                 // for gbs
668     nobjects++;                 // for vertices
669     nobjects++;                 // for colors
670     nobjects++;                 // for normals
671     nobjects++;                 // for texcoords
672
673     // points
674     short npts = 0;
675     start = 0; end = 1;
676     while ( start < (int)pt_materials.size() ) {
677         material = pt_materials[start];
678         while ( (end < (int)pt_materials.size()) &&
679                 (material == pt_materials[end]) ) {
680             end++;
681         }
682         npts++;
683         start = end; end = start + 1;
684     }
685     nobjects += npts;
686
687     // tris
688     short ntris = 0;
689     start = 0; end = 1;
690     while ( start < (int)tri_materials.size() ) {
691         material = tri_materials[start];
692         while ( (end < (int)tri_materials.size()) &&
693                 (material == tri_materials[end]) ) {
694             end++;
695         }
696         ntris++;
697         start = end; end = start + 1;
698     }
699     nobjects += ntris;
700
701     // strips
702     short nstrips = 0;
703     start = 0; end = 1;
704     while ( start < (int)strip_materials.size() ) {
705         material = strip_materials[start];
706         while ( (end < (int)strip_materials.size()) &&
707                 (material == strip_materials[end]) ) {
708             end++;
709         }
710         nstrips++;
711         start = end; end = start + 1;
712     }
713     nobjects += nstrips;
714
715     // fans
716     short nfans = 0;
717     start = 0; end = 1;
718     while ( start < (int)fan_materials.size() ) {
719         material = fan_materials[start];
720         while ( (end < (int)fan_materials.size()) &&
721                 (material == fan_materials[end]) ) {
722             end++;
723         }
724         nfans++;
725         start = end; end = start + 1;
726     }
727     nobjects += nfans;
728
729     cout << "total top level objects = " << nobjects << endl;
730     sgWriteShort( fp, nobjects );
731
732     // write bounding sphere
733     sgWriteChar( fp, (char)SG_BOUNDING_SPHERE );        // type
734     sgWriteShort( fp, 0 );                              // nproperties
735     sgWriteShort( fp, 1 );                              // nelements
736
737     sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
738     sgdVec3 center;
739     sgdSetVec3( center, gbs_center.x(), gbs_center.y(), gbs_center.z() );
740     sgWritedVec3( fp, center );
741     sgWriteFloat( fp, gbs_radius );
742
743     // dump vertex list
744     sgWriteChar( fp, (char)SG_VERTEX_LIST );             // type
745     sgWriteShort( fp, 0 );                               // nproperties
746     sgWriteShort( fp, 1 );                               // nelements
747     sgWriteUInt( fp, wgs84_nodes.size() * sizeof(float) * 3 ); // nbytes
748     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
749         p = wgs84_nodes[i] - gbs_center;
750         sgSetVec3( pt, p.x(), p.y(), p.z() );
751         sgWriteVec3( fp, pt );
752     }
753
754     // dump vertex color list
755     sgWriteChar( fp, (char)SG_COLOR_LIST );             // type
756     sgWriteShort( fp, 0 );                               // nproperties
757     sgWriteShort( fp, 1 );                               // nelements
758     sgWriteUInt( fp, colors.size() * sizeof(float) * 4 ); // nbytes
759     for ( i = 0; i < (int)colors.size(); ++i ) {
760         p = colors[i];
761         // Right now we have a place holder for color alpha but we
762         // need to update the interface so the calling program can
763         // provide the info.
764         sgSetVec4( color, p.x(), p.y(), p.z(), 1.0 );
765         sgWriteVec4( fp, color );
766     }
767
768     // dump vertex normal list
769     sgWriteChar( fp, (char)SG_NORMAL_LIST );            // type
770     sgWriteShort( fp, 0 );                              // nproperties
771     sgWriteShort( fp, 1 );                              // nelements
772     sgWriteUInt( fp, normals.size() * 3 );              // nbytes
773     char normal[3];
774     for ( i = 0; i < (int)normals.size(); ++i ) {
775         p = normals[i];
776         normal[0] = (unsigned char)((p.x() + 1.0) * 127.5);
777         normal[1] = (unsigned char)((p.y() + 1.0) * 127.5);
778         normal[2] = (unsigned char)((p.z() + 1.0) * 127.5);
779         sgWriteBytes( fp, 3, normal );
780     }
781
782     // dump texture coordinates
783     sgWriteChar( fp, (char)SG_TEXCOORD_LIST );          // type
784     sgWriteShort( fp, 0 );                              // nproperties
785     sgWriteShort( fp, 1 );                              // nelements
786     sgWriteUInt( fp, texcoords.size() * sizeof(float) * 2 ); // nbytes
787     for ( i = 0; i < (int)texcoords.size(); ++i ) {
788         p = texcoords[i];
789         sgSetVec2( t, p.x(), p.y() );
790         sgWriteVec2( fp, t );
791     }
792
793     // dump point groups if they exist
794     if ( pts_v.size() > 0 ) {
795         int start = 0;
796         int end = 1;
797         string material;
798         while ( start < (int)pt_materials.size() ) {
799             // find next group
800             material = pt_materials[start];
801             while ( (end < (int)pt_materials.size()) && 
802                     (material == pt_materials[end]) )
803                 {
804                     // cout << "end = " << end << endl;
805                     end++;
806                 }
807             // cout << "group = " << start << " to " << end - 1 << endl;
808
809             // write group headers
810             sgWriteChar( fp, (char)SG_POINTS );          // type
811             sgWriteShort( fp, 2 );                       // nproperties
812             sgWriteShort( fp, end - start );             // nelements
813
814             sgWriteChar( fp, (char)SG_MATERIAL );        // property
815             sgWriteUInt( fp, material.length() );        // nbytes
816             sgWriteBytes( fp, material.length(), material.c_str() );
817
818             idx_mask = 0;
819             idx_size = 0;
820             if ( pts_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
821             if ( pts_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
822             if ( pts_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
823             if ( pts_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
824             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
825             sgWriteUInt( fp, 1 );                        // nbytes
826             sgWriteChar( fp, idx_mask );
827
828             // write strips
829             for ( i = start; i < end; ++i ) {
830                 // nbytes
831                 sgWriteUInt( fp, pts_v[i].size() * idx_size * sizeof(short) );
832                 for ( j = 0; j < (int)pts_v[i].size(); ++j ) {
833                     if ( pts_v.size() ) { 
834                         sgWriteShort( fp, (short)pts_v[i][j] );
835                     }
836                     if ( pts_n.size() ) { 
837                         sgWriteShort( fp, (short)pts_n[i][j] );
838                     }
839                     if ( pts_c.size() ) { 
840                         sgWriteShort( fp, (short)pts_c[i][j] );
841                     }
842                     if ( pts_tc.size() ) { 
843                         sgWriteShort( fp, (short)pts_tc[i][j] );
844                     }
845                 }
846             }
847             
848             start = end;
849             end = start + 1;
850         }
851     }
852
853     // dump individual triangles if they exist
854     if ( tris_v.size() > 0 ) {
855         int start = 0;
856         int end = 1;
857         string material;
858         while ( start < (int)tri_materials.size() ) {
859             // find next group
860             material = tri_materials[start];
861             while ( (end < (int)tri_materials.size()) && 
862                     (material == tri_materials[end]) )
863             {
864                 // cout << "end = " << end << endl;
865                 end++;
866             }
867             // cout << "group = " << start << " to " << end - 1 << endl;
868
869             // write group headers
870             sgWriteChar( fp, (char)SG_TRIANGLE_FACES ); // type
871             sgWriteShort( fp, 2 );                      // nproperties
872             sgWriteShort( fp, 1 );                      // nelements
873
874             sgWriteChar( fp, (char)SG_MATERIAL );       // property
875             sgWriteUInt( fp, material.length() );        // nbytes
876             sgWriteBytes( fp, material.length(), material.c_str() );
877
878             idx_mask = 0;
879             idx_size = 0;
880             if ( tris_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
881             if ( tris_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
882             if ( tris_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
883             if ( tris_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
884             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
885             sgWriteUInt( fp, 1 );                        // nbytes
886             sgWriteChar( fp, idx_mask );
887
888             // nbytes
889             sgWriteUInt( fp, (end - start) * 3 * idx_size * sizeof(short) );
890
891             // write group
892             for ( i = start; i < end; ++i ) {
893                 for ( j = 0; j < 3; ++j ) {
894                     if ( tris_v.size() ) {
895                         sgWriteShort( fp, (short)tris_v[i][j] );
896                     }
897                     if ( tris_n.size() ) {
898                         sgWriteShort( fp, (short)tris_n[i][j] );
899                     }
900                     if ( tris_c.size() ) {
901                         sgWriteShort( fp, (short)tris_c[i][j] );
902                     }
903                     if ( tris_tc.size() ) {
904                         sgWriteShort( fp, (short)tris_tc[i][j] );
905                     }
906                 }
907             }
908
909             start = end;
910             end = start + 1;
911         }
912     }
913
914     // dump triangle strips
915     if ( strips_v.size() > 0 ) {
916         int start = 0;
917         int end = 1;
918         string material;
919         while ( start < (int)strip_materials.size() ) {
920             // find next group
921             material = strip_materials[start];
922             while ( (end < (int)strip_materials.size()) && 
923                     (material == strip_materials[end]) )
924                 {
925                     // cout << "end = " << end << endl;
926                     end++;
927                 }
928             // cout << "group = " << start << " to " << end - 1 << endl;
929
930             // write group headers
931             sgWriteChar( fp, (char)SG_TRIANGLE_STRIPS ); // type
932             sgWriteShort( fp, 2 );                       // nproperties
933             sgWriteShort( fp, end - start );             // nelements
934
935             sgWriteChar( fp, (char)SG_MATERIAL );        // property
936             sgWriteUInt( fp, material.length() );        // nbytes
937             sgWriteBytes( fp, material.length(), material.c_str() );
938
939             idx_mask = 0;
940             idx_size = 0;
941             if ( strips_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
942             if ( strips_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
943             if ( strips_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
944             if ( strips_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size;}
945             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
946             sgWriteUInt( fp, 1 );                        // nbytes
947             sgWriteChar( fp, idx_mask );
948
949             // write strips
950             for ( i = start; i < end; ++i ) {
951                 // nbytes
952                 sgWriteUInt( fp, strips_v[i].size() * idx_size * sizeof(short));
953                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
954                     if ( strips_v.size() ) { 
955                         sgWriteShort( fp, (short)strips_v[i][j] );
956                     }
957                     if ( strips_n.size() ) { 
958                         sgWriteShort( fp, (short)strips_n[i][j] );
959                     }
960                     if ( strips_c.size() ) { 
961                         sgWriteShort( fp, (short)strips_c[i][j] );
962                     }
963                     if ( strips_tc.size() ) { 
964                         sgWriteShort( fp, (short)strips_tc[i][j] );
965                     }
966                 }
967             }
968             
969             start = end;
970             end = start + 1;
971         }
972     }
973
974     // dump triangle fans
975     if ( fans_v.size() > 0 ) {
976         int start = 0;
977         int end = 1;
978         string material;
979         while ( start < (int)fan_materials.size() ) {
980             // find next group
981             material = fan_materials[start];
982             while ( (end < (int)fan_materials.size()) && 
983                     (material == fan_materials[end]) )
984                 {
985                     // cout << "end = " << end << endl;
986                     end++;
987                 }
988             // cout << "group = " << start << " to " << end - 1 << endl;
989
990             // write group headers
991             sgWriteChar( fp, (char)SG_TRIANGLE_FANS );   // type
992             sgWriteShort( fp, 2 );                       // nproperties
993             sgWriteShort( fp, end - start );             // nelements
994
995             sgWriteChar( fp, (char)SG_MATERIAL );       // property
996             sgWriteUInt( fp, material.length() );        // nbytes
997             sgWriteBytes( fp, material.length(), material.c_str() );
998
999             idx_mask = 0;
1000             idx_size = 0;
1001             if ( fans_v.size() ) { idx_mask |= SG_IDX_VERTICES; ++idx_size; }
1002             if ( fans_n.size() ) { idx_mask |= SG_IDX_NORMALS; ++idx_size; }
1003             if ( fans_c.size() ) { idx_mask |= SG_IDX_COLORS; ++idx_size; }
1004             if ( fans_tc.size() ) { idx_mask |= SG_IDX_TEXCOORDS; ++idx_size; }
1005             sgWriteChar( fp, (char)SG_INDEX_TYPES );     // property
1006             sgWriteUInt( fp, 1 );                        // nbytes
1007             sgWriteChar( fp, idx_mask );
1008
1009             // write fans
1010             for ( i = start; i < end; ++i ) {
1011                 // nbytes
1012                 sgWriteUInt( fp, fans_v[i].size() * idx_size * sizeof(short) );
1013                 for ( j = 0; j < (int)fans_v[i].size(); ++j ) {
1014                     if ( fans_v.size() ) {
1015                         sgWriteShort( fp, (short)fans_v[i][j] );
1016                     }
1017                     if ( fans_n.size() ) {
1018                         sgWriteShort( fp, (short)fans_n[i][j] );
1019                     }
1020                     if ( fans_c.size() ) {
1021                         sgWriteShort( fp, (short)fans_c[i][j] );
1022                     }
1023                     if ( fans_tc.size() ) {
1024                         sgWriteShort( fp, (short)fans_tc[i][j] );
1025                     }
1026                 }
1027             }
1028             
1029             start = end;
1030             end = start + 1;
1031         }
1032     }
1033
1034     // close the file
1035     gzclose(fp);
1036
1037     if ( sgWriteError() ) {
1038         cout << "We detected an error while writing the file." << endl;
1039         return false;
1040     }
1041
1042     return true;
1043 }
1044
1045
1046 // write out the structures to an ASCII file.  We assume that the
1047 // groups come to us sorted by material property.  If not, things
1048 // don't break, but the result won't be as optimal.
1049 bool SGBinObject::write_ascii( const string& base, const string& name,
1050                                const SGBucket& b )
1051 {
1052     Point3D p;
1053     int i, j;
1054
1055     string dir = base + "/" + b.gen_base_path();
1056     string command = "mkdir -p " + dir;
1057 #if defined(_MSC_VER) || defined(__MINGW32__)
1058     system( (string("mkdir ") + dir).c_str() );
1059 #else
1060     system(command.c_str());
1061 #endif
1062
1063     // string file = dir + "/" + b.gen_index_str();
1064     string file = dir + "/" + name;
1065     cout << "Output file = " << file << endl;
1066
1067     FILE *fp;
1068     if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
1069         cout << "ERROR: opening " << file << " for writing!" << endl;
1070         return false;
1071     }
1072
1073     cout << "triangles size = " << tris_v.size() << "  tri_materials = " 
1074          << tri_materials.size() << endl;
1075     cout << "strips size = " << strips_v.size() << "  strip_materials = " 
1076          << strip_materials.size() << endl;
1077     cout << "fans size = " << fans_v.size() << "  fan_materials = " 
1078          << fan_materials.size() << endl;
1079
1080     cout << "points = " << wgs84_nodes.size() << endl;
1081     cout << "tex coords = " << texcoords.size() << endl;
1082     // write headers
1083     fprintf(fp, "# FGFS Scenery\n");
1084     fprintf(fp, "# Version %s\n", SG_SCENERY_FILE_FORMAT);
1085
1086     time_t calendar_time = time(NULL);
1087     struct tm *local_tm;
1088     local_tm = localtime( &calendar_time );
1089     char time_str[256];
1090     strftime( time_str, 256, "%a %b %d %H:%M:%S %Z %Y", local_tm);
1091     fprintf(fp, "# Created %s\n", time_str );
1092     fprintf(fp, "\n");
1093
1094     // write bounding sphere
1095     fprintf(fp, "# gbs %.5f %.5f %.5f %.2f\n",
1096             gbs_center.x(), gbs_center.y(), gbs_center.z(), gbs_radius);
1097     fprintf(fp, "\n");
1098
1099     // dump vertex list
1100     fprintf(fp, "# vertex list\n");
1101     for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
1102         p = wgs84_nodes[i] - gbs_center;
1103         
1104         fprintf(fp,  "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1105     }
1106     fprintf(fp, "\n");
1107
1108     fprintf(fp, "# vertex normal list\n");
1109     for ( i = 0; i < (int)normals.size(); ++i ) {
1110         p = normals[i];
1111         fprintf(fp,  "vn %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
1112     }
1113     fprintf(fp, "\n");
1114
1115     // dump texture coordinates
1116     fprintf(fp, "# texture coordinate list\n");
1117     for ( i = 0; i < (int)texcoords.size(); ++i ) {
1118         p = texcoords[i];
1119         fprintf(fp,  "vt %.5f %.5f\n", p.x(), p.y() );
1120     }
1121     fprintf(fp, "\n");
1122
1123     // dump individual triangles if they exist
1124     if ( tris_v.size() > 0 ) {
1125         fprintf(fp, "# triangle groups\n");
1126
1127         int start = 0;
1128         int end = 1;
1129         string material;
1130         while ( start < (int)tri_materials.size() ) {
1131             // find next group
1132             material = tri_materials[start];
1133             while ( (end < (int)tri_materials.size()) && 
1134                     (material == tri_materials[end]) )
1135             {
1136                 // cout << "end = " << end << endl;
1137                 end++;
1138             }
1139             // cout << "group = " << start << " to " << end - 1 << endl;
1140
1141             // make a list of points for the group
1142             point_list group_nodes;
1143             group_nodes.clear();
1144             Point3D bs_center;
1145             double bs_radius = 0;
1146             for ( i = start; i < end; ++i ) {
1147                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1148                     group_nodes.push_back( wgs84_nodes[ tris_v[i][j] ] );
1149                     bs_center = calc_center( group_nodes );
1150                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1151                 }
1152             }
1153
1154             // write group headers
1155             fprintf(fp, "\n");
1156             fprintf(fp, "# usemtl %s\n", material.c_str());
1157             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1158                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1159
1160             // write groups
1161             for ( i = start; i < end; ++i ) {
1162                 fprintf(fp, "f");
1163                 for ( j = 0; j < (int)tris_v[i].size(); ++j ) {
1164                     fprintf(fp, " %d/%d", tris_v[i][j], tris_tc[i][j] );
1165                 }
1166                 fprintf(fp, "\n");
1167             }
1168
1169             start = end;
1170             end = start + 1;
1171         }
1172     }
1173
1174     // dump triangle groups
1175     if ( strips_v.size() > 0 ) {
1176         fprintf(fp, "# triangle strips\n");
1177
1178         int start = 0;
1179         int end = 1;
1180         string material;
1181         while ( start < (int)strip_materials.size() ) {
1182             // find next group
1183             material = strip_materials[start];
1184             while ( (end < (int)strip_materials.size()) && 
1185                     (material == strip_materials[end]) )
1186                 {
1187                     // cout << "end = " << end << endl;
1188                     end++;
1189                 }
1190             // cout << "group = " << start << " to " << end - 1 << endl;
1191
1192             // make a list of points for the group
1193             point_list group_nodes;
1194             group_nodes.clear();
1195             Point3D bs_center;
1196             double bs_radius = 0;
1197             for ( i = start; i < end; ++i ) {
1198                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1199                     group_nodes.push_back( wgs84_nodes[ strips_v[i][j] ] );
1200                     bs_center = calc_center( group_nodes );
1201                     bs_radius = sgCalcBoundingRadius( bs_center, group_nodes );
1202                 }
1203             }
1204
1205             // write group headers
1206             fprintf(fp, "\n");
1207             fprintf(fp, "# usemtl %s\n", material.c_str());
1208             fprintf(fp, "# bs %.4f %.4f %.4f %.2f\n",
1209                     bs_center.x(), bs_center.y(), bs_center.z(), bs_radius);
1210
1211             // write groups
1212             for ( i = start; i < end; ++i ) {
1213                 fprintf(fp, "ts");
1214                 for ( j = 0; j < (int)strips_v[i].size(); ++j ) {
1215                     fprintf(fp, " %d/%d", strips_v[i][j], strips_tc[i][j] );
1216                 }
1217                 fprintf(fp, "\n");
1218             }
1219             
1220             start = end;
1221             end = start + 1;
1222         }
1223     }
1224
1225     // close the file
1226     fclose(fp);
1227
1228     command = "gzip --force --best " + file;
1229     system(command.c_str());
1230
1231     return true;
1232 }