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