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