]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Modified Files:
[simgear.git] / simgear / scene / tgdb / obj.cxx
1 // obj.cxx -- routines to handle loading scenery and building the plib
2 //            scene graph.
3 //
4 // Written by Curtis Olson, started October 1997.
5 //
6 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
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.
12 //
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.
17 //
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #include <list>
32
33 #include STL_STRING
34
35 #include <osg/StateSet>
36 #include <osg/Geode>
37 #include <osg/Geometry>
38 #include <osg/Group>
39 #include <osg/LOD>
40
41 #include <simgear/bucket/newbucket.hxx>
42 #include <simgear/io/sg_binobj.hxx>
43 #include <simgear/math/sg_geodesy.hxx>
44 #include <simgear/math/sg_types.hxx>
45 #include <simgear/misc/texcoord.hxx>
46 #include <simgear/scene/material/mat.hxx>
47 #include <simgear/scene/material/matlib.hxx>
48 #include <simgear/scene/tgdb/leaf.hxx>
49 #include <simgear/scene/tgdb/pt_lights.hxx>
50 #include <simgear/scene/tgdb/userdata.hxx>
51
52 #include "obj.hxx"
53
54 SG_USING_STD(string);
55 SG_USING_STD(list);
56
57 struct Leaf {
58     GLenum type;
59     int index;
60 };
61
62
63 // Generate an ocean tile
64 bool SGGenTile( const string& path, SGBucket b,
65                 Point3D *center, double *bounding_radius,
66                 SGMaterialLib *matlib, osg::Group* group )
67 {
68     osg::StateSet *state = 0;
69
70     double tex_width = 1000.0;
71     // double tex_height;
72
73     // find Ocean material in the properties list
74     SGMaterial *mat = matlib->find( "Ocean" );
75     if ( mat != NULL ) {
76         // set the texture width and height values for this
77         // material
78         tex_width = mat->get_xsize();
79         // tex_height = newmat->get_ysize();
80         
81         // set ssgState
82         state = mat->get_state();
83     } else {
84         SG_LOG( SG_TERRAIN, SG_ALERT, 
85                 "Ack! unknown usemtl name = " << "Ocean" 
86                 << " in " << path );
87     }
88
89     // Calculate center point
90     double clon = b.get_center_lon();
91     double clat = b.get_center_lat();
92     double height = b.get_height();
93     double width = b.get_width();
94
95     *center = sgGeodToCart( Point3D(clon*SGD_DEGREES_TO_RADIANS,
96                                     clat*SGD_DEGREES_TO_RADIANS,
97                                     0.0) );
98     // cout << "center = " << center << endl;;
99     
100     // Caculate corner vertices
101     Point3D geod[4];
102     geod[0] = Point3D( clon - width/2.0, clat - height/2.0, 0.0 );
103     geod[1] = Point3D( clon + width/2.0, clat - height/2.0, 0.0 );
104     geod[2] = Point3D( clon + width/2.0, clat + height/2.0, 0.0 );
105     geod[3] = Point3D( clon - width/2.0, clat + height/2.0, 0.0 );
106
107     Point3D rad[4];
108     int i;
109     for ( i = 0; i < 4; ++i ) {
110         rad[i] = Point3D( geod[i].x() * SGD_DEGREES_TO_RADIANS,
111                           geod[i].y() * SGD_DEGREES_TO_RADIANS,
112                           geod[i].z() );
113     }
114
115     Point3D cart[4], rel[4];
116     for ( i = 0; i < 4; ++i ) {
117         cart[i] = sgGeodToCart(rad[i]);
118         rel[i] = cart[i] - *center;
119         // cout << "corner " << i << " = " << cart[i] << endl;
120     }
121
122     // Calculate bounding radius
123     *bounding_radius = center->distance3D( cart[0] );
124     // cout << "bounding radius = " << t->bounding_radius << endl;
125
126     // Calculate normals
127     Point3D normals[4];
128     for ( i = 0; i < 4; ++i ) {
129         double length = cart[i].distance3D( Point3D(0.0) );
130         normals[i] = cart[i] / length;
131         // cout << "normal = " << normals[i] << endl;
132     }
133
134     // Calculate texture coordinates
135     point_list geod_nodes;
136     geod_nodes.clear();
137     geod_nodes.reserve(4);
138     int_list rectangle;
139     rectangle.clear();
140     rectangle.reserve(4);
141     for ( i = 0; i < 4; ++i ) {
142         geod_nodes.push_back( geod[i] );
143         rectangle.push_back( i );
144     }
145     point_list texs = sgCalcTexCoords( b, geod_nodes, rectangle, 
146                                        1000.0 / tex_width );
147
148     // Allocate ssg structure
149     osg::Vec3Array *vl = new osg::Vec3Array;
150     osg::Vec3Array *nl = new osg::Vec3Array;
151     osg::Vec2Array *tl = new osg::Vec2Array;
152
153     for ( i = 0; i < 4; ++i ) {
154         vl->push_back(osg::Vec3(rel[i].x(), rel[i].y(), rel[i].z()));
155         nl->push_back(osg::Vec3(normals[i].x(), normals[i].y(), normals[i].z()));
156         tl->push_back(osg::Vec2(texs[i].x(), texs[i].y()));
157     }
158     
159
160     osg::Geometry* geometry = new osg::Geometry;
161     geometry->setVertexArray(vl);
162     geometry->setNormalArray(nl);
163     geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
164     geometry->setColorBinding(osg::Geometry::BIND_OFF);
165     geometry->setTexCoordArray(0, tl);
166     geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_FAN, 0, vl->size()));
167     osg::Geode* geode = new osg::Geode;
168     geode->setName(path);
169     geode->addDrawable(geometry);
170     geode->setStateSet(state);
171
172     group->addChild(geode);
173
174     return true;
175 }
176
177
178 /**
179  * SSG callback for an in-range leaf of randomly-placed objects.
180  *
181  * This pretraversal callback is attached to a branch that is
182  * traversed only when a leaf is in range.  If the leaf is not
183  * currently prepared to be populated with randomly-placed objects,
184  * this callback will prepare it (actual population is handled by
185  * the tri_in_range_callback for individual triangles).
186  *
187  * @param entity The entity to which the callback is attached (not used).
188  * @param mask The entity's traversal mask (not used).
189  * @return Always 1, to allow traversal and culling to continue.
190  */
191 // static int
192 // leaf_in_range_callback (ssgEntity * entity, int mask)
193 // {
194 //   SGLeafUserData * data = (SGLeafUserData *)entity->getUserData();
195
196 //   if (!data->is_filled_in) {
197 //                                 // Iterate through all the triangles
198 //                                 // and populate them.
199 //     int num_tris = data->leaf->getNumTriangles();
200 //     for ( int i = 0; i < num_tris; ++i ) {
201 //             data->setup_triangle(i);
202 //     }
203 //     data->is_filled_in = true;
204 //   }
205 //   return 1;
206 // }
207
208
209 /**
210  * SSG callback for an out-of-range leaf of randomly-placed objects.
211  *
212  * This pretraversal callback is attached to a branch that is
213  * traversed only when a leaf is out of range.  If the leaf is
214  * currently prepared to be populated with randomly-placed objects (or
215  * is actually populated), the objects will be removed.
216  *
217  * @param entity The entity to which the callback is attached (not used).
218  * @param mask The entity's traversal mask (not used).
219  * @return Always 0, to prevent any further traversal or culling.
220  */
221 // static int
222 // leaf_out_of_range_callback (ssgEntity * entity, int mask)
223 // {
224 //   SGLeafUserData * data = (SGLeafUserData *)entity->getUserData();
225 //   if (data->is_filled_in) {
226 //     data->branch->removeAllKids();
227 //     data->is_filled_in = false;
228 //   }
229 //   return 0;
230 // }
231
232
233 /**
234  * Randomly place objects on a surface.
235  *
236  * The leaf node provides the geometry of the surface, while the
237  * material provides the objects and placement density.  Latitude
238  * and longitude are required so that the objects can be rotated
239  * to the world-up vector.  This function does not actually add
240  * any objects; instead, it attaches an ssgRangeSelector to the
241  * branch with callbacks to generate the objects when needed.
242  *
243  * @param leaf The surface where the objects should be placed.
244  * @param branch The branch that will hold the randomly-placed objects.
245  * @param center The center of the leaf in FlightGear coordinates.
246  * @param material_name The name of the surface's material.
247  */
248 static void
249 gen_random_surface_objects (osg::Node *leaf,
250                             osg::Group *branch,
251                             Point3D *center,
252                             SGMaterial *mat )
253 {
254   // OSGFIXME
255 #if 0
256                                 // If the surface has no triangles, return
257                                 // now.
258     int num_tris = leaf->getNumTriangles();
259     if (num_tris < 1)
260         return;
261
262                                 // If the material has no randomly-placed
263                                 // objects, return now.
264     if (mat->get_object_group_count() < 1)
265         return;
266
267                                 // Calculate the geodetic centre of
268                                 // the tile, for aligning automatic
269                                 // objects.
270     double xyz[3], lon_rad, lat_rad, alt_m;
271     xyz[0] = center->x(); xyz[1] = center->y(); xyz[2] = center->z();
272     sgCartToGeod(xyz, &lat_rad, &lon_rad, &alt_m);
273
274                                 // LOD for the leaf
275                                 // max random object range: 20000m
276     osg::LOD * lod = new osg::LOD;
277     branch->addChild(lod);
278
279                                 // Create the in-range and out-of-range
280                                 // branches.
281     osg::Group * in_range = new osg::Group;
282 //     osg::Group * out_of_range = new osg::Group;
283     lod->addChild(in_range, 0, 20000 /*OSGFIXME hardcoded visibility ???*/);
284 //     lod->addChild(out_of_range, 20000, 1e30);
285
286     SGLeafUserData * data = new SGLeafUserData;
287     data->is_filled_in = false;
288     data->leaf = leaf;
289     data->mat = mat;
290     data->branch = in_range;
291     data->sin_lat = sin(lat_rad);
292     data->cos_lat = cos(lat_rad);
293     data->sin_lon = sin(lon_rad);
294     data->cos_lon = cos(lon_rad);
295
296     in_range->setUserData(data);
297     // OSGFIXME: implement random objects to be loaded when in sight
298 //     in_range->setTravCallback(SSG_CALLBACK_PRETRAV, leaf_in_range_callback);
299
300     // OSGFIXME: implement deletion of tiles that are no longer used
301 //     out_of_range->setUserData(data);
302 //     out_of_range->setTravCallback(SSG_CALLBACK_PRETRAV,
303 //                                    leaf_out_of_range_callback);
304 //     out_of_range
305 //       ->addChild(new SGDummyBSphereEntity(leaf->getBSphere()->getRadius()));
306 #endif
307 }
308
309
310 \f
311 ////////////////////////////////////////////////////////////////////////
312 // Scenery loaders.
313 ////////////////////////////////////////////////////////////////////////
314
315 // Load an Binary obj file
316 bool SGBinObjLoad( const string& path, const bool is_base,
317                    Point3D *center,
318                    double *bounding_radius,
319                    SGMaterialLib *matlib,
320                    bool use_random_objects,
321                    osg::Group *geometry,
322                    osg::Group *vasi_lights,
323                    osg::Group *rwy_lights,
324                    osg::Group *taxi_lights,
325                    osg::Vec3Array *ground_lights )
326 {
327     SGBinObject obj;
328
329     if ( ! obj.read_bin( path ) ) {
330         return false;
331     }
332
333     osg::Group *local_terrain = new osg::Group;
334     local_terrain->setName( "LocalTerrain" );
335     geometry->addChild( local_terrain );
336
337     geometry->setName(path);
338
339     // reference point (center offset/bounding sphere)
340     *center = obj.get_gbs_center();
341     *bounding_radius = obj.get_gbs_radius();
342
343     point_list const& nodes = obj.get_wgs84_nodes();
344     // point_list const& colors = obj.get_colors();
345     point_list const& normals = obj.get_normals();
346     point_list const& texcoords = obj.get_texcoords();
347
348     string material;
349     int_list tex_index;
350
351     group_list::size_type i;
352
353     // generate points
354     string_list const& pt_materials = obj.get_pt_materials();
355     group_list const& pts_v = obj.get_pts_v();
356     group_list const& pts_n = obj.get_pts_n();
357     for ( i = 0; i < pts_v.size(); ++i ) {
358         // cout << "pts_v.size() = " << pts_v.size() << endl;
359         if ( pt_materials[i].substr(0, 3) == "RWY" ) {
360             // airport environment lighting
361             SGVec3d up(center->x(), center->y(), center->z());
362             // returns a transform -> lod -> leaf structure
363             osg::Node *branch = SGMakeDirectionalLights( nodes, normals,
364                                                          pts_v[i], pts_n[i],
365                                                          matlib,
366                                                          pt_materials[i], up );
367             if ( pt_materials[i] == "RWY_VASI_LIGHTS" ) {
368                 vasi_lights->addChild( branch );
369             } else if ( pt_materials[i] == "RWY_BLUE_TAXIWAY_LIGHTS"
370                 || pt_materials[i] == "RWY_GREEN_TAXIWAY_LIGHTS" )
371             {
372                 taxi_lights->addChild( branch );
373             } else {
374                 rwy_lights->addChild( branch );
375             }
376         } else {
377             // other geometry
378             material = pt_materials[i];
379             tex_index.clear();
380             osg::Node *leaf = SGMakeLeaf( path, GL_POINTS, matlib, material,
381                                         nodes, normals, texcoords,
382                                         pts_v[i], pts_n[i], tex_index,
383                                         false, ground_lights );
384             local_terrain->addChild( leaf );
385         }
386     }
387
388     // Put all randomly-placed objects under a separate branch
389     // (actually an ssgRangeSelector) named "random-models".
390     osg::Group * random_object_branch = 0;
391     if (use_random_objects) {
392         osg::LOD* object_lod = new osg::LOD;
393         object_lod->setName("random-models");
394         geometry->addChild(object_lod);
395         random_object_branch = new osg::Group;
396         // Maximum 20km range for random objects
397         object_lod->addChild(random_object_branch, 0, 20000);
398     }
399
400     typedef map<string,list<Leaf> > LeafMap;
401     LeafMap leafMap;
402     Leaf leaf;
403     leaf.type = GL_TRIANGLES;
404     string_list const& tri_materials = obj.get_tri_materials();
405     group_list const& tris_v = obj.get_tris_v();
406     group_list const& tris_n = obj.get_tris_n();
407     group_list const& tris_tc = obj.get_tris_tc();
408     for ( i = 0; i < tris_v.size(); i++ ) {
409         leaf.index = i;
410         leafMap[ tri_materials[i] ].push_back( leaf );
411     }
412     leaf.type = GL_TRIANGLE_STRIP;
413     string_list const& strip_materials = obj.get_strip_materials();
414     group_list const& strips_v = obj.get_strips_v();
415     group_list const& strips_n = obj.get_strips_n();
416     group_list const& strips_tc = obj.get_strips_tc();
417     for ( i = 0; i < strips_v.size(); i++ ) {
418         leaf.index = i;
419         leafMap[ strip_materials[i] ].push_back( leaf );
420     }
421     leaf.type = GL_TRIANGLE_FAN;
422     string_list const& fan_materials = obj.get_fan_materials();
423     group_list const& fans_v = obj.get_fans_v();
424     group_list const& fans_n = obj.get_fans_n();
425     group_list const& fans_tc = obj.get_fans_tc();
426     for ( i = 0; i < fans_v.size(); i++ ) {
427         leaf.index = i;
428         leafMap[ fan_materials[i] ].push_back( leaf );
429     }
430
431     LeafMap::iterator lmi = leafMap.begin();
432     while ( lmi != leafMap.end() ) {
433         list<Leaf> &leaf_list = lmi->second;
434         list<Leaf>::iterator li = leaf_list.begin();
435         while ( li != leaf_list.end() ) {
436             Leaf &leaf = *li;
437             int ind = leaf.index;
438             if ( leaf.type == GL_TRIANGLES ) {
439                 osg::Node *leaf = SGMakeLeaf( path, GL_TRIANGLES, matlib,
440                                             tri_materials[ind],
441                                             nodes, normals, texcoords,
442                                             tris_v[ind], tris_n[ind], tris_tc[ind],
443                                             is_base, ground_lights );
444                 if ( use_random_objects ) {
445                     SGMaterial *mat = matlib->find( tri_materials[ind] );
446                     if ( mat == NULL ) {
447                         SG_LOG( SG_INPUT, SG_ALERT,
448                                 "Unknown material for random surface objects = "
449                                 << tri_materials[ind] );
450                     } else {
451                         gen_random_surface_objects( leaf, random_object_branch,
452                                                     center, mat );
453                     }
454                 }
455                 local_terrain->addChild( leaf );
456             } else if ( leaf.type == GL_TRIANGLE_STRIP ) {
457                 osg::Node *leaf = SGMakeLeaf( path, GL_TRIANGLE_STRIP,
458                                             matlib, strip_materials[ind],
459                                             nodes, normals, texcoords,
460                                             strips_v[ind], strips_n[ind], strips_tc[ind],
461                                             is_base, ground_lights );
462                 if ( use_random_objects ) {
463                     SGMaterial *mat = matlib->find( strip_materials[ind] );
464                     if ( mat == NULL ) {
465                         SG_LOG( SG_INPUT, SG_ALERT,
466                                 "Unknown material for random surface objects = "
467                                 << strip_materials[ind] );
468                     } else {
469                         gen_random_surface_objects( leaf, random_object_branch,
470                                                     center, mat );
471                     }
472                 }
473                 local_terrain->addChild( leaf );
474             } else {
475                 osg::Node *leaf = SGMakeLeaf( path, GL_TRIANGLE_FAN,
476                                             matlib, fan_materials[ind],
477                                             nodes, normals, texcoords,
478                                             fans_v[ind], fans_n[ind], fans_tc[ind],
479                                             is_base, ground_lights );
480                 if ( use_random_objects ) {
481                     SGMaterial *mat = matlib->find( fan_materials[ind] );
482                     if ( mat == NULL ) {
483                         SG_LOG( SG_INPUT, SG_ALERT,
484                                 "Unknown material for random surface objects = "
485                                 << fan_materials[ind] );
486                     } else {
487                         gen_random_surface_objects( leaf, random_object_branch,
488                                                     center, mat );
489                     }
490                 }
491                 local_terrain->addChild( leaf );
492             }
493             ++li;
494         }
495         ++lmi;
496     }
497
498     return true;
499 }