]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
VBO switch also controls random-buildings.
[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     bool useVBOs)
485   {
486     SGMaterialTriangleMap::iterator i;
487
488     // generate a repeatable random seed
489     mt seed;
490     mt_init(&seed, unsigned(123));
491
492     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
493       SGMaterial *mat = matlib->findCached(i->first);
494       SGTexturedTriangleBin triangleBin = i->second;
495
496       if (!mat)
497         continue;
498
499       osg::Texture2D* object_mask  = mat->get_object_mask(triangleBin);
500
501       int   group_count            = mat->get_object_group_count();
502       float building_coverage      = mat->get_building_coverage();
503       float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
504       float cos_max_density_angle  = mat->get_cos_object_max_density_slope_angle();
505
506       if (building_coverage == 0)
507          continue;
508
509       SGBuildingBin* bin = NULL;
510
511       if (building_coverage > 0) {
512         bin = new SGBuildingBin(mat, useVBOs);
513         randomBuildings.push_back(bin);
514       }
515
516       unsigned num = i->second.getNumTriangles();
517       int random_dropped = 0;
518       int mask_dropped = 0;
519       int building_dropped = 0;
520       int triangle_dropped = 0;
521
522       for (unsigned i = 0; i < num; ++i) {
523         SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
524
525         SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
526         SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
527         SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
528         SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
529         SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
530         SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
531         SGVec3f normal = cross(v0, v1);
532
533         // Ensure the slope isn't too steep by checking the
534         // cos of the angle between the slope normal and the
535         // vertical (conveniently the z-component of the normalized
536         // normal) and values passed in.
537         float cos = normalize(normal).z();
538         float slope_density = 1.0;
539         if (cos < cos_zero_density_angle) continue; // Too steep for any objects
540         if (cos < cos_max_density_angle) {
541           slope_density =
542             (cos - cos_zero_density_angle) /
543             (cos_max_density_angle - cos_zero_density_angle);
544         }
545
546         // Containers to hold the random buildings and objects generated
547         // for this triangle for collision detection purposes.
548         std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
549         std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
550
551         // Compute the area
552         float area = 0.5f*length(normal);
553         if (area <= SGLimitsf::min())
554           continue;
555
556         // Generate any random objects
557         if (use_random_objects && (group_count > 0))
558         {
559           for (int j = 0; j < group_count; j++)
560           {
561             SGMatModelGroup *object_group =  mat->get_object_group(j);
562             int nObjects = object_group->get_object_count();
563
564             if (nObjects == 0) continue;
565
566             // For each of the random models in the group, determine an appropriate
567             // number of random placements and insert them.
568             for (int k = 0; k < nObjects; k++) {
569               SGMatModel * object = object_group->get_object(k);
570
571               // Determine the number of objecst to place, taking into account
572               // the slope density factor.
573               double n = slope_density * area / object->get_coverage_m2();
574
575               // Use the zombie door method to determine fractional object placement.
576               n = n + mt_rand(&seed);
577
578               // place an object each unit of area
579               while ( n > 1.0 ) {
580                 float a = mt_rand(&seed);
581                 float b = mt_rand(&seed);
582                 if ( a + b > 1 ) {
583                   a = 1 - a;
584                   b = 1 - b;
585                 }
586
587                 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
588                 float rotation = static_cast<float>(mt_rand(&seed));
589
590                 // Check that the point is sufficiently far from
591                 // the edge of the triangle by measuring the distance
592                 // from the three lines that make up the triangle.
593                 float spacing = object->get_spacing_m();
594
595                 SGVec3f p = randomPoint - vorigin;
596                 float edges[] = { length(cross(p     , p - v0)) / length(v0),
597                                   length(cross(p - v0, p - v1)) / length(v1 - v0),
598                                   length(cross(p - v1, p     )) / length(v1)      };
599                 float edge_dist = *std::min_element(edges, edges + 3);
600
601                 if (edge_dist < spacing) {
602                   n -= 1.0;
603                   continue;
604                 }
605
606                 if (object_mask != NULL) {
607                   SGVec2f texCoord = torigin + a*t0 + b*t1;
608
609                   // Check this random point against the object mask
610                   // blue (for buildings) channel.
611                   osg::Image* img = object_mask->getImage();
612                   unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
613                   unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
614
615                   if (mt_rand(&seed) > img->getColor(x, y).b()) {
616                     // Failed object mask check
617                     n -= 1.0;
618                     continue;
619                   }
620
621                   rotation = img->getColor(x,y).r();
622                 }
623
624                 bool close = false;
625
626                 // Check it isn't too close to any other random objects in the triangle
627                 std::vector<std::pair<SGVec3f, float> >::iterator l;
628                 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
629                   float min_dist2 = (l->second + object->get_spacing_m()) *
630                                     (l->second + object->get_spacing_m());
631
632                   if (distSqr(l->first, randomPoint) > min_dist2) {
633                     close = true;
634                     continue;
635                   }
636                 }
637
638                 if (!close) {
639                     triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
640                     randomModels.insert(randomPoint,
641                                         object,
642                                         (int)object->get_randomized_range_m(&seed),
643                                         rotation);
644                 }
645               }
646             }
647           }
648         }
649
650         // Random objects now generated.  Now generate the random buildings (if any);
651         if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
652
653           // Calculate the number of buildings, taking into account building density (which is linear)
654           // and the slope density factor.
655           double num = building_density * building_density * slope_density * area / building_coverage;
656
657           // For partial units of area, use a zombie door method to
658           // create the proper random chance of an object being created
659           // for this triangle.
660           num = num + mt_rand(&seed);
661
662           if (num < 1.0f) {
663             continue;
664           }
665
666           // Cosine of the angle between the two vectors.
667           float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
668
669           // Determine a grid spacing in each vector such that the correct
670           // coverage will result.
671           float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
672           float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
673
674           stepv0 = std::min(stepv0, 1.0f);
675           stepv1 = std::min(stepv1, 1.0f);
676
677           // Start at a random point. a will be immediately incremented below.
678           float a = -mt_rand(&seed) * stepv0;
679           float b = mt_rand(&seed) * stepv1;
680
681           // Place an object each unit of area
682           while (num > 1.0) {
683             num -= 1.0;
684
685             // Set the next location to place a building
686             a += stepv0;
687
688             if ((a + b) > 1.0f) {
689               // Reached the end of the scan-line on v0. Reset and increment
690               // scan-line on v1
691               a = mt_rand(&seed) * stepv0;
692               b += stepv1;
693             }
694
695             if (b > 1.0f) {
696               // In a degenerate case of a single point, we might be outside the
697               // scanline.  Note that we need to still ensure that a+b < 1.
698               b = mt_rand(&seed) * stepv1 * (1.0f - a);
699             }
700
701             if ((a + b) > 1.0f ) {
702               // Truly degenerate case - simply choose a random point guaranteed
703               // to fulfil the constraing of a+b < 1.
704               a = mt_rand(&seed);
705               b = mt_rand(&seed) * (1.0f - a);
706             }
707
708             SGVec3f randomPoint = vorigin + a*v0 + b*v1;
709             float rotation = mt_rand(&seed);
710
711             if (object_mask != NULL) {
712               SGVec2f texCoord = torigin + a*t0 + b*t1;
713               osg::Image* img = object_mask->getImage();
714               int x = (int) (img->s() * texCoord.x()) % img->s();
715               int y = (int) (img->t() * texCoord.y()) % img->t();
716
717               // In some degenerate cases x or y can be < 1, in which case the mod operand fails
718               while (x < 0) x += img->s();
719               while (y < 0) y += img->t();
720
721               if (mt_rand(&seed) < img->getColor(x, y).b()) {
722                 // Object passes mask. Rotation is taken from the red channel
723                 rotation = img->getColor(x,y).r();
724               } else {
725                 // Fails mask test - try again.
726                 mask_dropped++;
727                 continue;
728               }
729             }
730
731             // Check building isn't too close to the triangle edge.
732             float type_roll = mt_rand(&seed);
733             SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
734             float radius = bin->getBuildingMaxRadius(buildingtype);
735
736             // Determine the actual center of the building, by shifting from the
737             // center of the front face to the true center.
738             osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
739                                                  osg::Vec3f(0.0, 0.0, 1.0));
740             SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
741
742             SGVec3f p = buildingCenter - vorigin;
743             float edges[] = { length(cross(p     , p - v0)) / length(v0),
744                               length(cross(p - v0, p - v1)) / length(v1 - v0),
745                               length(cross(p - v1, p     )) / length(v1)      };
746             float edge_dist = *std::min_element(edges, edges + 3);
747
748             if (edge_dist < radius) {
749               triangle_dropped++;
750               continue;
751             }
752
753             // Check building isn't too close to random objects and other buildings.
754             bool close = false;
755             std::vector<std::pair<SGVec3f, float> >::iterator iter;
756
757             for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
758               float min_dist = iter->second + radius;
759               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
760                 close = true;
761                 continue;
762               }
763             }
764
765             if (close) {
766               building_dropped++;
767               continue;
768             }
769
770             for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
771               float min_dist = iter->second + radius;
772               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
773                 close = true;
774                 continue;
775               }
776             }
777
778             if (close) {
779               random_dropped++;
780               continue;
781             }
782
783             std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
784             triangleBuildingList.push_back(pt);
785             bin->insert(randomPoint, rotation, buildingtype);
786           }
787         }
788
789         triangleObjectsList.clear();
790         triangleBuildingList.clear();
791       }
792
793       SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
794       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to mask: " << mask_dropped);
795       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to random object: " << random_dropped);
796       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to other buildings: " << building_dropped);
797     }
798   }
799
800   void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
801   {
802     SGMaterialTriangleMap::iterator i;
803
804     // generate a repeatable random seed
805     mt seed;
806
807     mt_init(&seed, unsigned(586));
808
809     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
810       SGMaterial *mat = matlib->findCached(i->first);
811       if (!mat)
812         continue;
813
814       float wood_coverage = mat->get_wood_coverage();
815       if ((wood_coverage <= 0) || (vegetation_density <= 0))
816         continue;
817
818       // Attributes that don't vary by tree but do vary by material
819       bool found = false;
820       TreeBin* bin = NULL;
821
822       BOOST_FOREACH(bin, randomForest)
823       {
824         if ((bin->texture           == mat->get_tree_texture()  ) &&
825             (bin->texture_varieties == mat->get_tree_varieties()) &&
826             (bin->range             == mat->get_tree_range()    ) &&
827             (bin->width             == mat->get_tree_width()    ) &&
828             (bin->height            == mat->get_tree_height()   )   ) {
829             found = true;
830             break;
831         }
832       }
833
834       if (!found) {
835         bin = new TreeBin();
836         bin->texture = mat->get_tree_texture();
837           SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
838         bin->range   = mat->get_tree_range();
839         bin->width   = mat->get_tree_width();
840         bin->height  = mat->get_tree_height();
841         bin->texture_varieties = mat->get_tree_varieties();
842         randomForest.push_back(bin);
843       }
844
845       std::vector<SGVec3f> randomPoints;
846       i->second.addRandomTreePoints(wood_coverage,
847                                     mat->get_object_mask(i->second),
848                                     vegetation_density,
849                                     mat->get_cos_tree_max_density_slope_angle(),
850                                     mat->get_cos_tree_zero_density_slope_angle(),
851                                     randomPoints);
852
853       std::vector<SGVec3f>::iterator k;
854       for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
855         bin->insert(*k);
856       }
857     }
858   }
859
860   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
861   {
862     if (!insertPtGeometry(obj, matlib))
863       return false;
864     if (!insertSurfaceGeometry(obj, matlib))
865       return false;
866     return true;
867   }
868 };
869
870 typedef std::pair<osg::Node*, int> ModelLOD;
871 struct MakeQuadLeaf {
872     osg::LOD* operator() () const { return new osg::LOD; }
873 };
874 struct AddModelLOD {
875     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
876     {
877         leaf->addChild(mlod.first, 0, mlod.second);
878     }
879 };
880 struct GetModelLODCoord {
881     GetModelLODCoord() {}
882     GetModelLODCoord(const GetModelLODCoord& rhs)
883     {}
884     osg::Vec3 operator() (const ModelLOD& mlod) const
885     {
886         return mlod.first->getBound().center();
887     }
888 };
889
890 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
891                         GetModelLODCoord>  RandomObjectsQuadtree;
892
893 class RandomObjectCallback : public OptionsReadFileCallback {
894 public:
895     virtual osgDB::ReaderWriter::ReadResult
896     readNode(const std::string&, const osgDB::Options*)
897     {
898         osg::ref_ptr<osg::Group> group = new osg::Group;
899         group->setName("Random Object and Lighting Group");
900         group->setDataVariance(osg::Object::STATIC);
901
902         osg::Node* node = loadTerrain();
903         if (node)
904           group->addChild(node);
905
906         osg::LOD* lightLOD = generateLightingTileObjects();
907         if (lightLOD)
908           group->addChild(lightLOD);
909
910         osg::LOD* objectLOD = generateRandomTileObjects();
911         if (objectLOD)
912           group->addChild(objectLOD);
913
914         return group.release();
915     }
916
917     // Load terrain if required
918     osg::Node* loadTerrain()
919     {
920       if (! _loadterrain)
921         return NULL;
922
923       SGBinObject tile;
924       if (!tile.read_bin(_path))
925         return NULL;
926
927       SGMaterialLibPtr matlib;
928       bool useVBOs = false;
929       bool simplifyNear    = false;
930       double ratio       = SG_SIMPLIFIER_RATIO;
931       double maxLength   = SG_SIMPLIFIER_MAX_LENGTH;
932       double maxError    = SG_SIMPLIFIER_MAX_ERROR;
933
934       if (_options) {
935         matlib = _options->getMaterialLib();
936         useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
937         SGPropertyNode* propertyNode = _options->getPropertyNode().get();
938         simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
939         ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
940         maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
941         maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
942       }
943
944       SGVec3d center = tile.get_gbs_center();
945       SGGeod geodPos = SGGeod::fromCart(center);
946       SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
947
948       // rotate the tiles so that the bounding boxes get nearly axis aligned.
949       // this will help the collision tree's bounding boxes a bit ...
950       std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
951       for (unsigned i = 0; i < nodes.size(); ++i)
952         nodes[i] = hlOr.transform(nodes[i]);
953       tile.set_wgs84_nodes(nodes);
954
955       SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
956       std::vector<SGVec3f> normals = tile.get_normals();
957       for (unsigned i = 0; i < normals.size(); ++i)
958         normals[i] = hlOrf.transform(normals[i]);
959       tile.set_normals(normals);
960
961       osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
962
963       if (!tileGeometryBin->insertBinObj(tile, matlib))
964         return NULL;
965
966       osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
967       if (node && simplifyNear) {
968         osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
969         node->accept(simplifier);
970       }
971
972       return node;
973     }
974
975     // Generate all the lighting objects for the tile.
976     osg::LOD* generateLightingTileObjects()
977     {
978       SGMaterialLibPtr matlib;
979
980       if (_options)
981         matlib = _options->getMaterialLib();
982
983       // FIXME: ugly, has a side effect
984       if (matlib)
985         _tileGeometryBin->computeRandomSurfaceLights(matlib);
986
987       GroundLightManager* lightManager = GroundLightManager::instance();
988       osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
989       SGVec3f up(0, 0, 1);
990
991       if (_tileGeometryBin->tileLights.getNumLights() > 0
992           || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
993         osg::Group* groundLights0 = new osg::Group;
994         groundLights0->setStateSet(lightManager->getGroundLightStateSet());
995         groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
996         osg::Geode* geode = new osg::Geode;
997         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
998         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
999         groundLights0->addChild(geode);
1000         lightGroup->addChild(groundLights0);
1001       }
1002
1003       if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
1004         osg::Group* groundLights1 = new osg::Group;
1005         groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1006         groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1007         osg::Group* groundLights2 = new osg::Group;
1008         groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1009         groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1010         osg::Geode* geode = new osg::Geode;
1011         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
1012         groundLights1->addChild(geode);
1013         lightGroup->addChild(groundLights1);
1014         geode = new osg::Geode;
1015         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
1016         groundLights2->addChild(geode);
1017         lightGroup->addChild(groundLights2);
1018       }
1019
1020       if (!_tileGeometryBin->vasiLights.empty()) {
1021         EffectGeode* vasiGeode = new EffectGeode;
1022         Effect* vasiEffect
1023             = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
1024         vasiGeode->setEffect(vasiEffect);
1025         SGVec4f red(1, 0, 0, 1);
1026         SGMaterial* mat = 0;
1027         if (matlib)
1028           mat = matlib->findCached("RWY_RED_LIGHTS");
1029         if (mat)
1030           red = mat->get_light_color();
1031         SGVec4f white(1, 1, 1, 1);
1032         mat = 0;
1033         if (matlib)
1034           mat = matlib->findCached("RWY_WHITE_LIGHTS");
1035         if (mat)
1036           white = mat->get_light_color();
1037         SGDirectionalLightListBin::const_iterator i;
1038         for (i = _tileGeometryBin->vasiLights.begin();
1039              i != _tileGeometryBin->vasiLights.end(); ++i) {
1040           vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1041         }
1042         vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1043         lightGroup->addChild(vasiGeode);
1044       }
1045
1046       Effect* runwayEffect = 0;
1047       if (_tileGeometryBin->runwayLights.getNumLights() > 0
1048           || !_tileGeometryBin->rabitLights.empty()
1049           || !_tileGeometryBin->reilLights.empty()
1050           || !_tileGeometryBin->odalLights.empty()
1051           || _tileGeometryBin->taxiLights.getNumLights() > 0)
1052           runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true, _options);
1053       if (_tileGeometryBin->runwayLights.getNumLights() > 0
1054           || !_tileGeometryBin->rabitLights.empty()
1055           || !_tileGeometryBin->reilLights.empty()
1056           || !_tileGeometryBin->odalLights.empty()
1057           || !_tileGeometryBin->holdshortLights.empty()
1058           || !_tileGeometryBin->guardLights.empty()) {
1059         osg::Group* rwyLights = new osg::Group;
1060         rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1061         rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1062         if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
1063           EffectGeode* geode = new EffectGeode;
1064           geode->setEffect(runwayEffect);
1065           geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1066           rwyLights->addChild(geode);
1067         }
1068         SGDirectionalLightListBin::const_iterator i;
1069         for (i = _tileGeometryBin->rabitLights.begin();
1070              i != _tileGeometryBin->rabitLights.end(); ++i) {
1071           rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1072         }
1073         for (i = _tileGeometryBin->reilLights.begin();
1074              i != _tileGeometryBin->reilLights.end(); ++i) {
1075           rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1076         }
1077         for (i = _tileGeometryBin->holdshortLights.begin();
1078              i != _tileGeometryBin->holdshortLights.end(); ++i) {
1079           rwyLights->addChild(SGLightFactory::getHoldShort(*i, _options));
1080         }
1081         for (i = _tileGeometryBin->guardLights.begin();
1082              i != _tileGeometryBin->guardLights.end(); ++i) {
1083           rwyLights->addChild(SGLightFactory::getGuard(*i, _options));
1084         }
1085         SGLightListBin::const_iterator j;
1086         for (j = _tileGeometryBin->odalLights.begin();
1087              j != _tileGeometryBin->odalLights.end(); ++j) {
1088           rwyLights->addChild(SGLightFactory::getOdal(*j, _options));
1089         }
1090         lightGroup->addChild(rwyLights);
1091       }
1092
1093       if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1094         osg::Group* taxiLights = new osg::Group;
1095         taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1096         taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1097         EffectGeode* geode = new EffectGeode;
1098         geode->setEffect(runwayEffect);
1099         geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1100         taxiLights->addChild(geode);
1101         lightGroup->addChild(taxiLights);
1102       }
1103
1104       osg::LOD* lightLOD = NULL;
1105
1106       if (lightGroup->getNumChildren() > 0) {
1107         lightLOD = new osg::LOD;
1108         lightLOD->addChild(lightGroup.get(), 0, 60000);
1109         // VASI is always on, so doesn't use light bits.
1110         lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1111       }
1112
1113       return lightLOD;
1114     }
1115
1116     // Generate all the random forest, objects and buildings for the tile
1117     osg::LOD* generateRandomTileObjects()
1118     {
1119       SGMaterialLibPtr matlib;
1120       bool use_random_objects = false;
1121       bool use_random_vegetation = false;
1122       bool use_random_buildings = false;
1123       float vegetation_density = 1.0f;
1124       float building_density = 1.0f;
1125       bool useVBOs = false;
1126       
1127       osg::ref_ptr<osg::Group> randomObjects;
1128       osg::ref_ptr<osg::Group> forestNode;
1129       osg::ref_ptr<osg::Group> buildingNode;
1130
1131       if (_options) {
1132         matlib = _options->getMaterialLib();
1133         SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1134         if (propertyNode) {
1135             use_random_objects
1136                 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1137                                              use_random_objects);
1138             use_random_vegetation
1139                 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1140                                              use_random_vegetation);
1141             vegetation_density
1142                 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1143                                               vegetation_density);
1144             use_random_buildings
1145                 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1146                                              use_random_buildings);
1147             building_density
1148                 = propertyNode->getFloatValue("/sim/rendering/building-density",
1149                                               building_density);
1150         }
1151         
1152         useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1153       }
1154
1155
1156
1157       if (matlib && (use_random_objects || use_random_buildings)) {
1158         _tileGeometryBin->computeRandomObjectsAndBuildings(matlib,
1159                                                          building_density,
1160                                                          use_random_objects,
1161                                                          use_random_buildings,
1162                                                          useVBOs);
1163       }
1164
1165
1166       if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1167         // Generate a repeatable random seed
1168         mt seed;
1169         mt_init(&seed, unsigned(123));
1170
1171         std::vector<ModelLOD> models;
1172         for (unsigned int i = 0;
1173              i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1174           SGMatModelBin::MatModel obj
1175             = _tileGeometryBin->randomModels.getMatModel(i);
1176
1177           SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1178           osg::Node* node = obj.model->get_random_model(root, &seed);
1179
1180           // Create a matrix to place the object in the correct
1181           // location, and then apply the rotation matrix created
1182           // above, with an additional random (or taken from
1183           // the object mask) heading rotation if appropriate.
1184           osg::Matrix transformMat;
1185           transformMat = osg::Matrix::translate(toOsg(obj.position));
1186           if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1187             // Rotate the object around the z axis.
1188             double hdg = mt_rand(&seed) * M_PI * 2;
1189             transformMat.preMult(osg::Matrix::rotate(hdg,
1190                                                      osg::Vec3d(0.0, 0.0, 1.0)));
1191           }
1192
1193           if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1194             // Rotate the object around the z axis.
1195             double hdg =  - obj.rotation * M_PI * 2;
1196             transformMat.preMult(osg::Matrix::rotate(hdg,
1197                                                      osg::Vec3d(0.0, 0.0, 1.0)));
1198           }
1199
1200           osg::MatrixTransform* position =
1201             new osg::MatrixTransform(transformMat);
1202           position->setName("positionRandomModel");
1203           position->addChild(node);
1204           models.push_back(ModelLOD(position, obj.lod));
1205         }
1206         RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1207         quadtree.buildQuadTree(models.begin(), models.end());
1208         randomObjects = quadtree.getRoot();
1209         randomObjects->setName("Random objects");
1210       }
1211
1212       if (! _tileGeometryBin->randomBuildings.empty()) {
1213         buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1214                                     _options);
1215         buildingNode->setName("Random buildings");
1216         _tileGeometryBin->randomBuildings.clear();
1217       }
1218
1219       if (use_random_vegetation && matlib) {
1220         // Now add some random forest.
1221         _tileGeometryBin->computeRandomForest(matlib, vegetation_density);
1222
1223         if (! _tileGeometryBin->randomForest.empty()) {
1224           forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1225                                     _options);
1226           forestNode->setName("Random trees");
1227         }
1228       }
1229
1230       osg::LOD* objectLOD = NULL;
1231
1232       if (randomObjects.valid() ||  forestNode.valid() || buildingNode.valid()) {
1233         objectLOD = new osg::LOD;
1234
1235         if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1236         if (forestNode.valid())  objectLOD->addChild(forestNode.get(), 0, 20000);
1237         if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1238
1239         unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1240         objectLOD->setNodeMask(nodeMask);
1241       }
1242
1243       return objectLOD;
1244     }
1245
1246     /// The original options to use for this bunch of models
1247     osg::ref_ptr<SGReaderWriterOptions> _options;
1248     osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1249     string _path;
1250     bool _loadterrain;
1251 };
1252
1253 osg::Node*
1254 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1255 {
1256     SGBinObject tile;
1257     if (!tile.read_bin(path))
1258       return NULL;
1259
1260     SGMaterialLibPtr matlib;
1261     bool useVBOs = false;
1262     bool simplifyDistant = false;
1263     bool simplifyNear    = false;
1264     double ratio       = SG_SIMPLIFIER_RATIO;
1265     double maxLength   = SG_SIMPLIFIER_MAX_LENGTH;
1266     double maxError    = SG_SIMPLIFIER_MAX_ERROR;
1267     double object_range = SG_OBJECT_RANGE;
1268
1269     if (options) {
1270       matlib = options->getMaterialLib();
1271       useVBOs = (options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1272       SGPropertyNode* propertyNode = options->getPropertyNode().get();
1273
1274       // We control whether we simplify the nearby terrain and distant terrain separatey.
1275       // However, we don't allow only simplifying the near terrain!
1276       simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
1277       simplifyDistant = simplifyNear || propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-far", simplifyDistant);
1278       ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
1279       maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
1280       maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
1281                         object_range = propertyNode->getDoubleValue("/sim/rendering/static-lod/rough", object_range);
1282     }
1283
1284     SGVec3d center = tile.get_gbs_center();
1285     SGGeod geodPos = SGGeod::fromCart(center);
1286     SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1287
1288     // rotate the tiles so that the bounding boxes get nearly axis aligned.
1289     // this will help the collision tree's bounding boxes a bit ...
1290     std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1291     for (unsigned i = 0; i < nodes.size(); ++i)
1292       nodes[i] = hlOr.transform(nodes[i]);
1293     tile.set_wgs84_nodes(nodes);
1294
1295     SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1296     std::vector<SGVec3f> normals = tile.get_normals();
1297     for (unsigned i = 0; i < normals.size(); ++i)
1298       normals[i] = hlOrf.transform(normals[i]);
1299     tile.set_normals(normals);
1300
1301     osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1302
1303     if (!tileGeometryBin->insertBinObj(tile, matlib))
1304       return NULL;
1305
1306
1307     osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
1308     if (node && simplifyDistant) {
1309       osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1310       node->accept(simplifier);
1311     }
1312
1313     // The toplevel transform for that tile.
1314     osg::MatrixTransform* transform = new osg::MatrixTransform;
1315     transform->setName(path);
1316     transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1317                          osg::Matrix::translate(toOsg(center)));
1318
1319     // PagedLOD for the random objects so we don't need to generate
1320     // them all on tile loading.
1321     osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1322     pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1323     pagedLOD->setName("pagedObjectLOD");
1324
1325     if (node) {
1326       if (simplifyNear == simplifyDistant) {
1327         // Same terrain type is used for both near and far distances,
1328         // so add it to the main group.
1329         osg::Group* terrainGroup = new osg::Group;
1330         terrainGroup->setName("BTGTerrainGroup");
1331         terrainGroup->addChild(node);
1332         transform->addChild(terrainGroup);
1333       } else if (simplifyDistant) {
1334         // Simplified terrain is only used in the distance, the
1335         // call-back below will re-generate the closer version
1336         pagedLOD->addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
1337       }
1338     }
1339
1340     // we just need to know about the read file callback that itself holds the data
1341     osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1342     randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1343     randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1344     randomObjectCallback->_path = std::string(path);
1345     randomObjectCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
1346
1347     osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1348     callbackOptions->setReadFileCallback(randomObjectCallback.get());
1349     pagedLOD->setDatabaseOptions(callbackOptions.get());
1350
1351     pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1352     pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
1353     transform->addChild(pagedLOD);
1354     transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
1355
1356     return transform;
1357 }