]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Fix VS2010 lack of fminf
[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 "obj.hxx"
30
31 #include <simgear/compiler.h>
32
33 #include <osg/Fog>
34 #include <osg/Geode>
35 #include <osg/Geometry>
36 #include <osg/Group>
37 #include <osg/LOD>
38 #include <osg/MatrixTransform>
39 #include <osg/Point>
40 #include <osg/Referenced>
41 #include <osg/StateSet>
42 #include <osg/Switch>
43
44 #include <osgUtil/Simplifier>
45
46 #include <boost/foreach.hpp>
47
48 #include <algorithm>
49
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/io/sg_binobj.hxx>
52 #include <simgear/math/sg_geodesy.hxx>
53 #include <simgear/math/sg_random.h>
54 #include <simgear/math/SGMisc.hxx>
55 #include <simgear/scene/material/Effect.hxx>
56 #include <simgear/scene/material/EffectGeode.hxx>
57 #include <simgear/scene/material/mat.hxx>
58 #include <simgear/scene/material/matmodel.hxx>
59 #include <simgear/scene/material/matlib.hxx>
60 #include <simgear/scene/model/SGOffsetTransform.hxx>
61 #include <simgear/scene/util/SGUpdateVisitor.hxx>
62 #include <simgear/scene/util/SGNodeMasks.hxx>
63 #include <simgear/scene/util/QuadTreeBuilder.hxx>
64 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
65 #include <simgear/scene/util/OptionsReadFileCallback.hxx>
66
67 #include "SGTexturedTriangleBin.hxx"
68 #include "SGLightBin.hxx"
69 #include "SGModelBin.hxx"
70 #include "SGBuildingBin.hxx"
71 #include "TreeBin.hxx"
72 #include "SGDirectionalLightBin.hxx"
73 #include "GroundLightManager.hxx"
74
75 #include "pt_lights.hxx"
76
77 #define SG_SIMPLIFIER_RATIO 0.001
78 #define SG_SIMPLIFIER_MAX_LENGTH 1000.0
79 #define SG_SIMPLIFIER_MAX_ERROR 2000.0
80 #define SG_OBJECT_RANGE 9000.0
81 #define SG_TILE_RADIUS 14000.0
82
83 using namespace simgear;
84
85 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
86 typedef std::list<SGLightBin> SGLightListBin;
87 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
88
89 class SGTileGeometryBin : public osg::Referenced {
90 public:
91   SGMaterialTriangleMap materialTriangleMap;
92   SGLightBin tileLights;
93   SGLightBin randomTileLights;
94   SGTreeBinList randomForest;
95   SGDirectionalLightBin runwayLights;
96   SGDirectionalLightBin taxiLights;
97   SGDirectionalLightListBin vasiLights;
98   SGDirectionalLightListBin rabitLights;
99   SGLightListBin odalLights;
100   SGDirectionalLightListBin holdshortLights;
101   SGDirectionalLightListBin guardLights;
102   SGDirectionalLightListBin reilLights;
103   SGMatModelBin randomModels;
104   SGBuildingBinList randomBuildings;
105
106   static SGVec4f
107   getMaterialLightColor(const SGMaterial* material)
108   {
109     if (!material)
110       return SGVec4f(1, 1, 1, 0.8);
111     return material->get_light_color();
112   }
113
114   static void
115   addPointGeometry(SGLightBin& lights,
116                    const std::vector<SGVec3d>& vertices,
117                    const SGVec4f& color,
118                    const int_list& pts_v)
119   {
120     for (unsigned i = 0; i < pts_v.size(); ++i)
121       lights.insert(toVec3f(vertices[pts_v[i]]), color);
122   }
123
124   static void
125   addPointGeometry(SGDirectionalLightBin& lights,
126                    const std::vector<SGVec3d>& vertices,
127                    const std::vector<SGVec3f>& normals,
128                    const SGVec4f& color,
129                    const int_list& pts_v,
130                    const int_list& pts_n)
131   {
132     // If the normal indices match the vertex indices, use seperate
133     // normal indices. Else reuse the vertex indices for the normals.
134     if (pts_v.size() == pts_n.size()) {
135       for (unsigned i = 0; i < pts_v.size(); ++i)
136         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
137     } else {
138       for (unsigned i = 0; i < pts_v.size(); ++i)
139         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
140     }
141   }
142
143   bool
144   insertPtGeometry(const SGBinObject& obj, SGMaterialCache* matcache)
145   {
146     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
147       SG_LOG(SG_TERRAIN, SG_ALERT,
148              "Group list sizes for points do not match!");
149       return false;
150     }
151
152     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
153       std::string materialName = obj.get_pt_materials()[grp];
154       SGMaterial* material = matcache->find(materialName);
155       SGVec4f color = getMaterialLightColor(material);
156
157       if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
158         // Just plain lights. Not something for the runway.
159         addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
160                          obj.get_pts_v()[grp]);
161       } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
162                  || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
163         addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
164                          color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
165       } else if (materialName == "RWY_VASI_LIGHTS") {
166         vasiLights.push_back(SGDirectionalLightBin());
167         addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
168                          obj.get_normals(), color, obj.get_pts_v()[grp],
169                          obj.get_pts_n()[grp]);
170       } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
171         rabitLights.push_back(SGDirectionalLightBin());
172         addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
173                          obj.get_normals(), color, obj.get_pts_v()[grp],
174                          obj.get_pts_n()[grp]);
175       } else if (materialName == "RWY_ODALS_LIGHTS") {
176         odalLights.push_back(SGLightBin());
177         addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
178                          color, obj.get_pts_v()[grp]);
179       } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
180         holdshortLights.push_back(SGDirectionalLightBin());
181         addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
182                          obj.get_normals(), color, obj.get_pts_v()[grp],
183                          obj.get_pts_n()[grp]);
184       } else if (materialName == "RWY_GUARD_LIGHTS") {
185         guardLights.push_back(SGDirectionalLightBin());
186         addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
187                          obj.get_normals(), color, obj.get_pts_v()[grp],
188                          obj.get_pts_n()[grp]);
189       } else if (materialName == "RWY_REIL_LIGHTS") {
190         reilLights.push_back(SGDirectionalLightBin());
191         addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
192                          obj.get_normals(), color, obj.get_pts_v()[grp],
193                          obj.get_pts_n()[grp]);
194       } else {
195         // what is left must be runway lights
196         addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
197                          obj.get_normals(), color, obj.get_pts_v()[grp],
198                          obj.get_pts_n()[grp]);
199       }
200     }
201
202     return true;
203   }
204
205
206   static SGVec2f
207   getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
208               const SGVec2f& tcScale, unsigned i)
209   {
210     if (tc.empty())
211       return tcScale;
212     else if (tc.size() == 1)
213       return mult(texCoords[tc[0]], tcScale);
214     else
215       return mult(texCoords[tc[i]], tcScale);
216   }
217
218   static void
219   addTriangleGeometry(SGTexturedTriangleBin& triangles,
220                       const SGBinObject& obj, unsigned grp,
221                       const SGVec2f& tc0Scale, 
222                       const SGVec2f& tc1Scale)
223   {
224     const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
225     const std::vector<SGVec3f>& normals(obj.get_normals());
226     const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
227     const int_list& tris_v(obj.get_tris_v()[grp]);
228     const int_list& tris_n(obj.get_tris_n()[grp]);
229     const tci_list& tris_tc(obj.get_tris_tcs()[grp]);
230     bool  num_norms_is_num_verts = true;  
231     
232     if (tris_v.size() != tris_n.size()) {
233         // If the normal indices do not match, they should be inmplicitly
234         // the same than the vertex indices. 
235         num_norms_is_num_verts = false;
236     }
237
238     if ( !tris_tc[1].empty() ) {
239         triangles.hasSecondaryTexCoord(true);
240     }
241     
242     for (unsigned i = 2; i < tris_v.size(); i += 3) {
243         SGVertNormTex v0;
244         v0.SetVertex( toVec3f(vertices[tris_v[i-2]]) );
245         v0.SetNormal( num_norms_is_num_verts ? normals[tris_n[i-2]] : 
246                                                normals[tris_v[i-2]] );
247         v0.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i-2) );
248         if (!tris_tc[1].empty()) {
249             v0.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i-2) );
250         }
251         SGVertNormTex v1;
252         v1.SetVertex( toVec3f(vertices[tris_v[i-1]]) );
253         v1.SetNormal( num_norms_is_num_verts ? normals[tris_n[i-1]] : 
254                                                normals[tris_v[i-1]] );
255         v1.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i-1) );
256         if (!tris_tc[1].empty()) {
257             v1.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i-1) );
258         }
259         SGVertNormTex v2;
260         v2.SetVertex( toVec3f(vertices[tris_v[i]]) );
261         v2.SetNormal( num_norms_is_num_verts ? normals[tris_n[i]] : 
262                                                normals[tris_v[i]] );
263         v2.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i) );
264         if (!tris_tc[1].empty()) {
265             v2.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i) );
266         }
267         
268         triangles.insert(v0, v1, v2);
269     }
270   }
271
272   static void
273   addStripGeometry(SGTexturedTriangleBin& triangles,
274                    const SGBinObject& obj, unsigned grp,
275                    const SGVec2f& tc0Scale, 
276                    const SGVec2f& tc1Scale)
277   {
278       const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
279       const std::vector<SGVec3f>& normals(obj.get_normals());
280       const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
281       const int_list& strips_v(obj.get_strips_v()[grp]);
282       const int_list& strips_n(obj.get_strips_n()[grp]);
283       const tci_list& strips_tc(obj.get_strips_tcs()[grp]);
284       bool  num_norms_is_num_verts = true;  
285       
286       if (strips_v.size() != strips_n.size()) {
287           // If the normal indices do not match, they should be inmplicitly
288           // the same than the vertex indices. 
289           num_norms_is_num_verts = false;
290       }
291       
292       if ( !strips_tc[1].empty() ) {
293           triangles.hasSecondaryTexCoord(true);
294       }
295       
296     for (unsigned i = 2; i < strips_v.size(); ++i) {
297       SGVertNormTex v0;
298       v0.SetVertex( toVec3f(vertices[strips_v[i-2]]) );
299       v0.SetNormal( num_norms_is_num_verts ? normals[strips_n[i-2]] : 
300                                              normals[strips_v[i-2]] );
301       v0.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[0], tc0Scale, i-2) );
302       if (!strips_tc[1].empty()) {
303           v0.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i-2) );
304       }
305       SGVertNormTex v1;
306       v1.SetVertex( toVec3f(vertices[strips_v[i-1]]) );
307       v1.SetNormal( num_norms_is_num_verts ? normals[strips_n[i-1]] : 
308                                              normals[strips_v[i-1]] );
309       v1.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[1], tc0Scale, i-1) );
310       if (!strips_tc[1].empty()) {
311           v1.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i-1) );
312       }
313       SGVertNormTex v2;
314       v2.SetVertex( toVec3f(vertices[strips_v[i]]) );
315       v2.SetNormal( num_norms_is_num_verts ? normals[strips_n[i]] : 
316                                              normals[strips_v[i]] );
317       v2.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[0], tc0Scale, i) );
318       if (!strips_tc[1].empty()) {
319           v2.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i) );
320       }
321       if (i%2)
322         triangles.insert(v1, v0, v2);
323       else
324         triangles.insert(v0, v1, v2);
325     }
326   }
327
328   static void
329   addFanGeometry(SGTexturedTriangleBin& triangles,
330                  const SGBinObject& obj, unsigned grp,
331                  const SGVec2f& tc0Scale, 
332                  const SGVec2f& tc1Scale)
333   {
334       const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
335       const std::vector<SGVec3f>& normals(obj.get_normals());
336       const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
337       const int_list& fans_v(obj.get_fans_v()[grp]);
338       const int_list& fans_n(obj.get_fans_n()[grp]);
339       const tci_list& fans_tc(obj.get_fans_tcs()[grp]);
340       bool  num_norms_is_num_verts = true;  
341       
342       if (fans_v.size() != fans_n.size()) {
343           // If the normal indices do not match, they should be inmplicitly
344           // the same than the vertex indices. 
345           num_norms_is_num_verts = false;
346       }
347       
348       if ( !fans_tc[1].empty() ) {
349           triangles.hasSecondaryTexCoord(true);
350       }
351       
352     SGVertNormTex v0;
353     v0.SetVertex( toVec3f(vertices[fans_v[0]]) );
354     v0.SetNormal( num_norms_is_num_verts ? normals[fans_n[0]] : 
355                                            normals[fans_v[0]] );
356     v0.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, 0) );
357     if (!fans_tc[1].empty()) {
358         v0.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, 0) );
359     }
360     SGVertNormTex v1;
361     v1.SetVertex( toVec3f(vertices[fans_v[1]]) );
362     v1.SetNormal( num_norms_is_num_verts ? normals[fans_n[1]] : 
363                                            normals[fans_v[1]] );
364     v1.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, 1) );
365     if (!fans_tc[1].empty()) {
366         v1.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, 1) );
367     }
368     for (unsigned i = 2; i < fans_v.size(); ++i) {
369       SGVertNormTex v2;
370       v2.SetVertex( toVec3f(vertices[fans_v[i]]) );
371       v2.SetNormal( num_norms_is_num_verts ? normals[fans_n[i]] : 
372                                              normals[fans_v[i]] );
373       v2.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, i) );
374       if (!fans_tc[1].empty()) {
375           v2.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, i) );
376       }
377       triangles.insert(v0, v1, v2);
378       v1 = v2;
379     }
380   }
381
382   SGVec2f getTexCoordScale(const std::string& name, SGMaterialCache* matcache)
383   {
384     if (!matcache)
385       return SGVec2f(1, 1);
386     SGMaterial* material = matcache->find(name);
387     if (!material)
388       return SGVec2f(1, 1);
389
390     return material->get_tex_coord_scale();
391   }
392
393   bool
394   insertSurfaceGeometry(const SGBinObject& obj, SGMaterialCache* matcache)
395   {
396     if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
397         obj.get_tris_tcs().size() < obj.get_tris_v().size()) {
398       SG_LOG(SG_TERRAIN, SG_ALERT,
399              "Group list sizes for triangles do not match!");
400       return false;
401     }
402
403     for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
404       std::string materialName = obj.get_tri_materials()[grp];
405       SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
406       SGVec2f tc1Scale(1.0, 1.0);
407       addTriangleGeometry(materialTriangleMap[materialName],
408                           obj, grp, tc0Scale, tc1Scale );
409     }
410
411     if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
412         obj.get_strips_tcs().size() < obj.get_strips_v().size()) {
413       SG_LOG(SG_TERRAIN, SG_ALERT,
414              "Group list sizes for strips do not match!");
415       return false;
416     }
417     for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
418       std::string materialName = obj.get_strip_materials()[grp];
419       SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
420       SGVec2f tc1Scale(1.0, 1.0);
421       addStripGeometry(materialTriangleMap[materialName],
422                           obj, grp, tc0Scale, tc1Scale);
423     }
424
425     if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
426         obj.get_fans_tcs().size() < obj.get_fans_v().size()) {
427       SG_LOG(SG_TERRAIN, SG_ALERT,
428              "Group list sizes for fans do not match!");
429       return false;
430     }
431     for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
432       std::string materialName = obj.get_fan_materials()[grp];
433       SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
434       SGVec2f tc1Scale(1.0, 1.0);
435       addFanGeometry(materialTriangleMap[materialName],
436                        obj, grp, tc0Scale, tc1Scale );
437     }
438     return true;
439   }
440
441   osg::Node* getSurfaceGeometry(SGMaterialCache* matcache, bool useVBOs) const
442   {
443     if (materialTriangleMap.empty())
444       return 0;
445
446     EffectGeode* eg = NULL;
447     osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : NULL);
448     if (group) {
449         group->setName("surfaceGeometryGroup");
450     }
451     
452     //osg::Geode* geode = new osg::Geode;
453     SGMaterialTriangleMap::const_iterator i;
454     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
455       osg::Geometry* geometry = i->second.buildGeometry(useVBOs);
456       SGMaterial *mat = NULL;
457       if (matcache) {
458         mat = matcache->find(i->first);
459       }
460       eg = new EffectGeode;
461       eg->setName("EffectGeode");
462       if (mat) {
463         eg->setEffect(mat->get_effect(i->second));
464       }
465       eg->addDrawable(geometry);
466       eg->runGenerators(geometry);  // Generate extra data needed by effect
467       if (group) {
468         group->addChild(eg);
469       }
470     }
471     
472     if (group) {
473         return group;
474     } else {
475         return eg;
476     }
477   }
478
479   void computeRandomSurfaceLights(SGMaterialCache* matcache)
480   {
481     SGMaterialTriangleMap::iterator i;
482
483     // generate a repeatable random seed
484     mt seed;
485     mt_init(&seed, unsigned(123));
486
487     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
488       SGMaterial *mat = matcache->find(i->first);
489       if (!mat)
490         continue;
491
492       float coverage = mat->get_light_coverage();
493       if (coverage <= 0)
494         continue;
495       if (coverage < 10000.0) {
496         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
497                << coverage << ", pushing up to 10000");
498         coverage = 10000;
499       }
500
501       std::vector<SGVec3f> randomPoints;
502       i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
503       std::vector<SGVec3f>::iterator j;
504       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
505         float zombie = mt_rand(&seed);
506         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
507         float factor = mt_rand(&seed);
508         factor *= factor;
509
510         float bright = 1;
511         SGVec4f color;
512         if ( zombie > 0.5 ) {
513           // 50% chance of yellowish
514           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
515         } else if (zombie > 0.15f) {
516           // 35% chance of whitish
517           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
518         } else if (zombie > 0.05f) {
519           // 10% chance of orangish
520           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
521         } else {
522           // 5% chance of redish
523           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
524         }
525         randomTileLights.insert(*j, color);
526       }
527     }
528   }
529
530   void computeRandomObjectsAndBuildings(
531     SGMaterialCache* matcache,
532     float building_density,
533     bool use_random_objects,
534     bool use_random_buildings,
535     bool useVBOs)
536   {
537     SGMaterialTriangleMap::iterator i;
538
539     // generate a repeatable random seed
540     mt seed;
541     mt_init(&seed, unsigned(123));
542
543     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
544       SGMaterial *mat = matcache->find(i->first);
545       SGTexturedTriangleBin triangleBin = i->second;
546
547       if (!mat)
548         continue;
549
550       osg::Texture2D* object_mask  = mat->get_object_mask(triangleBin);
551
552       int   group_count            = mat->get_object_group_count();
553       float building_coverage      = mat->get_building_coverage();
554       float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
555       float cos_max_density_angle  = mat->get_cos_object_max_density_slope_angle();
556
557       if (building_coverage == 0)
558          continue;
559
560       SGBuildingBin* bin = NULL;
561
562       if (building_coverage > 0) {
563         bin = new SGBuildingBin(mat, useVBOs);
564         randomBuildings.push_back(bin);
565       }
566
567       unsigned num = i->second.getNumTriangles();
568       int random_dropped = 0;
569       int mask_dropped = 0;
570       int building_dropped = 0;
571       int triangle_dropped = 0;
572
573       for (unsigned i = 0; i < num; ++i) {
574         SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
575
576         SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).GetVertex();
577         SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).GetVertex() - vorigin;
578         SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).GetVertex() - vorigin;
579         SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).GetTexCoord(0);
580         SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).GetTexCoord(0) - torigin;
581         SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).GetTexCoord(0) - torigin;
582         SGVec3f normal = cross(v0, v1);
583
584         // Ensure the slope isn't too steep by checking the
585         // cos of the angle between the slope normal and the
586         // vertical (conveniently the z-component of the normalized
587         // normal) and values passed in.
588         float cos = normalize(normal).z();
589         float slope_density = 1.0;
590         if (cos < cos_zero_density_angle) continue; // Too steep for any objects
591         if (cos < cos_max_density_angle) {
592           slope_density =
593             (cos - cos_zero_density_angle) /
594             (cos_max_density_angle - cos_zero_density_angle);
595         }
596
597         // Containers to hold the random buildings and objects generated
598         // for this triangle for collision detection purposes.
599         std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
600         std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
601
602         // Compute the area
603         float area = 0.5f*length(normal);
604         if (area <= SGLimitsf::min())
605           continue;
606
607         // Generate any random objects
608         if (use_random_objects && (group_count > 0))
609         {
610           for (int j = 0; j < group_count; j++)
611           {
612             SGMatModelGroup *object_group =  mat->get_object_group(j);
613             int nObjects = object_group->get_object_count();
614
615             if (nObjects == 0) continue;
616
617             // For each of the random models in the group, determine an appropriate
618             // number of random placements and insert them.
619             for (int k = 0; k < nObjects; k++) {
620               SGMatModel * object = object_group->get_object(k);
621
622               // Determine the number of objecst to place, taking into account
623               // the slope density factor.
624               double n = slope_density * area / object->get_coverage_m2();
625
626               // Use the zombie door method to determine fractional object placement.
627               n = n + mt_rand(&seed);
628
629               // place an object each unit of area
630               while ( n > 1.0 ) {
631                 float a = mt_rand(&seed);
632                 float b = mt_rand(&seed);
633                 if ( a + b > 1 ) {
634                   a = 1 - a;
635                   b = 1 - b;
636                 }
637
638                 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
639                 float rotation = static_cast<float>(mt_rand(&seed));
640
641                 // Check that the point is sufficiently far from
642                 // the edge of the triangle by measuring the distance
643                 // from the three lines that make up the triangle.
644                 float spacing = object->get_spacing_m();
645
646                 SGVec3f p = randomPoint - vorigin;
647                 float edges[] = { length(cross(p     , p - v0)) / length(v0),
648                                   length(cross(p - v0, p - v1)) / length(v1 - v0),
649                                   length(cross(p - v1, p     )) / length(v1)      };
650                 float edge_dist = *std::min_element(edges, edges + 3);
651
652                 if (edge_dist < spacing) {
653                   n -= 1.0;
654                   continue;
655                 }
656
657                 if (object_mask != NULL) {
658                   SGVec2f texCoord = torigin + a*t0 + b*t1;
659
660                   // Check this random point against the object mask
661                   // blue (for buildings) channel.
662                   osg::Image* img = object_mask->getImage();
663                   unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
664                   unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
665
666                   if (mt_rand(&seed) > img->getColor(x, y).b()) {
667                     // Failed object mask check
668                     n -= 1.0;
669                     continue;
670                   }
671
672                   rotation = img->getColor(x,y).r();
673                 }
674
675                 bool close = false;
676
677                 // Check it isn't too close to any other random objects in the triangle
678                 std::vector<std::pair<SGVec3f, float> >::iterator l;
679                 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
680                   float min_dist2 = (l->second + object->get_spacing_m()) *
681                                     (l->second + object->get_spacing_m());
682
683                   if (distSqr(l->first, randomPoint) > min_dist2) {
684                     close = true;
685                     continue;
686                   }
687                 }
688
689                 if (!close) {
690                     triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
691                     randomModels.insert(randomPoint,
692                                         object,
693                                         (int)object->get_randomized_range_m(&seed),
694                                         rotation);
695                 }
696               }
697             }
698           }
699         }
700
701         // Random objects now generated.  Now generate the random buildings (if any);
702         if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
703
704           // Calculate the number of buildings, taking into account building density (which is linear)
705           // and the slope density factor.
706           double num = building_density * building_density * slope_density * area / building_coverage;
707
708           // For partial units of area, use a zombie door method to
709           // create the proper random chance of an object being created
710           // for this triangle.
711           num = num + mt_rand(&seed);
712
713           if (num < 1.0f) {
714             continue;
715           }
716
717           // Cosine of the angle between the two vectors.
718           float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
719
720           // Determine a grid spacing in each vector such that the correct
721           // coverage will result.
722           float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
723           float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
724
725           stepv0 = std::min(stepv0, 1.0f);
726           stepv1 = std::min(stepv1, 1.0f);
727
728           // Start at a random point. a will be immediately incremented below.
729           float a = -mt_rand(&seed) * stepv0;
730           float b = mt_rand(&seed) * stepv1;
731
732           // Place an object each unit of area
733           while (num > 1.0) {
734             num -= 1.0;
735
736             // Set the next location to place a building
737             a += stepv0;
738
739             if ((a + b) > 1.0f) {
740               // Reached the end of the scan-line on v0. Reset and increment
741               // scan-line on v1
742               a = mt_rand(&seed) * stepv0;
743               b += stepv1;
744             }
745
746             if (b > 1.0f) {
747               // In a degenerate case of a single point, we might be outside the
748               // scanline.  Note that we need to still ensure that a+b < 1.
749               b = mt_rand(&seed) * stepv1 * (1.0f - a);
750             }
751
752             if ((a + b) > 1.0f ) {
753               // Truly degenerate case - simply choose a random point guaranteed
754               // to fulfil the constraing of a+b < 1.
755               a = mt_rand(&seed);
756               b = mt_rand(&seed) * (1.0f - a);
757             }
758
759             SGVec3f randomPoint = vorigin + a*v0 + b*v1;
760             float rotation = mt_rand(&seed);
761
762             if (object_mask != NULL) {
763               SGVec2f texCoord = torigin + a*t0 + b*t1;
764               osg::Image* img = object_mask->getImage();
765               int x = (int) (img->s() * texCoord.x()) % img->s();
766               int y = (int) (img->t() * texCoord.y()) % img->t();
767
768               // In some degenerate cases x or y can be < 1, in which case the mod operand fails
769               while (x < 0) x += img->s();
770               while (y < 0) y += img->t();
771
772               if (mt_rand(&seed) < img->getColor(x, y).b()) {
773                 // Object passes mask. Rotation is taken from the red channel
774                 rotation = img->getColor(x,y).r();
775               } else {
776                 // Fails mask test - try again.
777                 mask_dropped++;
778                 continue;
779               }
780             }
781
782             // Check building isn't too close to the triangle edge.
783             float type_roll = mt_rand(&seed);
784             SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
785             float radius = bin->getBuildingMaxRadius(buildingtype);
786
787             // Determine the actual center of the building, by shifting from the
788             // center of the front face to the true center.
789             osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
790                                                  osg::Vec3f(0.0, 0.0, 1.0));
791             SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
792
793             SGVec3f p = buildingCenter - vorigin;
794             float edges[] = { length(cross(p     , p - v0)) / length(v0),
795                               length(cross(p - v0, p - v1)) / length(v1 - v0),
796                               length(cross(p - v1, p     )) / length(v1)      };
797             float edge_dist = *std::min_element(edges, edges + 3);
798
799             if (edge_dist < radius) {
800               triangle_dropped++;
801               continue;
802             }
803
804             // Check building isn't too close to random objects and other buildings.
805             bool close = false;
806             std::vector<std::pair<SGVec3f, float> >::iterator iter;
807
808             for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
809               float min_dist = iter->second + radius;
810               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
811                 close = true;
812                 continue;
813               }
814             }
815
816             if (close) {
817               building_dropped++;
818               continue;
819             }
820
821             for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
822               float min_dist = iter->second + radius;
823               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
824                 close = true;
825                 continue;
826               }
827             }
828
829             if (close) {
830               random_dropped++;
831               continue;
832             }
833
834             std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
835             triangleBuildingList.push_back(pt);
836             bin->insert(randomPoint, rotation, buildingtype);
837           }
838         }
839
840         triangleObjectsList.clear();
841         triangleBuildingList.clear();
842       }
843
844       SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
845       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to mask: " << mask_dropped);
846       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to random object: " << random_dropped);
847       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to other buildings: " << building_dropped);
848     }
849   }
850
851   void computeRandomForest(SGMaterialCache* matcache, float vegetation_density)
852   {
853     SGMaterialTriangleMap::iterator i;
854
855     // generate a repeatable random seed
856     mt seed;
857
858     mt_init(&seed, unsigned(586));
859
860     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
861       SGMaterial *mat = matcache->find(i->first);
862       if (!mat)
863         continue;
864
865       float wood_coverage = mat->get_wood_coverage();
866       if ((wood_coverage <= 0) || (vegetation_density <= 0))
867         continue;
868
869       // Attributes that don't vary by tree but do vary by material
870       bool found = false;
871       TreeBin* bin = NULL;
872
873       BOOST_FOREACH(bin, randomForest)
874       {
875         if ((bin->texture           == mat->get_tree_texture()  ) &&
876             (bin->texture_varieties == mat->get_tree_varieties()) &&
877             (bin->range             == mat->get_tree_range()    ) &&
878             (bin->width             == mat->get_tree_width()    ) &&
879             (bin->height            == mat->get_tree_height()   )   ) {
880             found = true;
881             break;
882         }
883       }
884
885       if (!found) {
886         bin = new TreeBin();
887         bin->texture = mat->get_tree_texture();
888           SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
889         bin->range   = mat->get_tree_range();
890         bin->width   = mat->get_tree_width();
891         bin->height  = mat->get_tree_height();
892         bin->texture_varieties = mat->get_tree_varieties();
893         randomForest.push_back(bin);
894       }
895
896       std::vector<SGVec3f> randomPoints;
897       i->second.addRandomTreePoints(wood_coverage,
898                                     mat->get_object_mask(i->second),
899                                     vegetation_density,
900                                     mat->get_cos_tree_max_density_slope_angle(),
901                                     mat->get_cos_tree_zero_density_slope_angle(),
902                                     randomPoints);
903
904       std::vector<SGVec3f>::iterator k;
905       for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
906         bin->insert(*k);
907       }
908     }
909   }
910
911   bool insertBinObj(const SGBinObject& obj, SGMaterialCache* matcache)
912   {
913     if (!insertPtGeometry(obj, matcache))
914       return false;
915     if (!insertSurfaceGeometry(obj, matcache))
916       return false;
917     return true;
918   }
919 };
920
921 typedef std::pair<osg::Node*, int> ModelLOD;
922 struct MakeQuadLeaf {
923     osg::LOD* operator() () const { return new osg::LOD; }
924 };
925 struct AddModelLOD {
926     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
927     {
928         leaf->addChild(mlod.first, 0, mlod.second);
929     }
930 };
931 struct GetModelLODCoord {
932     GetModelLODCoord() {}
933     GetModelLODCoord(const GetModelLODCoord& rhs)
934     {}
935     osg::Vec3 operator() (const ModelLOD& mlod) const
936     {
937         return mlod.first->getBound().center();
938     }
939 };
940
941 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
942                         GetModelLODCoord>  RandomObjectsQuadtree;
943
944 class RandomObjectCallback : public OptionsReadFileCallback {
945 public:
946     virtual osgDB::ReaderWriter::ReadResult
947     readNode(const std::string&, const osgDB::Options*)
948     {
949         osg::ref_ptr<osg::Group> group = new osg::Group;
950         group->setName("Random Object and Lighting Group");
951         group->setDataVariance(osg::Object::STATIC);
952
953         osg::Node* node = loadTerrain();
954         if (node)
955           group->addChild(node);
956
957         osg::LOD* lightLOD = generateLightingTileObjects();
958         if (lightLOD)
959           group->addChild(lightLOD);
960
961         osg::LOD* objectLOD = generateRandomTileObjects();
962         if (objectLOD)
963           group->addChild(objectLOD);
964
965         return group.release();
966     }
967
968     // Load terrain if required
969     osg::Node* loadTerrain()
970     {
971       if (! _loadterrain)
972         return NULL;
973
974       SGBinObject tile;
975       if (!tile.read_bin(_path))
976         return NULL;
977
978       SGMaterialLibPtr matlib;
979       SGMaterialCache* matcache = 0;
980       bool useVBOs = false;
981       bool simplifyNear    = false;
982       double ratio       = SG_SIMPLIFIER_RATIO;
983       double maxLength   = SG_SIMPLIFIER_MAX_LENGTH;
984       double maxError    = SG_SIMPLIFIER_MAX_ERROR;
985
986       if (_options) {
987         matlib = _options->getMaterialLib();
988         useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
989         SGPropertyNode* propertyNode = _options->getPropertyNode().get();
990         simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
991         ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
992         maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
993         maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
994       }
995
996       // PSADRO TODO : we can do this in terragear 
997       // - why not add a bitmask of flags to the btg so we can precompute this?
998       // and only do it if it hasn't been done already
999       SGVec3d center = tile.get_gbs_center();
1000       SGGeod geodPos = SGGeod::fromCart(center);
1001       SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1002
1003       // Generate a materials cache
1004       if (matlib) matcache = matlib->generateMatCache(geodPos);
1005
1006       // rotate the tiles so that the bounding boxes get nearly axis aligned.
1007       // this will help the collision tree's bounding boxes a bit ...
1008       std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1009       for (unsigned i = 0; i < nodes.size(); ++i)
1010         nodes[i] = hlOr.transform(nodes[i]);
1011       tile.set_wgs84_nodes(nodes);
1012
1013       SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1014       std::vector<SGVec3f> normals = tile.get_normals();
1015       for (unsigned i = 0; i < normals.size(); ++i)
1016         normals[i] = hlOrf.transform(normals[i]);
1017       tile.set_normals(normals);
1018
1019       osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1020
1021       if (!tileGeometryBin->insertBinObj(tile, matcache))
1022         return NULL;
1023
1024       osg::Node* node = tileGeometryBin->getSurfaceGeometry(matcache, useVBOs);
1025       if (node && simplifyNear) {
1026         osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1027         node->accept(simplifier);
1028       }
1029
1030       return node;
1031     }
1032
1033     // Generate all the lighting objects for the tile.
1034     osg::LOD* generateLightingTileObjects()
1035     {
1036       if (_matcache)
1037         _tileGeometryBin->computeRandomSurfaceLights(_matcache);
1038
1039       GroundLightManager* lightManager = GroundLightManager::instance();
1040       osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
1041       SGVec3f up(0, 0, 1);
1042
1043       if (_tileGeometryBin->tileLights.getNumLights() > 0
1044           || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
1045         osg::Group* groundLights0 = new osg::Group;
1046         groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1047         groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1048         osg::Geode* geode = new osg::Geode;
1049         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
1050         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
1051         groundLights0->addChild(geode);
1052         lightGroup->addChild(groundLights0);
1053       }
1054
1055       if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
1056         osg::Group* groundLights1 = new osg::Group;
1057         groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1058         groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1059         osg::Group* groundLights2 = new osg::Group;
1060         groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1061         groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1062         osg::Geode* geode = new osg::Geode;
1063         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
1064         groundLights1->addChild(geode);
1065         lightGroup->addChild(groundLights1);
1066         geode = new osg::Geode;
1067         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
1068         groundLights2->addChild(geode);
1069         lightGroup->addChild(groundLights2);
1070       }
1071
1072       if (!_tileGeometryBin->vasiLights.empty()) {
1073         EffectGeode* vasiGeode = new EffectGeode;
1074         Effect* vasiEffect
1075             = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
1076         vasiGeode->setEffect(vasiEffect);
1077         SGVec4f red(1, 0, 0, 1);
1078         SGMaterial* mat = 0;
1079         if (_matcache)
1080           mat = _matcache->find("RWY_RED_LIGHTS");
1081         if (mat)
1082           red = mat->get_light_color();
1083         SGVec4f white(1, 1, 1, 1);
1084         mat = 0;
1085         if (_matcache)
1086           mat = _matcache->find("RWY_WHITE_LIGHTS");
1087         if (mat)
1088           white = mat->get_light_color();
1089         SGDirectionalLightListBin::const_iterator i;
1090         for (i = _tileGeometryBin->vasiLights.begin();
1091              i != _tileGeometryBin->vasiLights.end(); ++i) {
1092           vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1093         }
1094         vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1095         lightGroup->addChild(vasiGeode);
1096       }
1097
1098       Effect* runwayEffect = 0;
1099       if (_tileGeometryBin->runwayLights.getNumLights() > 0
1100           || !_tileGeometryBin->rabitLights.empty()
1101           || !_tileGeometryBin->reilLights.empty()
1102           || !_tileGeometryBin->odalLights.empty()
1103           || _tileGeometryBin->taxiLights.getNumLights() > 0)
1104           runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true, _options);
1105       if (_tileGeometryBin->runwayLights.getNumLights() > 0
1106           || !_tileGeometryBin->rabitLights.empty()
1107           || !_tileGeometryBin->reilLights.empty()
1108           || !_tileGeometryBin->odalLights.empty()
1109           || !_tileGeometryBin->holdshortLights.empty()
1110           || !_tileGeometryBin->guardLights.empty()) {
1111         osg::Group* rwyLights = new osg::Group;
1112         rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1113         rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1114         if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
1115           EffectGeode* geode = new EffectGeode;
1116           geode->setEffect(runwayEffect);
1117           geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1118           rwyLights->addChild(geode);
1119         }
1120         SGDirectionalLightListBin::const_iterator i;
1121         for (i = _tileGeometryBin->rabitLights.begin();
1122              i != _tileGeometryBin->rabitLights.end(); ++i) {
1123           rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1124         }
1125         for (i = _tileGeometryBin->reilLights.begin();
1126              i != _tileGeometryBin->reilLights.end(); ++i) {
1127           rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1128         }
1129         for (i = _tileGeometryBin->holdshortLights.begin();
1130              i != _tileGeometryBin->holdshortLights.end(); ++i) {
1131           rwyLights->addChild(SGLightFactory::getHoldShort(*i, _options));
1132         }
1133         for (i = _tileGeometryBin->guardLights.begin();
1134              i != _tileGeometryBin->guardLights.end(); ++i) {
1135           rwyLights->addChild(SGLightFactory::getGuard(*i, _options));
1136         }
1137         SGLightListBin::const_iterator j;
1138         for (j = _tileGeometryBin->odalLights.begin();
1139              j != _tileGeometryBin->odalLights.end(); ++j) {
1140           rwyLights->addChild(SGLightFactory::getOdal(*j, _options));
1141         }
1142         lightGroup->addChild(rwyLights);
1143       }
1144
1145       if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1146         osg::Group* taxiLights = new osg::Group;
1147         taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1148         taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1149         EffectGeode* geode = new EffectGeode;
1150         geode->setEffect(runwayEffect);
1151         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1152         taxiLights->addChild(geode);
1153         lightGroup->addChild(taxiLights);
1154       }
1155
1156       osg::LOD* lightLOD = NULL;
1157
1158       if (lightGroup->getNumChildren() > 0) {
1159         lightLOD = new osg::LOD;
1160         lightLOD->addChild(lightGroup.get(), 0, 60000);
1161         // VASI is always on, so doesn't use light bits.
1162         lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1163       }
1164
1165       return lightLOD;
1166     }
1167
1168     // Generate all the random forest, objects and buildings for the tile
1169     osg::LOD* generateRandomTileObjects()
1170     {
1171       SGMaterialLibPtr matlib;
1172       bool use_random_objects = false;
1173       bool use_random_vegetation = false;
1174       bool use_random_buildings = false;
1175       float vegetation_density = 1.0f;
1176       float building_density = 1.0f;
1177       bool useVBOs = false;
1178       
1179       osg::ref_ptr<osg::Group> randomObjects;
1180       osg::ref_ptr<osg::Group> forestNode;
1181       osg::ref_ptr<osg::Group> buildingNode;
1182
1183       if (_options) {
1184         matlib = _options->getMaterialLib();
1185         SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1186         if (propertyNode) {
1187             use_random_objects
1188                 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1189                                              use_random_objects);
1190             use_random_vegetation
1191                 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1192                                              use_random_vegetation);
1193             vegetation_density
1194                 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1195                                               vegetation_density);
1196             use_random_buildings
1197                 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1198                                              use_random_buildings);
1199             building_density
1200                 = propertyNode->getFloatValue("/sim/rendering/building-density",
1201                                               building_density);
1202         }
1203         
1204         useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1205       }
1206
1207
1208
1209       if (matlib && (use_random_objects || use_random_buildings)) {
1210         _tileGeometryBin->computeRandomObjectsAndBuildings(_matcache,
1211                                                          building_density,
1212                                                          use_random_objects,
1213                                                          use_random_buildings,
1214                                                          useVBOs);
1215       }
1216
1217
1218       if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1219         // Generate a repeatable random seed
1220         mt seed;
1221         mt_init(&seed, unsigned(123));
1222
1223         std::vector<ModelLOD> models;
1224         for (unsigned int i = 0;
1225              i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1226           SGMatModelBin::MatModel obj
1227             = _tileGeometryBin->randomModels.getMatModel(i);
1228
1229           SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1230           osg::Node* node = obj.model->get_random_model(root, &seed);
1231
1232           // Create a matrix to place the object in the correct
1233           // location, and then apply the rotation matrix created
1234           // above, with an additional random (or taken from
1235           // the object mask) heading rotation if appropriate.
1236           osg::Matrix transformMat;
1237           transformMat = osg::Matrix::translate(toOsg(obj.position));
1238           if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1239             // Rotate the object around the z axis.
1240             double hdg = mt_rand(&seed) * M_PI * 2;
1241             transformMat.preMult(osg::Matrix::rotate(hdg,
1242                                                      osg::Vec3d(0.0, 0.0, 1.0)));
1243           }
1244
1245           if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1246             // Rotate the object around the z axis.
1247             double hdg =  - obj.rotation * M_PI * 2;
1248             transformMat.preMult(osg::Matrix::rotate(hdg,
1249                                                      osg::Vec3d(0.0, 0.0, 1.0)));
1250           }
1251
1252           osg::MatrixTransform* position =
1253             new osg::MatrixTransform(transformMat);
1254           position->setName("positionRandomModel");
1255           position->addChild(node);
1256           models.push_back(ModelLOD(position, obj.lod));
1257         }
1258         RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1259         quadtree.buildQuadTree(models.begin(), models.end());
1260         randomObjects = quadtree.getRoot();
1261         randomObjects->setName("Random objects");
1262       }
1263
1264       if (! _tileGeometryBin->randomBuildings.empty()) {
1265         buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1266                                     _options);
1267         buildingNode->setName("Random buildings");
1268         _tileGeometryBin->randomBuildings.clear();
1269       }
1270
1271       if (use_random_vegetation && matlib) {
1272         // Now add some random forest.
1273         _tileGeometryBin->computeRandomForest(_matcache, vegetation_density);
1274
1275         if (! _tileGeometryBin->randomForest.empty()) {
1276           forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1277                                     _options);
1278           forestNode->setName("Random trees");
1279         }
1280       }
1281
1282       osg::LOD* objectLOD = NULL;
1283
1284       if (randomObjects.valid() ||  forestNode.valid() || buildingNode.valid()) {
1285         objectLOD = new osg::LOD;
1286
1287         if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1288         if (forestNode.valid())  objectLOD->addChild(forestNode.get(), 0, 20000);
1289         if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1290
1291         unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1292         objectLOD->setNodeMask(nodeMask);
1293       }
1294
1295       return objectLOD;
1296     }
1297
1298     /// The original options to use for this bunch of models
1299     osg::ref_ptr<SGReaderWriterOptions> _options;
1300     osg::ref_ptr<SGMaterialCache> _matcache;
1301     osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1302     string _path;
1303     bool _loadterrain;
1304 };
1305
1306 osg::Node*
1307 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1308 {
1309     SGBinObject tile;
1310     if (!tile.read_bin(path))
1311       return NULL;
1312
1313     SGMaterialLibPtr matlib;
1314     osg::ref_ptr<SGMaterialCache> matcache;
1315     bool useVBOs = false;
1316     bool simplifyDistant = false;
1317     bool simplifyNear    = false;
1318     double ratio       = SG_SIMPLIFIER_RATIO;
1319     double maxLength   = SG_SIMPLIFIER_MAX_LENGTH;
1320     double maxError    = SG_SIMPLIFIER_MAX_ERROR;
1321     double object_range = SG_OBJECT_RANGE;
1322
1323     if (options) {
1324       matlib = options->getMaterialLib();
1325       useVBOs = (options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1326       SGPropertyNode* propertyNode = options->getPropertyNode().get();
1327
1328       // We control whether we simplify the nearby terrain and distant terrain separatey.
1329       // However, we don't allow only simplifying the near terrain!
1330       simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
1331       simplifyDistant = simplifyNear || propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-far", simplifyDistant);
1332       ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
1333       maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
1334       maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
1335                         object_range = propertyNode->getDoubleValue("/sim/rendering/static-lod/rough", object_range);
1336     }
1337
1338     SGVec3d center = tile.get_gbs_center();
1339     SGGeod geodPos = SGGeod::fromCart(center);
1340     SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1341     if (matlib)
1342         matcache = matlib->generateMatCache(geodPos);
1343
1344     // rotate the tiles so that the bounding boxes get nearly axis aligned.
1345     // this will help the collision tree's bounding boxes a bit ...
1346     std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1347     for (unsigned i = 0; i < nodes.size(); ++i)
1348       nodes[i] = hlOr.transform(nodes[i]);
1349     tile.set_wgs84_nodes(nodes);
1350
1351     SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1352     std::vector<SGVec3f> normals = tile.get_normals();
1353     for (unsigned i = 0; i < normals.size(); ++i)
1354       normals[i] = hlOrf.transform(normals[i]);
1355     tile.set_normals(normals);
1356
1357     osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1358
1359     if (!tileGeometryBin->insertBinObj(tile, matcache))
1360       return NULL;
1361
1362     osg::Node* node = tileGeometryBin->getSurfaceGeometry(matcache, useVBOs);
1363     if (node && simplifyDistant) {
1364       osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1365       node->accept(simplifier);
1366     }
1367
1368     // The toplevel transform for that tile.
1369     osg::MatrixTransform* transform = new osg::MatrixTransform;
1370     transform->setName(path);
1371     transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1372                          osg::Matrix::translate(toOsg(center)));
1373
1374     // PagedLOD for the random objects so we don't need to generate
1375     // them all on tile loading.
1376     osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1377     pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1378     pagedLOD->setName("pagedObjectLOD");
1379
1380     if (node) {
1381       if (simplifyNear == simplifyDistant) {
1382         // Same terrain type is used for both near and far distances,
1383         // so add it to the main group.
1384         osg::Group* terrainGroup = new osg::Group;
1385         terrainGroup->setName("BTGTerrainGroup");
1386         terrainGroup->addChild(node);
1387         transform->addChild(terrainGroup);
1388       } else if (simplifyDistant) {
1389         // Simplified terrain is only used in the distance, the
1390         // call-back below will re-generate the closer version
1391         pagedLOD->addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
1392       }
1393     }
1394
1395     // we just need to know about the read file callback that itself holds the data
1396     osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1397     randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1398     randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1399     randomObjectCallback->_path = std::string(path);
1400     randomObjectCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
1401     randomObjectCallback->_matcache = matcache;
1402
1403     osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1404     callbackOptions->setReadFileCallback(randomObjectCallback.get());
1405     pagedLOD->setDatabaseOptions(callbackOptions.get());
1406
1407     pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1408     pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
1409     transform->addChild(pagedLOD);
1410     transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
1411
1412     return transform;
1413 }