]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Merge branch 'maint' into next
[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 <simgear/debug/logstream.hxx>
44 #include <simgear/io/sg_binobj.hxx>
45 #include <simgear/math/sg_geodesy.hxx>
46 #include <simgear/math/sg_random.h>
47 #include <simgear/scene/material/mat.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/scene/model/SGOffsetTransform.hxx>
50 #include <simgear/scene/util/SGUpdateVisitor.hxx>
51 #include <simgear/scene/util/SGNodeMasks.hxx>
52 #include <simgear/scene/util/QuadTreeBuilder.hxx>
53
54 #include "SGTexturedTriangleBin.hxx"
55 #include "SGLightBin.hxx"
56 #include "SGModelBin.hxx"
57 #include "TreeBin.hxx"
58 #include "SGDirectionalLightBin.hxx"
59 #include "GroundLightManager.hxx"
60
61
62 #include "userdata.hxx"
63 #include "pt_lights.hxx"
64
65 using namespace simgear;
66
67 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
68 typedef std::list<SGLightBin> SGLightListBin;
69 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
70
71 struct SGTileGeometryBin {
72   SGMaterialTriangleMap materialTriangleMap;
73   SGLightBin tileLights;
74   SGLightBin randomTileLights;
75   TreeBin randomForest;
76   SGDirectionalLightBin runwayLights;
77   SGDirectionalLightBin taxiLights;
78   SGDirectionalLightListBin vasiLights;
79   SGDirectionalLightListBin rabitLights;
80   SGLightListBin odalLights;
81   SGDirectionalLightListBin reilLights;
82   SGMatModelBin randomModels;
83
84   static SGVec4f
85   getMaterialLightColor(const SGMaterial* material)
86   {
87     if (!material)
88       return SGVec4f(1, 1, 1, 0.8);
89     return material->get_light_color();
90   }
91
92   static void
93   addPointGeometry(SGLightBin& lights,
94                    const std::vector<SGVec3d>& vertices,
95                    const SGVec4f& color,
96                    const int_list& pts_v)
97   {
98     for (unsigned i = 0; i < pts_v.size(); ++i)
99       lights.insert(toVec3f(vertices[pts_v[i]]), color);
100   }
101
102   static void
103   addPointGeometry(SGDirectionalLightBin& lights,
104                    const std::vector<SGVec3d>& vertices,
105                    const std::vector<SGVec3f>& normals,
106                    const SGVec4f& color,
107                    const int_list& pts_v,
108                    const int_list& pts_n)
109   {
110     // If the normal indices match the vertex indices, use seperate
111     // normal indices. Else reuse the vertex indices for the normals.
112     if (pts_v.size() == pts_n.size()) {
113       for (unsigned i = 0; i < pts_v.size(); ++i)
114         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
115     } else {
116       for (unsigned i = 0; i < pts_v.size(); ++i)
117         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
118     }
119   }
120
121   bool
122   insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
123   {
124     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
125       SG_LOG(SG_TERRAIN, SG_ALERT,
126              "Group list sizes for points do not match!");
127       return false;
128     }
129
130     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
131       std::string materialName = obj.get_pt_materials()[grp];
132       SGMaterial* material = matlib->find(materialName);
133       SGVec4f color = getMaterialLightColor(material);
134
135       if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
136         // Just plain lights. Not something for the runway.
137         addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
138                          obj.get_pts_v()[grp]);
139       } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
140                  || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
141         addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
142                          color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
143       } else if (materialName == "RWY_VASI_LIGHTS") {
144         vasiLights.push_back(SGDirectionalLightBin());
145         addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
146                          obj.get_normals(), color, obj.get_pts_v()[grp],
147                          obj.get_pts_n()[grp]);
148       } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
149         rabitLights.push_back(SGDirectionalLightBin());
150         addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
151                          obj.get_normals(), color, obj.get_pts_v()[grp],
152                          obj.get_pts_n()[grp]);
153       } else if (materialName == "RWY_ODALS_LIGHTS") {
154         odalLights.push_back(SGLightBin());
155         addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
156                          color, obj.get_pts_v()[grp]);
157       } else if (materialName == "RWY_REIL_LIGHTS") {
158         reilLights.push_back(SGDirectionalLightBin());
159         addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
160                          obj.get_normals(), color, obj.get_pts_v()[grp],
161                          obj.get_pts_n()[grp]);
162       } else {
163         // what is left must be runway lights
164         addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
165                          obj.get_normals(), color, obj.get_pts_v()[grp],
166                          obj.get_pts_n()[grp]);
167       }
168     }
169
170     return true;
171   }
172
173
174   static SGVec2f
175   getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
176               const SGVec2f& tcScale, unsigned i)
177   {
178     if (tc.empty())
179       return tcScale;
180     else if (tc.size() == 1)
181       return mult(texCoords[tc[0]], tcScale);
182     else
183       return mult(texCoords[tc[i]], tcScale);
184   }
185
186   static void
187   addTriangleGeometry(SGTexturedTriangleBin& triangles,
188                       const std::vector<SGVec3d>& vertices,
189                       const std::vector<SGVec3f>& normals,
190                       const std::vector<SGVec2f>& texCoords,
191                       const int_list& tris_v,
192                       const int_list& tris_n,
193                       const int_list& tris_tc,
194                       const SGVec2f& tcScale)
195   {
196     if (tris_v.size() != tris_n.size()) {
197       // If the normal indices do not match, they should be inmplicitly
198       // the same than the vertex indices. So just call ourselves again
199       // with the matching index vector.
200       addTriangleGeometry(triangles, vertices, normals, texCoords,
201                           tris_v, tris_v, tris_tc, tcScale);
202       return;
203     }
204
205     for (unsigned i = 2; i < tris_v.size(); i += 3) {
206       SGVertNormTex v0;
207       v0.vertex = toVec3f(vertices[tris_v[i-2]]);
208       v0.normal = normals[tris_n[i-2]];
209       v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
210       SGVertNormTex v1;
211       v1.vertex = toVec3f(vertices[tris_v[i-1]]);
212       v1.normal = normals[tris_n[i-1]];
213       v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
214       SGVertNormTex v2;
215       v2.vertex = toVec3f(vertices[tris_v[i]]);
216       v2.normal = normals[tris_n[i]];
217       v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
218       triangles.insert(v0, v1, v2);
219     }
220   }
221
222   static void
223   addStripGeometry(SGTexturedTriangleBin& triangles,
224                    const std::vector<SGVec3d>& vertices,
225                    const std::vector<SGVec3f>& normals,
226                    const std::vector<SGVec2f>& texCoords,
227                    const int_list& strips_v,
228                    const int_list& strips_n,
229                    const int_list& strips_tc,
230                    const SGVec2f& tcScale)
231   {
232     if (strips_v.size() != strips_n.size()) {
233       // If the normal indices do not match, they should be inmplicitly
234       // the same than the vertex indices. So just call ourselves again
235       // with the matching index vector.
236       addStripGeometry(triangles, vertices, normals, texCoords,
237                        strips_v, strips_v, strips_tc, tcScale);
238       return;
239     }
240
241     for (unsigned i = 2; i < strips_v.size(); ++i) {
242       SGVertNormTex v0;
243       v0.vertex = toVec3f(vertices[strips_v[i-2]]);
244       v0.normal = normals[strips_n[i-2]];
245       v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
246       SGVertNormTex v1;
247       v1.vertex = toVec3f(vertices[strips_v[i-1]]);
248       v1.normal = normals[strips_n[i-1]];
249       v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
250       SGVertNormTex v2;
251       v2.vertex = toVec3f(vertices[strips_v[i]]);
252       v2.normal = normals[strips_n[i]];
253       v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
254       if (i%2)
255         triangles.insert(v1, v0, v2);
256       else
257         triangles.insert(v0, v1, v2);
258     }
259   }
260   
261   static void
262   addFanGeometry(SGTexturedTriangleBin& triangles,
263                  const std::vector<SGVec3d>& vertices,
264                  const std::vector<SGVec3f>& normals,
265                  const std::vector<SGVec2f>& texCoords,
266                  const int_list& fans_v,
267                  const int_list& fans_n,
268                  const int_list& fans_tc,
269                  const SGVec2f& tcScale)
270   {
271     if (fans_v.size() != fans_n.size()) {
272       // If the normal indices do not match, they should be implicitly
273       // the same than the vertex indices. So just call ourselves again
274       // with the matching index vector.
275       addFanGeometry(triangles, vertices, normals, texCoords,
276                      fans_v, fans_v, fans_tc, tcScale);
277       return;
278     }
279
280     SGVertNormTex v0;
281     v0.vertex = toVec3f(vertices[fans_v[0]]);
282     v0.normal = normals[fans_n[0]];
283     v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
284     SGVertNormTex v1;
285     v1.vertex = toVec3f(vertices[fans_v[1]]);
286     v1.normal = normals[fans_n[1]];
287     v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
288     for (unsigned i = 2; i < fans_v.size(); ++i) {
289       SGVertNormTex v2;
290       v2.vertex = toVec3f(vertices[fans_v[i]]);
291       v2.normal = normals[fans_n[i]];
292       v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
293       triangles.insert(v0, v1, v2);
294       v1 = v2;
295     }
296   }
297
298   SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
299   {
300     if (!matlib)
301       return SGVec2f(1, 1);
302     SGMaterial* material = matlib->find(name);
303     if (!material)
304       return SGVec2f(1, 1);
305
306     return material->get_tex_coord_scale();
307   }
308
309   bool
310   insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
311   {
312     if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
313         obj.get_tris_tc().size() < obj.get_tris_v().size()) {
314       SG_LOG(SG_TERRAIN, SG_ALERT,
315              "Group list sizes for triangles do not match!");
316       return false;
317     }
318
319     for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
320       std::string materialName = obj.get_tri_materials()[grp];
321       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
322       addTriangleGeometry(materialTriangleMap[materialName],
323                           obj.get_wgs84_nodes(), obj.get_normals(),
324                           obj.get_texcoords(), obj.get_tris_v()[grp],
325                           obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
326                           tcScale);
327     }
328
329     if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
330         obj.get_strips_tc().size() < obj.get_strips_v().size()) {
331       SG_LOG(SG_TERRAIN, SG_ALERT,
332              "Group list sizes for strips do not match!");
333       return false;
334     }
335     for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
336       std::string materialName = obj.get_strip_materials()[grp];
337       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
338       addStripGeometry(materialTriangleMap[materialName],
339                        obj.get_wgs84_nodes(), obj.get_normals(),
340                        obj.get_texcoords(), obj.get_strips_v()[grp],
341                        obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
342                        tcScale);
343     }
344
345     if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
346         obj.get_fans_tc().size() < obj.get_fans_v().size()) {
347       SG_LOG(SG_TERRAIN, SG_ALERT,
348              "Group list sizes for fans do not match!");
349       return false;
350     }
351     for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
352       std::string materialName = obj.get_fan_materials()[grp];
353       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
354       addFanGeometry(materialTriangleMap[materialName],
355                      obj.get_wgs84_nodes(), obj.get_normals(),
356                      obj.get_texcoords(), obj.get_fans_v()[grp],
357                      obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
358                      tcScale);
359     }
360     return true;
361   }
362
363   osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
364   {
365     if (materialTriangleMap.empty())
366       return 0;
367
368     osg::Geode* geode = new osg::Geode;
369     SGMaterialTriangleMap::const_iterator i;
370     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
371       osg::Geometry* geometry = i->second.buildGeometry();
372       SGMaterial *mat = matlib->find(i->first);
373       if (mat)
374         geometry->setStateSet(mat->get_state());
375       geode->addDrawable(geometry);
376     }
377     return geode;
378   }
379
380   void computeRandomSurfaceLights(SGMaterialLib* matlib)
381   {
382     SGMaterialTriangleMap::iterator i;
383         
384     // generate a repeatable random seed
385     mt seed;
386     mt_init(&seed, unsigned(123));
387     
388     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
389       SGMaterial *mat = matlib->find(i->first);
390       if (!mat)
391         continue;
392
393       float coverage = mat->get_light_coverage();
394       if (coverage <= 0)
395         continue;
396       if (coverage < 10000.0) {
397         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
398                << coverage << ", pushing up to 10000");
399         coverage = 10000;
400       }
401       
402       std::vector<SGVec3f> randomPoints;
403       i->second.addRandomSurfacePoints(coverage, 3, randomPoints);
404       std::vector<SGVec3f>::iterator j;
405       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
406         float zombie = mt_rand(&seed);
407         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
408         float factor = mt_rand(&seed);
409         factor *= factor;
410
411         float bright = 1;
412         SGVec4f color;
413         if ( zombie > 0.5 ) {
414           // 50% chance of yellowish
415           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
416         } else if (zombie > 0.15f) {
417           // 35% chance of whitish
418           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
419         } else if (zombie > 0.05f) {
420           // 10% chance of orangish
421           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
422         } else {
423           // 5% chance of redish
424           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
425         }
426         randomTileLights.insert(*j, color);
427       }
428     }
429   }
430
431   void computeRandomForest(SGMaterialLib* matlib)
432   {
433     SGMaterialTriangleMap::iterator i;
434
435     // generate a repeatable random seed
436     mt seed;
437     mt_init(&seed, unsigned(586));
438
439     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
440       SGMaterial *mat = matlib->find(i->first);
441       if (!mat)
442         continue;
443
444       float coverage = mat->get_tree_coverage();
445       if (coverage <= 0)
446         continue;
447
448       // Attributes that don't vary by tree
449       randomForest.texture = mat->get_tree_texture();
450       randomForest.range   = mat->get_tree_range();
451       randomForest.width   = mat->get_tree_width();
452       randomForest.height  = mat->get_tree_height();
453       randomForest.texture_varieties = mat->get_tree_varieties();
454
455       std::vector<SGVec3f> randomPoints;
456       i->second.addRandomSurfacePoints(coverage, 0, randomPoints);
457       std::vector<SGVec3f>::iterator j;
458       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
459
460         // Apply a random scaling factor and texture index.
461         float scale = (mt_rand(&seed) + mt_rand(&seed)) / 2.0f + 0.5f;
462         int v = (int) (mt_rand(&seed) * mat->get_tree_varieties());
463         if (v == mat->get_tree_varieties()) v--;         
464         randomForest.insert(*j, v, scale);
465       }
466     }
467   }
468
469   void computeRandomObjects(SGMaterialLib* matlib)
470   {
471     SGMaterialTriangleMap::iterator i;
472
473     // generate a repeatable random seed
474     mt seed;
475     mt_init(&seed, unsigned(123));
476
477     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
478       SGMaterial *mat = matlib->find(i->first);
479       if (!mat)
480         continue;
481
482       int group_count = mat->get_object_group_count();
483
484       if (group_count > 0)
485       {
486         for (int j = 0; j < group_count; j++)
487         {
488           SGMatModelGroup *object_group =  mat->get_object_group(j);
489           int nObjects = object_group->get_object_count();
490
491           if (nObjects > 0)
492           {
493             // For each of the random models in the group, determine an appropriate
494             // number of random placements and insert them.
495             for (int k = 0; k < nObjects; k++) {
496               SGMatModel * object = object_group->get_object(k);
497
498               std::vector<SGVec3f> randomPoints;
499
500               i->second.addRandomPoints(object->get_coverage_m2(), randomPoints);
501               std::vector<SGVec3f>::iterator l;
502               for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
503                 randomModels.insert(*l, object, (int)object->get_randomized_range_m(&seed));
504               }
505             }
506           }
507         }
508       }
509     }
510   }
511
512   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
513   {
514     if (!insertPtGeometry(obj, matlib))
515       return false;
516     if (!insertSurfaceGeometry(obj, matlib))
517       return false;
518     return true;
519   }
520 };
521
522 typedef std::pair<osg::Node*, int> ModelLOD;
523 struct MakeQuadLeaf {
524     osg::LOD* operator() () const { return new osg::LOD; }
525 };
526 struct AddModelLOD {
527     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
528     {
529         leaf->addChild(mlod.first, 0, mlod.second);
530     }
531 };
532 struct GetModelLODCoord {
533     GetModelLODCoord() {}
534     GetModelLODCoord(const GetModelLODCoord& rhs)
535     {}
536     osg::Vec3 operator() (const ModelLOD& mlod) const
537     {
538         return mlod.first->getBound().center();
539     }
540 };
541
542 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
543                         GetModelLODCoord>  RandomObjectsQuadtree;
544
545 osg::Node*
546 SGLoadBTG(const std::string& path, SGMaterialLib *matlib, bool calc_lights, bool use_random_objects, bool use_random_vegetation)
547 {
548   SGBinObject tile;
549   if (!tile.read_bin(path))
550     return false;
551
552   SGVec3d center = tile.get_gbs_center2();
553   SGGeod geodPos = SGGeod::fromCart(center);
554   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
555
556   // rotate the tiles so that the bounding boxes get nearly axis aligned.
557   // this will help the collision tree's bounding boxes a bit ...
558   std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
559   for (unsigned i = 0; i < nodes.size(); ++i)
560     nodes[i] = hlOr.transform(nodes[i]);
561   tile.set_wgs84_nodes(nodes);
562
563   SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
564   std::vector<SGVec3f> normals = tile.get_normals();
565   for (unsigned i = 0; i < normals.size(); ++i)
566     normals[i] = hlOrf.transform(normals[i]);
567   tile.set_normals(normals);
568
569   SGTileGeometryBin tileGeometryBin;
570   if (!tileGeometryBin.insertBinObj(tile, matlib))
571     return false;
572
573   SGVec3f up(0, 0, 1);
574   GroundLightManager* lightManager = GroundLightManager::instance();
575
576   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
577   osg::ref_ptr<osg::Group> randomObjects;
578   osg::ref_ptr<osg::Group> randomForest;
579   osg::Group* terrainGroup = new osg::Group;
580
581   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
582   if (node)
583     terrainGroup->addChild(node);
584
585   if (use_random_objects || use_random_vegetation) {
586     if (use_random_objects) {
587       tileGeometryBin.computeRandomObjects(matlib);
588     
589       if (tileGeometryBin.randomModels.getNumModels() > 0) {
590         // Generate a repeatable random seed
591         mt seed;
592         mt_init(&seed, unsigned(123));
593
594         std::vector<ModelLOD> models;
595         for (unsigned int i = 0;
596              i < tileGeometryBin.randomModels.getNumModels(); i++) {
597           SGMatModelBin::MatModel obj
598             = tileGeometryBin.randomModels.getMatModel(i);
599           osg::Node* node = sgGetRandomModel(obj.model);
600         
601           // Create a matrix to place the object in the correct
602           // location, and then apply the rotation matrix created
603           // above, with an additional random heading rotation if appropriate.
604           osg::Matrix transformMat;
605           transformMat = osg::Matrix::translate(obj.position.osg());
606           if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
607             // Rotate the object around the z axis.
608             double hdg = mt_rand(&seed) * M_PI * 2;
609             transformMat.preMult(osg::Matrix::rotate(hdg,
610                                                      osg::Vec3d(0.0, 0.0, 1.0)));
611           }
612           osg::MatrixTransform* position =
613             new osg::MatrixTransform(transformMat);
614           position->addChild(node);
615           models.push_back(ModelLOD(position, obj.lod));
616         }
617         RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
618         quadtree.buildQuadTree(models.begin(), models.end());
619         randomObjects = quadtree.getRoot();
620         randomObjects->setName("random objects");
621       }
622     }
623
624     if (use_random_vegetation) {
625       // Now add some random forest.
626       tileGeometryBin.computeRandomForest(matlib);
627
628       if (tileGeometryBin.randomForest.getNumTrees() > 0) {
629         randomForest = createForest(tileGeometryBin.randomForest,
630                                     osg::Matrix::identity());
631         randomForest->setName("random trees");
632       }
633     } 
634   }
635
636   if (calc_lights) {
637     // FIXME: ugly, has a side effect
638     tileGeometryBin.computeRandomSurfaceLights(matlib);
639
640     if (tileGeometryBin.tileLights.getNumLights() > 0
641         || tileGeometryBin.randomTileLights.getNumLights() > 0) {
642       osg::Group* groundLights0 = new osg::Group;
643       groundLights0->setStateSet(lightManager->getGroundLightStateSet());
644       groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
645       osg::Geode* geode = new osg::Geode;
646       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
647       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
648       groundLights0->addChild(geode);
649       lightGroup->addChild(groundLights0);
650     }
651     if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
652       osg::Group* groundLights1 = new osg::Group;
653       groundLights1->setStateSet(lightManager->getGroundLightStateSet());
654       groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
655       osg::Group* groundLights2 = new osg::Group;
656       groundLights2->setStateSet(lightManager->getGroundLightStateSet());
657       groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
658       osg::Geode* geode = new osg::Geode;
659       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
660       groundLights1->addChild(geode);
661       lightGroup->addChild(groundLights1);
662       geode = new osg::Geode;
663       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
664       groundLights2->addChild(geode);
665       lightGroup->addChild(groundLights2);
666     }
667   }
668
669   if (!tileGeometryBin.vasiLights.empty()) {
670     osg::Geode* vasiGeode = new osg::Geode;
671     SGVec4f red(1, 0, 0, 1);
672     SGMaterial* mat = matlib->find("RWY_RED_LIGHTS");
673     if (mat)
674       red = mat->get_light_color();
675     SGVec4f white(1, 1, 1, 1);
676     mat = matlib->find("RWY_WHITE_LIGHTS");
677     if (mat)
678       white = mat->get_light_color();
679
680     SGDirectionalLightListBin::const_iterator i;
681     for (i = tileGeometryBin.vasiLights.begin();
682          i != tileGeometryBin.vasiLights.end(); ++i) {
683       vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
684     }
685     vasiGeode->setCullCallback(new SGPointSpriteLightCullCallback(osg::Vec3(1, 0.0001, 0.000001), 6));
686     vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
687     lightGroup->addChild(vasiGeode);
688   }
689
690   if (tileGeometryBin.runwayLights.getNumLights() > 0
691       || !tileGeometryBin.rabitLights.empty()
692       || !tileGeometryBin.reilLights.empty()
693       || !tileGeometryBin.odalLights.empty()) {
694     osg::Group* rwyLights = new osg::Group;
695     rwyLights->setCullCallback(new SGPointSpriteLightCullCallback);
696     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
697     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
698     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
699       osg::Geode* geode = new osg::Geode;
700       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
701                                                    .runwayLights));
702       rwyLights->addChild(geode);
703     }
704     SGDirectionalLightListBin::const_iterator i;
705     for (i = tileGeometryBin.rabitLights.begin();
706          i != tileGeometryBin.rabitLights.end(); ++i) {
707       rwyLights->addChild(SGLightFactory::getSequenced(*i));
708     }
709     for (i = tileGeometryBin.reilLights.begin();
710          i != tileGeometryBin.reilLights.end(); ++i) {
711       rwyLights->addChild(SGLightFactory::getSequenced(*i));
712     }
713     SGLightListBin::const_iterator j;
714     for (j = tileGeometryBin.odalLights.begin();
715          j != tileGeometryBin.odalLights.end(); ++j) {
716       rwyLights->addChild(SGLightFactory::getOdal(*j));
717     }
718     lightGroup->addChild(rwyLights);
719   }
720
721   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
722     osg::Group* taxiLights = new osg::Group;
723     taxiLights->setCullCallback(new SGPointSpriteLightCullCallback);
724     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
725     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
726     osg::Geode* geode = new osg::Geode;
727     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
728     taxiLights->addChild(geode);
729     lightGroup->addChild(taxiLights);
730   }
731
732   // The toplevel transform for that tile.
733   osg::MatrixTransform* transform = new osg::MatrixTransform;
734   transform->setName(path);
735   transform->setMatrix(osg::Matrix::rotate(hlOr.osg())*
736                        osg::Matrix::translate(center.osg()));
737   transform->addChild(terrainGroup);
738   if (lightGroup->getNumChildren() > 0) {
739     osg::LOD* lightLOD = new osg::LOD;
740     lightLOD->addChild(lightGroup.get(), 0, 30000);
741     // VASI is always on, so doesn't use light bits.
742     lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT); 
743     transform->addChild(lightLOD);
744   }
745   
746   if (randomObjects.valid() || randomForest.valid()) {
747   
748     // Add a LoD node, so we don't try to display anything when the tile center
749     // is more than 20km away.
750     osg::LOD* objectLOD = new osg::LOD;
751     
752     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
753     if (randomForest.valid())  objectLOD->addChild(randomForest.get(), 0, 20000);
754     
755     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
756     objectLOD->setNodeMask(nodeMask);
757     transform->addChild(objectLOD);
758   }
759   
760   return transform;
761 }