]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
spt: The bucket size case is already handled above.
[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/StateSet>
41 #include <osg/Switch>
42
43 #include <boost/foreach.hpp>
44
45 #include <algorithm>
46
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/io/sg_binobj.hxx>
49 #include <simgear/math/sg_geodesy.hxx>
50 #include <simgear/math/sg_random.h>
51 #include <simgear/math/SGMisc.hxx>
52 #include <simgear/scene/material/Effect.hxx>
53 #include <simgear/scene/material/EffectGeode.hxx>
54 #include <simgear/scene/material/mat.hxx>
55 #include <simgear/scene/material/matmodel.hxx>
56 #include <simgear/scene/material/matlib.hxx>
57 #include <simgear/scene/model/SGOffsetTransform.hxx>
58 #include <simgear/scene/util/SGUpdateVisitor.hxx>
59 #include <simgear/scene/util/SGNodeMasks.hxx>
60 #include <simgear/scene/util/QuadTreeBuilder.hxx>
61 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
62
63 #include "SGTexturedTriangleBin.hxx"
64 #include "SGLightBin.hxx"
65 #include "SGModelBin.hxx"
66 #include "SGBuildingBin.hxx"
67 #include "TreeBin.hxx"
68 #include "SGDirectionalLightBin.hxx"
69 #include "GroundLightManager.hxx"
70
71
72 #include "pt_lights.hxx"
73
74 using namespace simgear;
75
76 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
77 typedef std::list<SGLightBin> SGLightListBin;
78 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
79
80 struct SGTileGeometryBin {
81   SGMaterialTriangleMap materialTriangleMap;
82   SGLightBin tileLights;
83   SGLightBin randomTileLights;
84   SGTreeBinList randomForest;
85   SGDirectionalLightBin runwayLights;
86   SGDirectionalLightBin taxiLights;
87   SGDirectionalLightListBin vasiLights;
88   SGDirectionalLightListBin rabitLights;
89   SGLightListBin odalLights;
90   SGDirectionalLightListBin holdshortLights;
91   SGDirectionalLightListBin guardLights;
92   SGDirectionalLightListBin reilLights;
93   SGMatModelBin randomModels;
94   SGBuildingBinList randomBuildings;
95
96   static SGVec4f
97   getMaterialLightColor(const SGMaterial* material)
98   {
99     if (!material)
100       return SGVec4f(1, 1, 1, 0.8);
101     return material->get_light_color();
102   }
103
104   static void
105   addPointGeometry(SGLightBin& lights,
106                    const std::vector<SGVec3d>& vertices,
107                    const SGVec4f& color,
108                    const int_list& pts_v)
109   {
110     for (unsigned i = 0; i < pts_v.size(); ++i)
111       lights.insert(toVec3f(vertices[pts_v[i]]), color);
112   }
113
114   static void
115   addPointGeometry(SGDirectionalLightBin& lights,
116                    const std::vector<SGVec3d>& vertices,
117                    const std::vector<SGVec3f>& normals,
118                    const SGVec4f& color,
119                    const int_list& pts_v,
120                    const int_list& pts_n)
121   {
122     // If the normal indices match the vertex indices, use seperate
123     // normal indices. Else reuse the vertex indices for the normals.
124     if (pts_v.size() == pts_n.size()) {
125       for (unsigned i = 0; i < pts_v.size(); ++i)
126         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
127     } else {
128       for (unsigned i = 0; i < pts_v.size(); ++i)
129         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
130     }
131   }
132
133   bool
134   insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
135   {
136     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
137       SG_LOG(SG_TERRAIN, SG_ALERT,
138              "Group list sizes for points do not match!");
139       return false;
140     }
141
142     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
143       std::string materialName = obj.get_pt_materials()[grp];
144       SGMaterial* material = 0;
145       if (matlib)
146           material = matlib->find(materialName);
147       SGVec4f color = getMaterialLightColor(material);
148
149       if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
150         // Just plain lights. Not something for the runway.
151         addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
152                          obj.get_pts_v()[grp]);
153       } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
154                  || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
155         addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
156                          color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
157       } else if (materialName == "RWY_VASI_LIGHTS") {
158         vasiLights.push_back(SGDirectionalLightBin());
159         addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
160                          obj.get_normals(), color, obj.get_pts_v()[grp],
161                          obj.get_pts_n()[grp]);
162       } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
163         rabitLights.push_back(SGDirectionalLightBin());
164         addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
165                          obj.get_normals(), color, obj.get_pts_v()[grp],
166                          obj.get_pts_n()[grp]);
167       } else if (materialName == "RWY_ODALS_LIGHTS") {
168         odalLights.push_back(SGLightBin());
169         addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
170                          color, obj.get_pts_v()[grp]);
171       } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
172         holdshortLights.push_back(SGDirectionalLightBin());
173         addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
174                          obj.get_normals(), color, obj.get_pts_v()[grp],
175                          obj.get_pts_n()[grp]);
176       } else if (materialName == "RWY_GUARD_LIGHTS") {
177         guardLights.push_back(SGDirectionalLightBin());
178         addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
179                          obj.get_normals(), color, obj.get_pts_v()[grp],
180                          obj.get_pts_n()[grp]);
181       } else if (materialName == "RWY_REIL_LIGHTS") {
182         reilLights.push_back(SGDirectionalLightBin());
183         addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
184                          obj.get_normals(), color, obj.get_pts_v()[grp],
185                          obj.get_pts_n()[grp]);
186       } else {
187         // what is left must be runway lights
188         addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
189                          obj.get_normals(), color, obj.get_pts_v()[grp],
190                          obj.get_pts_n()[grp]);
191       }
192     }
193
194     return true;
195   }
196
197
198   static SGVec2f
199   getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
200               const SGVec2f& tcScale, unsigned i)
201   {
202     if (tc.empty())
203       return tcScale;
204     else if (tc.size() == 1)
205       return mult(texCoords[tc[0]], tcScale);
206     else
207       return mult(texCoords[tc[i]], tcScale);
208   }
209
210   static void
211   addTriangleGeometry(SGTexturedTriangleBin& triangles,
212                       const std::vector<SGVec3d>& vertices,
213                       const std::vector<SGVec3f>& normals,
214                       const std::vector<SGVec2f>& texCoords,
215                       const int_list& tris_v,
216                       const int_list& tris_n,
217                       const int_list& tris_tc,
218                       const SGVec2f& tcScale)
219   {
220     if (tris_v.size() != tris_n.size()) {
221       // If the normal indices do not match, they should be inmplicitly
222       // the same than the vertex indices. So just call ourselves again
223       // with the matching index vector.
224       addTriangleGeometry(triangles, vertices, normals, texCoords,
225                           tris_v, tris_v, tris_tc, tcScale);
226       return;
227     }
228
229     for (unsigned i = 2; i < tris_v.size(); i += 3) {
230       SGVertNormTex v0;
231       v0.vertex = toVec3f(vertices[tris_v[i-2]]);
232       v0.normal = normals[tris_n[i-2]];
233       v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
234       SGVertNormTex v1;
235       v1.vertex = toVec3f(vertices[tris_v[i-1]]);
236       v1.normal = normals[tris_n[i-1]];
237       v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
238       SGVertNormTex v2;
239       v2.vertex = toVec3f(vertices[tris_v[i]]);
240       v2.normal = normals[tris_n[i]];
241       v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
242       triangles.insert(v0, v1, v2);
243     }
244   }
245
246   static void
247   addStripGeometry(SGTexturedTriangleBin& triangles,
248                    const std::vector<SGVec3d>& vertices,
249                    const std::vector<SGVec3f>& normals,
250                    const std::vector<SGVec2f>& texCoords,
251                    const int_list& strips_v,
252                    const int_list& strips_n,
253                    const int_list& strips_tc,
254                    const SGVec2f& tcScale)
255   {
256     if (strips_v.size() != strips_n.size()) {
257       // If the normal indices do not match, they should be inmplicitly
258       // the same than the vertex indices. So just call ourselves again
259       // with the matching index vector.
260       addStripGeometry(triangles, vertices, normals, texCoords,
261                        strips_v, strips_v, strips_tc, tcScale);
262       return;
263     }
264
265     for (unsigned i = 2; i < strips_v.size(); ++i) {
266       SGVertNormTex v0;
267       v0.vertex = toVec3f(vertices[strips_v[i-2]]);
268       v0.normal = normals[strips_n[i-2]];
269       v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
270       SGVertNormTex v1;
271       v1.vertex = toVec3f(vertices[strips_v[i-1]]);
272       v1.normal = normals[strips_n[i-1]];
273       v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
274       SGVertNormTex v2;
275       v2.vertex = toVec3f(vertices[strips_v[i]]);
276       v2.normal = normals[strips_n[i]];
277       v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
278       if (i%2)
279         triangles.insert(v1, v0, v2);
280       else
281         triangles.insert(v0, v1, v2);
282     }
283   }
284   
285   static void
286   addFanGeometry(SGTexturedTriangleBin& triangles,
287                  const std::vector<SGVec3d>& vertices,
288                  const std::vector<SGVec3f>& normals,
289                  const std::vector<SGVec2f>& texCoords,
290                  const int_list& fans_v,
291                  const int_list& fans_n,
292                  const int_list& fans_tc,
293                  const SGVec2f& tcScale)
294   {
295     if (fans_v.size() != fans_n.size()) {
296       // If the normal indices do not match, they should be implicitly
297       // the same than the vertex indices. So just call ourselves again
298       // with the matching index vector.
299       addFanGeometry(triangles, vertices, normals, texCoords,
300                      fans_v, fans_v, fans_tc, tcScale);
301       return;
302     }
303
304     SGVertNormTex v0;
305     v0.vertex = toVec3f(vertices[fans_v[0]]);
306     v0.normal = normals[fans_n[0]];
307     v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
308     SGVertNormTex v1;
309     v1.vertex = toVec3f(vertices[fans_v[1]]);
310     v1.normal = normals[fans_n[1]];
311     v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
312     for (unsigned i = 2; i < fans_v.size(); ++i) {
313       SGVertNormTex v2;
314       v2.vertex = toVec3f(vertices[fans_v[i]]);
315       v2.normal = normals[fans_n[i]];
316       v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
317       triangles.insert(v0, v1, v2);
318       v1 = v2;
319     }
320   }
321
322   SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
323   {
324     if (!matlib)
325       return SGVec2f(1, 1);
326     SGMaterial* material = matlib->find(name);
327     if (!material)
328       return SGVec2f(1, 1);
329
330     return material->get_tex_coord_scale();
331   }
332
333   bool
334   insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
335   {
336     if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
337         obj.get_tris_tc().size() < obj.get_tris_v().size()) {
338       SG_LOG(SG_TERRAIN, SG_ALERT,
339              "Group list sizes for triangles do not match!");
340       return false;
341     }
342
343     for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
344       std::string materialName = obj.get_tri_materials()[grp];
345       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
346       addTriangleGeometry(materialTriangleMap[materialName],
347                           obj.get_wgs84_nodes(), obj.get_normals(),
348                           obj.get_texcoords(), obj.get_tris_v()[grp],
349                           obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
350                           tcScale);
351     }
352
353     if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
354         obj.get_strips_tc().size() < obj.get_strips_v().size()) {
355       SG_LOG(SG_TERRAIN, SG_ALERT,
356              "Group list sizes for strips do not match!");
357       return false;
358     }
359     for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
360       std::string materialName = obj.get_strip_materials()[grp];
361       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
362       addStripGeometry(materialTriangleMap[materialName],
363                        obj.get_wgs84_nodes(), obj.get_normals(),
364                        obj.get_texcoords(), obj.get_strips_v()[grp],
365                        obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
366                        tcScale);
367     }
368
369     if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
370         obj.get_fans_tc().size() < obj.get_fans_v().size()) {
371       SG_LOG(SG_TERRAIN, SG_ALERT,
372              "Group list sizes for fans do not match!");
373       return false;
374     }
375     for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
376       std::string materialName = obj.get_fan_materials()[grp];
377       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
378       addFanGeometry(materialTriangleMap[materialName],
379                      obj.get_wgs84_nodes(), obj.get_normals(),
380                      obj.get_texcoords(), obj.get_fans_v()[grp],
381                      obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
382                      tcScale);
383     }
384     return true;
385   }
386
387   osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
388   {
389     if (materialTriangleMap.empty())
390       return 0;
391
392     EffectGeode* eg = 0;
393     osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
394     //osg::Geode* geode = new osg::Geode;
395     SGMaterialTriangleMap::const_iterator i;
396     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
397       osg::Geometry* geometry = i->second.buildGeometry();
398       SGMaterial *mat = 0;
399       if (matlib)
400         mat = matlib->find(i->first);
401       eg = new EffectGeode;
402       if (mat)
403         eg->setEffect(mat->get_effect(i->second));
404       eg->addDrawable(geometry);
405       eg->runGenerators(geometry);  // Generate extra data needed by effect
406       if (group)
407         group->addChild(eg);
408     }
409     if (group)
410         return group;
411     else
412         return eg;
413   }
414
415   void computeRandomSurfaceLights(SGMaterialLib* matlib)
416   {
417     SGMaterialTriangleMap::iterator i;
418         
419     // generate a repeatable random seed
420     mt seed;
421     mt_init(&seed, unsigned(123));
422     
423     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
424       SGMaterial *mat = matlib->find(i->first);
425       if (!mat)
426         continue;
427
428       float coverage = mat->get_light_coverage();
429       if (coverage <= 0)
430         continue;
431       if (coverage < 10000.0) {
432         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
433                << coverage << ", pushing up to 10000");
434         coverage = 10000;
435       }
436       
437       std::vector<SGVec3f> randomPoints;
438       i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
439       std::vector<SGVec3f>::iterator j;
440       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
441         float zombie = mt_rand(&seed);
442         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
443         float factor = mt_rand(&seed);
444         factor *= factor;
445
446         float bright = 1;
447         SGVec4f color;
448         if ( zombie > 0.5 ) {
449           // 50% chance of yellowish
450           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
451         } else if (zombie > 0.15f) {
452           // 35% chance of whitish
453           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
454         } else if (zombie > 0.05f) {
455           // 10% chance of orangish
456           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
457         } else {
458           // 5% chance of redish
459           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
460         }
461         randomTileLights.insert(*j, color);
462       }
463     }
464   }
465   
466   void computeRandomObjectsAndBuildings(
467     SGMaterialLib* matlib, 
468     float building_density, 
469     bool use_random_objects, 
470     bool use_random_buildings)
471   {
472     SGMaterialTriangleMap::iterator i;
473         
474     // generate a repeatable random seed
475     mt seed;
476     mt_init(&seed, unsigned(123));
477     
478     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
479       SGMaterial *mat = matlib->find(i->first);
480       SGTexturedTriangleBin triangleBin = i->second;
481       
482       if (!mat)
483         continue;
484
485       osg::Texture2D* object_mask  = mat->get_object_mask(triangleBin);
486       int   group_count            = mat->get_object_group_count();
487       float building_coverage      = mat->get_building_coverage();      
488       float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
489       float cos_max_density_angle  = mat->get_cos_object_max_density_slope_angle();
490       
491       bool found = false;
492       SGBuildingBin* bin = NULL;
493       
494       if (building_coverage > 0) {      
495         BOOST_FOREACH(bin, randomBuildings)
496         {
497           if (bin->getMaterialName() == mat->get_names()[0]) {
498               found = true;
499               break;
500           }
501         }
502         
503         if (!found) {
504           bin = new SGBuildingBin(mat);
505           randomBuildings.push_back(bin);
506         }       
507       }            
508       
509       unsigned num = i->second.getNumTriangles();
510       int random_dropped = 0;
511       int mask_dropped = 0;
512       int building_dropped = 0;
513       int triangle_dropped = 0;
514
515       for (unsigned i = 0; i < num; ++i) {
516         SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
517         
518         SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
519         SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
520         SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
521         SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
522         SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
523         SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
524         SGVec3f normal = cross(v0, v1);
525         
526         // Ensure the slope isn't too steep by checking the
527         // cos of the angle between the slope normal and the
528         // vertical (conveniently the z-component of the normalized
529         // normal) and values passed in.                   
530         float cos = normalize(normal).z();
531         float slope_density = 1.0;
532         if (cos < cos_zero_density_angle) continue; // Too steep for any objects
533         if (cos < cos_max_density_angle) {
534           slope_density = 
535             (cos - cos_zero_density_angle) / 
536             (cos_max_density_angle - cos_zero_density_angle);
537         }
538                 
539         // Containers to hold the random buildings and objects generated
540         // for this triangle for collision detection purposes.
541         std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
542         std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
543         
544         // Compute the area
545         float area = 0.5f*length(normal);
546         if (area <= SGLimitsf::min())
547           continue;
548
549         // Generate any random objects          
550         if (use_random_objects && (group_count > 0))
551         {
552           for (int j = 0; j < group_count; j++)
553           {
554             SGMatModelGroup *object_group =  mat->get_object_group(j);
555             int nObjects = object_group->get_object_count();
556             
557             if (nObjects == 0) continue;
558               
559             // For each of the random models in the group, determine an appropriate
560             // number of random placements and insert them.
561             for (int k = 0; k < nObjects; k++) {
562               SGMatModel * object = object_group->get_object(k);
563               
564               // Determine the number of objecst to place, taking into account
565               // the slope density factor.
566               double n = slope_density * area / object->get_coverage_m2();
567               
568               // Use the zombie door method to determine fractional object placement.
569               n = n + mt_rand(&seed);
570
571               // place an object each unit of area
572               while ( n > 1.0 ) {
573                 float a = mt_rand(&seed);
574                 float b = mt_rand(&seed);
575                 if ( a + b > 1 ) {
576                   a = 1 - a;
577                   b = 1 - b;
578                 }
579
580                 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
581                 float rotation = static_cast<float>(mt_rand(&seed));
582                 
583                 // Check that the point is sufficiently far from
584                 // the edge of the triangle by measuring the distance
585                 // from the three lines that make up the triangle.                          
586                 float spacing = object->get_spacing_m();
587                 
588                 SGVec3f p = randomPoint - vorigin;          
589                 float edges[] = { length(cross(p     , p - v0)) / length(v0),
590                                   length(cross(p - v0, p - v1)) / length(v1 - v0),
591                                   length(cross(p - v1, p     )) / length(v1)      };
592                 float edge_dist = *std::min_element(edges, edges + 3);   
593                 
594                 if (edge_dist < spacing) { 
595                   n -= 1.0;
596                   continue; 
597                 }                
598                 
599                 if (object_mask != NULL) {
600                   SGVec2f texCoord = torigin + a*t0 + b*t1;
601                   
602                   // Check this random point against the object mask
603                   // blue (for buildings) channel. 
604                   osg::Image* img = object_mask->getImage();            
605                   unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
606                   unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
607                   
608                   if (mt_rand(&seed) > img->getColor(x, y).b()) { 
609                     // Failed object mask check
610                     n -= 1.0;
611                     continue;                    
612                   }
613                   
614                   rotation = img->getColor(x,y).r();
615                 }
616                 
617                 bool close = false;
618
619                 // Check it isn't too close to any other random objects in the triangle
620                 std::vector<std::pair<SGVec3f, float> >::iterator l;
621                 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
622                   float min_dist2 = (l->second + object->get_spacing_m()) * 
623                                     (l->second + object->get_spacing_m());
624                   
625                   if (distSqr(l->first, randomPoint) > min_dist2) {
626                     close = true;
627                     continue;
628                   }
629                 }
630                 
631                 if (!close) {
632                     triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
633                     randomModels.insert(randomPoint, 
634                                         object, 
635                                         (int)object->get_randomized_range_m(&seed), 
636                                         rotation);
637                 }
638                 
639                 n -= 1.0;
640               }
641             }
642           }
643         }        
644         
645         // Random objects now generated.  Now generate the random buildings (if any);
646         if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
647           
648           // Calculate the number of buildings, taking into account building density (which is linear)
649           // and the slope density factor.  
650           double num = building_density * building_density * slope_density * area / building_coverage;
651           
652           // For partial units of area, use a zombie door method to
653           // create the proper random chance of an object being created
654           // for this triangle.
655           num = num + mt_rand(&seed);
656
657           if (num < 1.0f) {
658             continue;          
659           }
660           
661           // Cosine of the angle between the two vectors.
662           float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
663
664           // Determine a grid spacing in each vector such that the correct
665           // coverage will result.
666           float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
667           float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
668           
669           stepv0 = std::min(stepv0, 1.0f);
670           stepv1 = std::min(stepv1, 1.0f);
671           
672           // Start at a random point. a will be immediately incremented below.
673           float a = -mt_rand(&seed) * stepv0;  
674           float b = mt_rand(&seed) * stepv1;
675
676           // Place an object each unit of area
677           while (num > 1.0) {
678
679             // Set the next location to place a building          
680             a += stepv0;
681             
682             if ((a + b) > 1.0f) {
683               // Reached the end of the scan-line on v0. Reset and increment
684               // scan-line on v1
685               a = mt_rand(&seed) * stepv0;
686               b += stepv1;
687             }
688             
689             if (b > 1.0f) {
690               // In a degenerate case of a single point, we might be outside the 
691               // scanline.  Note that we need to still ensure that a+b < 1.
692               b = mt_rand(&seed) * stepv1 * (1.0f - a);
693             }
694             
695             if ((a + b) > 1.0f ) {
696               // Truly degenerate case - simply choose a random point guaranteed
697               // to fulfil the constraing of a+b < 1.
698               a = mt_rand(&seed);
699               b = mt_rand(&seed) * (1.0f - a);
700             }
701             
702             SGVec3f randomPoint = vorigin + a*v0 + b*v1;
703             float rotation = mt_rand(&seed);
704             
705             if (object_mask != NULL) {
706               SGVec2f texCoord = torigin + a*t0 + b*t1;
707               osg::Image* img = object_mask->getImage();            
708               int x = (int) (img->s() * texCoord.x()) % img->s();
709               int y = (int) (img->t() * texCoord.y()) % img->t();
710               
711               // In some degenerate cases x or y can be < 1, in which case the mod operand fails
712               while (x < 0) x += img->s();
713               while (y < 0) y += img->t();
714
715               if (mt_rand(&seed) < img->getColor(x, y).b()) {  
716                 // Object passes mask. Rotation is taken from the red channel
717                 rotation = img->getColor(x,y).r();
718               } else {
719                 // Fails mask test - try again.
720                 mask_dropped++;
721                 num -= 1.0;
722                 continue;
723               }  
724             }
725
726             // Check building isn't too close to the triangle edge.
727             float type_roll = mt_rand(&seed);
728             SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
729             float radius = bin->getBuildingMaxRadius(buildingtype);
730                       
731             // Determine the actual center of the building, by shifting from the 
732             // center of the front face to the true center.
733             osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
734                                                  osg::Vec3f(0.0, 0.0, 1.0));
735             SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
736
737             SGVec3f p = buildingCenter - vorigin;          
738             float edges[] = { length(cross(p     , p - v0)) / length(v0),
739                               length(cross(p - v0, p - v1)) / length(v1 - v0),
740                               length(cross(p - v1, p     )) / length(v1)      };
741             float edge_dist = *std::min_element(edges, edges + 3);   
742             
743             if (edge_dist < radius) { 
744               num -= 1.0;
745               triangle_dropped++;
746               continue; 
747             }
748                       
749             // Check building isn't too close to random objects and other buildings.          
750             bool close = false;
751             std::vector<std::pair<SGVec3f, float> >::iterator iter;
752             
753             for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
754               float min_dist = iter->second + radius;
755               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
756                 close = true;
757                 continue;
758               }            
759             }
760             
761             if (close) {
762               num -= 1.0;
763               building_dropped++;
764               continue;            
765             }
766             
767             for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
768               float min_dist = iter->second + radius;
769               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
770                 close = true;
771                 continue;
772               }            
773             }
774             
775             if (close) {
776               num -= 1.0;
777               random_dropped++;
778               continue;            
779             }          
780
781             std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);              
782             triangleBuildingList.push_back(pt);
783             bin->insert(randomPoint, rotation, buildingtype);
784             num -= 1.0;
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->find(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 osg::Node*
893 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
894 {
895   SGBinObject tile;
896   if (!tile.read_bin(path))
897     return NULL;
898
899   SGMaterialLib* matlib = 0;
900   bool use_random_objects = false;
901   bool use_random_vegetation = false;
902   bool use_random_buildings = false;
903   float vegetation_density = 1.0f;  
904   float building_density = 1.0f;
905   if (options) {
906     matlib = options->getMaterialLib();
907     SGPropertyNode* propertyNode = options->getPropertyNode().get();
908     if (propertyNode) {
909         use_random_objects
910             = propertyNode->getBoolValue("/sim/rendering/random-objects",
911                                          use_random_objects);
912         use_random_vegetation
913             = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
914                                          use_random_vegetation);        
915         vegetation_density
916             = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
917                                           vegetation_density);
918         use_random_buildings
919             = propertyNode->getBoolValue("/sim/rendering/random-buildings",
920                                          use_random_buildings);        
921         building_density
922             = propertyNode->getFloatValue("/sim/rendering/building-density",
923                                           building_density);
924     }
925   }
926
927   SGVec3d center = tile.get_gbs_center();
928   SGGeod geodPos = SGGeod::fromCart(center);
929   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
930
931   // rotate the tiles so that the bounding boxes get nearly axis aligned.
932   // this will help the collision tree's bounding boxes a bit ...
933   std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
934   for (unsigned i = 0; i < nodes.size(); ++i)
935     nodes[i] = hlOr.transform(nodes[i]);
936   tile.set_wgs84_nodes(nodes);
937
938   SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
939   std::vector<SGVec3f> normals = tile.get_normals();
940   for (unsigned i = 0; i < normals.size(); ++i)
941     normals[i] = hlOrf.transform(normals[i]);
942   tile.set_normals(normals);
943
944   SGTileGeometryBin tileGeometryBin;
945   if (!tileGeometryBin.insertBinObj(tile, matlib))
946     return NULL;
947
948   SGVec3f up(0, 0, 1);
949   GroundLightManager* lightManager = GroundLightManager::instance();
950
951   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
952   osg::ref_ptr<osg::Group> randomObjects;
953   osg::ref_ptr<osg::Group> forestNode;
954   osg::ref_ptr<osg::Group> buildingNode;  
955   osg::Group* terrainGroup = new osg::Group;
956
957   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
958   if (node)
959     terrainGroup->addChild(node);
960     
961   if (matlib && (use_random_objects || use_random_buildings)) {
962     tileGeometryBin.computeRandomObjectsAndBuildings(matlib, 
963                                                      building_density, 
964                                                      use_random_objects, 
965                                                      use_random_buildings);    
966   }
967
968   if (tileGeometryBin.randomModels.getNumModels() > 0) {
969     // Generate a repeatable random seed
970     mt seed;
971     mt_init(&seed, unsigned(123));
972
973     std::vector<ModelLOD> models;
974     for (unsigned int i = 0;
975          i < tileGeometryBin.randomModels.getNumModels(); i++) {
976       SGMatModelBin::MatModel obj
977         = tileGeometryBin.randomModels.getMatModel(i);          
978
979       SGPropertyNode* root = options->getPropertyNode()->getRootNode();
980       osg::Node* node = obj.model->get_random_model(root, &seed);
981     
982       // Create a matrix to place the object in the correct
983       // location, and then apply the rotation matrix created
984       // above, with an additional random (or taken from
985       // the object mask) heading rotation if appropriate.
986       osg::Matrix transformMat;
987       transformMat = osg::Matrix::translate(toOsg(obj.position));
988       if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
989         // Rotate the object around the z axis.
990         double hdg = mt_rand(&seed) * M_PI * 2;
991         transformMat.preMult(osg::Matrix::rotate(hdg,
992                                                  osg::Vec3d(0.0, 0.0, 1.0)));
993       }
994
995       if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
996         // Rotate the object around the z axis.
997         double hdg =  - obj.rotation * M_PI * 2;
998         transformMat.preMult(osg::Matrix::rotate(hdg,
999                                                  osg::Vec3d(0.0, 0.0, 1.0)));
1000       }
1001       
1002       osg::MatrixTransform* position =
1003         new osg::MatrixTransform(transformMat);
1004       position->addChild(node);
1005       models.push_back(ModelLOD(position, obj.lod));
1006     }
1007     RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1008     quadtree.buildQuadTree(models.begin(), models.end());
1009     randomObjects = quadtree.getRoot();
1010     randomObjects->setName("Random objects");
1011   }
1012
1013   if (tileGeometryBin.randomBuildings.size() > 0) {
1014     buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1015                                 options);                                
1016     buildingNode->setName("Random buildings");
1017   }
1018
1019   if (use_random_vegetation && matlib) {
1020     // Now add some random forest.
1021     tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1022     
1023     if (tileGeometryBin.randomForest.size() > 0) {
1024       forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1025                                 options);
1026       forestNode->setName("Random trees");
1027     }
1028   }  
1029
1030   // FIXME: ugly, has a side effect
1031   if (matlib)
1032     tileGeometryBin.computeRandomSurfaceLights(matlib);
1033
1034   if (tileGeometryBin.tileLights.getNumLights() > 0
1035       || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1036     osg::Group* groundLights0 = new osg::Group;
1037     groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1038     groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1039     osg::Geode* geode = new osg::Geode;
1040     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1041     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1042     groundLights0->addChild(geode);
1043     lightGroup->addChild(groundLights0);
1044   }
1045   
1046   if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1047     osg::Group* groundLights1 = new osg::Group;
1048     groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1049     groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1050     osg::Group* groundLights2 = new osg::Group;
1051     groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1052     groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1053     osg::Geode* geode = new osg::Geode;
1054     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1055     groundLights1->addChild(geode);
1056     lightGroup->addChild(groundLights1);
1057     geode = new osg::Geode;
1058     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1059     groundLights2->addChild(geode);
1060     lightGroup->addChild(groundLights2);
1061   }
1062
1063   if (!tileGeometryBin.vasiLights.empty()) {
1064     EffectGeode* vasiGeode = new EffectGeode;
1065     Effect* vasiEffect
1066         = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1067     vasiGeode->setEffect(vasiEffect);
1068     SGVec4f red(1, 0, 0, 1);
1069     SGMaterial* mat = 0;
1070     if (matlib)
1071       mat = matlib->find("RWY_RED_LIGHTS");
1072     if (mat)
1073       red = mat->get_light_color();
1074     SGVec4f white(1, 1, 1, 1);
1075     mat = 0;
1076     if (matlib)
1077       mat = matlib->find("RWY_WHITE_LIGHTS");
1078     if (mat)
1079       white = mat->get_light_color();
1080     SGDirectionalLightListBin::const_iterator i;
1081     for (i = tileGeometryBin.vasiLights.begin();
1082          i != tileGeometryBin.vasiLights.end(); ++i) {
1083       vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1084     }
1085     vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1086     lightGroup->addChild(vasiGeode);
1087   }
1088   
1089   Effect* runwayEffect = 0;
1090   if (tileGeometryBin.runwayLights.getNumLights() > 0
1091       || !tileGeometryBin.rabitLights.empty()
1092       || !tileGeometryBin.reilLights.empty()
1093       || !tileGeometryBin.odalLights.empty()
1094       || tileGeometryBin.taxiLights.getNumLights() > 0)
1095       runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1096   if (tileGeometryBin.runwayLights.getNumLights() > 0
1097       || !tileGeometryBin.rabitLights.empty()
1098       || !tileGeometryBin.reilLights.empty()
1099       || !tileGeometryBin.odalLights.empty()
1100       || !tileGeometryBin.holdshortLights.empty()
1101       || !tileGeometryBin.guardLights.empty()) {
1102     osg::Group* rwyLights = new osg::Group;
1103     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1104     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1105     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1106       EffectGeode* geode = new EffectGeode;
1107       geode->setEffect(runwayEffect);
1108       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1109                                                    .runwayLights));
1110       rwyLights->addChild(geode);
1111     }
1112     SGDirectionalLightListBin::const_iterator i;
1113     for (i = tileGeometryBin.rabitLights.begin();
1114          i != tileGeometryBin.rabitLights.end(); ++i) {
1115       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1116     }
1117     for (i = tileGeometryBin.reilLights.begin();
1118          i != tileGeometryBin.reilLights.end(); ++i) {
1119       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1120     }
1121     for (i = tileGeometryBin.holdshortLights.begin();
1122          i != tileGeometryBin.holdshortLights.end(); ++i) {
1123       rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1124     }
1125     for (i = tileGeometryBin.guardLights.begin();
1126          i != tileGeometryBin.guardLights.end(); ++i) {
1127       rwyLights->addChild(SGLightFactory::getGuard(*i));
1128     }
1129     SGLightListBin::const_iterator j;
1130     for (j = tileGeometryBin.odalLights.begin();
1131          j != tileGeometryBin.odalLights.end(); ++j) {
1132       rwyLights->addChild(SGLightFactory::getOdal(*j));
1133     }
1134     lightGroup->addChild(rwyLights);
1135   }
1136
1137   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1138     osg::Group* taxiLights = new osg::Group;
1139     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1140     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1141     EffectGeode* geode = new EffectGeode;
1142     geode->setEffect(runwayEffect);
1143     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1144     taxiLights->addChild(geode);
1145     lightGroup->addChild(taxiLights);
1146   }
1147
1148   // The toplevel transform for that tile.
1149   osg::MatrixTransform* transform = new osg::MatrixTransform;
1150   transform->setName(path);
1151   transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1152                        osg::Matrix::translate(toOsg(center)));
1153   transform->addChild(terrainGroup);
1154   if (lightGroup->getNumChildren() > 0) {
1155     osg::LOD* lightLOD = new osg::LOD;
1156     lightLOD->addChild(lightGroup.get(), 0, 60000);
1157     // VASI is always on, so doesn't use light bits.
1158     lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1159     transform->addChild(lightLOD);
1160   }
1161   
1162   if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1163   
1164     // Add a LoD node, so we don't try to display anything when the tile center
1165     // is more than 20km away.
1166     osg::LOD* objectLOD = new osg::LOD;
1167     
1168     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1169     if (forestNode.valid())  objectLOD->addChild(forestNode.get(), 0, 20000);
1170     if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1171     
1172     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1173     objectLOD->setNodeMask(nodeMask);
1174     transform->addChild(objectLOD);
1175   }
1176   transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
1177   
1178   return transform;
1179 }