1 // obj.cxx -- routines to handle "sorta" WaveFront .obj format files.
3 // Written by Curtis Olson, started October 1997.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
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.
28 #ifdef SG_MATH_EXCEPTION_CLASH
35 #include <simgear/compiler.h>
36 #include <simgear/io/sg_binobj.hxx>
40 #include <vector> // STL
41 #include <ctype.h> // isdigit()
43 #include <simgear/constants.h>
44 #include <simgear/debug/logstream.hxx>
45 #include <simgear/math/point3d.hxx>
46 #include <simgear/math/polar3d.hxx>
47 #include <simgear/math/sg_geodesy.hxx>
48 #include <simgear/math/sg_random.h>
49 #include <simgear/misc/sgstream.hxx>
50 #include <simgear/misc/stopwatch.hxx>
51 #include <simgear/misc/texcoord.hxx>
53 #include <Main/globals.hxx>
54 #include <Main/fg_props.hxx>
55 #include <Time/light.hxx>
56 #include <Scenery/tileentry.hxx>
66 typedef vector < int > int_list;
67 typedef int_list::iterator int_list_iterator;
68 typedef int_list::const_iterator int_point_list_iterator;
71 static double normals[FG_MAX_NODES][3];
72 static double tex_coords[FG_MAX_NODES*3][3];
75 runway_lights_predraw (ssgEntity * e)
77 // Turn on lights only at night
78 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
79 return int(sun_angle > 90.0);
83 #define FG_TEX_CONSTANT 69.0
85 // Calculate texture coordinates for a given point.
86 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
89 // double tmplon, tmplat;
91 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
92 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
94 cp = Point3D( node[0] + ref.x(),
98 pp = sgCartToPolar3d(cp);
100 // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
101 // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
102 // cout << tmplon << " " << tmplat << endl;
104 pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
105 pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
107 if ( pp.x() < 0.0 ) {
108 pp.setx( pp.x() + 11.0 );
111 if ( pp.y() < 0.0 ) {
112 pp.sety( pp.y() + 11.0 );
115 // cout << pp << endl;
121 // Generate an ocean tile
122 bool fgGenTile( const string& path, SGBucket b,
124 double *bounding_radius,
125 ssgBranch* geometry )
129 ssgSimpleState *state = NULL;
131 geometry -> setName ( (char *)path.c_str() ) ;
133 double tex_width = 1000.0;
134 // double tex_height;
136 // find Ocean material in the properties list
137 newmat = material_lib.find( "Ocean" );
138 if ( newmat != NULL ) {
139 // set the texture width and height values for this
141 tex_width = newmat->get_xsize();
142 // tex_height = newmat->get_ysize();
145 state = newmat->get_state();
147 SG_LOG( SG_TERRAIN, SG_ALERT,
148 "Ack! unknown usemtl name = " << "Ocean"
152 // Calculate center point
153 double clon = b.get_center_lon();
154 double clat = b.get_center_lat();
155 double height = b.get_height();
156 double width = b.get_width();
158 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
159 clat*SGD_DEGREES_TO_RADIANS,
161 // cout << "center = " << center << endl;;
163 // Caculate corner vertices
165 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
166 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
167 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
168 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
172 for ( i = 0; i < 4; ++i ) {
173 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
174 geod[i].y() * SGD_DEGREES_TO_RADIANS,
178 Point3D cart[4], rel[4];
179 for ( i = 0; i < 4; ++i ) {
180 cart[i] = sgGeodToCart(rad[i]);
181 rel[i] = cart[i] - *center;
182 // cout << "corner " << i << " = " << cart[i] << endl;
185 // Calculate bounding radius
186 *bounding_radius = center->distance3D( cart[0] );
187 // cout << "bounding radius = " << t->bounding_radius << endl;
191 for ( i = 0; i < 4; ++i ) {
192 double length = cart[i].distance3D( Point3D(0.0) );
193 normals[i] = cart[i] / length;
194 // cout << "normal = " << normals[i] << endl;
197 // Calculate texture coordinates
198 point_list geod_nodes;
202 for ( i = 0; i < 4; ++i ) {
203 geod_nodes.push_back( geod[i] );
204 rectangle.push_back( i );
206 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
207 1000.0 / tex_width );
209 // Allocate ssg structure
210 ssgVertexArray *vl = new ssgVertexArray( 4 );
211 ssgNormalArray *nl = new ssgNormalArray( 4 );
212 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
213 ssgColourArray *cl = new ssgColourArray( 1 );
216 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
219 // sgVec3 *vtlist = new sgVec3 [ 4 ];
220 // t->vec3_ptrs.push_back( vtlist );
221 // sgVec3 *vnlist = new sgVec3 [ 4 ];
222 // t->vec3_ptrs.push_back( vnlist );
223 // sgVec2 *tclist = new sgVec2 [ 4 ];
224 // t->vec2_ptrs.push_back( tclist );
228 for ( i = 0; i < 4; ++i ) {
230 rel[i].x(), rel[i].y(), rel[i].z() );
234 normals[i].x(), normals[i].y(), normals[i].z() );
237 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
242 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
244 leaf->setState( state );
246 geometry->addKid( leaf );
252 static void random_pt_inside_tri( float *res,
253 float *n1, float *n2, float *n3 )
257 double a = sg_random();
258 double b = sg_random();
263 double c = 1 - a - b;
265 sgScaleVec3( p1, n1, a );
266 sgScaleVec3( p2, n2, b );
267 sgScaleVec3( p3, n3, c );
269 sgAddVec3( res, p1, p2 );
270 sgAddVec3( res, p3 );
274 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
276 int num = leaf->getNumTriangles();
278 short int n1, n2, n3;
282 // generate a repeatable random seed
283 p1 = leaf->getVertex( 0 );
284 unsigned int seed = (unsigned int)p1[0];
287 for ( int i = 0; i < num; ++i ) {
288 leaf->getTriangle( i, &n1, &n2, &n3 );
289 p1 = leaf->getVertex(n1);
290 p2 = leaf->getVertex(n2);
291 p3 = leaf->getVertex(n3);
292 double area = sgTriArea( p1, p2, p3 );
293 double num = area / factor;
295 // generate a light point for each unit of area
296 while ( num > 1.0 ) {
297 random_pt_inside_tri( result, p1, p2, p3 );
298 lights->add( result );
301 // for partial units of area, use a zombie door method to
302 // create the proper random chance of a light being created
305 if ( sg_random() <= num ) {
306 // a zombie made it through our door
307 random_pt_inside_tri( result, p1, p2, p3 );
308 lights->add( result );
317 * Add an object to a random location inside a triangle.
319 * @param p1 The first vertex of the triangle.
320 * @param p2 The second vertex of the triangle.
321 * @param p3 The third vertex of the triangle.
322 * @param center The center of the triangle.
323 * @param ROT The world-up rotation matrix.
324 * @param mat The material object.
325 * @param object_index The index of the dynamically-placed object in
327 * @param branch The branch where the object should be added to the
331 add_object_to_triangle (sgVec3 p1, sgVec3 p2, sgVec3 p3, sgVec3 center,
332 sgMat4 ROT, FGNewMat * mat, int object_index,
337 random_pt_inside_tri(result, p1, p2, p3);
338 sgSubVec3(result, center);
340 sgMakeTransMat4(OBJ_pos, result);
341 sgCopyMat4(OBJ, ROT);
342 sgPostMultMat4(OBJ, OBJ_pos);
343 ssgTransform * pos = new ssgTransform;
344 pos->setTransform(OBJ);
345 pos->addKid(mat->get_object(object_index));
349 class RandomObjectUserData : public ssgBase
364 * Fill in a triangle with randomly-placed objects.
366 * This method is invoked by a callback when the triangle is in range
367 * but not yet populated.
369 * @param p1 The first vertex of the triangle.
370 * @param p2 The second vertex of the triangle.
371 * @param p3 The third vertex of the triangle.
372 * @param mat The triangle's material.
373 * @param object_index The index of the random object in the triangle.
374 * @param branch The branch where the objects should be added.
375 * @param ROT The rotation matrix to align objects with the earth's
379 fill_in_triangle (float * p1, float * p2, float * p3, FGNewMat * mat,
380 int object_index, ssgBranch * branch, sgMat4 ROT)
384 (p1[0] + p2[0] + p3[0]) / 3.0,
385 (p1[1] + p2[1] + p3[1]) / 3.0,
386 (p1[2] + p2[2] + p3[2]) / 3.0);
387 double area = sgTriArea(p1, p2, p3);
388 double num = area / mat->get_object_coverage(object_index);
390 // place an object each unit of area
391 while ( num > 1.0 ) {
392 add_object_to_triangle(p1, p2, p3, center,
393 ROT, mat, object_index, branch);
396 // for partial units of area, use a zombie door method to
397 // create the proper random chance of an object being created
400 if ( sg_random() <= num ) {
401 // a zombie made it through our door
402 add_object_to_triangle(p1, p2, p3, center,
403 ROT, mat, object_index, branch);
410 * SSG callback for an in-range triangle of randomly-placed objects.
412 * This pretraversal callback is attached to a branch that is traversed
413 * only when a triangle is in range. If the triangle is not currently
414 * populated with randomly-placed objects, this callback will populate
417 * @param entity The entity to which the callback is attached (not used).
418 * @param mask The entity's traversal mask (not used).
419 * @return Always 1, to allow traversal and culling to continue.
422 in_range_callback (ssgEntity * entity, int mask)
424 RandomObjectUserData * data = (RandomObjectUserData *)entity->getUserData();
425 if (!data->is_filled_in) {
426 fill_in_triangle(data->p1, data->p2, data->p3, data->mat,
427 data->object_index, data->branch, data->ROT);
428 data->is_filled_in = true;
435 * SSG callback for an out-of-range triangle of randomly-placed objects.
437 * This pretraversal callback is attached to a branch that is traversed
438 * only when a triangle is out of range. If the triangle is currently
439 * populated with randomly-placed objects, the objects will be removed.
442 * @param entity The entity to which the callback is attached (not used).
443 * @param mask The entity's traversal mask (not used).
444 * @return Always 0, to prevent any further traversal or culling.
447 out_of_range_callback (ssgEntity * entity, int mask)
449 RandomObjectUserData * data = (RandomObjectUserData *)entity->getUserData();
450 if (data->is_filled_in) {
451 data->branch->removeAllKids();
452 data->is_filled_in = false;
459 * Singleton ssgEntity with a dummy bounding sphere, to fool culling.
461 * This forces the in-range and out-of-range branches to be visited
462 * when appropriate, even if they have no children. It's ugly, but
463 * it works and seems fairly efficient (since branches can still
464 * be culled when they're out of the view frustum).
466 class DummyBSphereEntity : public ssgEntity
469 virtual ~DummyBSphereEntity () {}
470 virtual void recalcBSphere () { bsphere_is_invalid = false; }
471 virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
472 virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
473 virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
474 virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
475 static ssgEntity * get_entity ();
477 DummyBSphereEntity ()
479 bsphere.setCenter(0, 0, 0);
480 bsphere.setRadius(10);
482 static DummyBSphereEntity * entity;
486 DummyBSphereEntity * DummyBSphereEntity::entity = 0;
490 * Ensure that only one copy of the dummy entity exists.
492 * @return The singleton copy of the DummyBSphereEntity.
495 DummyBSphereEntity::get_entity ()
498 entity = new DummyBSphereEntity;
506 * Set up a triangle for randomly-placed objects.
508 * No objects will be added unless the triangle comes into range.
510 * @param leaf The leaf containing the data for the terrain surface.
511 * @param tri_index The index of the triangle in the leaf.
512 * @param mat The material data for the triangle.
513 * @param branch The branch to which the randomly-placed objects
515 * @param ROT A rotation matrix to align the objects with the earth's
516 * surface at the current lat/lon.
519 setup_triangle (float * p1, float * p2, float * p3,
520 FGNewMat * mat, ssgBranch * branch, sgMat4 ROT)
522 // Set up a single center point for LOD
525 (p1[0] + p2[0] + p3[0]) / 3.0,
526 (p1[1] + p2[1] + p3[1]) / 3.0,
527 (p1[2] + p2[2] + p3[2]) / 3.0);
529 // Set up a transformation to the center
530 // point, so that everything else can
531 // be specified relative to it.
532 ssgTransform * location = new ssgTransform;
534 sgMakeTransMat4(TRANS, center);
535 location->setTransform(TRANS);
536 branch->addKid(location);
538 // Calculate the triangle area.
539 double area = sgTriArea(p1, p2, p3);
541 // Iterate through all the object types.
542 int num_objects = mat->get_object_count();
543 for (int i = 0; i < num_objects; i++) {
545 // Set up the range selector. Note that
546 // we provide only two ranges, so the
547 // upper limit will be infinity.
548 float ranges[] = {0, mat->get_object_lod(i), 9999999};
549 ssgRangeSelector * lod = new ssgRangeSelector;
550 lod->setRanges(ranges, 3);
551 location->addKid(lod);
553 // Create the in-range and out-of-range
555 ssgBranch * in_range = new ssgBranch;
556 ssgBranch * out_of_range = new ssgBranch;
558 // Set up the user data for if/when
559 // the random objects in this triangle
561 RandomObjectUserData * data = new RandomObjectUserData;
562 data->is_filled_in = false;
567 data->object_index = i;
568 data->branch = in_range;
569 sgCopyMat4(data->ROT, ROT);
571 // Set up the in-range node.
572 in_range->setUserData(data);
573 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
575 lod->addKid(in_range);
577 // Set up the out-of-range node.
578 out_of_range->setUserData(data);
579 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
580 out_of_range_callback);
581 out_of_range->addKid(DummyBSphereEntity::get_entity());
582 lod->addKid(out_of_range);
588 * Create a rotation matrix to align an object for the current lat/lon.
590 * By default, objects are aligned for the north pole. This code
591 * calculates a matrix to rotate them for the surface of the earth in
592 * the current location.
594 * TODO: there should be a single version of this method somewhere
595 * for all of SimGear.
597 * @param ROT The resulting rotation matrix.
598 * @param hdg_deg The object heading in degrees.
599 * @param lon_deg The longitude in degrees.
600 * @param lat_deg The latitude in degrees.
603 makeWorldUpRotationMatrix (sgMat4 ROT, double hdg_deg,
604 double lon_deg, double lat_deg)
606 sgVec3 obj_right, obj_up;
607 sgSetVec3(obj_right, 0.0, 1.0, 0.0); // Y axis
608 sgSetVec3(obj_up, 0.0, 0.0, 1.0); // Z axis
609 sgMat4 ROT_lon, ROT_lat, ROT_hdg;
610 sgMakeRotMat4(ROT_lon, lon_deg, obj_up);
611 sgMakeRotMat4(ROT_lat, 90 - lat_deg, obj_right);
612 sgMakeRotMat4(ROT_hdg, hdg_deg, obj_up);
613 sgCopyMat4(ROT, ROT_hdg);
614 sgPostMultMat4(ROT, ROT_lat);
615 sgPostMultMat4(ROT, ROT_lon);
620 * Randomly place objects on a surface.
622 * The leaf node provides the geometry of the surface, while the
623 * material provides the objects and placement density. Latitude
624 * and longitude are required so that the objects can be rotated
625 * to the world-up vector.
627 * @param leaf The surface where the objects should be placed.
628 * @param branch The branch that will hold the randomly-placed objects.
629 * @param lon_deg The longitude of the surface center, in degrees.
630 * @param lat_deg The latitude of the surface center, in degrees.
631 * @param material_name The name of the surface's material.
634 gen_random_surface_objects (ssgLeaf *leaf,
638 const string &material_name)
640 float hdg_deg = 0.0; // do something here later
642 // First, look up the material
644 FGNewMat * mat = material_lib.find(material_name);
646 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
650 // If the material has no randomly-placed
651 // objects, return now.
652 int num_objects = mat->get_object_count();
656 // If the surface has no triangles, return
658 int num_tris = leaf->getNumTriangles();
662 // Make a rotation matrix to align the
663 // object for this point on the earth's
666 makeWorldUpRotationMatrix(ROT, hdg_deg, lon_deg, lat_deg);
668 // generate a repeatable random seed
669 sg_srandom((unsigned int)(leaf->getVertex(0)[0]));
671 // Iterate through all the triangles
672 // and populate them.
673 for ( int i = 0; i < num_tris; ++i ) {
675 leaf->getTriangle(i, &n1, &n2, &n3);
676 setup_triangle(leaf->getVertex(n1),
685 ////////////////////////////////////////////////////////////////////////
687 ////////////////////////////////////////////////////////////////////////
690 // Load an Ascii obj file
691 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
692 ssgVertexArray *lights, const bool is_base)
694 FGNewMat *newmat = NULL;
698 // sgVec3 approx_normal;
699 // double normal[3], scale = 0.0;
700 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
701 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
702 // GLint display_list = 0;
704 bool in_faces = false;
705 int vncount, vtcount;
706 int n1 = 0, n2 = 0, n3 = 0;
708 // int last1 = 0, last2 = 0;
713 double scenery_version = 0.0;
714 double tex_width = 1000.0, tex_height = 1000.0;
715 bool shared_done = false;
716 int_list fan_vertices;
717 int_list fan_tex_coords;
719 ssgSimpleState *state = NULL;
720 sgVec3 *vtlist, *vnlist;
723 ssgBranch *tile = new ssgBranch () ;
725 tile -> setName ( (char *)path.c_str() ) ;
727 // Attempt to open "path.gz" or "path"
728 sg_gzifstream in( path );
729 if ( ! in.is_open() ) {
730 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
731 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
738 shading = fgGetBool("/sim/rendering/shading");
746 t->bounding_radius = 0.0;
750 // StopWatch stopwatch;
751 // stopwatch.start();
753 // ignore initial comments and blank lines. (priming the pump)
754 // in >> skipcomment;
761 while ( in.get(c) && c != '\0' ) {
764 while ( ! in.eof() ) {
769 if ( in.get( c ) && c == '#' ) {
770 // process a comment line
772 // getline( in, line );
773 // cout << "comment = " << line << endl;
777 if ( token == "Version" ) {
778 // read scenery versions number
779 in >> scenery_version;
780 // cout << "scenery_version = " << scenery_version << endl;
781 if ( scenery_version > 0.4 ) {
782 SG_LOG( SG_TERRAIN, SG_ALERT,
783 "\nYou are attempting to load a tile format that\n"
784 << "is newer than this version of flightgear can\n"
785 << "handle. You should upgrade your copy of\n"
786 << "FlightGear to the newest version. For\n"
787 << "details, please see:\n"
788 << "\n http://www.flightgear.org\n" );
791 } else if ( token == "gbs" ) {
792 // reference point (center offset)
794 in >> t->center >> t->bounding_radius;
798 in >> junk1 >> junk2;
801 // cout << "center = " << center
802 // << " radius = " << t->bounding_radius << endl;
803 } else if ( token == "bs" ) {
804 // reference point (center offset)
808 in >> junk1 >> junk2;
809 } else if ( token == "usemtl" ) {
810 // material property specification
812 // if first usemtl with shared_done = false, then set
813 // shared_done true and build the ssg shared lists
814 if ( ! shared_done ) {
816 if ( (int)nodes.size() != vncount ) {
817 SG_LOG( SG_TERRAIN, SG_ALERT,
818 "Tile has mismatched nodes = " << nodes.size()
819 << " and normals = " << vncount << " : "
825 vtlist = new sgVec3 [ nodes.size() ];
826 t->vec3_ptrs.push_back( vtlist );
827 vnlist = new sgVec3 [ vncount ];
828 t->vec3_ptrs.push_back( vnlist );
829 tclist = new sgVec2 [ vtcount ];
830 t->vec2_ptrs.push_back( tclist );
832 for ( i = 0; i < (int)nodes.size(); ++i ) {
833 sgSetVec3( vtlist[i],
834 nodes[i][0], nodes[i][1], nodes[i][2] );
836 for ( i = 0; i < vncount; ++i ) {
837 sgSetVec3( vnlist[i],
842 for ( i = 0; i < vtcount; ++i ) {
843 sgSetVec2( tclist[i],
849 // display_list = xglGenLists(1);
850 // xglNewList(display_list, GL_COMPILE);
851 // printf("xglGenLists(); xglNewList();\n");
854 // scan the material line
857 // find this material in the properties list
859 newmat = material_lib.find( material );
860 if ( newmat == NULL ) {
861 // see if this is an on the fly texture
863 int pos = file.rfind( "/" );
864 file = file.substr( 0, pos );
865 // cout << "current file = " << file << endl;
868 // cout << "current file = " << file << endl;
869 if ( ! material_lib.add_item( file ) ) {
870 SG_LOG( SG_TERRAIN, SG_ALERT,
871 "Ack! unknown usemtl name = " << material
874 // locate our newly created material
875 newmat = material_lib.find( material );
876 if ( newmat == NULL ) {
877 SG_LOG( SG_TERRAIN, SG_ALERT,
878 "Ack! bad on the fly materia create = "
879 << material << " in " << path );
884 if ( newmat != NULL ) {
885 // set the texture width and height values for this
887 tex_width = newmat->get_xsize();
888 tex_height = newmat->get_ysize();
889 state = newmat->get_state();
890 coverage = newmat->get_light_coverage();
891 // cout << "(w) = " << tex_width << " (h) = "
892 // << tex_width << endl;
897 // unknown comment, just gobble the input until the
907 // cout << "token = " << token << endl;
909 if ( token == "vn" ) {
911 if ( vncount < FG_MAX_NODES ) {
912 in >> normals[vncount][0]
913 >> normals[vncount][1]
914 >> normals[vncount][2];
917 SG_LOG( SG_TERRAIN, SG_ALERT,
918 "Read too many vertex normals in " << path
919 << " ... dying :-(" );
922 } else if ( token == "vt" ) {
923 // vertex texture coordinate
924 if ( vtcount < FG_MAX_NODES*3 ) {
925 in >> tex_coords[vtcount][0]
926 >> tex_coords[vtcount][1];
929 SG_LOG( SG_TERRAIN, SG_ALERT,
930 "Read too many vertex texture coords in " << path
935 } else if ( token == "v" ) {
937 if ( t->ncount < FG_MAX_NODES ) {
938 /* in >> nodes[t->ncount][0]
939 >> nodes[t->ncount][1]
940 >> nodes[t->ncount][2]; */
942 nodes.push_back(node);
947 SG_LOG( SG_TERRAIN, SG_ALERT,
948 "Read too many nodes in " << path
949 << " ... dying :-(");
952 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
953 // triangle fan, strip, or individual face
954 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
956 fan_vertices.clear();
957 fan_tex_coords.clear();
960 // xglBegin(GL_TRIANGLE_FAN);
963 fan_vertices.push_back( n1 );
964 // xglNormal3dv(normals[n1]);
965 if ( in.get( c ) && c == '/' ) {
967 fan_tex_coords.push_back( tex );
968 if ( scenery_version >= 0.4 ) {
969 if ( tex_width > 0 ) {
970 tclist[tex][0] *= (1000.0 / tex_width);
972 if ( tex_height > 0 ) {
973 tclist[tex][1] *= (1000.0 / tex_height);
976 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
977 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
980 pp = local_calc_tex_coords(nodes[n1], center);
982 // xglTexCoord2f(pp.x(), pp.y());
983 // xglVertex3dv(nodes[n1].get_n());
986 fan_vertices.push_back( n2 );
987 // xglNormal3dv(normals[n2]);
988 if ( in.get( c ) && c == '/' ) {
990 fan_tex_coords.push_back( tex );
991 if ( scenery_version >= 0.4 ) {
992 if ( tex_width > 0 ) {
993 tclist[tex][0] *= (1000.0 / tex_width);
995 if ( tex_height > 0 ) {
996 tclist[tex][1] *= (1000.0 / tex_height);
999 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1000 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1003 pp = local_calc_tex_coords(nodes[n2], center);
1005 // xglTexCoord2f(pp.x(), pp.y());
1006 // xglVertex3dv(nodes[n2].get_n());
1008 // read all subsequent numbers until next thing isn't a number
1015 if ( ! isdigit(c) || in.eof() ) {
1020 fan_vertices.push_back( n3 );
1021 // cout << " triangle = "
1022 // << n1 << "," << n2 << "," << n3
1024 // xglNormal3dv(normals[n3]);
1025 if ( in.get( c ) && c == '/' ) {
1027 fan_tex_coords.push_back( tex );
1028 if ( scenery_version >= 0.4 ) {
1029 if ( tex_width > 0 ) {
1030 tclist[tex][0] *= (1000.0 / tex_width);
1032 if ( tex_height > 0 ) {
1033 tclist[tex][1] *= (1000.0 / tex_height);
1036 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1037 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1040 pp = local_calc_tex_coords(nodes[n3], center);
1042 // xglTexCoord2f(pp.x(), pp.y());
1043 // xglVertex3dv(nodes[n3].get_n());
1045 if ( (token == "tf") || (token == "f") ) {
1058 // build the ssg entity
1059 int size = (int)fan_vertices.size();
1060 ssgVertexArray *vl = new ssgVertexArray( size );
1061 ssgNormalArray *nl = new ssgNormalArray( size );
1062 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1063 ssgColourArray *cl = new ssgColourArray( 1 );
1066 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1071 for ( i = 0; i < size; ++i ) {
1072 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1075 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1078 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1082 ssgLeaf *leaf = NULL;
1083 if ( token == "tf" ) {
1086 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1087 } else if ( token == "ts" ) {
1090 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1091 } else if ( token == "f" ) {
1094 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1096 // leaf->makeDList();
1097 leaf->setState( state );
1099 tile->addKid( leaf );
1102 if ( coverage > 0.0 ) {
1103 if ( coverage < 10000.0 ) {
1104 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1105 << coverage << ", pushing up to 10000");
1108 gen_random_surface_points(leaf, lights, coverage);
1112 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1113 << path << " = " << token );
1116 // eat white space before start of while loop so if we are
1117 // done with useful input it is noticed before hand.
1126 // stopwatch.stop();
1127 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1128 // "Loaded " << path << " in "
1129 // << stopwatch.elapsedSeconds() << " seconds" );
1135 ssgLeaf *gen_leaf( const string& path,
1136 const GLenum ty, const string& material,
1137 const point_list& nodes, const point_list& normals,
1138 const point_list& texcoords,
1139 const int_list node_index,
1140 const int_list normal_index,
1141 const int_list& tex_index,
1142 const bool calc_lights, ssgVertexArray *lights )
1144 double tex_width = 1000.0, tex_height = 1000.0;
1145 ssgSimpleState *state = NULL;
1146 float coverage = -1;
1148 FGNewMat *newmat = material_lib.find( material );
1149 if ( newmat == NULL ) {
1150 // see if this is an on the fly texture
1152 int pos = file.rfind( "/" );
1153 file = file.substr( 0, pos );
1154 // cout << "current file = " << file << endl;
1157 // cout << "current file = " << file << endl;
1158 if ( ! material_lib.add_item( file ) ) {
1159 SG_LOG( SG_TERRAIN, SG_ALERT,
1160 "Ack! unknown usemtl name = " << material
1161 << " in " << path );
1163 // locate our newly created material
1164 newmat = material_lib.find( material );
1165 if ( newmat == NULL ) {
1166 SG_LOG( SG_TERRAIN, SG_ALERT,
1167 "Ack! bad on the fly material create = "
1168 << material << " in " << path );
1173 if ( newmat != NULL ) {
1174 // set the texture width and height values for this
1176 tex_width = newmat->get_xsize();
1177 tex_height = newmat->get_ysize();
1178 state = newmat->get_state();
1179 coverage = newmat->get_light_coverage();
1180 // cout << "(w) = " << tex_width << " (h) = "
1181 // << tex_width << endl;
1192 int size = node_index.size();
1194 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1197 ssgVertexArray *vl = new ssgVertexArray( size );
1199 for ( i = 0; i < size; ++i ) {
1200 node = nodes[ node_index[i] ];
1201 sgSetVec3( tmp3, node[0], node[1], node[2] );
1207 ssgNormalArray *nl = new ssgNormalArray( size );
1208 if ( normal_index.size() ) {
1209 // object file specifies normal indices (i.e. normal indices
1211 for ( i = 0; i < size; ++i ) {
1212 normal = normals[ normal_index[i] ];
1213 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1217 // use implied normal indices. normal index = vertex index.
1218 for ( i = 0; i < size; ++i ) {
1219 normal = normals[ node_index[i] ];
1220 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1226 ssgColourArray *cl = new ssgColourArray( 1 );
1227 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1230 // texture coordinates
1231 size = tex_index.size();
1233 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1235 texcoord = texcoords[ tex_index[0] ];
1236 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1237 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1238 if ( tex_width > 0 ) {
1239 tmp2[0] *= (1000.0 / tex_width);
1241 if ( tex_height > 0 ) {
1242 tmp2[1] *= (1000.0 / tex_height);
1245 } else if ( size > 1 ) {
1246 for ( i = 0; i < size; ++i ) {
1247 texcoord = texcoords[ tex_index[i] ];
1248 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1249 if ( tex_width > 0 ) {
1250 tmp2[0] *= (1000.0 / tex_width);
1252 if ( tex_height > 0 ) {
1253 tmp2[1] *= (1000.0 / tex_height);
1259 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1261 // lookup the state record
1263 leaf->setState( state );
1265 if ( calc_lights ) {
1266 if ( coverage > 0.0 ) {
1267 if ( coverage < 10000.0 ) {
1268 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1269 << coverage << ", pushing up to 10000");
1272 gen_random_surface_points(leaf, lights, coverage);
1280 // Load an Binary obj file
1281 bool fgBinObjLoad( const string& path, const bool is_base,
1283 double *bounding_radius,
1284 ssgBranch* geometry,
1285 ssgBranch* rwy_lights,
1286 ssgVertexArray *ground_lights )
1289 bool use_dynamic_objects =
1290 fgGetBool("/sim/rendering/dynamic-objects", false);
1292 if ( ! obj.read_bin( path ) ) {
1296 geometry->setName( (char *)path.c_str() );
1298 double geod_lon = 0.0, geod_lat = 0.0, geod_alt = 0.0,
1299 geod_sl_radius = 0.0;
1301 // reference point (center offset/bounding sphere)
1302 *center = obj.get_gbs_center();
1303 *bounding_radius = obj.get_gbs_radius();
1305 // Calculate the geodetic centre of
1306 // the tile, for aligning automatic
1308 Point3D geoc = sgCartToPolar3d(*center);
1309 geod_lon = geoc.lon();
1310 sgGeocToGeod(geoc.lat(), geoc.radius(),
1311 &geod_lat, &geod_alt, &geod_sl_radius);
1312 geod_lon *= SGD_RADIANS_TO_DEGREES;
1313 geod_lat *= SGD_RADIANS_TO_DEGREES;
1316 point_list nodes = obj.get_wgs84_nodes();
1317 point_list colors = obj.get_colors();
1318 point_list normals = obj.get_normals();
1319 point_list texcoords = obj.get_texcoords();
1321 string material, tmp_mat;
1322 int_list vertex_index;
1323 int_list normal_index;
1327 bool is_lighting = false;
1330 string_list pt_materials = obj.get_pt_materials();
1331 group_list pts_v = obj.get_pts_v();
1332 group_list pts_n = obj.get_pts_n();
1333 for ( i = 0; i < (int)pts_v.size(); ++i ) {
1334 // cout << "pts_v.size() = " << pts_v.size() << endl;
1335 tmp_mat = pt_materials[i];
1336 if ( tmp_mat.substr(0, 3) == "RWY" ) {
1337 material = "LIGHTS";
1342 vertex_index = pts_v[i];
1343 normal_index = pts_n[i];
1345 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1346 nodes, normals, texcoords,
1347 vertex_index, normal_index, tex_index,
1348 false, ground_lights );
1350 if ( is_lighting ) {
1351 float ranges[] = { 0, 12000 };
1352 leaf->setCallback(SSG_CALLBACK_PREDRAW, runway_lights_predraw);
1353 ssgRangeSelector * lod = new ssgRangeSelector;
1354 lod->setRanges(ranges, 2);
1356 rwy_lights->addKid(lod);
1358 geometry->addKid( leaf );
1362 // generate triangles
1363 string_list tri_materials = obj.get_tri_materials();
1364 group_list tris_v = obj.get_tris_v();
1365 group_list tris_n = obj.get_tris_n();
1366 group_list tris_tc = obj.get_tris_tc();
1367 for ( i = 0; i < (int)tris_v.size(); ++i ) {
1368 material = tri_materials[i];
1369 vertex_index = tris_v[i];
1370 normal_index = tris_n[i];
1371 tex_index = tris_tc[i];
1372 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, material,
1373 nodes, normals, texcoords,
1374 vertex_index, normal_index, tex_index,
1375 is_base, ground_lights );
1377 if (use_dynamic_objects)
1378 gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1380 geometry->addKid( leaf );
1384 string_list strip_materials = obj.get_strip_materials();
1385 group_list strips_v = obj.get_strips_v();
1386 group_list strips_n = obj.get_strips_n();
1387 group_list strips_tc = obj.get_strips_tc();
1388 for ( i = 0; i < (int)strips_v.size(); ++i ) {
1389 material = strip_materials[i];
1390 vertex_index = strips_v[i];
1391 normal_index = strips_n[i];
1392 tex_index = strips_tc[i];
1393 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, material,
1394 nodes, normals, texcoords,
1395 vertex_index, normal_index, tex_index,
1396 is_base, ground_lights );
1398 if (use_dynamic_objects)
1399 gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1401 geometry->addKid( leaf );
1405 string_list fan_materials = obj.get_fan_materials();
1406 group_list fans_v = obj.get_fans_v();
1407 group_list fans_n = obj.get_fans_n();
1408 group_list fans_tc = obj.get_fans_tc();
1409 for ( i = 0; i < (int)fans_v.size(); ++i ) {
1410 material = fan_materials[i];
1411 vertex_index = fans_v[i];
1412 normal_index = fans_n[i];
1413 tex_index = fans_tc[i];
1414 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, material,
1415 nodes, normals, texcoords,
1416 vertex_index, normal_index, tex_index,
1417 is_base, ground_lights );
1418 if (use_dynamic_objects)
1419 gen_random_surface_objects(leaf, geometry, geod_lon, geod_lat,
1421 geometry->addKid( leaf );