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