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];
77 // not used because plib branches don't honor call backs.
79 runway_lights_pretrav (ssgEntity * e, int mask)
81 // Turn on lights only at night
82 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
83 return int((sun_angle > 85.0) ||
84 (fgGetDouble("/environment/visibility-m") < 5000.0));
88 #define FG_TEX_CONSTANT 69.0
90 // Calculate texture coordinates for a given point.
91 static Point3D local_calc_tex_coords(const Point3D& node, const Point3D& ref) {
94 // double tmplon, tmplat;
96 // cout << "-> " << node[0] << " " << node[1] << " " << node[2] << endl;
97 // cout << "-> " << ref.x() << " " << ref.y() << " " << ref.z() << endl;
99 cp = Point3D( node[0] + ref.x(),
103 pp = sgCartToPolar3d(cp);
105 // tmplon = pp.lon() * SGD_RADIANS_TO_DEGREES;
106 // tmplat = pp.lat() * SGD_RADIANS_TO_DEGREES;
107 // cout << tmplon << " " << tmplat << endl;
109 pp.setx( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.x(), 11.0) );
110 pp.sety( fmod(SGD_RADIANS_TO_DEGREES * FG_TEX_CONSTANT * pp.y(), 11.0) );
112 if ( pp.x() < 0.0 ) {
113 pp.setx( pp.x() + 11.0 );
116 if ( pp.y() < 0.0 ) {
117 pp.sety( pp.y() + 11.0 );
120 // cout << pp << endl;
126 // Generate an ocean tile
127 bool fgGenTile( const string& path, SGBucket b,
129 double *bounding_radius,
130 ssgBranch* geometry )
134 ssgSimpleState *state = NULL;
136 geometry -> setName ( (char *)path.c_str() ) ;
138 double tex_width = 1000.0;
139 // double tex_height;
141 // find Ocean material in the properties list
142 newmat = material_lib.find( "Ocean" );
143 if ( newmat != NULL ) {
144 // set the texture width and height values for this
146 tex_width = newmat->get_xsize();
147 // tex_height = newmat->get_ysize();
150 state = newmat->get_state();
152 SG_LOG( SG_TERRAIN, SG_ALERT,
153 "Ack! unknown usemtl name = " << "Ocean"
157 // Calculate center point
158 double clon = b.get_center_lon();
159 double clat = b.get_center_lat();
160 double height = b.get_height();
161 double width = b.get_width();
163 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
164 clat*SGD_DEGREES_TO_RADIANS,
166 // cout << "center = " << center << endl;;
168 // Caculate corner vertices
170 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
171 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
172 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
173 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
177 for ( i = 0; i < 4; ++i ) {
178 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
179 geod[i].y() * SGD_DEGREES_TO_RADIANS,
183 Point3D cart[4], rel[4];
184 for ( i = 0; i < 4; ++i ) {
185 cart[i] = sgGeodToCart(rad[i]);
186 rel[i] = cart[i] - *center;
187 // cout << "corner " << i << " = " << cart[i] << endl;
190 // Calculate bounding radius
191 *bounding_radius = center->distance3D( cart[0] );
192 // cout << "bounding radius = " << t->bounding_radius << endl;
196 for ( i = 0; i < 4; ++i ) {
197 double length = cart[i].distance3D( Point3D(0.0) );
198 normals[i] = cart[i] / length;
199 // cout << "normal = " << normals[i] << endl;
202 // Calculate texture coordinates
203 point_list geod_nodes;
205 geod_nodes.reserve(4);
208 rectangle.reserve(4);
209 for ( i = 0; i < 4; ++i ) {
210 geod_nodes.push_back( geod[i] );
211 rectangle.push_back( i );
213 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
214 1000.0 / tex_width );
216 // Allocate ssg structure
217 ssgVertexArray *vl = new ssgVertexArray( 4 );
218 ssgNormalArray *nl = new ssgNormalArray( 4 );
219 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
220 ssgColourArray *cl = new ssgColourArray( 1 );
223 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
226 // sgVec3 *vtlist = new sgVec3 [ 4 ];
227 // t->vec3_ptrs.push_back( vtlist );
228 // sgVec3 *vnlist = new sgVec3 [ 4 ];
229 // t->vec3_ptrs.push_back( vnlist );
230 // sgVec2 *tclist = new sgVec2 [ 4 ];
231 // t->vec2_ptrs.push_back( tclist );
235 for ( i = 0; i < 4; ++i ) {
237 rel[i].x(), rel[i].y(), rel[i].z() );
241 normals[i].x(), normals[i].y(), normals[i].z() );
244 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
249 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
251 leaf->setState( state );
253 geometry->addKid( leaf );
259 static void random_pt_inside_tri( float *res,
260 float *n1, float *n2, float *n3 )
262 double a = sg_random();
263 double b = sg_random();
268 double c = 1 - a - b;
270 res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
271 res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
272 res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
276 static void gen_random_surface_points( ssgLeaf *leaf, ssgVertexArray *lights,
278 int tris = leaf->getNumTriangles();
280 short int n1, n2, n3;
284 // generate a repeatable random seed
285 p1 = leaf->getVertex( 0 );
286 unsigned int seed = (unsigned int)(fabs(p1[0]*100));
289 for ( int i = 0; i < tris; ++i ) {
290 leaf->getTriangle( i, &n1, &n2, &n3 );
291 p1 = leaf->getVertex(n1);
292 p2 = leaf->getVertex(n2);
293 p3 = leaf->getVertex(n3);
294 double area = sgTriArea( p1, p2, p3 );
295 double num = area / factor;
297 // generate a light point for each unit of area
298 while ( num > 1.0 ) {
299 random_pt_inside_tri( result, p1, p2, p3 );
300 lights->add( result );
303 // for partial units of area, use a zombie door method to
304 // create the proper random chance of a light being created
307 if ( sg_random() <= num ) {
308 // a zombie made it through our door
309 random_pt_inside_tri( result, p1, p2, p3 );
310 lights->add( result );
319 * User data for populating leaves when they come in range.
321 class LeafUserData : public ssgBase
333 void setup_triangle( int i );
338 * User data for populating triangles when they come in range.
340 class TriUserData : public ssgBase
349 FGNewMat::ObjectGroup * object_group;
351 LeafUserData * leafData;
354 void fill_in_triangle();
355 void add_object_to_triangle(FGNewMat::Object * object);
356 void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
361 * Fill in a triangle with randomly-placed objects.
363 * This method is invoked by a callback when the triangle is in range
364 * but not yet populated.
368 void TriUserData::fill_in_triangle ()
370 // generate a repeatable random seed
373 int nObjects = object_group->get_object_count();
375 for (int i = 0; i < nObjects; i++) {
376 FGNewMat::Object * object = object_group->get_object(i);
377 double num = area / object->get_coverage_m2();
379 // place an object each unit of area
380 while ( num > 1.0 ) {
381 add_object_to_triangle(object);
384 // for partial units of area, use a zombie door method to
385 // create the proper random chance of an object being created
388 if ( sg_random() <= num ) {
389 // a zombie made it through our door
390 add_object_to_triangle(object);
396 void TriUserData::add_object_to_triangle (FGNewMat::Object * object)
398 // Set up the random heading if required.
400 if (object->get_heading_type() == FGNewMat::Object::HEADING_RANDOM)
401 hdg_deg = sg_random() * 360;
404 makeWorldMatrix(mat, hdg_deg);
406 ssgTransform * pos = new ssgTransform;
407 pos->setTransform(mat);
408 pos->addKid(object->get_random_model());
412 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
415 mat[0][0] = leafData->sin_lat * leafData->cos_lon;
416 mat[0][1] = leafData->sin_lat * leafData->sin_lon;
417 mat[0][2] = -leafData->cos_lat;
420 mat[1][0] = -leafData->sin_lon;
421 mat[1][1] = leafData->cos_lon;
425 float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
426 float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
427 mat[0][0] = cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
428 mat[0][1] = cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
429 mat[0][2] = -cos_hdg * leafData->cos_lat;
432 mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
433 mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
434 mat[1][2] = sin_hdg * leafData->cos_lat;
438 mat[2][0] = leafData->cos_lat * leafData->cos_lon;
439 mat[2][1] = leafData->cos_lat * leafData->sin_lon;
440 mat[2][2] = leafData->sin_lat;
443 // translate to random point in triangle
445 random_pt_inside_tri(result, p1, p2, p3);
446 sgSubVec3(mat[3], result, center);
452 * SSG callback for an in-range triangle of randomly-placed objects.
454 * This pretraversal callback is attached to a branch that is traversed
455 * only when a triangle is in range. If the triangle is not currently
456 * populated with randomly-placed objects, this callback will populate
459 * @param entity The entity to which the callback is attached (not used).
460 * @param mask The entity's traversal mask (not used).
461 * @return Always 1, to allow traversal and culling to continue.
464 tri_in_range_callback (ssgEntity * entity, int mask)
466 TriUserData * data = (TriUserData *)entity->getUserData();
467 if (!data->is_filled_in) {
468 data->fill_in_triangle();
469 data->is_filled_in = true;
476 * SSG callback for an out-of-range triangle of randomly-placed objects.
478 * This pretraversal callback is attached to a branch that is traversed
479 * only when a triangle is out of range. If the triangle is currently
480 * populated with randomly-placed objects, the objects will be removed.
483 * @param entity The entity to which the callback is attached (not used).
484 * @param mask The entity's traversal mask (not used).
485 * @return Always 0, to prevent any further traversal or culling.
488 tri_out_of_range_callback (ssgEntity * entity, int mask)
490 TriUserData * data = (TriUserData *)entity->getUserData();
491 if (data->is_filled_in) {
492 data->branch->removeAllKids();
493 data->is_filled_in = false;
500 * ssgEntity with a dummy bounding sphere, to fool culling.
502 * This forces the in-range and out-of-range branches to be visited
503 * when appropriate, even if they have no children. It's ugly, but
504 * it works and seems fairly efficient (since branches can still
505 * be culled when they're out of the view frustum).
507 class DummyBSphereEntity : public ssgBranch
510 DummyBSphereEntity (float radius)
512 bsphere.setCenter(0, 0, 0);
513 bsphere.setRadius(radius);
515 virtual ~DummyBSphereEntity () {}
516 virtual void recalcBSphere () { bsphere_is_invalid = false; }
521 * Calculate the bounding radius of a triangle from its center.
523 * @param center The triangle center.
524 * @param p1 The first point in the triangle.
525 * @param p2 The second point in the triangle.
526 * @param p3 The third point in the triangle.
527 * @return The greatest distance any point lies from the center.
530 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
532 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
533 sgDistanceSquaredVec3(center, p2),
534 sgDistanceSquaredVec3(center, p3) ) );
539 * Set up a triangle for randomly-placed objects.
541 * No objects will be added unless the triangle comes into range.
545 void LeafUserData::setup_triangle (int i )
548 leaf->getTriangle(i, &n1, &n2, &n3);
550 float * p1 = leaf->getVertex(n1);
551 float * p2 = leaf->getVertex(n2);
552 float * p3 = leaf->getVertex(n3);
554 // Set up a single center point for LOD
557 (p1[0] + p2[0] + p3[0]) / 3.0,
558 (p1[1] + p2[1] + p3[1]) / 3.0,
559 (p1[2] + p2[2] + p3[2]) / 3.0);
560 double area = sgTriArea(p1, p2, p3);
562 // maximum radius of an object from center.
563 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
565 // Set up a transformation to the center
566 // point, so that everything else can
567 // be specified relative to it.
568 ssgTransform * location = new ssgTransform;
570 sgMakeTransMat4(TRANS, center);
571 location->setTransform(TRANS);
572 branch->addKid(location);
574 // Iterate through all the object types.
575 int num_groups = mat->get_object_group_count();
576 for (int j = 0; j < num_groups; j++) {
577 // Look up the random object.
578 FGNewMat::ObjectGroup * group = mat->get_object_group(j);
580 // Set up the range selector for the entire
581 // triangle; note that we use the object
582 // range plus the bounding radius here, to
583 // allow for objects far from the center.
584 float ranges[] = { 0,
585 group->get_range_m() + bounding_radius,
587 ssgRangeSelector * lod = new ssgRangeSelector;
588 lod->setRanges(ranges, 3);
589 location->addKid(lod);
591 // Create the in-range and out-of-range
593 ssgBranch * in_range = new ssgBranch;
594 ssgBranch * out_of_range = new ssgBranch;
596 // Set up the user data for if/when
597 // the random objects in this triangle
599 TriUserData * data = new TriUserData;
600 data->is_filled_in = false;
604 sgCopyVec3 (data->center, center);
606 data->object_group = group;
607 data->branch = in_range;
608 data->leafData = this;
609 data->seed = (unsigned int)(p1[0] * j);
611 // Set up the in-range node.
612 in_range->setUserData(data);
613 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
614 tri_in_range_callback);
615 lod->addKid(in_range);
617 // Set up the out-of-range node.
618 out_of_range->setUserData(data);
619 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
620 tri_out_of_range_callback);
621 out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
622 lod->addKid(out_of_range);
627 * SSG callback for an in-range leaf of randomly-placed objects.
629 * This pretraversal callback is attached to a branch that is
630 * traversed only when a leaf is in range. If the leaf is not
631 * currently prepared to be populated with randomly-placed objects,
632 * this callback will prepare it (actual population is handled by
633 * the tri_in_range_callback for individual triangles).
635 * @param entity The entity to which the callback is attached (not used).
636 * @param mask The entity's traversal mask (not used).
637 * @return Always 1, to allow traversal and culling to continue.
640 leaf_in_range_callback (ssgEntity * entity, int mask)
642 LeafUserData * data = (LeafUserData *)entity->getUserData();
644 if (!data->is_filled_in) {
645 // Iterate through all the triangles
646 // and populate them.
647 int num_tris = data->leaf->getNumTriangles();
648 for ( int i = 0; i < num_tris; ++i ) {
649 data->setup_triangle(i);
651 data->is_filled_in = true;
658 * SSG callback for an out-of-range leaf of randomly-placed objects.
660 * This pretraversal callback is attached to a branch that is
661 * traversed only when a leaf is out of range. If the leaf is
662 * currently prepared to be populated with randomly-placed objects (or
663 * is actually populated), the objects will be removed.
665 * @param entity The entity to which the callback is attached (not used).
666 * @param mask The entity's traversal mask (not used).
667 * @return Always 0, to prevent any further traversal or culling.
670 leaf_out_of_range_callback (ssgEntity * entity, int mask)
672 LeafUserData * data = (LeafUserData *)entity->getUserData();
673 if (data->is_filled_in) {
674 data->branch->removeAllKids();
675 data->is_filled_in = false;
682 * Randomly place objects on a surface.
684 * The leaf node provides the geometry of the surface, while the
685 * material provides the objects and placement density. Latitude
686 * and longitude are required so that the objects can be rotated
687 * to the world-up vector. This function does not actually add
688 * any objects; instead, it attaches an ssgRangeSelector to the
689 * branch with callbacks to generate the objects when needed.
691 * @param leaf The surface where the objects should be placed.
692 * @param branch The branch that will hold the randomly-placed objects.
693 * @param center The center of the leaf in FlightGear coordinates.
694 * @param material_name The name of the surface's material.
697 gen_random_surface_objects (ssgLeaf *leaf,
700 const string &material_name)
702 // If the surface has no triangles, return
704 int num_tris = leaf->getNumTriangles();
708 // Get the material for this surface.
709 FGNewMat * mat = material_lib.find(material_name);
711 SG_LOG(SG_INPUT, SG_ALERT, "Unknown material " << material_name);
715 // If the material has no randomly-placed
716 // objects, return now.
717 if (mat->get_object_group_count() < 1)
720 // Calculate the geodetic centre of
721 // the tile, for aligning automatic
723 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
724 Point3D geoc = sgCartToPolar3d(*center);
725 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
726 sgGeocToGeod(geoc.lat(), geoc.radius(),
727 &lat_rad, &alt_m, &sl_radius_m);
728 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
731 // max random object range: 20000m
732 float ranges[] = { 0, 20000, 1000000 };
733 ssgRangeSelector * lod = new ssgRangeSelector;
734 lod->setRanges(ranges, 3);
737 // Create the in-range and out-of-range
739 ssgBranch * in_range = new ssgBranch;
740 ssgBranch * out_of_range = new ssgBranch;
741 lod->addKid(in_range);
742 lod->addKid(out_of_range);
744 LeafUserData * data = new LeafUserData;
745 data->is_filled_in = false;
748 data->branch = in_range;
749 data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
750 data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
751 data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
752 data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
754 in_range->setUserData(data);
755 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
756 out_of_range->setUserData(data);
757 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
758 leaf_out_of_range_callback);
760 ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
765 ////////////////////////////////////////////////////////////////////////
767 ////////////////////////////////////////////////////////////////////////
770 // Load an Ascii obj file
771 ssgBranch *fgAsciiObjLoad( const string& path, FGTileEntry *t,
772 ssgVertexArray *lights, const bool is_base)
774 FGNewMat *newmat = NULL;
778 // sgVec3 approx_normal;
779 // double normal[3], scale = 0.0;
780 // double x, y, z, xmax, xmin, ymax, ymin, zmax, zmin;
781 // GLfloat sgenparams[] = { 1.0, 0.0, 0.0, 0.0 };
782 // GLint display_list = 0;
784 bool in_faces = false;
785 int vncount, vtcount;
786 int n1 = 0, n2 = 0, n3 = 0;
788 // int last1 = 0, last2 = 0;
793 double scenery_version = 0.0;
794 double tex_width = 1000.0, tex_height = 1000.0;
795 bool shared_done = false;
796 int_list fan_vertices;
797 int_list fan_tex_coords;
799 ssgSimpleState *state = NULL;
800 sgVec3 *vtlist, *vnlist;
803 ssgBranch *tile = new ssgBranch () ;
805 tile -> setName ( (char *)path.c_str() ) ;
807 // Attempt to open "path.gz" or "path"
808 sg_gzifstream in( path );
809 if ( ! in.is_open() ) {
810 SG_LOG( SG_TERRAIN, SG_DEBUG, "Cannot open file: " << path );
811 SG_LOG( SG_TERRAIN, SG_DEBUG, "default to ocean tile: " << path );
818 shading = fgGetBool("/sim/rendering/shading");
826 t->bounding_radius = 0.0;
830 // StopWatch stopwatch;
831 // stopwatch.start();
833 // ignore initial comments and blank lines. (priming the pump)
834 // in >> skipcomment;
841 while ( in.get(c) && c != '\0' ) {
844 while ( ! in.eof() ) {
848 if ( in.get( c ) && c == '#' ) {
849 // process a comment line
851 // getline( in, line );
852 // cout << "comment = " << line << endl;
856 if ( token == "Version" ) {
857 // read scenery versions number
858 in >> scenery_version;
859 // cout << "scenery_version = " << scenery_version << endl;
860 if ( scenery_version > 0.4 ) {
861 SG_LOG( SG_TERRAIN, SG_ALERT,
862 "\nYou are attempting to load a tile format that\n"
863 << "is newer than this version of flightgear can\n"
864 << "handle. You should upgrade your copy of\n"
865 << "FlightGear to the newest version. For\n"
866 << "details, please see:\n"
867 << "\n http://www.flightgear.org\n" );
870 } else if ( token == "gbs" ) {
871 // reference point (center offset)
873 in >> t->center >> t->bounding_radius;
877 in >> junk1 >> junk2;
880 // cout << "center = " << center
881 // << " radius = " << t->bounding_radius << endl;
882 } else if ( token == "bs" ) {
883 // reference point (center offset)
887 in >> junk1 >> junk2;
888 } else if ( token == "usemtl" ) {
889 // material property specification
891 // if first usemtl with shared_done = false, then set
892 // shared_done true and build the ssg shared lists
893 if ( ! shared_done ) {
895 if ( (int)nodes.size() != vncount ) {
896 SG_LOG( SG_TERRAIN, SG_ALERT,
897 "Tile has mismatched nodes = " << nodes.size()
898 << " and normals = " << vncount << " : "
904 vtlist = new sgVec3 [ nodes.size() ];
905 t->vec3_ptrs.push_back( vtlist );
906 vnlist = new sgVec3 [ vncount ];
907 t->vec3_ptrs.push_back( vnlist );
908 tclist = new sgVec2 [ vtcount ];
909 t->vec2_ptrs.push_back( tclist );
911 for ( i = 0; i < (int)nodes.size(); ++i ) {
912 sgSetVec3( vtlist[i],
913 nodes[i][0], nodes[i][1], nodes[i][2] );
915 for ( i = 0; i < vncount; ++i ) {
916 sgSetVec3( vnlist[i],
921 for ( i = 0; i < vtcount; ++i ) {
922 sgSetVec2( tclist[i],
928 // display_list = xglGenLists(1);
929 // xglNewList(display_list, GL_COMPILE);
930 // printf("xglGenLists(); xglNewList();\n");
933 // scan the material line
936 // find this material in the properties list
938 newmat = material_lib.find( material );
939 if ( newmat == NULL ) {
940 // see if this is an on the fly texture
942 int pos = file.rfind( "/" );
943 file = file.substr( 0, pos );
944 // cout << "current file = " << file << endl;
947 // cout << "current file = " << file << endl;
948 if ( ! material_lib.add_item( file ) ) {
949 SG_LOG( SG_TERRAIN, SG_ALERT,
950 "Ack! unknown usemtl name = " << material
953 // locate our newly created material
954 newmat = material_lib.find( material );
955 if ( newmat == NULL ) {
956 SG_LOG( SG_TERRAIN, SG_ALERT,
957 "Ack! bad on the fly materia create = "
958 << material << " in " << path );
963 if ( newmat != NULL ) {
964 // set the texture width and height values for this
966 tex_width = newmat->get_xsize();
967 tex_height = newmat->get_ysize();
968 state = newmat->get_state();
969 coverage = newmat->get_light_coverage();
970 // cout << "(w) = " << tex_width << " (h) = "
971 // << tex_width << endl;
976 // unknown comment, just gobble the input until the
986 // cout << "token = " << token << endl;
988 if ( token == "vn" ) {
990 if ( vncount < FG_MAX_NODES ) {
991 in >> normals[vncount][0]
992 >> normals[vncount][1]
993 >> normals[vncount][2];
996 SG_LOG( SG_TERRAIN, SG_ALERT,
997 "Read too many vertex normals in " << path
998 << " ... dying :-(" );
1001 } else if ( token == "vt" ) {
1002 // vertex texture coordinate
1003 if ( vtcount < FG_MAX_NODES*3 ) {
1004 in >> tex_coords[vtcount][0]
1005 >> tex_coords[vtcount][1];
1008 SG_LOG( SG_TERRAIN, SG_ALERT,
1009 "Read too many vertex texture coords in " << path
1014 } else if ( token == "v" ) {
1016 if ( t->ncount < FG_MAX_NODES ) {
1017 /* in >> nodes[t->ncount][0]
1018 >> nodes[t->ncount][1]
1019 >> nodes[t->ncount][2]; */
1021 nodes.push_back(node);
1026 SG_LOG( SG_TERRAIN, SG_ALERT,
1027 "Read too many nodes in " << path
1028 << " ... dying :-(");
1031 } else if ( (token == "tf") || (token == "ts") || (token == "f") ) {
1032 // triangle fan, strip, or individual face
1033 // SG_LOG( SG_TERRAIN, SG_INFO, "new fan or strip");
1035 fan_vertices.clear();
1036 fan_tex_coords.clear();
1039 // xglBegin(GL_TRIANGLE_FAN);
1042 fan_vertices.push_back( n1 );
1043 // xglNormal3dv(normals[n1]);
1044 if ( in.get( c ) && c == '/' ) {
1046 fan_tex_coords.push_back( tex );
1047 if ( scenery_version >= 0.4 ) {
1048 if ( tex_width > 0 ) {
1049 tclist[tex][0] *= (1000.0 / tex_width);
1051 if ( tex_height > 0 ) {
1052 tclist[tex][1] *= (1000.0 / tex_height);
1055 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1056 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1059 pp = local_calc_tex_coords(nodes[n1], center);
1061 // xglTexCoord2f(pp.x(), pp.y());
1062 // xglVertex3dv(nodes[n1].get_n());
1065 fan_vertices.push_back( n2 );
1066 // xglNormal3dv(normals[n2]);
1067 if ( in.get( c ) && c == '/' ) {
1069 fan_tex_coords.push_back( tex );
1070 if ( scenery_version >= 0.4 ) {
1071 if ( tex_width > 0 ) {
1072 tclist[tex][0] *= (1000.0 / tex_width);
1074 if ( tex_height > 0 ) {
1075 tclist[tex][1] *= (1000.0 / tex_height);
1078 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1079 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1082 pp = local_calc_tex_coords(nodes[n2], center);
1084 // xglTexCoord2f(pp.x(), pp.y());
1085 // xglVertex3dv(nodes[n2].get_n());
1087 // read all subsequent numbers until next thing isn't a number
1094 if ( ! isdigit(c) || in.eof() ) {
1099 fan_vertices.push_back( n3 );
1100 // cout << " triangle = "
1101 // << n1 << "," << n2 << "," << n3
1103 // xglNormal3dv(normals[n3]);
1104 if ( in.get( c ) && c == '/' ) {
1106 fan_tex_coords.push_back( tex );
1107 if ( scenery_version >= 0.4 ) {
1108 if ( tex_width > 0 ) {
1109 tclist[tex][0] *= (1000.0 / tex_width);
1111 if ( tex_height > 0 ) {
1112 tclist[tex][1] *= (1000.0 / tex_height);
1115 pp.setx( tex_coords[tex][0] * (1000.0 / tex_width) );
1116 pp.sety( tex_coords[tex][1] * (1000.0 / tex_height) );
1119 pp = local_calc_tex_coords(nodes[n3], center);
1121 // xglTexCoord2f(pp.x(), pp.y());
1122 // xglVertex3dv(nodes[n3].get_n());
1124 if ( (token == "tf") || (token == "f") ) {
1137 // build the ssg entity
1138 int size = (int)fan_vertices.size();
1139 ssgVertexArray *vl = new ssgVertexArray( size );
1140 ssgNormalArray *nl = new ssgNormalArray( size );
1141 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1142 ssgColourArray *cl = new ssgColourArray( 1 );
1145 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
1150 for ( i = 0; i < size; ++i ) {
1151 sgCopyVec3( tmp3, vtlist[ fan_vertices[i] ] );
1154 sgCopyVec3( tmp3, vnlist[ fan_vertices[i] ] );
1157 sgCopyVec2( tmp2, tclist[ fan_tex_coords[i] ] );
1161 ssgLeaf *leaf = NULL;
1162 if ( token == "tf" ) {
1165 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
1166 } else if ( token == "ts" ) {
1169 new ssgVtxTable ( GL_TRIANGLE_STRIP, vl, nl, tl, cl );
1170 } else if ( token == "f" ) {
1173 new ssgVtxTable ( GL_TRIANGLES, vl, nl, tl, cl );
1175 // leaf->makeDList();
1176 leaf->setState( state );
1178 tile->addKid( leaf );
1181 if ( coverage > 0.0 ) {
1182 if ( coverage < 10000.0 ) {
1183 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1184 << coverage << ", pushing up to 10000");
1187 gen_random_surface_points(leaf, lights, coverage);
1191 SG_LOG( SG_TERRAIN, SG_WARN, "Unknown token in "
1192 << path << " = " << token );
1195 // eat white space before start of while loop so if we are
1196 // done with useful input it is noticed before hand.
1205 // stopwatch.stop();
1206 // SG_LOG( SG_TERRAIN, SG_DEBUG,
1207 // "Loaded " << path << " in "
1208 // << stopwatch.elapsedSeconds() << " seconds" );
1214 ssgLeaf *gen_leaf( const string& path,
1215 const GLenum ty, const string& material,
1216 const point_list& nodes, const point_list& normals,
1217 const point_list& texcoords,
1218 const int_list& node_index,
1219 const int_list& normal_index,
1220 const int_list& tex_index,
1221 const bool calc_lights, ssgVertexArray *lights )
1223 double tex_width = 1000.0, tex_height = 1000.0;
1224 ssgSimpleState *state = NULL;
1225 float coverage = -1;
1227 FGNewMat *newmat = material_lib.find( material );
1228 if ( newmat == NULL ) {
1229 // see if this is an on the fly texture
1231 string::size_type pos = file.rfind( "/" );
1232 file = file.substr( 0, pos );
1233 // cout << "current file = " << file << endl;
1236 // cout << "current file = " << file << endl;
1237 if ( ! material_lib.add_item( file ) ) {
1238 SG_LOG( SG_TERRAIN, SG_ALERT,
1239 "Ack! unknown usemtl name = " << material
1240 << " in " << path );
1242 // locate our newly created material
1243 newmat = material_lib.find( material );
1244 if ( newmat == NULL ) {
1245 SG_LOG( SG_TERRAIN, SG_ALERT,
1246 "Ack! bad on the fly material create = "
1247 << material << " in " << path );
1252 if ( newmat != NULL ) {
1253 // set the texture width and height values for this
1255 tex_width = newmat->get_xsize();
1256 tex_height = newmat->get_ysize();
1257 state = newmat->get_state();
1258 coverage = newmat->get_light_coverage();
1259 // cout << "(w) = " << tex_width << " (h) = "
1260 // << tex_width << endl;
1271 int size = node_index.size();
1273 SG_LOG( SG_TERRAIN, SG_ALERT, "Woh! node list size < 1" );
1276 ssgVertexArray *vl = new ssgVertexArray( size );
1278 for ( i = 0; i < size; ++i ) {
1279 node = nodes[ node_index[i] ];
1280 sgSetVec3( tmp3, node[0], node[1], node[2] );
1286 ssgNormalArray *nl = new ssgNormalArray( size );
1287 if ( normal_index.size() ) {
1288 // object file specifies normal indices (i.e. normal indices
1290 for ( i = 0; i < size; ++i ) {
1291 normal = normals[ normal_index[i] ];
1292 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1296 // use implied normal indices. normal index = vertex index.
1297 for ( i = 0; i < size; ++i ) {
1298 normal = normals[ node_index[i] ];
1299 sgSetVec3( tmp3, normal[0], normal[1], normal[2] );
1305 ssgColourArray *cl = new ssgColourArray( 1 );
1306 sgSetVec4( tmp4, 1.0, 1.0, 1.0, 1.0 );
1309 // texture coordinates
1310 size = tex_index.size();
1312 ssgTexCoordArray *tl = new ssgTexCoordArray( size );
1314 texcoord = texcoords[ tex_index[0] ];
1315 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1316 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1317 if ( tex_width > 0 ) {
1318 tmp2[0] *= (1000.0 / tex_width);
1320 if ( tex_height > 0 ) {
1321 tmp2[1] *= (1000.0 / tex_height);
1324 } else if ( size > 1 ) {
1325 for ( i = 0; i < size; ++i ) {
1326 texcoord = texcoords[ tex_index[i] ];
1327 sgSetVec2( tmp2, texcoord[0], texcoord[1] );
1328 if ( tex_width > 0 ) {
1329 tmp2[0] *= (1000.0 / tex_width);
1331 if ( tex_height > 0 ) {
1332 tmp2[1] *= (1000.0 / tex_height);
1338 ssgLeaf *leaf = new ssgVtxTable ( ty, vl, nl, tl, cl );
1340 // lookup the state record
1342 leaf->setState( state );
1344 if ( calc_lights ) {
1345 if ( coverage > 0.0 ) {
1346 if ( coverage < 10000.0 ) {
1347 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
1348 << coverage << ", pushing up to 10000");
1351 gen_random_surface_points(leaf, lights, coverage);
1359 // Load an Binary obj file
1360 bool fgBinObjLoad( const string& path, const bool is_base,
1362 double *bounding_radius,
1363 ssgBranch* geometry,
1364 ssgBranch* rwy_lights,
1365 ssgBranch* taxi_lights,
1366 ssgVertexArray *ground_lights )
1369 bool use_random_objects =
1370 fgGetBool("/sim/rendering/random-objects", true);
1372 if ( ! obj.read_bin( path ) ) {
1376 geometry->setName( (char *)path.c_str() );
1378 // reference point (center offset/bounding sphere)
1379 *center = obj.get_gbs_center();
1380 *bounding_radius = obj.get_gbs_radius();
1382 point_list const& nodes = obj.get_wgs84_nodes();
1383 // point_list const& colors = obj.get_colors();
1384 point_list const& normals = obj.get_normals();
1385 point_list const& texcoords = obj.get_texcoords();
1390 group_list::size_type i;
1393 string_list const& pt_materials = obj.get_pt_materials();
1394 group_list const& pts_v = obj.get_pts_v();
1395 group_list const& pts_n = obj.get_pts_n();
1396 for ( i = 0; i < pts_v.size(); ++i ) {
1397 // cout << "pts_v.size() = " << pts_v.size() << endl;
1398 if ( pt_materials[i].substr(0, 3) == "RWY" ) {
1400 sgSetVec3( up, center->x(), center->y(), center->z() );
1401 // returns a transform -> lod -> leaf structure
1402 ssgBranch *branch = gen_directional_lights( nodes, normals,
1406 // branches don't honor callbacks as far as I know so I'm
1407 // commenting this out to avoid a plib runtime warning.
1408 branch->setTravCallback( SSG_CALLBACK_PRETRAV,
1409 runway_lights_pretrav );
1410 if ( pt_materials[i].substr(0, 16) == "RWY_BLUE_TAXIWAY" ) {
1411 taxi_lights->addKid( branch );
1413 rwy_lights->addKid( branch );
1416 material = pt_materials[i];
1418 ssgLeaf *leaf = gen_leaf( path, GL_POINTS, material,
1419 nodes, normals, texcoords,
1420 pts_v[i], pts_n[i], tex_index,
1421 false, ground_lights );
1422 geometry->addKid( leaf );
1426 // Put all randomly-placed objects under a separate branch
1427 // (actually an ssgRangeSelector) named "random-models".
1428 ssgBranch * random_object_branch = 0;
1429 if (use_random_objects) {
1430 float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
1431 ssgRangeSelector * object_lod = new ssgRangeSelector;
1432 object_lod->setRanges(ranges, 2);
1433 object_lod->setName("random-models");
1434 geometry->addKid(object_lod);
1435 random_object_branch = new ssgBranch;
1436 object_lod->addKid(random_object_branch);
1439 // generate triangles
1440 string_list const& tri_materials = obj.get_tri_materials();
1441 group_list const& tris_v = obj.get_tris_v();
1442 group_list const& tris_n = obj.get_tris_n();
1443 group_list const& tris_tc = obj.get_tris_tc();
1444 for ( i = 0; i < tris_v.size(); ++i ) {
1445 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLES, tri_materials[i],
1446 nodes, normals, texcoords,
1447 tris_v[i], tris_n[i], tris_tc[i],
1448 is_base, ground_lights );
1450 if (use_random_objects)
1451 gen_random_surface_objects(leaf, random_object_branch,
1452 center, tri_materials[i]);
1453 geometry->addKid( leaf );
1457 string_list const& strip_materials = obj.get_strip_materials();
1458 group_list const& strips_v = obj.get_strips_v();
1459 group_list const& strips_n = obj.get_strips_n();
1460 group_list const& strips_tc = obj.get_strips_tc();
1461 for ( i = 0; i < strips_v.size(); ++i ) {
1462 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_STRIP, strip_materials[i],
1463 nodes, normals, texcoords,
1464 strips_v[i], strips_n[i], strips_tc[i],
1465 is_base, ground_lights );
1467 if (use_random_objects)
1468 gen_random_surface_objects(leaf, random_object_branch,
1469 center,strip_materials[i]);
1470 geometry->addKid( leaf );
1474 string_list const& fan_materials = obj.get_fan_materials();
1475 group_list const& fans_v = obj.get_fans_v();
1476 group_list const& fans_n = obj.get_fans_n();
1477 group_list const& fans_tc = obj.get_fans_tc();
1478 for ( i = 0; i < fans_v.size(); ++i ) {
1479 ssgLeaf *leaf = gen_leaf( path, GL_TRIANGLE_FAN, fan_materials[i],
1480 nodes, normals, texcoords,
1481 fans_v[i], fans_n[i], fans_tc[i],
1482 is_base, ground_lights );
1483 if (use_random_objects)
1484 gen_random_surface_objects(leaf, random_object_branch,
1485 center, fan_materials[i]);
1486 geometry->addKid( leaf );