1 // obj.cxx -- routines to handle loading scenery and building the plib
4 // Written by Curtis Olson, started October 1997.
6 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #ifdef SG_MATH_EXCEPTION_CLASH
36 #include <simgear/compiler.h>
37 #include <simgear/sg_inlines.h>
38 #include <simgear/io/sg_binobj.hxx>
42 #include <vector> // STL
43 #include <ctype.h> // isdigit()
45 #include <simgear/constants.h>
46 #include <simgear/debug/logstream.hxx>
47 #include <simgear/math/point3d.hxx>
48 #include <simgear/math/polar3d.hxx>
49 #include <simgear/math/sg_geodesy.hxx>
50 #include <simgear/math/sg_random.h>
51 #include <simgear/math/vector.hxx>
52 #include <simgear/misc/sgstream.hxx>
53 #include <simgear/misc/stopwatch.hxx>
54 #include <simgear/misc/texcoord.hxx>
55 #include <simgear/scene/material/mat.hxx>
56 #include <simgear/scene/material/matlib.hxx>
57 #include <simgear/scene/tgdb/leaf.hxx>
58 #include <simgear/scene/tgdb/pt_lights.hxx>
60 #include <Main/globals.hxx>
61 #include <Main/fg_props.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 // Generate an ocean tile
75 bool fgGenTile( const string& path, SGBucket b,
76 Point3D *center, double *bounding_radius,
77 SGMaterialLib *matlib, ssgBranch* geometry )
79 ssgSimpleState *state = NULL;
81 geometry->setName( (char *)path.c_str() );
83 double tex_width = 1000.0;
86 // find Ocean material in the properties list
87 SGMaterial *mat = matlib->find( "Ocean" );
89 // set the texture width and height values for this
91 tex_width = mat->get_xsize();
92 // tex_height = newmat->get_ysize();
95 state = mat->get_state();
97 SG_LOG( SG_TERRAIN, SG_ALERT,
98 "Ack! unknown usemtl name = " << "Ocean"
102 // Calculate center point
103 double clon = b.get_center_lon();
104 double clat = b.get_center_lat();
105 double height = b.get_height();
106 double width = b.get_width();
108 *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
109 clat*SGD_DEGREES_TO_RADIANS,
111 // cout << "center = " << center << endl;;
113 // Caculate corner vertices
115 geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
116 geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
117 geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
118 geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
122 for ( i = 0; i < 4; ++i ) {
123 rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
124 geod[i].y() * SGD_DEGREES_TO_RADIANS,
128 Point3D cart[4], rel[4];
129 for ( i = 0; i < 4; ++i ) {
130 cart[i] = sgGeodToCart(rad[i]);
131 rel[i] = cart[i] - *center;
132 // cout << "corner " << i << " = " << cart[i] << endl;
135 // Calculate bounding radius
136 *bounding_radius = center->distance3D( cart[0] );
137 // cout << "bounding radius = " << t->bounding_radius << endl;
141 for ( i = 0; i < 4; ++i ) {
142 double length = cart[i].distance3D( Point3D(0.0) );
143 normals[i] = cart[i] / length;
144 // cout << "normal = " << normals[i] << endl;
147 // Calculate texture coordinates
148 point_list geod_nodes;
150 geod_nodes.reserve(4);
153 rectangle.reserve(4);
154 for ( i = 0; i < 4; ++i ) {
155 geod_nodes.push_back( geod[i] );
156 rectangle.push_back( i );
158 point_list texs = calc_tex_coords( b, geod_nodes, rectangle,
159 1000.0 / tex_width );
161 // Allocate ssg structure
162 ssgVertexArray *vl = new ssgVertexArray( 4 );
163 ssgNormalArray *nl = new ssgNormalArray( 4 );
164 ssgTexCoordArray *tl = new ssgTexCoordArray( 4 );
165 ssgColourArray *cl = new ssgColourArray( 1 );
168 sgSetVec4( color, 1.0, 1.0, 1.0, 1.0 );
171 // sgVec3 *vtlist = new sgVec3 [ 4 ];
172 // t->vec3_ptrs.push_back( vtlist );
173 // sgVec3 *vnlist = new sgVec3 [ 4 ];
174 // t->vec3_ptrs.push_back( vnlist );
175 // sgVec2 *tclist = new sgVec2 [ 4 ];
176 // t->vec2_ptrs.push_back( tclist );
180 for ( i = 0; i < 4; ++i ) {
182 rel[i].x(), rel[i].y(), rel[i].z() );
186 normals[i].x(), normals[i].y(), normals[i].z() );
189 sgSetVec2( tmp2, texs[i].x(), texs[i].y());
194 new ssgVtxTable ( GL_TRIANGLE_FAN, vl, nl, tl, cl );
196 leaf->setState( state );
198 geometry->addKid( leaf );
204 static void random_pt_inside_tri( float *res,
205 float *n1, float *n2, float *n3 )
207 double a = sg_random();
208 double b = sg_random();
213 double c = 1 - a - b;
215 res[0] = n1[0]*a + n2[0]*b + n3[0]*c;
216 res[1] = n1[1]*a + n2[1]*b + n3[1]*c;
217 res[2] = n1[2]*a + n2[2]*b + n3[2]*c;
222 * User data for populating leaves when they come in range.
224 class LeafUserData : public ssgBase
236 void setup_triangle( int i );
241 * User data for populating triangles when they come in range.
243 class TriUserData : public ssgBase
252 SGMaterial::ObjectGroup * object_group;
254 LeafUserData * leafData;
257 void fill_in_triangle();
258 void add_object_to_triangle(SGMaterial::Object * object);
259 void makeWorldMatrix (sgMat4 ROT, double hdg_deg );
264 * Fill in a triangle with randomly-placed objects.
266 * This method is invoked by a callback when the triangle is in range
267 * but not yet populated.
271 void TriUserData::fill_in_triangle ()
273 // generate a repeatable random seed
276 int nObjects = object_group->get_object_count();
278 for (int i = 0; i < nObjects; i++) {
279 SGMaterial::Object * object = object_group->get_object(i);
280 double num = area / object->get_coverage_m2();
282 // place an object each unit of area
283 while ( num > 1.0 ) {
284 add_object_to_triangle(object);
287 // for partial units of area, use a zombie door method to
288 // create the proper random chance of an object being created
291 if ( sg_random() <= num ) {
292 // a zombie made it through our door
293 add_object_to_triangle(object);
299 void TriUserData::add_object_to_triangle (SGMaterial::Object * object)
301 // Set up the random heading if required.
303 if (object->get_heading_type() == SGMaterial::Object::HEADING_RANDOM)
304 hdg_deg = sg_random() * 360;
307 makeWorldMatrix(mat, hdg_deg);
309 ssgTransform * pos = new ssgTransform;
310 pos->setTransform(mat);
311 pos->addKid( object->get_random_model( globals->get_model_loader(),
312 globals->get_fg_root(),
313 globals->get_props(),
314 globals->get_sim_time_sec() )
319 void TriUserData::makeWorldMatrix (sgMat4 mat, double hdg_deg )
322 mat[0][0] = leafData->sin_lat * leafData->cos_lon;
323 mat[0][1] = leafData->sin_lat * leafData->sin_lon;
324 mat[0][2] = -leafData->cos_lat;
327 mat[1][0] = -leafData->sin_lon;
328 mat[1][1] = leafData->cos_lon;
332 float sin_hdg = sin( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
333 float cos_hdg = cos( hdg_deg * SGD_DEGREES_TO_RADIANS ) ;
334 mat[0][0] = cos_hdg * leafData->sin_lat * leafData->cos_lon - sin_hdg * leafData->sin_lon;
335 mat[0][1] = cos_hdg * leafData->sin_lat * leafData->sin_lon + sin_hdg * leafData->cos_lon;
336 mat[0][2] = -cos_hdg * leafData->cos_lat;
339 mat[1][0] = -sin_hdg * leafData->sin_lat * leafData->cos_lon - cos_hdg * leafData->sin_lon;
340 mat[1][1] = -sin_hdg * leafData->sin_lat * leafData->sin_lon + cos_hdg * leafData->cos_lon;
341 mat[1][2] = sin_hdg * leafData->cos_lat;
345 mat[2][0] = leafData->cos_lat * leafData->cos_lon;
346 mat[2][1] = leafData->cos_lat * leafData->sin_lon;
347 mat[2][2] = leafData->sin_lat;
350 // translate to random point in triangle
352 random_pt_inside_tri(result, p1, p2, p3);
353 sgSubVec3(mat[3], result, center);
359 * SSG callback for an in-range triangle of randomly-placed objects.
361 * This pretraversal callback is attached to a branch that is traversed
362 * only when a triangle is in range. If the triangle is not currently
363 * populated with randomly-placed objects, this callback will populate
366 * @param entity The entity to which the callback is attached (not used).
367 * @param mask The entity's traversal mask (not used).
368 * @return Always 1, to allow traversal and culling to continue.
371 tri_in_range_callback (ssgEntity * entity, int mask)
373 TriUserData * data = (TriUserData *)entity->getUserData();
374 if (!data->is_filled_in) {
375 data->fill_in_triangle();
376 data->is_filled_in = true;
383 * SSG callback for an out-of-range triangle of randomly-placed objects.
385 * This pretraversal callback is attached to a branch that is traversed
386 * only when a triangle is out of range. If the triangle is currently
387 * populated with randomly-placed objects, the objects will be removed.
390 * @param entity The entity to which the callback is attached (not used).
391 * @param mask The entity's traversal mask (not used).
392 * @return Always 0, to prevent any further traversal or culling.
395 tri_out_of_range_callback (ssgEntity * entity, int mask)
397 TriUserData * data = (TriUserData *)entity->getUserData();
398 if (data->is_filled_in) {
399 data->branch->removeAllKids();
400 data->is_filled_in = false;
407 * ssgEntity with a dummy bounding sphere, to fool culling.
409 * This forces the in-range and out-of-range branches to be visited
410 * when appropriate, even if they have no children. It's ugly, but
411 * it works and seems fairly efficient (since branches can still
412 * be culled when they're out of the view frustum).
414 class DummyBSphereEntity : public ssgBranch
417 DummyBSphereEntity (float radius)
419 bsphere.setCenter(0, 0, 0);
420 bsphere.setRadius(radius);
422 virtual ~DummyBSphereEntity () {}
423 virtual void recalcBSphere () { bsphere_is_invalid = false; }
428 * Calculate the bounding radius of a triangle from its center.
430 * @param center The triangle center.
431 * @param p1 The first point in the triangle.
432 * @param p2 The second point in the triangle.
433 * @param p3 The third point in the triangle.
434 * @return The greatest distance any point lies from the center.
437 get_bounding_radius( sgVec3 center, float *p1, float *p2, float *p3)
439 return sqrt( SG_MAX3( sgDistanceSquaredVec3(center, p1),
440 sgDistanceSquaredVec3(center, p2),
441 sgDistanceSquaredVec3(center, p3) ) );
446 * Set up a triangle for randomly-placed objects.
448 * No objects will be added unless the triangle comes into range.
452 void LeafUserData::setup_triangle (int i )
455 leaf->getTriangle(i, &n1, &n2, &n3);
457 float * p1 = leaf->getVertex(n1);
458 float * p2 = leaf->getVertex(n2);
459 float * p3 = leaf->getVertex(n3);
461 // Set up a single center point for LOD
464 (p1[0] + p2[0] + p3[0]) / 3.0,
465 (p1[1] + p2[1] + p3[1]) / 3.0,
466 (p1[2] + p2[2] + p3[2]) / 3.0);
467 double area = sgTriArea(p1, p2, p3);
469 // maximum radius of an object from center.
470 double bounding_radius = get_bounding_radius(center, p1, p2, p3);
472 // Set up a transformation to the center
473 // point, so that everything else can
474 // be specified relative to it.
475 ssgTransform * location = new ssgTransform;
477 sgMakeTransMat4(TRANS, center);
478 location->setTransform(TRANS);
479 branch->addKid(location);
481 // Iterate through all the object types.
482 int num_groups = mat->get_object_group_count();
483 for (int j = 0; j < num_groups; j++) {
484 // Look up the random object.
485 SGMaterial::ObjectGroup * group = mat->get_object_group(j);
487 // Set up the range selector for the entire
488 // triangle; note that we use the object
489 // range plus the bounding radius here, to
490 // allow for objects far from the center.
491 float ranges[] = { 0,
492 group->get_range_m() + bounding_radius,
494 ssgRangeSelector * lod = new ssgRangeSelector;
495 lod->setRanges(ranges, 3);
496 location->addKid(lod);
498 // Create the in-range and out-of-range
500 ssgBranch * in_range = new ssgBranch;
501 ssgBranch * out_of_range = new ssgBranch;
503 // Set up the user data for if/when
504 // the random objects in this triangle
506 TriUserData * data = new TriUserData;
507 data->is_filled_in = false;
511 sgCopyVec3 (data->center, center);
513 data->object_group = group;
514 data->branch = in_range;
515 data->leafData = this;
516 data->seed = (unsigned int)(p1[0] * j);
518 // Set up the in-range node.
519 in_range->setUserData(data);
520 in_range->setTravCallback(SSG_CALLBACK_PRETRAV,
521 tri_in_range_callback);
522 lod->addKid(in_range);
524 // Set up the out-of-range node.
525 out_of_range->setUserData(data);
526 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
527 tri_out_of_range_callback);
528 out_of_range->addKid(new DummyBSphereEntity(bounding_radius));
529 lod->addKid(out_of_range);
534 * SSG callback for an in-range leaf of randomly-placed objects.
536 * This pretraversal callback is attached to a branch that is
537 * traversed only when a leaf is in range. If the leaf is not
538 * currently prepared to be populated with randomly-placed objects,
539 * this callback will prepare it (actual population is handled by
540 * the tri_in_range_callback for individual triangles).
542 * @param entity The entity to which the callback is attached (not used).
543 * @param mask The entity's traversal mask (not used).
544 * @return Always 1, to allow traversal and culling to continue.
547 leaf_in_range_callback (ssgEntity * entity, int mask)
549 LeafUserData * data = (LeafUserData *)entity->getUserData();
551 if (!data->is_filled_in) {
552 // Iterate through all the triangles
553 // and populate them.
554 int num_tris = data->leaf->getNumTriangles();
555 for ( int i = 0; i < num_tris; ++i ) {
556 data->setup_triangle(i);
558 data->is_filled_in = true;
565 * SSG callback for an out-of-range leaf of randomly-placed objects.
567 * This pretraversal callback is attached to a branch that is
568 * traversed only when a leaf is out of range. If the leaf is
569 * currently prepared to be populated with randomly-placed objects (or
570 * is actually populated), the objects will be removed.
572 * @param entity The entity to which the callback is attached (not used).
573 * @param mask The entity's traversal mask (not used).
574 * @return Always 0, to prevent any further traversal or culling.
577 leaf_out_of_range_callback (ssgEntity * entity, int mask)
579 LeafUserData * data = (LeafUserData *)entity->getUserData();
580 if (data->is_filled_in) {
581 data->branch->removeAllKids();
582 data->is_filled_in = false;
589 * Randomly place objects on a surface.
591 * The leaf node provides the geometry of the surface, while the
592 * material provides the objects and placement density. Latitude
593 * and longitude are required so that the objects can be rotated
594 * to the world-up vector. This function does not actually add
595 * any objects; instead, it attaches an ssgRangeSelector to the
596 * branch with callbacks to generate the objects when needed.
598 * @param leaf The surface where the objects should be placed.
599 * @param branch The branch that will hold the randomly-placed objects.
600 * @param center The center of the leaf in FlightGear coordinates.
601 * @param material_name The name of the surface's material.
604 gen_random_surface_objects (ssgLeaf *leaf,
609 // If the surface has no triangles, return
611 int num_tris = leaf->getNumTriangles();
615 // If the material has no randomly-placed
616 // objects, return now.
617 if (mat->get_object_group_count() < 1)
620 // Calculate the geodetic centre of
621 // the tile, for aligning automatic
623 double lon_deg, lat_rad, lat_deg, alt_m, sl_radius_m;
624 Point3D geoc = sgCartToPolar3d(*center);
625 lon_deg = geoc.lon() * SGD_RADIANS_TO_DEGREES;
626 sgGeocToGeod(geoc.lat(), geoc.radius(),
627 &lat_rad, &alt_m, &sl_radius_m);
628 lat_deg = lat_rad * SGD_RADIANS_TO_DEGREES;
631 // max random object range: 20000m
632 float ranges[] = { 0, 20000, 1000000 };
633 ssgRangeSelector * lod = new ssgRangeSelector;
634 lod->setRanges(ranges, 3);
637 // Create the in-range and out-of-range
639 ssgBranch * in_range = new ssgBranch;
640 ssgBranch * out_of_range = new ssgBranch;
641 lod->addKid(in_range);
642 lod->addKid(out_of_range);
644 LeafUserData * data = new LeafUserData;
645 data->is_filled_in = false;
648 data->branch = in_range;
649 data->sin_lat = sin(lat_deg * SGD_DEGREES_TO_RADIANS);
650 data->cos_lat = cos(lat_deg * SGD_DEGREES_TO_RADIANS);
651 data->sin_lon = sin(lon_deg * SGD_DEGREES_TO_RADIANS);
652 data->cos_lon = cos(lon_deg * SGD_DEGREES_TO_RADIANS);
654 in_range->setUserData(data);
655 in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
656 out_of_range->setUserData(data);
657 out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
658 leaf_out_of_range_callback);
660 ->addKid(new DummyBSphereEntity(leaf->getBSphere()->getRadius()));
665 ////////////////////////////////////////////////////////////////////////
667 ////////////////////////////////////////////////////////////////////////
669 // Load an Binary obj file
670 bool fgBinObjLoad( const string& path, const bool is_base,
672 double *bounding_radius,
673 SGMaterialLib *matlib,
674 bool use_random_objects,
676 ssgBranch* rwy_lights,
677 ssgBranch* taxi_lights,
678 ssgVertexArray *ground_lights )
682 if ( ! obj.read_bin( path ) ) {
686 geometry->setName( (char *)path.c_str() );
688 // reference point (center offset/bounding sphere)
689 *center = obj.get_gbs_center();
690 *bounding_radius = obj.get_gbs_radius();
692 point_list const& nodes = obj.get_wgs84_nodes();
693 // point_list const& colors = obj.get_colors();
694 point_list const& normals = obj.get_normals();
695 point_list const& texcoords = obj.get_texcoords();
700 group_list::size_type i;
703 string_list const& pt_materials = obj.get_pt_materials();
704 group_list const& pts_v = obj.get_pts_v();
705 group_list const& pts_n = obj.get_pts_n();
706 for ( i = 0; i < pts_v.size(); ++i ) {
707 // cout << "pts_v.size() = " << pts_v.size() << endl;
708 if ( pt_materials[i].substr(0, 3) == "RWY" ) {
710 sgSetVec3( up, center->x(), center->y(), center->z() );
711 // returns a transform -> lod -> leaf structure
712 ssgBranch *branch = sgMakeDirectionalLights( nodes, normals,
715 pt_materials[i], up );
716 if ( pt_materials[i].substr(0, 16) == "RWY_BLUE_TAXIWAY" ) {
717 taxi_lights->addKid( branch );
719 rwy_lights->addKid( branch );
722 material = pt_materials[i];
724 ssgLeaf *leaf = sgMakeLeaf( path, GL_POINTS, matlib, material,
725 nodes, normals, texcoords,
726 pts_v[i], pts_n[i], tex_index,
727 false, ground_lights );
728 geometry->addKid( leaf );
732 // Put all randomly-placed objects under a separate branch
733 // (actually an ssgRangeSelector) named "random-models".
734 ssgBranch * random_object_branch = 0;
735 if (use_random_objects) {
736 float ranges[] = { 0, 20000 }; // Maximum 20km range for random objects
737 ssgRangeSelector * object_lod = new ssgRangeSelector;
738 object_lod->setRanges(ranges, 2);
739 object_lod->setName("random-models");
740 geometry->addKid(object_lod);
741 random_object_branch = new ssgBranch;
742 object_lod->addKid(random_object_branch);
745 // generate triangles
746 string_list const& tri_materials = obj.get_tri_materials();
747 group_list const& tris_v = obj.get_tris_v();
748 group_list const& tris_n = obj.get_tris_n();
749 group_list const& tris_tc = obj.get_tris_tc();
750 for ( i = 0; i < tris_v.size(); ++i ) {
751 ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLES, matlib,
753 nodes, normals, texcoords,
754 tris_v[i], tris_n[i], tris_tc[i],
755 is_base, ground_lights );
757 if ( use_random_objects ) {
758 SGMaterial *mat = matlib->find( tri_materials[i] );
760 SG_LOG( SG_INPUT, SG_ALERT,
761 "Unknown material for random surface objects = "
762 << tri_materials[i] );
764 gen_random_surface_objects( leaf, random_object_branch,
767 geometry->addKid( leaf );
771 string_list const& strip_materials = obj.get_strip_materials();
772 group_list const& strips_v = obj.get_strips_v();
773 group_list const& strips_n = obj.get_strips_n();
774 group_list const& strips_tc = obj.get_strips_tc();
775 for ( i = 0; i < strips_v.size(); ++i ) {
776 ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_STRIP,
777 matlib, strip_materials[i],
778 nodes, normals, texcoords,
779 strips_v[i], strips_n[i], strips_tc[i],
780 is_base, ground_lights );
782 if ( use_random_objects ) {
783 SGMaterial *mat = matlib->find( strip_materials[i] );
785 SG_LOG( SG_INPUT, SG_ALERT,
786 "Unknown material for random surface objects = "
787 << strip_materials[i] );
789 gen_random_surface_objects( leaf, random_object_branch,
792 geometry->addKid( leaf );
796 string_list const& fan_materials = obj.get_fan_materials();
797 group_list const& fans_v = obj.get_fans_v();
798 group_list const& fans_n = obj.get_fans_n();
799 group_list const& fans_tc = obj.get_fans_tc();
800 for ( i = 0; i < fans_v.size(); ++i ) {
801 ssgLeaf *leaf = sgMakeLeaf( path, GL_TRIANGLE_FAN,
802 matlib, fan_materials[i],
803 nodes, normals, texcoords,
804 fans_v[i], fans_n[i], fans_tc[i],
805 is_base, ground_lights );
806 if ( use_random_objects ) {
807 SGMaterial *mat = matlib->find( fan_materials[i] );
809 SG_LOG( SG_INPUT, SG_ALERT,
810 "Unknown material for random surface objects = "
811 << fan_materials[i] );
813 gen_random_surface_objects( leaf, random_object_branch,
816 geometry->addKid( leaf );