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/sg_inlines.h>
37 #include <simgear/io/sg_binobj.hxx>
41 #include <vector> // STL
42 #include <ctype.h> // isdigit()
44 #include <simgear/constants.h>
45 #include <simgear/debug/logstream.hxx>
46 #include <simgear/math/point3d.hxx>
47 #include <simgear/math/polar3d.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/vector.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/misc/stopwatch.hxx>
53 #include <simgear/misc/texcoord.hxx>
55 #include <Main/globals.hxx>
56 #include <Main/fg_props.hxx>
57 #include <Time/light.hxx>
58 #include <Scenery/tileentry.hxx>
62 #include "pt_lights.hxx"
69 typedef vector < int > int_list;
70 typedef int_list::iterator int_list_iterator;
71 typedef int_list::const_iterator int_point_list_iterator;
74 static double normals[FG_MAX_NODES][3];
75 static double tex_coords[FG_MAX_NODES*3][3];
78 // not used because plib branches don't honor call backs.
80 runway_lights_predraw (ssgEntity * e)
82 // Turn on lights only at night
83 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
84 return int((sun_angle > 90.0) ||
85 (fgGetDouble("/environment/visibility-m") < 5000.0));
90 #define FG_TEX_CONSTANT 69.0
92 // Calculate texture coordinates for a given point.
93 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
96 // double tmplon, tmplat;
98 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
99 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
101 cp = Point3D( node[0] + ref.x(),
105 pp = sgCartToPolar3d(cp);
107 // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
108 // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
109 // cout << tmplon << " " << tmplat << endl;
111 pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
112 pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
114 if ( pp.x() < 0.0 ) {
115 pp.setx( pp.x() + 11.0 );
118 if ( pp.y() < 0.0 ) {
119 pp.sety( pp.y() + 11.0 );
122 // cout << pp << endl;
128 // Generate an ocean tile
129 bool fgGenTile( const string& path, SGBucket b,
131 double *bounding_radius,
132 ssgBranch* geometry )
136 ssgSimpleState *state = NULL;
138 geometry -> setName ( (char *)path.c_str() ) ;
140 double tex_width = 1000.0;
141 // double tex_height;
143 // find Ocean material in the properties list
144 newmat = material_lib.find( "Ocean" );
145 if ( newmat != NULL ) {
146 // set the texture width and height values for this
148 tex_width = newmat->get_xsize();
149 // tex_height = newmat->get_ysize();
152 state = newmat->get_state();
154 SG_LOG( SG_TERRAIN, SG_ALERT,
155 "Ack! unknown usemtl name = " << "Ocean"
159 // Calculate center point
160 double clon = b.get_center_lon();
161 double clat = b.get_center_lat();
162 double height = b.get_height();
163 double width = b.get_width();
165 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
166 clat*SGD_DEGREES_TO_RADIANS,
168 // cout << "center = " << center << endl;;
170 // Caculate corner vertices
172 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
173 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
174 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
175 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
179 for ( i = 0; i < 4; ++i ) {
180 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
181 geod[i].y() * SGD_DEGREES_TO_RADIANS,
185 Point3D cart[4], rel[4];
186 for ( i = 0; i < 4; ++i ) {
187 cart[i] = sgGeodToCart(rad[i]);
188 rel[i] = cart[i] - *center;
189 // cout << "corner " << i << " = " << cart[i] << endl;
192 // Calculate bounding radius
193 *bounding_radius = center->distance3D( cart[0] );
194 // cout << "bounding radius = " << t->bounding_radius << endl;
198 for ( i = 0; i < 4; ++i ) {
199 double length = cart[i].distance3D( Point3D(0.0) );
200 normals[i] = cart[i] / length;
201 // cout << "normal = " << normals[i] << endl;
204 // Calculate texture coordinates
205 point_list geod_nodes;
207 geod_nodes.reserve(4);
210 rectangle.reserve(4);
211 for ( i = 0; i < 4; ++i ) {
212 geod_nodes.push_back( geod[i] );
213 rectangle.push_back( i );
215 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
216 1000.0 / tex_width );
218 // Allocate ssg structure
219 ssgVertexArray *vl = new ssgVertexArray( 4 );
220 ssgNormalArray *nl = new ssgNormalArray( 4 );
221 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
222 ssgColourArray *cl = new ssgColourArray( 1 );
225 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
228 // sgVec3 *vtlist = new sgVec3 [ 4 ];
229 // t->vec3_ptrs.push_back( vtlist );
230 // sgVec3 *vnlist = new sgVec3 [ 4 ];
231 // t->vec3_ptrs.push_back( vnlist );
232 // sgVec2 *tclist = new sgVec2 [ 4 ];
233 // t->vec2_ptrs.push_back( tclist );
237 for ( i = 0; i < 4; ++i ) {
239 rel[i].x(), rel[i].y(), rel[i].z() );
243 normals[i].x(), normals[i].y(), normals[i].z() );
246 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
251 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
253 leaf->setState( state );
255 geometry->addKid( leaf );
261 static void random_pt_inside_tri( float *res,
262 float *n1, float *n2, float *n3 )
264 double a = sg_random();
265 double b = sg_random();
270 double c = 1 - a - b;
272 res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
273 res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
274 res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
278 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
280 int num = leaf->getNumTriangles();
282 short int n1, n2, n3;
286 // generate a repeatable random seed
287 p1 = leaf->getVertex( 0 );
288 unsigned int seed = (unsigned int)(fabs(p1[0]*100));
291 for ( int i = 0; i < num; ++i ) {
292 leaf->getTriangle( i, &n1, &n2, &n3 );
293 p1 = leaf->getVertex(n1);
294 p2 = leaf->getVertex(n2);
295 p3 = leaf->getVertex(n3);
296 double area = sgTriArea( p1, p2, p3 );
297 double num = area / factor;
299 // generate a light point for each unit of area
300 while ( num > 1.0 ) {
301 random_pt_inside_tri( result, p1, p2, p3 );
302 lights->add( result );
305 // for partial units of area, use a zombie door method to
306 // create the proper random chance of a light being created
309 if ( sg_random() <= num ) {
310 // a zombie made it through our door
311 random_pt_inside_tri( result, p1, p2, p3 );
312 lights->add( result );
321 * User data for populating leaves when they come in range.
323 class LeafUserData : public ssgBase
335 void setup_triangle( int i );
340 * User data for populating triangles when they come in range.
342 class TriUserData : public ssgBase
351 FGNewMat::ObjectGroup * object_group;
353 LeafUserData * leafData;
356 void fill_in_triangle();
357 void add_object_to_triangle(FGNewMat::Object * object);
358 void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
363 * Fill in a triangle with randomly-placed objects.
365 * This method is invoked by a callback when the triangle is in range
366 * but not yet populated.
370 void TriUserData::fill_in_triangle ()
372 // generate a repeatable random seed
375 int nObjects = object_group->get_object_count();
377 for (int i = 0; i < nObjects; i++) {
378 FGNewMat::Object * object = object_group->get_object(i);
379 double num = area / object->get_coverage_m2();
381 // place an object each unit of area
382 while ( num > 1.0 ) {
383 add_object_to_triangle(object);
386 // for partial units of area, use a zombie door method to
387 // create the proper random chance of an object being created
390 if ( sg_random() <= num ) {
391 // a zombie made it through our door
392 add_object_to_triangle(object);
398 void TriUserData::add_object_to_triangle (FGNewMat::Object * object)
400 // Set up the random heading if required.
402 if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
403 hdg_deg = sg_random() * 360;
406 makeWorldMatrix(mat, hdg_deg);
408 ssgTransform * pos = new ssgTransform;
409 pos->setTransform(mat);
410 pos->addKid(object->get_random_model());
414 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
417 mat[0][0] = leafData->sin_lat * leafData->cos_lon;
418 mat[0][1] = leafData->sin_lat * leafData->sin_lon;
419 mat[0][2] = -leafData->cos_lat;
422 mat[1][0] = -leafData->sin_lon;
423 mat[1][1] = leafData->cos_lon;
427 float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
428 float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
429 mat[0][0] = cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
430 mat[0][1] = cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
431 mat[0][2] = -cos_hdg * leafData->cos_lat;
434 mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
435 mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
436 mat[1][2] = sin_hdg * leafData->cos_lat;
440 mat[2][0] = leafData->cos_lat * leafData->cos_lon;
441 mat[2][1] = leafData->cos_lat * leafData->sin_lon;
442 mat[2][2] = leafData->sin_lat;
445 // translate to random point in triangle
447 random_pt_inside_tri(result, p1, p2, p3);
448 sgSubVec3(mat[3], result, center);
454 * SSG callback for an in-range triangle of randomly-placed objects.
456 * This pretraversal callback is attached to a branch that is traversed
457 * only when a triangle is in range. If the triangle is not currently
458 * populated with randomly-placed objects, this callback will populate
461 * @param entity The entity to which the callback is attached (not used).
462 * @param mask The entity's traversal mask (not used).
463 * @return Always 1, to allow traversal and culling to continue.
466 tri_in_range_callback (ssgEntity * entity, int mask)
468 TriUserData * data = (TriUserData *)entity->getUserData();
469 if (!data->is_filled_in) {
470 data->fill_in_triangle();
471 data->is_filled_in = true;
478 * SSG callback for an out-of-range triangle of randomly-placed objects.
480 * This pretraversal callback is attached to a branch that is traversed
481 * only when a triangle is out of range. If the triangle is currently
482 * populated with randomly-placed objects, the objects will be removed.
485 * @param entity The entity to which the callback is attached (not used).
486 * @param mask The entity's traversal mask (not used).
487 * @return Always 0, to prevent any further traversal or culling.
490 tri_out_of_range_callback (ssgEntity * entity, int mask)
492 TriUserData * data = (TriUserData *)entity->getUserData();
493 if (data->is_filled_in) {
494 data->branch->removeAllKids();
495 data->is_filled_in = false;
502 * ssgEntity with a dummy bounding sphere, to fool culling.
504 * This forces the in-range and out-of-range branches to be visited
505 * when appropriate, even if they have no children. It's ugly, but
506 * it works and seems fairly efficient (since branches can still
507 * be culled when they're out of the view frustum).
509 class DummyBSphereEntity : public ssgEntity
512 DummyBSphereEntity (float radius)
514 bsphere.setCenter(0, 0, 0);
515 bsphere.setRadius(radius);
517 virtual ~DummyBSphereEntity () {}
518 virtual void recalcBSphere () { bsphere_is_invalid = false; }
519 virtual void cull (sgFrustum *f, sgMat4 m, int test_needed) {}
520 virtual void isect (sgSphere *s, sgMat4 m, int test_needed) {}
521 virtual void hot (sgVec3 s, sgMat4 m, int test_needed) {}
522 virtual void los (sgVec3 s, sgMat4 m, int test_needed) {}
527 * Calculate the bounding radius of a triangle from its center.
529 * @param center The triangle center.
530 * @param p1 The first point in the triangle.
531 * @param p2 The second point in the triangle.
532 * @param p3 The third point in the triangle.
533 * @return The greatest distance any point lies from the center.
536 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
538 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
539 sgDistanceSquaredVec3(center, p2),
540 sgDistanceSquaredVec3(center, p3) ) );
545 * Set up a triangle for randomly-placed objects.
547 * No objects will be added unless the triangle comes into range.
551 void LeafUserData::setup_triangle (int i )
554 leaf->getTriangle(i, &n1, &n2, &n3);
556 float * p1 = leaf->getVertex(n1);
557 float * p2 = leaf->getVertex(n2);
558 float * p3 = leaf->getVertex(n3);
560 // Set up a single center point for LOD
563 (p1[0] + p2[0] + p3[0]) / 3.0,
564 (p1[1] + p2[1] + p3[1]) / 3.0,
565 (p1[2] + p2[2] + p3[2]) / 3.0);
566 double area = sgTriArea(p1, p2, p3);
568 // maximum radius of an object from center.
569 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
571 // Set up a transformation to the center
572 // point, so that everything else can
573 // be specified relative to it.
574 ssgTransform * location = new ssgTransform;
576 sgMakeTransMat4(TRANS, center);
577 location->setTransform(TRANS);
578 branch->addKid(location);
580 // Iterate through all the object types.
581 int num_groups = mat->get_object_group_count();
582 for (int j = 0; j < num_groups; j++) {
583 // Look up the random object.
584 FGNewMat::ObjectGroup * group = mat->get_object_group(j);
586 // Set up the range selector for the entire
587 // triangle; note that we use the object
588 // range plus the bounding radius here, to
589 // allow for objects far from the center.
590 float ranges[] = { 0,
591 group->get_range_m() + bounding_radius,
593 ssgRangeSelector * lod = new ssgRangeSelector;
594 lod->setRanges(ranges, 3);
595 location->addKid(lod);
597 // Create the in-range and out-of-range
599 ssgBranch * in_range = new ssgBranch;
600 ssgBranch * out_of_range = new ssgBranch;
602 // Set up the user data for if/when
603 // the random objects in this triangle
605 TriUserData * data = new TriUserData;
606 data->is_filled_in = false;
610 sgCopyVec3 (data->center, center);
612 data->object_group = group;
613 data->branch = in_range;
614 data->leafData = this;
615 data->seed = (unsigned int)(p1[0] * j);
617 // Set up the in-range node.
618 in_range->setUserData(data);
619 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
620 tri_in_range_callback);
621 lod->addKid(in_range);
623 // Set up the out-of-range node.
624 out_of_range->setUserData(data);
625 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
626 tri_out_of_range_callback);
627 out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
628 lod->addKid(out_of_range);
633 * SSG callback for an in-range leaf of randomly-placed objects.
635 * This pretraversal callback is attached to a branch that is
636 * traversed only when a leaf is in range. If the leaf is not
637 * currently prepared to be populated with randomly-placed objects,
638 * this callback will prepare it (actual population is handled by
639 * the tri_in_range_callback for individual triangles).
641 * @param entity The entity to which the callback is attached (not used).
642 * @param mask The entity's traversal mask (not used).
643 * @return Always 1, to allow traversal and culling to continue.
646 leaf_in_range_callback (ssgEntity * entity, int mask)
648 LeafUserData * data = (LeafUserData *)entity->getUserData();
650 if (!data->is_filled_in) {
651 // Iterate through all the triangles
652 // and populate them.
653 int num_tris = data->leaf->getNumTriangles();
654 for ( int i = 0; i < num_tris; ++i ) {
655 data->setup_triangle(i);
657 data->is_filled_in = true;
664 * SSG callback for an out-of-range leaf of randomly-placed objects.
666 * This pretraversal callback is attached to a branch that is
667 * traversed only when a leaf is out of range. If the leaf is
668 * currently prepared to be populated with randomly-placed objects (or
669 * is actually populated), the objects will be removed.
671 * @param entity The entity to which the callback is attached (not used).
672 * @param mask The entity's traversal mask (not used).
673 * @return Always 0, to prevent any further traversal or culling.
676 leaf_out_of_range_callback (ssgEntity * entity, int mask)
678 LeafUserData * data = (LeafUserData *)entity->getUserData();
679 if (data->is_filled_in) {
680 data->branch->removeAllKids();
681 data->is_filled_in = false;
688 * Randomly place objects on a surface.
690 * The leaf node provides the geometry of the surface, while the
691 * material provides the objects and placement density. Latitude
692 * and longitude are required so that the objects can be rotated
693 * to the world-up vector. This function does not actually add
694 * any objects; instead, it attaches an ssgRangeSelector to the
695 * branch with callbacks to generate the objects when needed.
697 * @param leaf The surface where the objects should be placed.
698 * @param branch The branch that will hold the randomly-placed objects.
699 * @param center The center of the leaf in FlightGear coordinates.
700 * @param material_name The name of the surface's material.
703 gen_random_surface_objects (ssgLeaf *leaf,
706 const string &material_name)
708 // If the surface has no triangles, return
710 int num_tris = leaf->getNumTriangles();
714 // Get the material for this surface.
715 FGNewMat * mat = material_lib.find(material_name);
717 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
721 // If the material has no randomly-placed
722 // objects, return now.
723 if (mat->get_object_group_count() < 1)
726 // Calculate the geodetic centre of
727 // the tile, for aligning automatic
729 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
730 Point3D geoc = sgCartToPolar3d(*center);
731 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
732 sgGeocToGeod(geoc.lat(), geoc.radius(),
733 &lat_rad, &alt_m, &sl_radius_m);
734 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
737 // max random object range: 20000m
738 float ranges[] = { 0, 20000, 1000000 };
739 ssgRangeSelector * lod = new ssgRangeSelector;
740 lod->setRanges(ranges, 3);
743 // Create the in-range and out-of-range
745 ssgBranch * in_range = new ssgBranch;
746 ssgBranch * out_of_range = new ssgBranch;
747 lod->addKid(in_range);
748 lod->addKid(out_of_range);
750 LeafUserData * data = new LeafUserData;
751 data->is_filled_in = false;
754 data->branch = in_range;
755 data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
756 data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
757 data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
758 data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
760 in_range->setUserData(data);
761 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
762 out_of_range->setUserData(data);
763 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
764 leaf_out_of_range_callback);
766 ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
771 ////////////////////////////////////////////////////////////////////////
773 ////////////////////////////////////////////////////////////////////////
776 // Load an Ascii obj file
777 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
778 ssgVertexArray *lights, const bool is_base)
780 FGNewMat *newmat = NULL;
784 // sgVec3 approx_normal;
785 // double normal[3], scale = 0.0;
786 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
787 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
788 // GLint display_list = 0;
790 bool in_faces = false;
791 int vncount, vtcount;
792 int n1 = 0, n2 = 0, n3 = 0;
794 // int last1 = 0, last2 = 0;
799 double scenery_version = 0.0;
800 double tex_width = 1000.0, tex_height = 1000.0;
801 bool shared_done = false;
802 int_list fan_vertices;
803 int_list fan_tex_coords;
805 ssgSimpleState *state = NULL;
806 sgVec3 *vtlist, *vnlist;
809 ssgBranch *tile = new ssgBranch () ;
811 tile -> setName ( (char *)path.c_str() ) ;
813 // Attempt to open "path.gz" or "path"
814 sg_gzifstream in( path );
815 if ( ! in.is_open() ) {
816 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
817 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
824 shading = fgGetBool("/sim/rendering/shading");
832 t->bounding_radius = 0.0;
836 // StopWatch stopwatch;
837 // stopwatch.start();
839 // ignore initial comments and blank lines. (priming the pump)
840 // in >> skipcomment;
847 while ( in.get(c) && c != '\0' ) {
850 while ( ! in.eof() ) {
854 if ( in.get( c ) && c == '#' ) {
855 // process a comment line
857 // getline( in, line );
858 // cout << "comment = " << line << endl;
862 if ( token == "Version" ) {
863 // read scenery versions number
864 in >> scenery_version;
865 // cout << "scenery_version = " << scenery_version << endl;
866 if ( scenery_version > 0.4 ) {
867 SG_LOG( SG_TERRAIN, SG_ALERT,
868 "\nYou are attempting to load a tile format that\n"
869 << "is newer than this version of flightgear can\n"
870 << "handle. You should upgrade your copy of\n"
871 << "FlightGear to the newest version. For\n"
872 << "details, please see:\n"
873 << "\n http://www.flightgear.org\n" );
876 } else if ( token == "gbs" ) {
877 // reference point (center offset)
879 in >> t->center >> t->bounding_radius;
883 in >> junk1 >> junk2;
886 // cout << "center = " << center
887 // << " radius = " << t->bounding_radius << endl;
888 } else if ( token == "bs" ) {
889 // reference point (center offset)
893 in >> junk1 >> junk2;
894 } else if ( token == "usemtl" ) {
895 // material property specification
897 // if first usemtl with shared_done = false, then set
898 // shared_done true and build the ssg shared lists
899 if ( ! shared_done ) {
901 if ( (int)nodes.size() != vncount ) {
902 SG_LOG( SG_TERRAIN, SG_ALERT,
903 "Tile has mismatched nodes = " << nodes.size()
904 << " and normals = " << vncount << " : "
910 vtlist = new sgVec3 [ nodes.size() ];
911 t->vec3_ptrs.push_back( vtlist );
912 vnlist = new sgVec3 [ vncount ];
913 t->vec3_ptrs.push_back( vnlist );
914 tclist = new sgVec2 [ vtcount ];
915 t->vec2_ptrs.push_back( tclist );
917 for ( i = 0; i < (int)nodes.size(); ++i ) {
918 sgSetVec3( vtlist[i],
919 nodes[i][0], nodes[i][1], nodes[i][2] );
921 for ( i = 0; i < vncount; ++i ) {
922 sgSetVec3( vnlist[i],
927 for ( i = 0; i < vtcount; ++i ) {
928 sgSetVec2( tclist[i],
934 // display_list = xglGenLists(1);
935 // xglNewList(display_list, GL_COMPILE);
936 // printf("xglGenLists(); xglNewList();\n");
939 // scan the material line
942 // find this material in the properties list
944 newmat = material_lib.find( material );
945 if ( newmat == NULL ) {
946 // see if this is an on the fly texture
948 int pos = file.rfind( "/" );
949 file = file.substr( 0, pos );
950 // cout << "current file = " << file << endl;
953 // cout << "current file = " << file << endl;
954 if ( ! material_lib.add_item( file ) ) {
955 SG_LOG( SG_TERRAIN, SG_ALERT,
956 "Ack! unknown usemtl name = " << material
959 // locate our newly created material
960 newmat = material_lib.find( material );
961 if ( newmat == NULL ) {
962 SG_LOG( SG_TERRAIN, SG_ALERT,
963 "Ack! bad on the fly materia create = "
964 << material << " in " << path );
969 if ( newmat != NULL ) {
970 // set the texture width and height values for this
972 tex_width = newmat->get_xsize();
973 tex_height = newmat->get_ysize();
974 state = newmat->get_state();
975 coverage = newmat->get_light_coverage();
976 // cout << "(w) = " << tex_width << " (h) = "
977 // << tex_width << endl;
982 // unknown comment, just gobble the input until the
992 // cout << "token = " << token << endl;
994 if ( token == "vn" ) {
996 if ( vncount < FG_MAX_NODES ) {
997 in >> normals[vncount][0]
998 >> normals[vncount][1]
999 >> normals[vncount][2];
1002 SG_LOG( SG_TERRAIN, SG_ALERT,
1003 "Read too many vertex normals in " << path
1004 << " ... dying :-(" );
1007 } else if ( token == "vt" ) {
1008 // vertex texture coordinate
1009 if ( vtcount < FG_MAX_NODES*3 ) {
1010 in >> tex_coords[vtcount][0]
1011 >> tex_coords[vtcount][1];
1014 SG_LOG( SG_TERRAIN, SG_ALERT,
1015 "Read too many vertex texture coords in " << path
1020 } else if ( token == "v" ) {
1022 if ( t->ncount < FG_MAX_NODES ) {
1023 /* in >> nodes[t->ncount][0]
1024 >> nodes[t->ncount][1]
1025 >> nodes[t->ncount][2]; */
1027 nodes.push_back(node);
1032 SG_LOG( SG_TERRAIN, SG_ALERT,
1033 "Read too many nodes in " << path
1034 << " ... dying :-(");
1037 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1038 // triangle fan, strip, or individual face
1039 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1041 fan_vertices.clear();
1042 fan_tex_coords.clear();
1045 // xglBegin(GL_TRIANGLE_FAN);
1048 fan_vertices.push_back( n1 );
1049 // xglNormal3dv(normals[n1]);
1050 if ( in.get( c ) && c == '/' ) {
1052 fan_tex_coords.push_back( tex );
1053 if ( scenery_version >= 0.4 ) {
1054 if ( tex_width > 0 ) {
1055 tclist[tex][0] *= (1000.0 / tex_width);
1057 if ( tex_height > 0 ) {
1058 tclist[tex][1] *= (1000.0 / tex_height);
1061 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1062 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1065 pp = local_calc_tex_coords(nodes[n1], center);
1067 // xglTexCoord2f(pp.x(), pp.y());
1068 // xglVertex3dv(nodes[n1].get_n());
1071 fan_vertices.push_back( n2 );
1072 // xglNormal3dv(normals[n2]);
1073 if ( in.get( c ) && c == '/' ) {
1075 fan_tex_coords.push_back( tex );
1076 if ( scenery_version >= 0.4 ) {
1077 if ( tex_width > 0 ) {
1078 tclist[tex][0] *= (1000.0 / tex_width);
1080 if ( tex_height > 0 ) {
1081 tclist[tex][1] *= (1000.0 / tex_height);
1084 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1085 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1088 pp = local_calc_tex_coords(nodes[n2], center);
1090 // xglTexCoord2f(pp.x(), pp.y());
1091 // xglVertex3dv(nodes[n2].get_n());
1093 // read all subsequent numbers until next thing isn't a number
1100 if ( ! isdigit(c) || in.eof() ) {
1105 fan_vertices.push_back( n3 );
1106 // cout << " triangle = "
1107 // << n1 << "," << n2 << "," << n3
1109 // xglNormal3dv(normals[n3]);
1110 if ( in.get( c ) && c == '/' ) {
1112 fan_tex_coords.push_back( tex );
1113 if ( scenery_version >= 0.4 ) {
1114 if ( tex_width > 0 ) {
1115 tclist[tex][0] *= (1000.0 / tex_width);
1117 if ( tex_height > 0 ) {
1118 tclist[tex][1] *= (1000.0 / tex_height);
1121 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1122 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1125 pp = local_calc_tex_coords(nodes[n3], center);
1127 // xglTexCoord2f(pp.x(), pp.y());
1128 // xglVertex3dv(nodes[n3].get_n());
1130 if ( (token == "tf") || (token == "f") ) {
1143 // build the ssg entity
1144 int size = (int)fan_vertices.size();
1145 ssgVertexArray *vl = new ssgVertexArray( size );
1146 ssgNormalArray *nl = new ssgNormalArray( size );
1147 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1148 ssgColourArray *cl = new ssgColourArray( 1 );
1151 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1156 for ( i = 0; i < size; ++i ) {
1157 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1160 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1163 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1167 ssgLeaf *leaf = NULL;
1168 if ( token == "tf" ) {
1171 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1172 } else if ( token == "ts" ) {
1175 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1176 } else if ( token == "f" ) {
1179 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1181 // leaf->makeDList();
1182 leaf->setState( state );
1184 tile->addKid( leaf );
1187 if ( coverage > 0.0 ) {
1188 if ( coverage < 10000.0 ) {
1189 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1190 << coverage << ", pushing up to 10000");
1193 gen_random_surface_points(leaf, lights, coverage);
1197 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1198 << path << " = " << token );
1201 // eat white space before start of while loop so if we are
1202 // done with useful input it is noticed before hand.
1211 // stopwatch.stop();
1212 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1213 // "Loaded " << path << " in "
1214 // << stopwatch.elapsedSeconds() << " seconds" );
1220 ssgLeaf *gen_leaf( const string& path,
1221 const GLenum ty, const string& material,
1222 const point_list& nodes, const point_list& normals,
1223 const point_list& texcoords,
1224 const int_list& node_index,
1225 const int_list& normal_index,
1226 const int_list& tex_index,
1227 const bool calc_lights, ssgVertexArray *lights )
1229 double tex_width = 1000.0, tex_height = 1000.0;
1230 ssgSimpleState *state = NULL;
1231 float coverage = -1;
1233 FGNewMat *newmat = material_lib.find( material );
1234 if ( newmat == NULL ) {
1235 // see if this is an on the fly texture
1237 string::size_type pos = file.rfind( "/" );
1238 file = file.substr( 0, pos );
1239 // cout << "current file = " << file << endl;
1242 // cout << "current file = " << file << endl;
1243 if ( ! material_lib.add_item( file ) ) {
1244 SG_LOG( SG_TERRAIN, SG_ALERT,
1245 "Ack! unknown usemtl name = " << material
1246 << " in " << path );
1248 // locate our newly created material
1249 newmat = material_lib.find( material );
1250 if ( newmat == NULL ) {
1251 SG_LOG( SG_TERRAIN, SG_ALERT,
1252 "Ack! bad on the fly material create = "
1253 << material << " in " << path );
1258 if ( newmat != NULL ) {
1259 // set the texture width and height values for this
1261 tex_width = newmat->get_xsize();
1262 tex_height = newmat->get_ysize();
1263 state = newmat->get_state();
1264 coverage = newmat->get_light_coverage();
1265 // cout << "(w) = " << tex_width << " (h) = "
1266 // << tex_width << endl;
1277 int size = node_index.size();
1279 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1282 ssgVertexArray *vl = new ssgVertexArray( size );
1284 for ( i = 0; i < size; ++i ) {
1285 node = nodes[ node_index[i] ];
1286 sgSetVec3( tmp3, node[0], node[1], node[2] );
1292 ssgNormalArray *nl = new ssgNormalArray( size );
1293 if ( normal_index.size() ) {
1294 // object file specifies normal indices (i.e. normal indices
1296 for ( i = 0; i < size; ++i ) {
1297 normal = normals[ normal_index[i] ];
1298 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1302 // use implied normal indices. normal index = vertex index.
1303 for ( i = 0; i < size; ++i ) {
1304 normal = normals[ node_index[i] ];
1305 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1311 ssgColourArray *cl = new ssgColourArray( 1 );
1312 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1315 // texture coordinates
1316 size = tex_index.size();
1318 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1320 texcoord = texcoords[ tex_index[0] ];
1321 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1322 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1323 if ( tex_width > 0 ) {
1324 tmp2[0] *= (1000.0 / tex_width);
1326 if ( tex_height > 0 ) {
1327 tmp2[1] *= (1000.0 / tex_height);
1330 } else if ( size > 1 ) {
1331 for ( i = 0; i < size; ++i ) {
1332 texcoord = texcoords[ tex_index[i] ];
1333 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1334 if ( tex_width > 0 ) {
1335 tmp2[0] *= (1000.0 / tex_width);
1337 if ( tex_height > 0 ) {
1338 tmp2[1] *= (1000.0 / tex_height);
1344 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1346 // lookup the state record
1348 leaf->setState( state );
1350 if ( calc_lights ) {
1351 if ( coverage > 0.0 ) {
1352 if ( coverage < 10000.0 ) {
1353 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1354 << coverage << ", pushing up to 10000");
1357 gen_random_surface_points(leaf, lights, coverage);
1365 // Load an Binary obj file
1366 bool fgBinObjLoad( const string& path, const bool is_base,
1368 double *bounding_radius,
1369 ssgBranch* geometry,
1370 ssgBranch* rwy_lights,
1371 ssgBranch* taxi_lights,
1372 ssgVertexArray *ground_lights )
1375 bool use_random_objects =
1376 fgGetBool("/sim/rendering/random-objects", true);
1378 if ( ! obj.read_bin( path ) ) {
1382 geometry->setName( (char *)path.c_str() );
1384 // reference point (center offset/bounding sphere)
1385 *center = obj.get_gbs_center();
1386 *bounding_radius = obj.get_gbs_radius();
1388 point_list const& nodes = obj.get_wgs84_nodes();
1389 point_list const& colors = obj.get_colors();
1390 point_list const& normals = obj.get_normals();
1391 point_list const& texcoords = obj.get_texcoords();
1396 group_list::size_type i;
1399 string_list const& pt_materials = obj.get_pt_materials();
1400 group_list const& pts_v = obj.get_pts_v();
1401 group_list const& pts_n = obj.get_pts_n();
1402 for ( i = 0; i < pts_v.size(); ++i ) {
1403 // cout << "pts_v.size() = " << pts_v.size() << endl;
1404 if ( pt_materials[i].substr(0, 3) == "RWY" ) {
1406 sgSetVec3( up, center->x(), center->y(), center->z() );
1407 // returns a transform -> lod -> leaf structure
1408 ssgBranch *branch = gen_directional_lights( nodes, normals,
1412 // branches don't honor callbacks as far as I know so I'm
1413 // commenting this out to avoid a plib runtime warning.
1414 // branch->setCallback( SSG_CALLBACK_PREDRAW,
1415 // runway_lights_predraw );
1416 if ( pt_materials[i].substr(0, 16) == "RWY_BLUE_TAXIWAY" ) {
1417 taxi_lights->addKid( branch );
1419 rwy_lights->addKid( branch );
1422 material = pt_materials[i];
1424 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1425 nodes, normals, texcoords,
1426 pts_v[i], pts_n[i], tex_index,
1427 false, ground_lights );
1428 geometry->addKid( leaf );
1432 // Put all randomly-placed objects under a separate branch
1433 // (actually an ssgRangeSelector) named "random-models".
1434 ssgBranch * random_object_branch = 0;
1435 if (use_random_objects) {
1436 float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
1437 ssgRangeSelector * object_lod = new ssgRangeSelector;
1438 object_lod->setRanges(ranges, 2);
1439 object_lod->setName("random-models");
1440 geometry->addKid(object_lod);
1441 random_object_branch = new ssgBranch;
1442 object_lod->addKid(random_object_branch);
1445 // generate triangles
1446 string_list const& tri_materials = obj.get_tri_materials();
1447 group_list const& tris_v = obj.get_tris_v();
1448 group_list const& tris_n = obj.get_tris_n();
1449 group_list const& tris_tc = obj.get_tris_tc();
1450 for ( i = 0; i < tris_v.size(); ++i ) {
1451 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
1452 nodes, normals, texcoords,
1453 tris_v[i], tris_n[i], tris_tc[i],
1454 is_base, ground_lights );
1456 if (use_random_objects)
1457 gen_random_surface_objects(leaf, random_object_branch,
1458 center, tri_materials[i]);
1459 geometry->addKid( leaf );
1463 string_list const& strip_materials = obj.get_strip_materials();
1464 group_list const& strips_v = obj.get_strips_v();
1465 group_list const& strips_n = obj.get_strips_n();
1466 group_list const& strips_tc = obj.get_strips_tc();
1467 for ( i = 0; i < strips_v.size(); ++i ) {
1468 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
1469 nodes, normals, texcoords,
1470 strips_v[i], strips_n[i], strips_tc[i],
1471 is_base, ground_lights );
1473 if (use_random_objects)
1474 gen_random_surface_objects(leaf, random_object_branch,
1475 center,strip_materials[i]);
1476 geometry->addKid( leaf );
1480 string_list const& fan_materials = obj.get_fan_materials();
1481 group_list const& fans_v = obj.get_fans_v();
1482 group_list const& fans_n = obj.get_fans_n();
1483 group_list const& fans_tc = obj.get_fans_tc();
1484 for ( i = 0; i < fans_v.size(); ++i ) {
1485 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
1486 nodes, normals, texcoords,
1487 fans_v[i], fans_n[i], fans_tc[i],
1488 is_base, ground_lights );
1489 if (use_random_objects)
1490 gen_random_surface_objects(leaf, random_object_branch,
1491 center, fan_materials[i]);
1492 geometry->addKid( leaf );