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, SGMaterialCache* matcache)
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 = matcache->find(materialName);
155 SGVec4f color = getMaterialLightColor(material);
157 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
158 // Just plain lights. Not something for the runway.
159 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
160 obj.get_pts_v()[grp]);
161 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
162 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
163 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
164 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
165 } else if (materialName == "RWY_VASI_LIGHTS") {
166 vasiLights.push_back(SGDirectionalLightBin());
167 addPointGeometry(vasiLights.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_SEQUENCED_LIGHTS") {
171 rabitLights.push_back(SGDirectionalLightBin());
172 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
173 obj.get_normals(), color, obj.get_pts_v()[grp],
174 obj.get_pts_n()[grp]);
175 } else if (materialName == "RWY_ODALS_LIGHTS") {
176 odalLights.push_back(SGLightBin());
177 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
178 color, obj.get_pts_v()[grp]);
179 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
180 holdshortLights.push_back(SGDirectionalLightBin());
181 addPointGeometry(holdshortLights.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_GUARD_LIGHTS") {
185 guardLights.push_back(SGDirectionalLightBin());
186 addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
187 obj.get_normals(), color, obj.get_pts_v()[grp],
188 obj.get_pts_n()[grp]);
189 } else if (materialName == "RWY_REIL_LIGHTS") {
190 reilLights.push_back(SGDirectionalLightBin());
191 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
192 obj.get_normals(), color, obj.get_pts_v()[grp],
193 obj.get_pts_n()[grp]);
195 // what is left must be runway lights
196 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
197 obj.get_normals(), color, obj.get_pts_v()[grp],
198 obj.get_pts_n()[grp]);
207 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
208 const SGVec2f& tcScale, unsigned i)
212 else if (tc.size() == 1)
213 return mult(texCoords[tc[0]], tcScale);
215 return mult(texCoords[tc[i]], tcScale);
219 addTriangleGeometry(SGTexturedTriangleBin& triangles,
220 const SGBinObject& obj, unsigned grp,
221 const SGVec2f& tc0Scale,
222 const SGVec2f& tc1Scale)
224 const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
225 const std::vector<SGVec3f>& normals(obj.get_normals());
226 const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
227 const int_list& tris_v(obj.get_tris_v()[grp]);
228 const int_list& tris_n(obj.get_tris_n()[grp]);
229 const tci_list& tris_tc(obj.get_tris_tcs()[grp]);
230 bool num_norms_is_num_verts = true;
232 if (tris_v.size() != tris_n.size()) {
233 // If the normal indices do not match, they should be inmplicitly
234 // the same than the vertex indices.
235 num_norms_is_num_verts = false;
238 if ( !tris_tc[1].empty() ) {
239 triangles.hasSecondaryTexCoord(true);
242 for (unsigned i = 2; i < tris_v.size(); i += 3) {
244 v0.SetVertex( toVec3f(vertices[tris_v[i-2]]) );
245 v0.SetNormal( num_norms_is_num_verts ? normals[tris_n[i-2]] :
246 normals[tris_v[i-2]] );
247 v0.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i-2) );
248 if (!tris_tc[1].empty()) {
249 v0.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i-2) );
252 v1.SetVertex( toVec3f(vertices[tris_v[i-1]]) );
253 v1.SetNormal( num_norms_is_num_verts ? normals[tris_n[i-1]] :
254 normals[tris_v[i-1]] );
255 v1.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i-1) );
256 if (!tris_tc[1].empty()) {
257 v1.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i-1) );
260 v2.SetVertex( toVec3f(vertices[tris_v[i]]) );
261 v2.SetNormal( num_norms_is_num_verts ? normals[tris_n[i]] :
262 normals[tris_v[i]] );
263 v2.SetTexCoord( 0, getTexCoord(texCoords, tris_tc[0], tc0Scale, i) );
264 if (!tris_tc[1].empty()) {
265 v2.SetTexCoord( 1, getTexCoord(texCoords, tris_tc[1], tc1Scale, i) );
268 triangles.insert(v0, v1, v2);
273 addStripGeometry(SGTexturedTriangleBin& triangles,
274 const SGBinObject& obj, unsigned grp,
275 const SGVec2f& tc0Scale,
276 const SGVec2f& tc1Scale)
278 const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
279 const std::vector<SGVec3f>& normals(obj.get_normals());
280 const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
281 const int_list& strips_v(obj.get_strips_v()[grp]);
282 const int_list& strips_n(obj.get_strips_n()[grp]);
283 const tci_list& strips_tc(obj.get_strips_tcs()[grp]);
284 bool num_norms_is_num_verts = true;
286 if (strips_v.size() != strips_n.size()) {
287 // If the normal indices do not match, they should be inmplicitly
288 // the same than the vertex indices.
289 num_norms_is_num_verts = false;
292 if ( !strips_tc[1].empty() ) {
293 triangles.hasSecondaryTexCoord(true);
296 for (unsigned i = 2; i < strips_v.size(); ++i) {
298 v0.SetVertex( toVec3f(vertices[strips_v[i-2]]) );
299 v0.SetNormal( num_norms_is_num_verts ? normals[strips_n[i-2]] :
300 normals[strips_v[i-2]] );
301 v0.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[0], tc0Scale, i-2) );
302 if (!strips_tc[1].empty()) {
303 v0.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i-2) );
306 v1.SetVertex( toVec3f(vertices[strips_v[i-1]]) );
307 v1.SetNormal( num_norms_is_num_verts ? normals[strips_n[i-1]] :
308 normals[strips_v[i-1]] );
309 v1.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[1], tc0Scale, i-1) );
310 if (!strips_tc[1].empty()) {
311 v1.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i-1) );
314 v2.SetVertex( toVec3f(vertices[strips_v[i]]) );
315 v2.SetNormal( num_norms_is_num_verts ? normals[strips_n[i]] :
316 normals[strips_v[i]] );
317 v2.SetTexCoord( 0, getTexCoord(texCoords, strips_tc[0], tc0Scale, i) );
318 if (!strips_tc[1].empty()) {
319 v2.SetTexCoord( 1, getTexCoord(texCoords, strips_tc[1], tc1Scale, i) );
322 triangles.insert(v1, v0, v2);
324 triangles.insert(v0, v1, v2);
329 addFanGeometry(SGTexturedTriangleBin& triangles,
330 const SGBinObject& obj, unsigned grp,
331 const SGVec2f& tc0Scale,
332 const SGVec2f& tc1Scale)
334 const std::vector<SGVec3d>& vertices(obj.get_wgs84_nodes());
335 const std::vector<SGVec3f>& normals(obj.get_normals());
336 const std::vector<SGVec2f>& texCoords(obj.get_texcoords());
337 const int_list& fans_v(obj.get_fans_v()[grp]);
338 const int_list& fans_n(obj.get_fans_n()[grp]);
339 const tci_list& fans_tc(obj.get_fans_tcs()[grp]);
340 bool num_norms_is_num_verts = true;
342 if (fans_v.size() != fans_n.size()) {
343 // If the normal indices do not match, they should be inmplicitly
344 // the same than the vertex indices.
345 num_norms_is_num_verts = false;
348 if ( !fans_tc[1].empty() ) {
349 triangles.hasSecondaryTexCoord(true);
353 v0.SetVertex( toVec3f(vertices[fans_v[0]]) );
354 v0.SetNormal( num_norms_is_num_verts ? normals[fans_n[0]] :
355 normals[fans_v[0]] );
356 v0.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, 0) );
357 if (!fans_tc[1].empty()) {
358 v0.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, 0) );
361 v1.SetVertex( toVec3f(vertices[fans_v[1]]) );
362 v1.SetNormal( num_norms_is_num_verts ? normals[fans_n[1]] :
363 normals[fans_v[1]] );
364 v1.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, 1) );
365 if (!fans_tc[1].empty()) {
366 v1.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, 1) );
368 for (unsigned i = 2; i < fans_v.size(); ++i) {
370 v2.SetVertex( toVec3f(vertices[fans_v[i]]) );
371 v2.SetNormal( num_norms_is_num_verts ? normals[fans_n[i]] :
372 normals[fans_v[i]] );
373 v2.SetTexCoord( 0, getTexCoord(texCoords, fans_tc[0], tc0Scale, i) );
374 if (!fans_tc[1].empty()) {
375 v2.SetTexCoord( 1, getTexCoord(texCoords, fans_tc[1], tc1Scale, i) );
377 triangles.insert(v0, v1, v2);
382 SGVec2f getTexCoordScale(const std::string& name, SGMaterialCache* matcache)
385 return SGVec2f(1, 1);
386 SGMaterial* material = matcache->find(name);
388 return SGVec2f(1, 1);
390 return material->get_tex_coord_scale();
394 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialCache* matcache)
396 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
397 obj.get_tris_tcs().size() < obj.get_tris_v().size()) {
398 SG_LOG(SG_TERRAIN, SG_ALERT,
399 "Group list sizes for triangles do not match!");
403 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
404 std::string materialName = obj.get_tri_materials()[grp];
405 SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
406 SGVec2f tc1Scale(1.0, 1.0);
407 addTriangleGeometry(materialTriangleMap[materialName],
408 obj, grp, tc0Scale, tc1Scale );
411 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
412 obj.get_strips_tcs().size() < obj.get_strips_v().size()) {
413 SG_LOG(SG_TERRAIN, SG_ALERT,
414 "Group list sizes for strips do not match!");
417 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
418 std::string materialName = obj.get_strip_materials()[grp];
419 SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
420 SGVec2f tc1Scale(1.0, 1.0);
421 addStripGeometry(materialTriangleMap[materialName],
422 obj, grp, tc0Scale, tc1Scale);
425 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
426 obj.get_fans_tcs().size() < obj.get_fans_v().size()) {
427 SG_LOG(SG_TERRAIN, SG_ALERT,
428 "Group list sizes for fans do not match!");
431 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
432 std::string materialName = obj.get_fan_materials()[grp];
433 SGVec2f tc0Scale = getTexCoordScale(materialName, matcache);
434 SGVec2f tc1Scale(1.0, 1.0);
435 addFanGeometry(materialTriangleMap[materialName],
436 obj, grp, tc0Scale, tc1Scale );
441 osg::Node* getSurfaceGeometry(SGMaterialCache* matcache, bool useVBOs) const
443 if (materialTriangleMap.empty())
446 EffectGeode* eg = NULL;
447 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : NULL);
449 group->setName("surfaceGeometryGroup");
452 //osg::Geode* geode = new osg::Geode;
453 SGMaterialTriangleMap::const_iterator i;
454 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
455 osg::Geometry* geometry = i->second.buildGeometry(useVBOs);
456 SGMaterial *mat = NULL;
458 mat = matcache->find(i->first);
460 eg = new EffectGeode;
461 eg->setName("EffectGeode");
463 eg->setEffect(mat->get_effect(i->second));
465 eg->addDrawable(geometry);
466 eg->runGenerators(geometry); // Generate extra data needed by effect
479 void computeRandomSurfaceLights(SGMaterialCache* matcache)
481 SGMaterialTriangleMap::iterator i;
483 // generate a repeatable random seed
485 mt_init(&seed, unsigned(123));
487 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
488 SGMaterial *mat = matcache->find(i->first);
492 float coverage = mat->get_light_coverage();
495 if (coverage < 10000.0) {
496 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
497 << coverage << ", pushing up to 10000");
501 std::vector<SGVec3f> randomPoints;
502 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
503 std::vector<SGVec3f>::iterator j;
504 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
505 float zombie = mt_rand(&seed);
506 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
507 float factor = mt_rand(&seed);
512 if ( zombie > 0.5 ) {
513 // 50% chance of yellowish
514 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
515 } else if (zombie > 0.15f) {
516 // 35% chance of whitish
517 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
518 } else if (zombie > 0.05f) {
519 // 10% chance of orangish
520 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
522 // 5% chance of redish
523 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
525 randomTileLights.insert(*j, color);
530 void computeRandomObjectsAndBuildings(
531 SGMaterialCache* matcache,
532 float building_density,
533 bool use_random_objects,
534 bool use_random_buildings,
537 SGMaterialTriangleMap::iterator i;
539 // generate a repeatable random seed
541 mt_init(&seed, unsigned(123));
543 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
544 SGMaterial *mat = matcache->find(i->first);
545 SGTexturedTriangleBin triangleBin = i->second;
550 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
552 int group_count = mat->get_object_group_count();
553 float building_coverage = mat->get_building_coverage();
554 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
555 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
557 if (building_coverage == 0)
560 SGBuildingBin* bin = NULL;
562 if (building_coverage > 0) {
563 bin = new SGBuildingBin(mat, useVBOs);
564 randomBuildings.push_back(bin);
567 unsigned num = i->second.getNumTriangles();
568 int random_dropped = 0;
569 int mask_dropped = 0;
570 int building_dropped = 0;
571 int triangle_dropped = 0;
573 for (unsigned i = 0; i < num; ++i) {
574 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
576 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).GetVertex();
577 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).GetVertex() - vorigin;
578 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).GetVertex() - vorigin;
579 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).GetTexCoord(0);
580 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).GetTexCoord(0) - torigin;
581 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).GetTexCoord(0) - torigin;
582 SGVec3f normal = cross(v0, v1);
584 // Ensure the slope isn't too steep by checking the
585 // cos of the angle between the slope normal and the
586 // vertical (conveniently the z-component of the normalized
587 // normal) and values passed in.
588 float cos = normalize(normal).z();
589 float slope_density = 1.0;
590 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
591 if (cos < cos_max_density_angle) {
593 (cos - cos_zero_density_angle) /
594 (cos_max_density_angle - cos_zero_density_angle);
597 // Containers to hold the random buildings and objects generated
598 // for this triangle for collision detection purposes.
599 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
600 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
603 float area = 0.5f*length(normal);
604 if (area <= SGLimitsf::min())
607 // Generate any random objects
608 if (use_random_objects && (group_count > 0))
610 for (int j = 0; j < group_count; j++)
612 SGMatModelGroup *object_group = mat->get_object_group(j);
613 int nObjects = object_group->get_object_count();
615 if (nObjects == 0) continue;
617 // For each of the random models in the group, determine an appropriate
618 // number of random placements and insert them.
619 for (int k = 0; k < nObjects; k++) {
620 SGMatModel * object = object_group->get_object(k);
622 // Determine the number of objecst to place, taking into account
623 // the slope density factor.
624 double n = slope_density * area / object->get_coverage_m2();
626 // Use the zombie door method to determine fractional object placement.
627 n = n + mt_rand(&seed);
629 // place an object each unit of area
631 float a = mt_rand(&seed);
632 float b = mt_rand(&seed);
638 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
639 float rotation = static_cast<float>(mt_rand(&seed));
641 // Check that the point is sufficiently far from
642 // the edge of the triangle by measuring the distance
643 // from the three lines that make up the triangle.
644 float spacing = object->get_spacing_m();
646 SGVec3f p = randomPoint - vorigin;
647 float edges[] = { length(cross(p , p - v0)) / length(v0),
648 length(cross(p - v0, p - v1)) / length(v1 - v0),
649 length(cross(p - v1, p )) / length(v1) };
650 float edge_dist = *std::min_element(edges, edges + 3);
652 if (edge_dist < spacing) {
657 if (object_mask != NULL) {
658 SGVec2f texCoord = torigin + a*t0 + b*t1;
660 // Check this random point against the object mask
661 // blue (for buildings) channel.
662 osg::Image* img = object_mask->getImage();
663 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
664 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
666 if (mt_rand(&seed) > img->getColor(x, y).b()) {
667 // Failed object mask check
672 rotation = img->getColor(x,y).r();
677 // Check it isn't too close to any other random objects in the triangle
678 std::vector<std::pair<SGVec3f, float> >::iterator l;
679 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
680 float min_dist2 = (l->second + object->get_spacing_m()) *
681 (l->second + object->get_spacing_m());
683 if (distSqr(l->first, randomPoint) > min_dist2) {
690 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
691 randomModels.insert(randomPoint,
693 (int)object->get_randomized_range_m(&seed),
701 // Random objects now generated. Now generate the random buildings (if any);
702 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
704 // Calculate the number of buildings, taking into account building density (which is linear)
705 // and the slope density factor.
706 double num = building_density * building_density * slope_density * area / building_coverage;
708 // For partial units of area, use a zombie door method to
709 // create the proper random chance of an object being created
710 // for this triangle.
711 num = num + mt_rand(&seed);
717 // Cosine of the angle between the two vectors.
718 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
720 // Determine a grid spacing in each vector such that the correct
721 // coverage will result.
722 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
723 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
725 stepv0 = std::min(stepv0, 1.0f);
726 stepv1 = std::min(stepv1, 1.0f);
728 // Start at a random point. a will be immediately incremented below.
729 float a = -mt_rand(&seed) * stepv0;
730 float b = mt_rand(&seed) * stepv1;
732 // Place an object each unit of area
736 // Set the next location to place a building
739 if ((a + b) > 1.0f) {
740 // Reached the end of the scan-line on v0. Reset and increment
742 a = mt_rand(&seed) * stepv0;
747 // In a degenerate case of a single point, we might be outside the
748 // scanline. Note that we need to still ensure that a+b < 1.
749 b = mt_rand(&seed) * stepv1 * (1.0f - a);
752 if ((a + b) > 1.0f ) {
753 // Truly degenerate case - simply choose a random point guaranteed
754 // to fulfil the constraing of a+b < 1.
756 b = mt_rand(&seed) * (1.0f - a);
759 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
760 float rotation = mt_rand(&seed);
762 if (object_mask != NULL) {
763 SGVec2f texCoord = torigin + a*t0 + b*t1;
764 osg::Image* img = object_mask->getImage();
765 int x = (int) (img->s() * texCoord.x()) % img->s();
766 int y = (int) (img->t() * texCoord.y()) % img->t();
768 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
769 while (x < 0) x += img->s();
770 while (y < 0) y += img->t();
772 if (mt_rand(&seed) < img->getColor(x, y).b()) {
773 // Object passes mask. Rotation is taken from the red channel
774 rotation = img->getColor(x,y).r();
776 // Fails mask test - try again.
782 // Check building isn't too close to the triangle edge.
783 float type_roll = mt_rand(&seed);
784 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
785 float radius = bin->getBuildingMaxRadius(buildingtype);
787 // Determine the actual center of the building, by shifting from the
788 // center of the front face to the true center.
789 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
790 osg::Vec3f(0.0, 0.0, 1.0));
791 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
793 SGVec3f p = buildingCenter - vorigin;
794 float edges[] = { length(cross(p , p - v0)) / length(v0),
795 length(cross(p - v0, p - v1)) / length(v1 - v0),
796 length(cross(p - v1, p )) / length(v1) };
797 float edge_dist = *std::min_element(edges, edges + 3);
799 if (edge_dist < radius) {
804 // Check building isn't too close to random objects and other buildings.
806 std::vector<std::pair<SGVec3f, float> >::iterator iter;
808 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
809 float min_dist = iter->second + radius;
810 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
821 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
822 float min_dist = iter->second + radius;
823 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
834 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
835 triangleBuildingList.push_back(pt);
836 bin->insert(randomPoint, rotation, buildingtype);
840 triangleObjectsList.clear();
841 triangleBuildingList.clear();
844 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
845 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
846 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
847 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
851 void computeRandomForest(SGMaterialCache* matcache, float vegetation_density)
853 SGMaterialTriangleMap::iterator i;
855 // generate a repeatable random seed
858 mt_init(&seed, unsigned(586));
860 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
861 SGMaterial *mat = matcache->find(i->first);
865 float wood_coverage = mat->get_wood_coverage();
866 if ((wood_coverage <= 0) || (vegetation_density <= 0))
869 // Attributes that don't vary by tree but do vary by material
873 BOOST_FOREACH(bin, randomForest)
875 if ((bin->texture == mat->get_tree_texture() ) &&
876 (bin->texture_varieties == mat->get_tree_varieties()) &&
877 (bin->range == mat->get_tree_range() ) &&
878 (bin->width == mat->get_tree_width() ) &&
879 (bin->height == mat->get_tree_height() ) ) {
887 bin->texture = mat->get_tree_texture();
888 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
889 bin->range = mat->get_tree_range();
890 bin->width = mat->get_tree_width();
891 bin->height = mat->get_tree_height();
892 bin->texture_varieties = mat->get_tree_varieties();
893 randomForest.push_back(bin);
896 std::vector<SGVec3f> randomPoints;
897 i->second.addRandomTreePoints(wood_coverage,
898 mat->get_object_mask(i->second),
900 mat->get_cos_tree_max_density_slope_angle(),
901 mat->get_cos_tree_zero_density_slope_angle(),
904 std::vector<SGVec3f>::iterator k;
905 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
911 bool insertBinObj(const SGBinObject& obj, SGMaterialCache* matcache)
913 if (!insertPtGeometry(obj, matcache))
915 if (!insertSurfaceGeometry(obj, matcache))
921 typedef std::pair<osg::Node*, int> ModelLOD;
922 struct MakeQuadLeaf {
923 osg::LOD* operator() () const { return new osg::LOD; }
926 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
928 leaf->addChild(mlod.first, 0, mlod.second);
931 struct GetModelLODCoord {
932 GetModelLODCoord() {}
933 GetModelLODCoord(const GetModelLODCoord& rhs)
935 osg::Vec3 operator() (const ModelLOD& mlod) const
937 return mlod.first->getBound().center();
941 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
942 GetModelLODCoord> RandomObjectsQuadtree;
944 class RandomObjectCallback : public OptionsReadFileCallback {
946 virtual osgDB::ReaderWriter::ReadResult
947 readNode(const std::string&, const osgDB::Options*)
949 osg::ref_ptr<osg::Group> group = new osg::Group;
950 group->setName("Random Object and Lighting Group");
951 group->setDataVariance(osg::Object::STATIC);
953 osg::Node* node = loadTerrain();
955 group->addChild(node);
957 osg::LOD* lightLOD = generateLightingTileObjects();
959 group->addChild(lightLOD);
961 osg::LOD* objectLOD = generateRandomTileObjects();
963 group->addChild(objectLOD);
965 return group.release();
968 // Load terrain if required
969 osg::Node* loadTerrain()
975 if (!tile.read_bin(_path))
978 SGMaterialLibPtr matlib;
979 SGMaterialCache* matcache = 0;
980 bool useVBOs = false;
981 bool simplifyNear = false;
982 double ratio = SG_SIMPLIFIER_RATIO;
983 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
984 double maxError = SG_SIMPLIFIER_MAX_ERROR;
987 matlib = _options->getMaterialLib();
988 useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
989 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
990 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
991 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
992 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
993 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
996 // PSADRO TODO : we can do this in terragear
997 // - why not add a bitmask of flags to the btg so we can precompute this?
998 // and only do it if it hasn't been done already
999 SGVec3d center = tile.get_gbs_center();
1000 SGGeod geodPos = SGGeod::fromCart(center);
1001 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1003 // Generate a materials cache
1004 if (matlib) matcache = matlib->generateMatCache(geodPos);
1006 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1007 // this will help the collision tree's bounding boxes a bit ...
1008 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1009 for (unsigned i = 0; i < nodes.size(); ++i)
1010 nodes[i] = hlOr.transform(nodes[i]);
1011 tile.set_wgs84_nodes(nodes);
1013 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1014 std::vector<SGVec3f> normals = tile.get_normals();
1015 for (unsigned i = 0; i < normals.size(); ++i)
1016 normals[i] = hlOrf.transform(normals[i]);
1017 tile.set_normals(normals);
1019 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1021 if (!tileGeometryBin->insertBinObj(tile, matcache))
1024 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matcache, useVBOs);
1025 if (node && simplifyNear) {
1026 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1027 node->accept(simplifier);
1033 // Generate all the lighting objects for the tile.
1034 osg::LOD* generateLightingTileObjects()
1037 _tileGeometryBin->computeRandomSurfaceLights(_matcache);
1039 GroundLightManager* lightManager = GroundLightManager::instance();
1040 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
1041 SGVec3f up(0, 0, 1);
1043 if (_tileGeometryBin->tileLights.getNumLights() > 0
1044 || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
1045 osg::Group* groundLights0 = new osg::Group;
1046 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1047 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1048 osg::Geode* geode = new osg::Geode;
1049 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
1050 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
1051 groundLights0->addChild(geode);
1052 lightGroup->addChild(groundLights0);
1055 if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
1056 osg::Group* groundLights1 = new osg::Group;
1057 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1058 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1059 osg::Group* groundLights2 = new osg::Group;
1060 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1061 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1062 osg::Geode* geode = new osg::Geode;
1063 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
1064 groundLights1->addChild(geode);
1065 lightGroup->addChild(groundLights1);
1066 geode = new osg::Geode;
1067 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
1068 groundLights2->addChild(geode);
1069 lightGroup->addChild(groundLights2);
1072 if (!_tileGeometryBin->vasiLights.empty()) {
1073 EffectGeode* vasiGeode = new EffectGeode;
1075 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
1076 vasiGeode->setEffect(vasiEffect);
1077 SGVec4f red(1, 0, 0, 1);
1078 SGMaterial* mat = 0;
1080 mat = _matcache->find("RWY_RED_LIGHTS");
1082 red = mat->get_light_color();
1083 SGVec4f white(1, 1, 1, 1);
1086 mat = _matcache->find("RWY_WHITE_LIGHTS");
1088 white = mat->get_light_color();
1089 SGDirectionalLightListBin::const_iterator i;
1090 for (i = _tileGeometryBin->vasiLights.begin();
1091 i != _tileGeometryBin->vasiLights.end(); ++i) {
1092 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1094 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1095 lightGroup->addChild(vasiGeode);
1098 Effect* runwayEffect = 0;
1099 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1100 || !_tileGeometryBin->rabitLights.empty()
1101 || !_tileGeometryBin->reilLights.empty()
1102 || !_tileGeometryBin->odalLights.empty()
1103 || _tileGeometryBin->taxiLights.getNumLights() > 0)
1104 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true, _options);
1105 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1106 || !_tileGeometryBin->rabitLights.empty()
1107 || !_tileGeometryBin->reilLights.empty()
1108 || !_tileGeometryBin->odalLights.empty()
1109 || !_tileGeometryBin->holdshortLights.empty()
1110 || !_tileGeometryBin->guardLights.empty()) {
1111 osg::Group* rwyLights = new osg::Group;
1112 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1113 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1114 if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
1115 EffectGeode* geode = new EffectGeode;
1116 geode->setEffect(runwayEffect);
1117 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1118 rwyLights->addChild(geode);
1120 SGDirectionalLightListBin::const_iterator i;
1121 for (i = _tileGeometryBin->rabitLights.begin();
1122 i != _tileGeometryBin->rabitLights.end(); ++i) {
1123 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1125 for (i = _tileGeometryBin->reilLights.begin();
1126 i != _tileGeometryBin->reilLights.end(); ++i) {
1127 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1129 for (i = _tileGeometryBin->holdshortLights.begin();
1130 i != _tileGeometryBin->holdshortLights.end(); ++i) {
1131 rwyLights->addChild(SGLightFactory::getHoldShort(*i, _options));
1133 for (i = _tileGeometryBin->guardLights.begin();
1134 i != _tileGeometryBin->guardLights.end(); ++i) {
1135 rwyLights->addChild(SGLightFactory::getGuard(*i, _options));
1137 SGLightListBin::const_iterator j;
1138 for (j = _tileGeometryBin->odalLights.begin();
1139 j != _tileGeometryBin->odalLights.end(); ++j) {
1140 rwyLights->addChild(SGLightFactory::getOdal(*j, _options));
1142 lightGroup->addChild(rwyLights);
1145 if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1146 osg::Group* taxiLights = new osg::Group;
1147 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1148 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1149 EffectGeode* geode = new EffectGeode;
1150 geode->setEffect(runwayEffect);
1151 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1152 taxiLights->addChild(geode);
1153 lightGroup->addChild(taxiLights);
1156 osg::LOD* lightLOD = NULL;
1158 if (lightGroup->getNumChildren() > 0) {
1159 lightLOD = new osg::LOD;
1160 lightLOD->addChild(lightGroup.get(), 0, 60000);
1161 // VASI is always on, so doesn't use light bits.
1162 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1168 // Generate all the random forest, objects and buildings for the tile
1169 osg::LOD* generateRandomTileObjects()
1171 SGMaterialLibPtr matlib;
1172 bool use_random_objects = false;
1173 bool use_random_vegetation = false;
1174 bool use_random_buildings = false;
1175 float vegetation_density = 1.0f;
1176 float building_density = 1.0f;
1177 bool useVBOs = false;
1179 osg::ref_ptr<osg::Group> randomObjects;
1180 osg::ref_ptr<osg::Group> forestNode;
1181 osg::ref_ptr<osg::Group> buildingNode;
1184 matlib = _options->getMaterialLib();
1185 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1188 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1189 use_random_objects);
1190 use_random_vegetation
1191 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1192 use_random_vegetation);
1194 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1195 vegetation_density);
1196 use_random_buildings
1197 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1198 use_random_buildings);
1200 = propertyNode->getFloatValue("/sim/rendering/building-density",
1204 useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1209 if (matlib && (use_random_objects || use_random_buildings)) {
1210 _tileGeometryBin->computeRandomObjectsAndBuildings(_matcache,
1213 use_random_buildings,
1218 if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1219 // Generate a repeatable random seed
1221 mt_init(&seed, unsigned(123));
1223 std::vector<ModelLOD> models;
1224 for (unsigned int i = 0;
1225 i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1226 SGMatModelBin::MatModel obj
1227 = _tileGeometryBin->randomModels.getMatModel(i);
1229 SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1230 osg::Node* node = obj.model->get_random_model(root, &seed);
1232 // Create a matrix to place the object in the correct
1233 // location, and then apply the rotation matrix created
1234 // above, with an additional random (or taken from
1235 // the object mask) heading rotation if appropriate.
1236 osg::Matrix transformMat;
1237 transformMat = osg::Matrix::translate(toOsg(obj.position));
1238 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1239 // Rotate the object around the z axis.
1240 double hdg = mt_rand(&seed) * M_PI * 2;
1241 transformMat.preMult(osg::Matrix::rotate(hdg,
1242 osg::Vec3d(0.0, 0.0, 1.0)));
1245 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1246 // Rotate the object around the z axis.
1247 double hdg = - obj.rotation * M_PI * 2;
1248 transformMat.preMult(osg::Matrix::rotate(hdg,
1249 osg::Vec3d(0.0, 0.0, 1.0)));
1252 osg::MatrixTransform* position =
1253 new osg::MatrixTransform(transformMat);
1254 position->setName("positionRandomModel");
1255 position->addChild(node);
1256 models.push_back(ModelLOD(position, obj.lod));
1258 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1259 quadtree.buildQuadTree(models.begin(), models.end());
1260 randomObjects = quadtree.getRoot();
1261 randomObjects->setName("Random objects");
1264 if (! _tileGeometryBin->randomBuildings.empty()) {
1265 buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1267 buildingNode->setName("Random buildings");
1268 _tileGeometryBin->randomBuildings.clear();
1271 if (use_random_vegetation && matlib) {
1272 // Now add some random forest.
1273 _tileGeometryBin->computeRandomForest(_matcache, vegetation_density);
1275 if (! _tileGeometryBin->randomForest.empty()) {
1276 forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1278 forestNode->setName("Random trees");
1282 osg::LOD* objectLOD = NULL;
1284 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1285 objectLOD = new osg::LOD;
1287 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1288 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1289 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1291 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1292 objectLOD->setNodeMask(nodeMask);
1298 /// The original options to use for this bunch of models
1299 osg::ref_ptr<SGReaderWriterOptions> _options;
1300 osg::ref_ptr<SGMaterialCache> _matcache;
1301 osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1307 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1310 if (!tile.read_bin(path))
1313 SGMaterialLibPtr matlib;
1314 osg::ref_ptr<SGMaterialCache> matcache;
1315 bool useVBOs = false;
1316 bool simplifyDistant = false;
1317 bool simplifyNear = false;
1318 double ratio = SG_SIMPLIFIER_RATIO;
1319 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
1320 double maxError = SG_SIMPLIFIER_MAX_ERROR;
1321 double object_range = SG_OBJECT_RANGE;
1324 matlib = options->getMaterialLib();
1325 useVBOs = (options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1326 SGPropertyNode* propertyNode = options->getPropertyNode().get();
1328 // We control whether we simplify the nearby terrain and distant terrain separatey.
1329 // However, we don't allow only simplifying the near terrain!
1330 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
1331 simplifyDistant = simplifyNear || propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-far", simplifyDistant);
1332 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
1333 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
1334 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
1335 object_range = propertyNode->getDoubleValue("/sim/rendering/static-lod/rough", object_range);
1338 SGVec3d center = tile.get_gbs_center();
1339 SGGeod geodPos = SGGeod::fromCart(center);
1340 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1342 matcache = matlib->generateMatCache(geodPos);
1344 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1345 // this will help the collision tree's bounding boxes a bit ...
1346 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1347 for (unsigned i = 0; i < nodes.size(); ++i)
1348 nodes[i] = hlOr.transform(nodes[i]);
1349 tile.set_wgs84_nodes(nodes);
1351 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1352 std::vector<SGVec3f> normals = tile.get_normals();
1353 for (unsigned i = 0; i < normals.size(); ++i)
1354 normals[i] = hlOrf.transform(normals[i]);
1355 tile.set_normals(normals);
1357 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1359 if (!tileGeometryBin->insertBinObj(tile, matcache))
1362 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matcache, useVBOs);
1363 if (node && simplifyDistant) {
1364 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1365 node->accept(simplifier);
1368 // The toplevel transform for that tile.
1369 osg::MatrixTransform* transform = new osg::MatrixTransform;
1370 transform->setName(path);
1371 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1372 osg::Matrix::translate(toOsg(center)));
1374 // PagedLOD for the random objects so we don't need to generate
1375 // them all on tile loading.
1376 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1377 pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1378 pagedLOD->setName("pagedObjectLOD");
1381 if (simplifyNear == simplifyDistant) {
1382 // Same terrain type is used for both near and far distances,
1383 // so add it to the main group.
1384 osg::Group* terrainGroup = new osg::Group;
1385 terrainGroup->setName("BTGTerrainGroup");
1386 terrainGroup->addChild(node);
1387 transform->addChild(terrainGroup);
1388 } else if (simplifyDistant) {
1389 // Simplified terrain is only used in the distance, the
1390 // call-back below will re-generate the closer version
1391 pagedLOD->addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
1395 // we just need to know about the read file callback that itself holds the data
1396 osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1397 randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1398 randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1399 randomObjectCallback->_path = std::string(path);
1400 randomObjectCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
1401 randomObjectCallback->_matcache = matcache;
1403 osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1404 callbackOptions->setReadFileCallback(randomObjectCallback.get());
1405 pagedLOD->setDatabaseOptions(callbackOptions.get());
1407 pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1408 pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
1409 transform->addChild(pagedLOD);
1410 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );