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