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