1 // obj.cxx -- routines to handle loading scenery and building the plib
4 // Written by Curtis Olson, started October 1997.
6 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
26 # include <simgear_config.h>
31 #include <simgear/compiler.h>
35 #include <osg/Geometry>
38 #include <osg/MatrixTransform>
40 #include <osg/Referenced>
41 #include <osg/StateSet>
44 #include <osgUtil/Simplifier>
46 #include <boost/foreach.hpp>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/io/sg_binobj.hxx>
52 #include <simgear/math/sg_geodesy.hxx>
53 #include <simgear/math/sg_random.h>
54 #include <simgear/math/SGMisc.hxx>
55 #include <simgear/scene/material/Effect.hxx>
56 #include <simgear/scene/material/EffectGeode.hxx>
57 #include <simgear/scene/material/mat.hxx>
58 #include <simgear/scene/material/matmodel.hxx>
59 #include <simgear/scene/material/matlib.hxx>
60 #include <simgear/scene/model/SGOffsetTransform.hxx>
61 #include <simgear/scene/util/SGUpdateVisitor.hxx>
62 #include <simgear/scene/util/SGNodeMasks.hxx>
63 #include <simgear/scene/util/QuadTreeBuilder.hxx>
64 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
65 #include <simgear/scene/util/OptionsReadFileCallback.hxx>
67 #include "SGTexturedTriangleBin.hxx"
68 #include "SGLightBin.hxx"
69 #include "SGModelBin.hxx"
70 #include "SGBuildingBin.hxx"
71 #include "TreeBin.hxx"
72 #include "SGDirectionalLightBin.hxx"
73 #include "GroundLightManager.hxx"
75 #include "pt_lights.hxx"
77 #define SG_SIMPLIFIER_RATIO 0.001
78 #define SG_SIMPLIFIER_MAX_LENGTH 1000.0
79 #define SG_SIMPLIFIER_MAX_ERROR 2000.0
80 #define SG_OBJECT_RANGE 9000.0
81 #define SG_TILE_RADIUS 14000.0
83 using namespace simgear;
85 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
86 typedef std::list<SGLightBin> SGLightListBin;
87 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
89 class SGTileGeometryBin : public osg::Referenced {
91 SGMaterialTriangleMap materialTriangleMap;
92 SGLightBin tileLights;
93 SGLightBin randomTileLights;
94 SGTreeBinList randomForest;
95 SGDirectionalLightBin runwayLights;
96 SGDirectionalLightBin taxiLights;
97 SGDirectionalLightListBin vasiLights;
98 SGDirectionalLightListBin rabitLights;
99 SGLightListBin odalLights;
100 SGDirectionalLightListBin holdshortLights;
101 SGDirectionalLightListBin guardLights;
102 SGDirectionalLightListBin reilLights;
103 SGMatModelBin randomModels;
104 SGBuildingBinList randomBuildings;
107 getMaterialLightColor(const SGMaterial* material)
110 return SGVec4f(1, 1, 1, 0.8);
111 return material->get_light_color();
115 addPointGeometry(SGLightBin& lights,
116 const std::vector<SGVec3d>& vertices,
117 const SGVec4f& color,
118 const int_list& pts_v)
120 for (unsigned i = 0; i < pts_v.size(); ++i)
121 lights.insert(toVec3f(vertices[pts_v[i]]), color);
125 addPointGeometry(SGDirectionalLightBin& lights,
126 const std::vector<SGVec3d>& vertices,
127 const std::vector<SGVec3f>& normals,
128 const SGVec4f& color,
129 const int_list& pts_v,
130 const int_list& pts_n)
132 // If the normal indices match the vertex indices, use seperate
133 // normal indices. Else reuse the vertex indices for the normals.
134 if (pts_v.size() == pts_n.size()) {
135 for (unsigned i = 0; i < pts_v.size(); ++i)
136 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
138 for (unsigned i = 0; i < pts_v.size(); ++i)
139 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
144 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
146 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
147 SG_LOG(SG_TERRAIN, SG_ALERT,
148 "Group list sizes for points do not match!");
152 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
153 std::string materialName = obj.get_pt_materials()[grp];
154 SGMaterial* material = 0;
156 material = matlib->findCached(materialName);
157 SGVec4f color = getMaterialLightColor(material);
159 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
160 // Just plain lights. Not something for the runway.
161 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
162 obj.get_pts_v()[grp]);
163 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
164 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
165 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
166 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
167 } else if (materialName == "RWY_VASI_LIGHTS") {
168 vasiLights.push_back(SGDirectionalLightBin());
169 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
170 obj.get_normals(), color, obj.get_pts_v()[grp],
171 obj.get_pts_n()[grp]);
172 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
173 rabitLights.push_back(SGDirectionalLightBin());
174 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
175 obj.get_normals(), color, obj.get_pts_v()[grp],
176 obj.get_pts_n()[grp]);
177 } else if (materialName == "RWY_ODALS_LIGHTS") {
178 odalLights.push_back(SGLightBin());
179 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
180 color, obj.get_pts_v()[grp]);
181 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
182 holdshortLights.push_back(SGDirectionalLightBin());
183 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
184 obj.get_normals(), color, obj.get_pts_v()[grp],
185 obj.get_pts_n()[grp]);
186 } else if (materialName == "RWY_GUARD_LIGHTS") {
187 guardLights.push_back(SGDirectionalLightBin());
188 addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
189 obj.get_normals(), color, obj.get_pts_v()[grp],
190 obj.get_pts_n()[grp]);
191 } else if (materialName == "RWY_REIL_LIGHTS") {
192 reilLights.push_back(SGDirectionalLightBin());
193 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
194 obj.get_normals(), color, obj.get_pts_v()[grp],
195 obj.get_pts_n()[grp]);
197 // what is left must be runway lights
198 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
199 obj.get_normals(), color, obj.get_pts_v()[grp],
200 obj.get_pts_n()[grp]);
209 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
210 const SGVec2f& tcScale, unsigned i)
214 else if (tc.size() == 1)
215 return mult(texCoords[tc[0]], tcScale);
217 return mult(texCoords[tc[i]], tcScale);
221 addTriangleGeometry(SGTexturedTriangleBin& triangles,
222 const std::vector<SGVec3d>& vertices,
223 const std::vector<SGVec3f>& normals,
224 const std::vector<SGVec2f>& texCoords,
225 const int_list& tris_v,
226 const int_list& tris_n,
227 const int_list& tris_tc,
228 const SGVec2f& tcScale)
230 if (tris_v.size() != tris_n.size()) {
231 // If the normal indices do not match, they should be inmplicitly
232 // the same than the vertex indices. So just call ourselves again
233 // with the matching index vector.
234 addTriangleGeometry(triangles, vertices, normals, texCoords,
235 tris_v, tris_v, tris_tc, tcScale);
239 for (unsigned i = 2; i < tris_v.size(); i += 3) {
241 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
242 v0.normal = normals[tris_n[i-2]];
243 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
245 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
246 v1.normal = normals[tris_n[i-1]];
247 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
249 v2.vertex = toVec3f(vertices[tris_v[i]]);
250 v2.normal = normals[tris_n[i]];
251 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
252 triangles.insert(v0, v1, v2);
257 addStripGeometry(SGTexturedTriangleBin& triangles,
258 const std::vector<SGVec3d>& vertices,
259 const std::vector<SGVec3f>& normals,
260 const std::vector<SGVec2f>& texCoords,
261 const int_list& strips_v,
262 const int_list& strips_n,
263 const int_list& strips_tc,
264 const SGVec2f& tcScale)
266 if (strips_v.size() != strips_n.size()) {
267 // If the normal indices do not match, they should be inmplicitly
268 // the same than the vertex indices. So just call ourselves again
269 // with the matching index vector.
270 addStripGeometry(triangles, vertices, normals, texCoords,
271 strips_v, strips_v, strips_tc, tcScale);
275 for (unsigned i = 2; i < strips_v.size(); ++i) {
277 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
278 v0.normal = normals[strips_n[i-2]];
279 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
281 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
282 v1.normal = normals[strips_n[i-1]];
283 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
285 v2.vertex = toVec3f(vertices[strips_v[i]]);
286 v2.normal = normals[strips_n[i]];
287 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
289 triangles.insert(v1, v0, v2);
291 triangles.insert(v0, v1, v2);
296 addFanGeometry(SGTexturedTriangleBin& triangles,
297 const std::vector<SGVec3d>& vertices,
298 const std::vector<SGVec3f>& normals,
299 const std::vector<SGVec2f>& texCoords,
300 const int_list& fans_v,
301 const int_list& fans_n,
302 const int_list& fans_tc,
303 const SGVec2f& tcScale)
305 if (fans_v.size() != fans_n.size()) {
306 // If the normal indices do not match, they should be implicitly
307 // the same than the vertex indices. So just call ourselves again
308 // with the matching index vector.
309 addFanGeometry(triangles, vertices, normals, texCoords,
310 fans_v, fans_v, fans_tc, tcScale);
315 v0.vertex = toVec3f(vertices[fans_v[0]]);
316 v0.normal = normals[fans_n[0]];
317 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
319 v1.vertex = toVec3f(vertices[fans_v[1]]);
320 v1.normal = normals[fans_n[1]];
321 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
322 for (unsigned i = 2; i < fans_v.size(); ++i) {
324 v2.vertex = toVec3f(vertices[fans_v[i]]);
325 v2.normal = normals[fans_n[i]];
326 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
327 triangles.insert(v0, v1, v2);
332 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
335 return SGVec2f(1, 1);
336 SGMaterial* material = matlib->findCached(name);
338 return SGVec2f(1, 1);
340 return material->get_tex_coord_scale();
344 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
346 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
347 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
348 SG_LOG(SG_TERRAIN, SG_ALERT,
349 "Group list sizes for triangles do not match!");
353 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
354 std::string materialName = obj.get_tri_materials()[grp];
355 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
356 addTriangleGeometry(materialTriangleMap[materialName],
357 obj.get_wgs84_nodes(), obj.get_normals(),
358 obj.get_texcoords(), obj.get_tris_v()[grp],
359 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
363 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
364 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
365 SG_LOG(SG_TERRAIN, SG_ALERT,
366 "Group list sizes for strips do not match!");
369 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
370 std::string materialName = obj.get_strip_materials()[grp];
371 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
372 addStripGeometry(materialTriangleMap[materialName],
373 obj.get_wgs84_nodes(), obj.get_normals(),
374 obj.get_texcoords(), obj.get_strips_v()[grp],
375 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
379 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
380 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
381 SG_LOG(SG_TERRAIN, SG_ALERT,
382 "Group list sizes for fans do not match!");
385 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
386 std::string materialName = obj.get_fan_materials()[grp];
387 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
388 addFanGeometry(materialTriangleMap[materialName],
389 obj.get_wgs84_nodes(), obj.get_normals(),
390 obj.get_texcoords(), obj.get_fans_v()[grp],
391 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
397 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib, bool useVBOs) const
399 if (materialTriangleMap.empty())
403 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
404 //osg::Geode* geode = new osg::Geode;
405 SGMaterialTriangleMap::const_iterator i;
406 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
407 osg::Geometry* geometry = i->second.buildGeometry(useVBOs);
410 mat = matlib->findCached(i->first);
411 eg = new EffectGeode;
412 eg->setName("EffectGeode");
414 eg->setEffect(mat->get_effect(i->second));
415 eg->addDrawable(geometry);
416 eg->runGenerators(geometry); // Generate extra data needed by effect
418 group->setName("surfaceGeometryGroup");
428 void computeRandomSurfaceLights(SGMaterialLib* matlib)
430 SGMaterialTriangleMap::iterator i;
432 // generate a repeatable random seed
434 mt_init(&seed, unsigned(123));
436 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
437 SGMaterial *mat = matlib->findCached(i->first);
441 float coverage = mat->get_light_coverage();
444 if (coverage < 10000.0) {
445 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
446 << coverage << ", pushing up to 10000");
450 std::vector<SGVec3f> randomPoints;
451 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
452 std::vector<SGVec3f>::iterator j;
453 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
454 float zombie = mt_rand(&seed);
455 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
456 float factor = mt_rand(&seed);
461 if ( zombie > 0.5 ) {
462 // 50% chance of yellowish
463 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
464 } else if (zombie > 0.15f) {
465 // 35% chance of whitish
466 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
467 } else if (zombie > 0.05f) {
468 // 10% chance of orangish
469 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
471 // 5% chance of redish
472 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
474 randomTileLights.insert(*j, color);
479 void computeRandomObjectsAndBuildings(
480 SGMaterialLib* matlib,
481 float building_density,
482 bool use_random_objects,
483 bool use_random_buildings,
486 SGMaterialTriangleMap::iterator i;
488 // generate a repeatable random seed
490 mt_init(&seed, unsigned(123));
492 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
493 SGMaterial *mat = matlib->findCached(i->first);
494 SGTexturedTriangleBin triangleBin = i->second;
499 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
501 int group_count = mat->get_object_group_count();
502 float building_coverage = mat->get_building_coverage();
503 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
504 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
506 if (building_coverage == 0)
509 SGBuildingBin* bin = NULL;
511 if (building_coverage > 0) {
512 bin = new SGBuildingBin(mat, useVBOs);
513 randomBuildings.push_back(bin);
516 unsigned num = i->second.getNumTriangles();
517 int random_dropped = 0;
518 int mask_dropped = 0;
519 int building_dropped = 0;
520 int triangle_dropped = 0;
522 for (unsigned i = 0; i < num; ++i) {
523 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
525 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
526 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
527 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
528 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
529 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
530 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
531 SGVec3f normal = cross(v0, v1);
533 // Ensure the slope isn't too steep by checking the
534 // cos of the angle between the slope normal and the
535 // vertical (conveniently the z-component of the normalized
536 // normal) and values passed in.
537 float cos = normalize(normal).z();
538 float slope_density = 1.0;
539 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
540 if (cos < cos_max_density_angle) {
542 (cos - cos_zero_density_angle) /
543 (cos_max_density_angle - cos_zero_density_angle);
546 // Containers to hold the random buildings and objects generated
547 // for this triangle for collision detection purposes.
548 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
549 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
552 float area = 0.5f*length(normal);
553 if (area <= SGLimitsf::min())
556 // Generate any random objects
557 if (use_random_objects && (group_count > 0))
559 for (int j = 0; j < group_count; j++)
561 SGMatModelGroup *object_group = mat->get_object_group(j);
562 int nObjects = object_group->get_object_count();
564 if (nObjects == 0) continue;
566 // For each of the random models in the group, determine an appropriate
567 // number of random placements and insert them.
568 for (int k = 0; k < nObjects; k++) {
569 SGMatModel * object = object_group->get_object(k);
571 // Determine the number of objecst to place, taking into account
572 // the slope density factor.
573 double n = slope_density * area / object->get_coverage_m2();
575 // Use the zombie door method to determine fractional object placement.
576 n = n + mt_rand(&seed);
578 // place an object each unit of area
580 float a = mt_rand(&seed);
581 float b = mt_rand(&seed);
587 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
588 float rotation = static_cast<float>(mt_rand(&seed));
590 // Check that the point is sufficiently far from
591 // the edge of the triangle by measuring the distance
592 // from the three lines that make up the triangle.
593 float spacing = object->get_spacing_m();
595 SGVec3f p = randomPoint - vorigin;
596 float edges[] = { length(cross(p , p - v0)) / length(v0),
597 length(cross(p - v0, p - v1)) / length(v1 - v0),
598 length(cross(p - v1, p )) / length(v1) };
599 float edge_dist = *std::min_element(edges, edges + 3);
601 if (edge_dist < spacing) {
606 if (object_mask != NULL) {
607 SGVec2f texCoord = torigin + a*t0 + b*t1;
609 // Check this random point against the object mask
610 // blue (for buildings) channel.
611 osg::Image* img = object_mask->getImage();
612 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
613 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
615 if (mt_rand(&seed) > img->getColor(x, y).b()) {
616 // Failed object mask check
621 rotation = img->getColor(x,y).r();
626 // Check it isn't too close to any other random objects in the triangle
627 std::vector<std::pair<SGVec3f, float> >::iterator l;
628 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
629 float min_dist2 = (l->second + object->get_spacing_m()) *
630 (l->second + object->get_spacing_m());
632 if (distSqr(l->first, randomPoint) > min_dist2) {
639 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
640 randomModels.insert(randomPoint,
642 (int)object->get_randomized_range_m(&seed),
650 // Random objects now generated. Now generate the random buildings (if any);
651 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
653 // Calculate the number of buildings, taking into account building density (which is linear)
654 // and the slope density factor.
655 double num = building_density * building_density * slope_density * area / building_coverage;
657 // For partial units of area, use a zombie door method to
658 // create the proper random chance of an object being created
659 // for this triangle.
660 num = num + mt_rand(&seed);
666 // Cosine of the angle between the two vectors.
667 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
669 // Determine a grid spacing in each vector such that the correct
670 // coverage will result.
671 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
672 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
674 stepv0 = std::min(stepv0, 1.0f);
675 stepv1 = std::min(stepv1, 1.0f);
677 // Start at a random point. a will be immediately incremented below.
678 float a = -mt_rand(&seed) * stepv0;
679 float b = mt_rand(&seed) * stepv1;
681 // Place an object each unit of area
685 // Set the next location to place a building
688 if ((a + b) > 1.0f) {
689 // Reached the end of the scan-line on v0. Reset and increment
691 a = mt_rand(&seed) * stepv0;
696 // In a degenerate case of a single point, we might be outside the
697 // scanline. Note that we need to still ensure that a+b < 1.
698 b = mt_rand(&seed) * stepv1 * (1.0f - a);
701 if ((a + b) > 1.0f ) {
702 // Truly degenerate case - simply choose a random point guaranteed
703 // to fulfil the constraing of a+b < 1.
705 b = mt_rand(&seed) * (1.0f - a);
708 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
709 float rotation = mt_rand(&seed);
711 if (object_mask != NULL) {
712 SGVec2f texCoord = torigin + a*t0 + b*t1;
713 osg::Image* img = object_mask->getImage();
714 int x = (int) (img->s() * texCoord.x()) % img->s();
715 int y = (int) (img->t() * texCoord.y()) % img->t();
717 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
718 while (x < 0) x += img->s();
719 while (y < 0) y += img->t();
721 if (mt_rand(&seed) < img->getColor(x, y).b()) {
722 // Object passes mask. Rotation is taken from the red channel
723 rotation = img->getColor(x,y).r();
725 // Fails mask test - try again.
731 // Check building isn't too close to the triangle edge.
732 float type_roll = mt_rand(&seed);
733 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
734 float radius = bin->getBuildingMaxRadius(buildingtype);
736 // Determine the actual center of the building, by shifting from the
737 // center of the front face to the true center.
738 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
739 osg::Vec3f(0.0, 0.0, 1.0));
740 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
742 SGVec3f p = buildingCenter - vorigin;
743 float edges[] = { length(cross(p , p - v0)) / length(v0),
744 length(cross(p - v0, p - v1)) / length(v1 - v0),
745 length(cross(p - v1, p )) / length(v1) };
746 float edge_dist = *std::min_element(edges, edges + 3);
748 if (edge_dist < radius) {
753 // Check building isn't too close to random objects and other buildings.
755 std::vector<std::pair<SGVec3f, float> >::iterator iter;
757 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
758 float min_dist = iter->second + radius;
759 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
770 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
771 float min_dist = iter->second + radius;
772 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
783 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
784 triangleBuildingList.push_back(pt);
785 bin->insert(randomPoint, rotation, buildingtype);
789 triangleObjectsList.clear();
790 triangleBuildingList.clear();
793 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
794 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
795 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
796 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
800 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
802 SGMaterialTriangleMap::iterator i;
804 // generate a repeatable random seed
807 mt_init(&seed, unsigned(586));
809 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
810 SGMaterial *mat = matlib->findCached(i->first);
814 float wood_coverage = mat->get_wood_coverage();
815 if ((wood_coverage <= 0) || (vegetation_density <= 0))
818 // Attributes that don't vary by tree but do vary by material
822 BOOST_FOREACH(bin, randomForest)
824 if ((bin->texture == mat->get_tree_texture() ) &&
825 (bin->texture_varieties == mat->get_tree_varieties()) &&
826 (bin->range == mat->get_tree_range() ) &&
827 (bin->width == mat->get_tree_width() ) &&
828 (bin->height == mat->get_tree_height() ) ) {
836 bin->texture = mat->get_tree_texture();
837 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
838 bin->range = mat->get_tree_range();
839 bin->width = mat->get_tree_width();
840 bin->height = mat->get_tree_height();
841 bin->texture_varieties = mat->get_tree_varieties();
842 randomForest.push_back(bin);
845 std::vector<SGVec3f> randomPoints;
846 i->second.addRandomTreePoints(wood_coverage,
847 mat->get_object_mask(i->second),
849 mat->get_cos_tree_max_density_slope_angle(),
850 mat->get_cos_tree_zero_density_slope_angle(),
853 std::vector<SGVec3f>::iterator k;
854 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
860 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
862 if (!insertPtGeometry(obj, matlib))
864 if (!insertSurfaceGeometry(obj, matlib))
870 typedef std::pair<osg::Node*, int> ModelLOD;
871 struct MakeQuadLeaf {
872 osg::LOD* operator() () const { return new osg::LOD; }
875 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
877 leaf->addChild(mlod.first, 0, mlod.second);
880 struct GetModelLODCoord {
881 GetModelLODCoord() {}
882 GetModelLODCoord(const GetModelLODCoord& rhs)
884 osg::Vec3 operator() (const ModelLOD& mlod) const
886 return mlod.first->getBound().center();
890 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
891 GetModelLODCoord> RandomObjectsQuadtree;
893 class RandomObjectCallback : public OptionsReadFileCallback {
895 virtual osgDB::ReaderWriter::ReadResult
896 readNode(const std::string&, const osgDB::Options*)
898 osg::ref_ptr<osg::Group> group = new osg::Group;
899 group->setName("Random Object and Lighting Group");
900 group->setDataVariance(osg::Object::STATIC);
902 osg::Node* node = loadTerrain();
904 group->addChild(node);
906 osg::LOD* lightLOD = generateLightingTileObjects();
908 group->addChild(lightLOD);
910 osg::LOD* objectLOD = generateRandomTileObjects();
912 group->addChild(objectLOD);
914 return group.release();
917 // Load terrain if required
918 osg::Node* loadTerrain()
924 if (!tile.read_bin(_path))
927 SGMaterialLibPtr matlib;
928 bool useVBOs = false;
929 bool simplifyNear = false;
930 double ratio = SG_SIMPLIFIER_RATIO;
931 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
932 double maxError = SG_SIMPLIFIER_MAX_ERROR;
935 matlib = _options->getMaterialLib();
936 useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
937 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
938 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
939 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
940 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
941 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
944 SGVec3d center = tile.get_gbs_center();
945 SGGeod geodPos = SGGeod::fromCart(center);
946 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
948 // rotate the tiles so that the bounding boxes get nearly axis aligned.
949 // this will help the collision tree's bounding boxes a bit ...
950 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
951 for (unsigned i = 0; i < nodes.size(); ++i)
952 nodes[i] = hlOr.transform(nodes[i]);
953 tile.set_wgs84_nodes(nodes);
955 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
956 std::vector<SGVec3f> normals = tile.get_normals();
957 for (unsigned i = 0; i < normals.size(); ++i)
958 normals[i] = hlOrf.transform(normals[i]);
959 tile.set_normals(normals);
961 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
963 if (!tileGeometryBin->insertBinObj(tile, matlib))
966 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
967 if (node && simplifyNear) {
968 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
969 node->accept(simplifier);
975 // Generate all the lighting objects for the tile.
976 osg::LOD* generateLightingTileObjects()
978 SGMaterialLibPtr matlib;
981 matlib = _options->getMaterialLib();
983 // FIXME: ugly, has a side effect
985 _tileGeometryBin->computeRandomSurfaceLights(matlib);
987 GroundLightManager* lightManager = GroundLightManager::instance();
988 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
991 if (_tileGeometryBin->tileLights.getNumLights() > 0
992 || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
993 osg::Group* groundLights0 = new osg::Group;
994 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
995 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
996 osg::Geode* geode = new osg::Geode;
997 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
998 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
999 groundLights0->addChild(geode);
1000 lightGroup->addChild(groundLights0);
1003 if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
1004 osg::Group* groundLights1 = new osg::Group;
1005 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1006 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1007 osg::Group* groundLights2 = new osg::Group;
1008 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1009 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1010 osg::Geode* geode = new osg::Geode;
1011 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
1012 groundLights1->addChild(geode);
1013 lightGroup->addChild(groundLights1);
1014 geode = new osg::Geode;
1015 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
1016 groundLights2->addChild(geode);
1017 lightGroup->addChild(groundLights2);
1020 if (!_tileGeometryBin->vasiLights.empty()) {
1021 EffectGeode* vasiGeode = new EffectGeode;
1023 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
1024 vasiGeode->setEffect(vasiEffect);
1025 SGVec4f red(1, 0, 0, 1);
1026 SGMaterial* mat = 0;
1028 mat = matlib->findCached("RWY_RED_LIGHTS");
1030 red = mat->get_light_color();
1031 SGVec4f white(1, 1, 1, 1);
1034 mat = matlib->findCached("RWY_WHITE_LIGHTS");
1036 white = mat->get_light_color();
1037 SGDirectionalLightListBin::const_iterator i;
1038 for (i = _tileGeometryBin->vasiLights.begin();
1039 i != _tileGeometryBin->vasiLights.end(); ++i) {
1040 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1042 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1043 lightGroup->addChild(vasiGeode);
1046 Effect* runwayEffect = 0;
1047 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1048 || !_tileGeometryBin->rabitLights.empty()
1049 || !_tileGeometryBin->reilLights.empty()
1050 || !_tileGeometryBin->odalLights.empty()
1051 || _tileGeometryBin->taxiLights.getNumLights() > 0)
1052 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true, _options);
1053 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1054 || !_tileGeometryBin->rabitLights.empty()
1055 || !_tileGeometryBin->reilLights.empty()
1056 || !_tileGeometryBin->odalLights.empty()
1057 || !_tileGeometryBin->holdshortLights.empty()
1058 || !_tileGeometryBin->guardLights.empty()) {
1059 osg::Group* rwyLights = new osg::Group;
1060 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1061 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1062 if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
1063 EffectGeode* geode = new EffectGeode;
1064 geode->setEffect(runwayEffect);
1065 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1066 rwyLights->addChild(geode);
1068 SGDirectionalLightListBin::const_iterator i;
1069 for (i = _tileGeometryBin->rabitLights.begin();
1070 i != _tileGeometryBin->rabitLights.end(); ++i) {
1071 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1073 for (i = _tileGeometryBin->reilLights.begin();
1074 i != _tileGeometryBin->reilLights.end(); ++i) {
1075 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1077 for (i = _tileGeometryBin->holdshortLights.begin();
1078 i != _tileGeometryBin->holdshortLights.end(); ++i) {
1079 rwyLights->addChild(SGLightFactory::getHoldShort(*i, _options));
1081 for (i = _tileGeometryBin->guardLights.begin();
1082 i != _tileGeometryBin->guardLights.end(); ++i) {
1083 rwyLights->addChild(SGLightFactory::getGuard(*i, _options));
1085 SGLightListBin::const_iterator j;
1086 for (j = _tileGeometryBin->odalLights.begin();
1087 j != _tileGeometryBin->odalLights.end(); ++j) {
1088 rwyLights->addChild(SGLightFactory::getOdal(*j, _options));
1090 lightGroup->addChild(rwyLights);
1093 if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1094 osg::Group* taxiLights = new osg::Group;
1095 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1096 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1097 EffectGeode* geode = new EffectGeode;
1098 geode->setEffect(runwayEffect);
1099 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1100 taxiLights->addChild(geode);
1101 lightGroup->addChild(taxiLights);
1104 osg::LOD* lightLOD = NULL;
1106 if (lightGroup->getNumChildren() > 0) {
1107 lightLOD = new osg::LOD;
1108 lightLOD->addChild(lightGroup.get(), 0, 60000);
1109 // VASI is always on, so doesn't use light bits.
1110 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1116 // Generate all the random forest, objects and buildings for the tile
1117 osg::LOD* generateRandomTileObjects()
1119 SGMaterialLibPtr matlib;
1120 bool use_random_objects = false;
1121 bool use_random_vegetation = false;
1122 bool use_random_buildings = false;
1123 float vegetation_density = 1.0f;
1124 float building_density = 1.0f;
1125 bool useVBOs = false;
1127 osg::ref_ptr<osg::Group> randomObjects;
1128 osg::ref_ptr<osg::Group> forestNode;
1129 osg::ref_ptr<osg::Group> buildingNode;
1132 matlib = _options->getMaterialLib();
1133 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1136 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1137 use_random_objects);
1138 use_random_vegetation
1139 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1140 use_random_vegetation);
1142 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1143 vegetation_density);
1144 use_random_buildings
1145 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1146 use_random_buildings);
1148 = propertyNode->getFloatValue("/sim/rendering/building-density",
1152 useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1157 if (matlib && (use_random_objects || use_random_buildings)) {
1158 _tileGeometryBin->computeRandomObjectsAndBuildings(matlib,
1161 use_random_buildings,
1166 if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1167 // Generate a repeatable random seed
1169 mt_init(&seed, unsigned(123));
1171 std::vector<ModelLOD> models;
1172 for (unsigned int i = 0;
1173 i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1174 SGMatModelBin::MatModel obj
1175 = _tileGeometryBin->randomModels.getMatModel(i);
1177 SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1178 osg::Node* node = obj.model->get_random_model(root, &seed);
1180 // Create a matrix to place the object in the correct
1181 // location, and then apply the rotation matrix created
1182 // above, with an additional random (or taken from
1183 // the object mask) heading rotation if appropriate.
1184 osg::Matrix transformMat;
1185 transformMat = osg::Matrix::translate(toOsg(obj.position));
1186 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1187 // Rotate the object around the z axis.
1188 double hdg = mt_rand(&seed) * M_PI * 2;
1189 transformMat.preMult(osg::Matrix::rotate(hdg,
1190 osg::Vec3d(0.0, 0.0, 1.0)));
1193 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1194 // Rotate the object around the z axis.
1195 double hdg = - obj.rotation * M_PI * 2;
1196 transformMat.preMult(osg::Matrix::rotate(hdg,
1197 osg::Vec3d(0.0, 0.0, 1.0)));
1200 osg::MatrixTransform* position =
1201 new osg::MatrixTransform(transformMat);
1202 position->setName("positionRandomModel");
1203 position->addChild(node);
1204 models.push_back(ModelLOD(position, obj.lod));
1206 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1207 quadtree.buildQuadTree(models.begin(), models.end());
1208 randomObjects = quadtree.getRoot();
1209 randomObjects->setName("Random objects");
1212 if (! _tileGeometryBin->randomBuildings.empty()) {
1213 buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1215 buildingNode->setName("Random buildings");
1216 _tileGeometryBin->randomBuildings.clear();
1219 if (use_random_vegetation && matlib) {
1220 // Now add some random forest.
1221 _tileGeometryBin->computeRandomForest(matlib, vegetation_density);
1223 if (! _tileGeometryBin->randomForest.empty()) {
1224 forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1226 forestNode->setName("Random trees");
1230 osg::LOD* objectLOD = NULL;
1232 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1233 objectLOD = new osg::LOD;
1235 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1236 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1237 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1239 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1240 objectLOD->setNodeMask(nodeMask);
1246 /// The original options to use for this bunch of models
1247 osg::ref_ptr<SGReaderWriterOptions> _options;
1248 osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1254 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1257 if (!tile.read_bin(path))
1260 SGMaterialLibPtr matlib;
1261 bool useVBOs = false;
1262 bool simplifyDistant = false;
1263 bool simplifyNear = false;
1264 double ratio = SG_SIMPLIFIER_RATIO;
1265 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
1266 double maxError = SG_SIMPLIFIER_MAX_ERROR;
1267 double object_range = SG_OBJECT_RANGE;
1270 matlib = options->getMaterialLib();
1271 useVBOs = (options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1272 SGPropertyNode* propertyNode = options->getPropertyNode().get();
1274 // We control whether we simplify the nearby terrain and distant terrain separatey.
1275 // However, we don't allow only simplifying the near terrain!
1276 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
1277 simplifyDistant = simplifyNear || propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-far", simplifyDistant);
1278 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
1279 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
1280 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
1281 object_range = propertyNode->getDoubleValue("/sim/rendering/static-lod/rough", object_range);
1284 SGVec3d center = tile.get_gbs_center();
1285 SGGeod geodPos = SGGeod::fromCart(center);
1286 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1288 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1289 // this will help the collision tree's bounding boxes a bit ...
1290 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1291 for (unsigned i = 0; i < nodes.size(); ++i)
1292 nodes[i] = hlOr.transform(nodes[i]);
1293 tile.set_wgs84_nodes(nodes);
1295 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1296 std::vector<SGVec3f> normals = tile.get_normals();
1297 for (unsigned i = 0; i < normals.size(); ++i)
1298 normals[i] = hlOrf.transform(normals[i]);
1299 tile.set_normals(normals);
1301 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1303 if (!tileGeometryBin->insertBinObj(tile, matlib))
1307 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
1308 if (node && simplifyDistant) {
1309 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1310 node->accept(simplifier);
1313 // The toplevel transform for that tile.
1314 osg::MatrixTransform* transform = new osg::MatrixTransform;
1315 transform->setName(path);
1316 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1317 osg::Matrix::translate(toOsg(center)));
1319 // PagedLOD for the random objects so we don't need to generate
1320 // them all on tile loading.
1321 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1322 pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1323 pagedLOD->setName("pagedObjectLOD");
1326 if (simplifyNear == simplifyDistant) {
1327 // Same terrain type is used for both near and far distances,
1328 // so add it to the main group.
1329 osg::Group* terrainGroup = new osg::Group;
1330 terrainGroup->setName("BTGTerrainGroup");
1331 terrainGroup->addChild(node);
1332 transform->addChild(terrainGroup);
1333 } else if (simplifyDistant) {
1334 // Simplified terrain is only used in the distance, the
1335 // call-back below will re-generate the closer version
1336 pagedLOD->addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
1340 // we just need to know about the read file callback that itself holds the data
1341 osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1342 randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1343 randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1344 randomObjectCallback->_path = std::string(path);
1345 randomObjectCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
1347 osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1348 callbackOptions->setReadFileCallback(randomObjectCallback.get());
1349 pagedLOD->setDatabaseOptions(callbackOptions.get());
1351 pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1352 pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
1353 transform->addChild(pagedLOD);
1354 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );