]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Fixed a crash: the singleton needs to be instantiated the first time SGCommandMgr...
[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       eg->setName("EffectGeode");
403       if (mat)
404         eg->setEffect(mat->get_effect(i->second));
405       eg->addDrawable(geometry);
406       eg->runGenerators(geometry);  // Generate extra data needed by effect
407       if (group) {
408         group->setName("surfaceGeometryGroup");
409         group->addChild(eg);
410       }
411     }
412     if (group)
413         return group;
414     else
415         return eg;
416   }
417
418   void computeRandomSurfaceLights(SGMaterialLib* matlib)
419   {
420     SGMaterialTriangleMap::iterator i;
421         
422     // generate a repeatable random seed
423     mt seed;
424     mt_init(&seed, unsigned(123));
425     
426     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
427       SGMaterial *mat = matlib->find(i->first);
428       if (!mat)
429         continue;
430
431       float coverage = mat->get_light_coverage();
432       if (coverage <= 0)
433         continue;
434       if (coverage < 10000.0) {
435         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
436                << coverage << ", pushing up to 10000");
437         coverage = 10000;
438       }
439       
440       std::vector<SGVec3f> randomPoints;
441       i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
442       std::vector<SGVec3f>::iterator j;
443       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
444         float zombie = mt_rand(&seed);
445         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
446         float factor = mt_rand(&seed);
447         factor *= factor;
448
449         float bright = 1;
450         SGVec4f color;
451         if ( zombie > 0.5 ) {
452           // 50% chance of yellowish
453           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
454         } else if (zombie > 0.15f) {
455           // 35% chance of whitish
456           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
457         } else if (zombie > 0.05f) {
458           // 10% chance of orangish
459           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
460         } else {
461           // 5% chance of redish
462           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
463         }
464         randomTileLights.insert(*j, color);
465       }
466     }
467   }
468   
469   void computeRandomObjectsAndBuildings(
470     SGMaterialLib* matlib, 
471     float building_density, 
472     bool use_random_objects, 
473     bool use_random_buildings)
474   {
475     SGMaterialTriangleMap::iterator i;
476         
477     // generate a repeatable random seed
478     mt seed;
479     mt_init(&seed, unsigned(123));
480     
481     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
482       SGMaterial *mat = matlib->find(i->first);
483       SGTexturedTriangleBin triangleBin = i->second;
484       
485       if (!mat)
486         continue;
487
488       osg::Texture2D* object_mask  = mat->get_object_mask(triangleBin);
489       int   group_count            = mat->get_object_group_count();
490       float building_coverage      = mat->get_building_coverage();      
491       float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
492       float cos_max_density_angle  = mat->get_cos_object_max_density_slope_angle();
493       
494       bool found = false;
495       SGBuildingBin* bin = NULL;
496       
497       if (building_coverage > 0) {      
498         BOOST_FOREACH(bin, randomBuildings)
499         {
500           if (bin->getMaterialName() == mat->get_names()[0]) {
501               found = true;
502               break;
503           }
504         }
505         
506         if (!found) {
507           bin = new SGBuildingBin(mat);
508           randomBuildings.push_back(bin);
509         }       
510       }            
511       
512       unsigned num = i->second.getNumTriangles();
513       int random_dropped = 0;
514       int mask_dropped = 0;
515       int building_dropped = 0;
516       int triangle_dropped = 0;
517
518       for (unsigned i = 0; i < num; ++i) {
519         SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
520         
521         SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
522         SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
523         SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
524         SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
525         SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
526         SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
527         SGVec3f normal = cross(v0, v1);
528         
529         // Ensure the slope isn't too steep by checking the
530         // cos of the angle between the slope normal and the
531         // vertical (conveniently the z-component of the normalized
532         // normal) and values passed in.                   
533         float cos = normalize(normal).z();
534         float slope_density = 1.0;
535         if (cos < cos_zero_density_angle) continue; // Too steep for any objects
536         if (cos < cos_max_density_angle) {
537           slope_density = 
538             (cos - cos_zero_density_angle) / 
539             (cos_max_density_angle - cos_zero_density_angle);
540         }
541                 
542         // Containers to hold the random buildings and objects generated
543         // for this triangle for collision detection purposes.
544         std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
545         std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
546         
547         // Compute the area
548         float area = 0.5f*length(normal);
549         if (area <= SGLimitsf::min())
550           continue;
551
552         // Generate any random objects          
553         if (use_random_objects && (group_count > 0))
554         {
555           for (int j = 0; j < group_count; j++)
556           {
557             SGMatModelGroup *object_group =  mat->get_object_group(j);
558             int nObjects = object_group->get_object_count();
559             
560             if (nObjects == 0) continue;
561               
562             // For each of the random models in the group, determine an appropriate
563             // number of random placements and insert them.
564             for (int k = 0; k < nObjects; k++) {
565               SGMatModel * object = object_group->get_object(k);
566               
567               // Determine the number of objecst to place, taking into account
568               // the slope density factor.
569               double n = slope_density * area / object->get_coverage_m2();
570               
571               // Use the zombie door method to determine fractional object placement.
572               n = n + mt_rand(&seed);
573
574               // place an object each unit of area
575               while ( n > 1.0 ) {
576                 float a = mt_rand(&seed);
577                 float b = mt_rand(&seed);
578                 if ( a + b > 1 ) {
579                   a = 1 - a;
580                   b = 1 - b;
581                 }
582
583                 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
584                 float rotation = static_cast<float>(mt_rand(&seed));
585                 
586                 // Check that the point is sufficiently far from
587                 // the edge of the triangle by measuring the distance
588                 // from the three lines that make up the triangle.                          
589                 float spacing = object->get_spacing_m();
590                 
591                 SGVec3f p = randomPoint - vorigin;          
592                 float edges[] = { length(cross(p     , p - v0)) / length(v0),
593                                   length(cross(p - v0, p - v1)) / length(v1 - v0),
594                                   length(cross(p - v1, p     )) / length(v1)      };
595                 float edge_dist = *std::min_element(edges, edges + 3);   
596                 
597                 if (edge_dist < spacing) { 
598                   n -= 1.0;
599                   continue; 
600                 }                
601                 
602                 if (object_mask != NULL) {
603                   SGVec2f texCoord = torigin + a*t0 + b*t1;
604                   
605                   // Check this random point against the object mask
606                   // blue (for buildings) channel. 
607                   osg::Image* img = object_mask->getImage();            
608                   unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
609                   unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
610                   
611                   if (mt_rand(&seed) > img->getColor(x, y).b()) { 
612                     // Failed object mask check
613                     n -= 1.0;
614                     continue;                    
615                   }
616                   
617                   rotation = img->getColor(x,y).r();
618                 }
619                 
620                 bool close = false;
621
622                 // Check it isn't too close to any other random objects in the triangle
623                 std::vector<std::pair<SGVec3f, float> >::iterator l;
624                 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
625                   float min_dist2 = (l->second + object->get_spacing_m()) * 
626                                     (l->second + object->get_spacing_m());
627                   
628                   if (distSqr(l->first, randomPoint) > min_dist2) {
629                     close = true;
630                     continue;
631                   }
632                 }
633                 
634                 if (!close) {
635                     triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
636                     randomModels.insert(randomPoint, 
637                                         object, 
638                                         (int)object->get_randomized_range_m(&seed), 
639                                         rotation);
640                 }
641                 
642                 n -= 1.0;
643               }
644             }
645           }
646         }        
647         
648         // Random objects now generated.  Now generate the random buildings (if any);
649         if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
650           
651           // Calculate the number of buildings, taking into account building density (which is linear)
652           // and the slope density factor.  
653           double num = building_density * building_density * slope_density * area / building_coverage;
654           
655           // For partial units of area, use a zombie door method to
656           // create the proper random chance of an object being created
657           // for this triangle.
658           num = num + mt_rand(&seed);
659
660           if (num < 1.0f) {
661             continue;          
662           }
663           
664           // Cosine of the angle between the two vectors.
665           float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
666
667           // Determine a grid spacing in each vector such that the correct
668           // coverage will result.
669           float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
670           float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
671           
672           stepv0 = std::min(stepv0, 1.0f);
673           stepv1 = std::min(stepv1, 1.0f);
674           
675           // Start at a random point. a will be immediately incremented below.
676           float a = -mt_rand(&seed) * stepv0;  
677           float b = mt_rand(&seed) * stepv1;
678
679           // Place an object each unit of area
680           while (num > 1.0) {
681
682             // Set the next location to place a building          
683             a += stepv0;
684             
685             if ((a + b) > 1.0f) {
686               // Reached the end of the scan-line on v0. Reset and increment
687               // scan-line on v1
688               a = mt_rand(&seed) * stepv0;
689               b += stepv1;
690             }
691             
692             if (b > 1.0f) {
693               // In a degenerate case of a single point, we might be outside the 
694               // scanline.  Note that we need to still ensure that a+b < 1.
695               b = mt_rand(&seed) * stepv1 * (1.0f - a);
696             }
697             
698             if ((a + b) > 1.0f ) {
699               // Truly degenerate case - simply choose a random point guaranteed
700               // to fulfil the constraing of a+b < 1.
701               a = mt_rand(&seed);
702               b = mt_rand(&seed) * (1.0f - a);
703             }
704             
705             SGVec3f randomPoint = vorigin + a*v0 + b*v1;
706             float rotation = mt_rand(&seed);
707             
708             if (object_mask != NULL) {
709               SGVec2f texCoord = torigin + a*t0 + b*t1;
710               osg::Image* img = object_mask->getImage();            
711               int x = (int) (img->s() * texCoord.x()) % img->s();
712               int y = (int) (img->t() * texCoord.y()) % img->t();
713               
714               // In some degenerate cases x or y can be < 1, in which case the mod operand fails
715               while (x < 0) x += img->s();
716               while (y < 0) y += img->t();
717
718               if (mt_rand(&seed) < img->getColor(x, y).b()) {  
719                 // Object passes mask. Rotation is taken from the red channel
720                 rotation = img->getColor(x,y).r();
721               } else {
722                 // Fails mask test - try again.
723                 mask_dropped++;
724                 num -= 1.0;
725                 continue;
726               }  
727             }
728
729             // Check building isn't too close to the triangle edge.
730             float type_roll = mt_rand(&seed);
731             SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
732             float radius = bin->getBuildingMaxRadius(buildingtype);
733                       
734             // Determine the actual center of the building, by shifting from the 
735             // center of the front face to the true center.
736             osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
737                                                  osg::Vec3f(0.0, 0.0, 1.0));
738             SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
739
740             SGVec3f p = buildingCenter - vorigin;          
741             float edges[] = { length(cross(p     , p - v0)) / length(v0),
742                               length(cross(p - v0, p - v1)) / length(v1 - v0),
743                               length(cross(p - v1, p     )) / length(v1)      };
744             float edge_dist = *std::min_element(edges, edges + 3);   
745             
746             if (edge_dist < radius) { 
747               num -= 1.0;
748               triangle_dropped++;
749               continue; 
750             }
751                       
752             // Check building isn't too close to random objects and other buildings.          
753             bool close = false;
754             std::vector<std::pair<SGVec3f, float> >::iterator iter;
755             
756             for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
757               float min_dist = iter->second + radius;
758               if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
759                 close = true;
760                 continue;
761               }            
762             }
763             
764             if (close) {
765               num -= 1.0;
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               num -= 1.0;
780               random_dropped++;
781               continue;            
782             }          
783
784             std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);              
785             triangleBuildingList.push_back(pt);
786             bin->insert(randomPoint, rotation, buildingtype);
787             num -= 1.0;
788           }
789         }
790         
791         triangleObjectsList.clear();
792         triangleBuildingList.clear();        
793       }
794       
795       SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
796       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to mask: " << mask_dropped);
797       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to random object: " << random_dropped);
798       SG_LOG(SG_TERRAIN, SG_DEBUG, "  Dropped due to other buildings: " << building_dropped);
799     }
800   }
801   
802   void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
803   {
804     SGMaterialTriangleMap::iterator i;
805
806     // generate a repeatable random seed
807     mt seed;
808
809     mt_init(&seed, unsigned(586));
810
811     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
812       SGMaterial *mat = matlib->find(i->first);
813       if (!mat)
814         continue;
815
816       float wood_coverage = mat->get_wood_coverage();
817       if ((wood_coverage <= 0) || (vegetation_density <= 0))
818         continue;
819               
820       // Attributes that don't vary by tree but do vary by material
821       bool found = false;
822       TreeBin* bin = NULL;
823       
824       BOOST_FOREACH(bin, randomForest)
825       {
826         if ((bin->texture           == mat->get_tree_texture()  ) &&
827             (bin->texture_varieties == mat->get_tree_varieties()) &&
828             (bin->range             == mat->get_tree_range()    ) &&
829             (bin->width             == mat->get_tree_width()    ) &&
830             (bin->height            == mat->get_tree_height()   )   ) {
831             found = true;
832             break;
833         }
834       }
835       
836       if (!found) {
837         bin = new TreeBin();
838         bin->texture = mat->get_tree_texture();
839           SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
840         bin->range   = mat->get_tree_range();
841         bin->width   = mat->get_tree_width();
842         bin->height  = mat->get_tree_height();
843         bin->texture_varieties = mat->get_tree_varieties();
844         randomForest.push_back(bin);
845       }
846
847       std::vector<SGVec3f> randomPoints;
848       i->second.addRandomTreePoints(wood_coverage,
849                                     mat->get_object_mask(i->second),
850                                     vegetation_density,
851                                     mat->get_cos_tree_max_density_slope_angle(),
852                                     mat->get_cos_tree_zero_density_slope_angle(),
853                                     randomPoints);
854       
855       std::vector<SGVec3f>::iterator k;
856       for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
857         bin->insert(*k);
858       }
859     }
860   }
861
862   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
863   {
864     if (!insertPtGeometry(obj, matlib))
865       return false;
866     if (!insertSurfaceGeometry(obj, matlib))
867       return false;
868     return true;
869   }
870 };
871
872 typedef std::pair<osg::Node*, int> ModelLOD;
873 struct MakeQuadLeaf {
874     osg::LOD* operator() () const { return new osg::LOD; }
875 };
876 struct AddModelLOD {
877     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
878     {
879         leaf->addChild(mlod.first, 0, mlod.second);
880     }
881 };
882 struct GetModelLODCoord {
883     GetModelLODCoord() {}
884     GetModelLODCoord(const GetModelLODCoord& rhs)
885     {}
886     osg::Vec3 operator() (const ModelLOD& mlod) const
887     {
888         return mlod.first->getBound().center();
889     }
890 };
891
892 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
893                         GetModelLODCoord>  RandomObjectsQuadtree;
894
895 osg::Node*
896 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
897 {
898   SGBinObject tile;
899   if (!tile.read_bin(path))
900     return NULL;
901
902   SGMaterialLib* matlib = 0;
903   bool use_random_objects = false;
904   bool use_random_vegetation = false;
905   bool use_random_buildings = false;
906   float vegetation_density = 1.0f;  
907   float building_density = 1.0f;
908   if (options) {
909     matlib = options->getMaterialLib();
910     SGPropertyNode* propertyNode = options->getPropertyNode().get();
911     if (propertyNode) {
912         use_random_objects
913             = propertyNode->getBoolValue("/sim/rendering/random-objects",
914                                          use_random_objects);
915         use_random_vegetation
916             = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
917                                          use_random_vegetation);        
918         vegetation_density
919             = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
920                                           vegetation_density);
921         use_random_buildings
922             = propertyNode->getBoolValue("/sim/rendering/random-buildings",
923                                          use_random_buildings);        
924         building_density
925             = propertyNode->getFloatValue("/sim/rendering/building-density",
926                                           building_density);
927     }
928   }
929
930   SGVec3d center = tile.get_gbs_center();
931   SGGeod geodPos = SGGeod::fromCart(center);
932   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
933
934   // rotate the tiles so that the bounding boxes get nearly axis aligned.
935   // this will help the collision tree's bounding boxes a bit ...
936   std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
937   for (unsigned i = 0; i < nodes.size(); ++i)
938     nodes[i] = hlOr.transform(nodes[i]);
939   tile.set_wgs84_nodes(nodes);
940
941   SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
942   std::vector<SGVec3f> normals = tile.get_normals();
943   for (unsigned i = 0; i < normals.size(); ++i)
944     normals[i] = hlOrf.transform(normals[i]);
945   tile.set_normals(normals);
946
947   SGTileGeometryBin tileGeometryBin;
948   if (!tileGeometryBin.insertBinObj(tile, matlib))
949     return NULL;
950
951   SGVec3f up(0, 0, 1);
952   GroundLightManager* lightManager = GroundLightManager::instance();
953
954   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
955   osg::ref_ptr<osg::Group> randomObjects;
956   osg::ref_ptr<osg::Group> forestNode;
957   osg::ref_ptr<osg::Group> buildingNode;  
958   osg::Group* terrainGroup = new osg::Group;
959   terrainGroup->setName("BTGTerrainGroup");
960       
961   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
962   if (node)
963     terrainGroup->addChild(node);
964     
965   if (matlib && (use_random_objects || use_random_buildings)) {
966     tileGeometryBin.computeRandomObjectsAndBuildings(matlib, 
967                                                      building_density, 
968                                                      use_random_objects, 
969                                                      use_random_buildings);    
970   }
971
972   if (tileGeometryBin.randomModels.getNumModels() > 0) {
973     // Generate a repeatable random seed
974     mt seed;
975     mt_init(&seed, unsigned(123));
976
977     std::vector<ModelLOD> models;
978     for (unsigned int i = 0;
979          i < tileGeometryBin.randomModels.getNumModels(); i++) {
980       SGMatModelBin::MatModel obj
981         = tileGeometryBin.randomModels.getMatModel(i);          
982
983       SGPropertyNode* root = options->getPropertyNode()->getRootNode();
984       osg::Node* node = obj.model->get_random_model(root, &seed);
985     
986       // Create a matrix to place the object in the correct
987       // location, and then apply the rotation matrix created
988       // above, with an additional random (or taken from
989       // the object mask) heading rotation if appropriate.
990       osg::Matrix transformMat;
991       transformMat = osg::Matrix::translate(toOsg(obj.position));
992       if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
993         // Rotate the object around the z axis.
994         double hdg = mt_rand(&seed) * M_PI * 2;
995         transformMat.preMult(osg::Matrix::rotate(hdg,
996                                                  osg::Vec3d(0.0, 0.0, 1.0)));
997       }
998
999       if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1000         // Rotate the object around the z axis.
1001         double hdg =  - obj.rotation * M_PI * 2;
1002         transformMat.preMult(osg::Matrix::rotate(hdg,
1003                                                  osg::Vec3d(0.0, 0.0, 1.0)));
1004       }
1005       
1006       osg::MatrixTransform* position =
1007         new osg::MatrixTransform(transformMat);
1008       position->setName("positionRandomeModel");
1009       position->addChild(node);
1010       models.push_back(ModelLOD(position, obj.lod));
1011     }
1012     RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1013     quadtree.buildQuadTree(models.begin(), models.end());
1014     randomObjects = quadtree.getRoot();
1015     randomObjects->setName("Random objects");
1016   }
1017
1018   if (! tileGeometryBin.randomBuildings.empty()) {
1019     buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1020                                 options);                                
1021     buildingNode->setName("Random buildings");
1022   }
1023
1024   if (use_random_vegetation && matlib) {
1025     // Now add some random forest.
1026     tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1027     
1028     if (! tileGeometryBin.randomForest.empty()) {
1029       forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1030                                 options);
1031       forestNode->setName("Random trees");
1032     }
1033   }  
1034
1035   // FIXME: ugly, has a side effect
1036   if (matlib)
1037     tileGeometryBin.computeRandomSurfaceLights(matlib);
1038
1039   if (tileGeometryBin.tileLights.getNumLights() > 0
1040       || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1041     osg::Group* groundLights0 = new osg::Group;
1042     groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1043     groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1044     osg::Geode* geode = new osg::Geode;
1045     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1046     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1047     groundLights0->addChild(geode);
1048     lightGroup->addChild(groundLights0);
1049   }
1050   
1051   if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1052     osg::Group* groundLights1 = new osg::Group;
1053     groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1054     groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1055     osg::Group* groundLights2 = new osg::Group;
1056     groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1057     groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1058     osg::Geode* geode = new osg::Geode;
1059     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1060     groundLights1->addChild(geode);
1061     lightGroup->addChild(groundLights1);
1062     geode = new osg::Geode;
1063     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1064     groundLights2->addChild(geode);
1065     lightGroup->addChild(groundLights2);
1066   }
1067
1068   if (!tileGeometryBin.vasiLights.empty()) {
1069     EffectGeode* vasiGeode = new EffectGeode;
1070     Effect* vasiEffect
1071         = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1072     vasiGeode->setEffect(vasiEffect);
1073     SGVec4f red(1, 0, 0, 1);
1074     SGMaterial* mat = 0;
1075     if (matlib)
1076       mat = matlib->find("RWY_RED_LIGHTS");
1077     if (mat)
1078       red = mat->get_light_color();
1079     SGVec4f white(1, 1, 1, 1);
1080     mat = 0;
1081     if (matlib)
1082       mat = matlib->find("RWY_WHITE_LIGHTS");
1083     if (mat)
1084       white = mat->get_light_color();
1085     SGDirectionalLightListBin::const_iterator i;
1086     for (i = tileGeometryBin.vasiLights.begin();
1087          i != tileGeometryBin.vasiLights.end(); ++i) {
1088       vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1089     }
1090     vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1091     lightGroup->addChild(vasiGeode);
1092   }
1093   
1094   Effect* runwayEffect = 0;
1095   if (tileGeometryBin.runwayLights.getNumLights() > 0
1096       || !tileGeometryBin.rabitLights.empty()
1097       || !tileGeometryBin.reilLights.empty()
1098       || !tileGeometryBin.odalLights.empty()
1099       || tileGeometryBin.taxiLights.getNumLights() > 0)
1100       runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1101   if (tileGeometryBin.runwayLights.getNumLights() > 0
1102       || !tileGeometryBin.rabitLights.empty()
1103       || !tileGeometryBin.reilLights.empty()
1104       || !tileGeometryBin.odalLights.empty()
1105       || !tileGeometryBin.holdshortLights.empty()
1106       || !tileGeometryBin.guardLights.empty()) {
1107     osg::Group* rwyLights = new osg::Group;
1108     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1109     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1110     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1111       EffectGeode* geode = new EffectGeode;
1112       geode->setEffect(runwayEffect);
1113       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1114                                                    .runwayLights));
1115       rwyLights->addChild(geode);
1116     }
1117     SGDirectionalLightListBin::const_iterator i;
1118     for (i = tileGeometryBin.rabitLights.begin();
1119          i != tileGeometryBin.rabitLights.end(); ++i) {
1120       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1121     }
1122     for (i = tileGeometryBin.reilLights.begin();
1123          i != tileGeometryBin.reilLights.end(); ++i) {
1124       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1125     }
1126     for (i = tileGeometryBin.holdshortLights.begin();
1127          i != tileGeometryBin.holdshortLights.end(); ++i) {
1128       rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1129     }
1130     for (i = tileGeometryBin.guardLights.begin();
1131          i != tileGeometryBin.guardLights.end(); ++i) {
1132       rwyLights->addChild(SGLightFactory::getGuard(*i));
1133     }
1134     SGLightListBin::const_iterator j;
1135     for (j = tileGeometryBin.odalLights.begin();
1136          j != tileGeometryBin.odalLights.end(); ++j) {
1137       rwyLights->addChild(SGLightFactory::getOdal(*j));
1138     }
1139     lightGroup->addChild(rwyLights);
1140   }
1141
1142   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1143     osg::Group* taxiLights = new osg::Group;
1144     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1145     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1146     EffectGeode* geode = new EffectGeode;
1147     geode->setEffect(runwayEffect);
1148     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1149     taxiLights->addChild(geode);
1150     lightGroup->addChild(taxiLights);
1151   }
1152
1153   // The toplevel transform for that tile.
1154   osg::MatrixTransform* transform = new osg::MatrixTransform;
1155   transform->setName(path);
1156   transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1157                        osg::Matrix::translate(toOsg(center)));
1158   transform->addChild(terrainGroup);
1159   if (lightGroup->getNumChildren() > 0) {
1160     osg::LOD* lightLOD = new osg::LOD;
1161     lightLOD->addChild(lightGroup.get(), 0, 60000);
1162     // VASI is always on, so doesn't use light bits.
1163     lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1164     transform->addChild(lightLOD);
1165   }
1166   
1167   if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1168   
1169     // Add a LoD node, so we don't try to display anything when the tile center
1170     // is more than 20km away.
1171     osg::LOD* objectLOD = new osg::LOD;
1172     
1173     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1174     if (forestNode.valid())  objectLOD->addChild(forestNode.get(), 0, 20000);
1175     if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1176     
1177     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1178     objectLOD->setNodeMask(nodeMask);
1179     transform->addChild(objectLOD);
1180   }
1181   transform->setNodeMask( ~simgear::MODELLIGHT_BIT );
1182   
1183   return transform;
1184 }