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/StateSet>
43 #include <boost/foreach.hpp>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/io/sg_binobj.hxx>
49 #include <simgear/math/sg_geodesy.hxx>
50 #include <simgear/math/sg_random.h>
51 #include <simgear/scene/material/Effect.hxx>
52 #include <simgear/scene/material/EffectGeode.hxx>
53 #include <simgear/scene/material/mat.hxx>
54 #include <simgear/scene/material/matlib.hxx>
55 #include <simgear/scene/model/SGOffsetTransform.hxx>
56 #include <simgear/scene/util/SGUpdateVisitor.hxx>
57 #include <simgear/scene/util/SGNodeMasks.hxx>
58 #include <simgear/scene/util/QuadTreeBuilder.hxx>
60 #include "SGTexturedTriangleBin.hxx"
61 #include "SGLightBin.hxx"
62 #include "SGModelBin.hxx"
63 #include "SGBuildingBin.hxx"
64 #include "TreeBin.hxx"
65 #include "SGDirectionalLightBin.hxx"
66 #include "GroundLightManager.hxx"
69 #include "pt_lights.hxx"
71 using namespace simgear;
73 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
74 typedef std::list<SGLightBin> SGLightListBin;
75 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
77 struct SGTileGeometryBin {
78 SGMaterialTriangleMap materialTriangleMap;
79 SGLightBin tileLights;
80 SGLightBin randomTileLights;
81 SGTreeBinList randomForest;
82 SGDirectionalLightBin runwayLights;
83 SGDirectionalLightBin taxiLights;
84 SGDirectionalLightListBin vasiLights;
85 SGDirectionalLightListBin rabitLights;
86 SGLightListBin odalLights;
87 SGDirectionalLightListBin reilLights;
88 SGMatModelBin randomModels;
89 SGBuildingBinList randomBuildings;
92 getMaterialLightColor(const SGMaterial* material)
95 return SGVec4f(1, 1, 1, 0.8);
96 return material->get_light_color();
100 addPointGeometry(SGLightBin& lights,
101 const std::vector<SGVec3d>& vertices,
102 const SGVec4f& color,
103 const int_list& pts_v)
105 for (unsigned i = 0; i < pts_v.size(); ++i)
106 lights.insert(toVec3f(vertices[pts_v[i]]), color);
110 addPointGeometry(SGDirectionalLightBin& lights,
111 const std::vector<SGVec3d>& vertices,
112 const std::vector<SGVec3f>& normals,
113 const SGVec4f& color,
114 const int_list& pts_v,
115 const int_list& pts_n)
117 // If the normal indices match the vertex indices, use seperate
118 // normal indices. Else reuse the vertex indices for the normals.
119 if (pts_v.size() == pts_n.size()) {
120 for (unsigned i = 0; i < pts_v.size(); ++i)
121 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
123 for (unsigned i = 0; i < pts_v.size(); ++i)
124 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
129 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
131 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
132 SG_LOG(SG_TERRAIN, SG_ALERT,
133 "Group list sizes for points do not match!");
137 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
138 std::string materialName = obj.get_pt_materials()[grp];
139 SGMaterial* material = 0;
141 material = matlib->find(materialName);
142 SGVec4f color = getMaterialLightColor(material);
144 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
145 // Just plain lights. Not something for the runway.
146 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
147 obj.get_pts_v()[grp]);
148 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
149 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
150 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
151 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
152 } else if (materialName == "RWY_VASI_LIGHTS") {
153 vasiLights.push_back(SGDirectionalLightBin());
154 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
155 obj.get_normals(), color, obj.get_pts_v()[grp],
156 obj.get_pts_n()[grp]);
157 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
158 rabitLights.push_back(SGDirectionalLightBin());
159 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
160 obj.get_normals(), color, obj.get_pts_v()[grp],
161 obj.get_pts_n()[grp]);
162 } else if (materialName == "RWY_ODALS_LIGHTS") {
163 odalLights.push_back(SGLightBin());
164 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
165 color, obj.get_pts_v()[grp]);
166 } else if (materialName == "RWY_REIL_LIGHTS") {
167 reilLights.push_back(SGDirectionalLightBin());
168 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
169 obj.get_normals(), color, obj.get_pts_v()[grp],
170 obj.get_pts_n()[grp]);
172 // what is left must be runway lights
173 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
174 obj.get_normals(), color, obj.get_pts_v()[grp],
175 obj.get_pts_n()[grp]);
184 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
185 const SGVec2f& tcScale, unsigned i)
189 else if (tc.size() == 1)
190 return mult(texCoords[tc[0]], tcScale);
192 return mult(texCoords[tc[i]], tcScale);
196 addTriangleGeometry(SGTexturedTriangleBin& triangles,
197 const std::vector<SGVec3d>& vertices,
198 const std::vector<SGVec3f>& normals,
199 const std::vector<SGVec2f>& texCoords,
200 const int_list& tris_v,
201 const int_list& tris_n,
202 const int_list& tris_tc,
203 const SGVec2f& tcScale)
205 if (tris_v.size() != tris_n.size()) {
206 // If the normal indices do not match, they should be inmplicitly
207 // the same than the vertex indices. So just call ourselves again
208 // with the matching index vector.
209 addTriangleGeometry(triangles, vertices, normals, texCoords,
210 tris_v, tris_v, tris_tc, tcScale);
214 for (unsigned i = 2; i < tris_v.size(); i += 3) {
216 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
217 v0.normal = normals[tris_n[i-2]];
218 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
220 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
221 v1.normal = normals[tris_n[i-1]];
222 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
224 v2.vertex = toVec3f(vertices[tris_v[i]]);
225 v2.normal = normals[tris_n[i]];
226 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
227 triangles.insert(v0, v1, v2);
232 addStripGeometry(SGTexturedTriangleBin& triangles,
233 const std::vector<SGVec3d>& vertices,
234 const std::vector<SGVec3f>& normals,
235 const std::vector<SGVec2f>& texCoords,
236 const int_list& strips_v,
237 const int_list& strips_n,
238 const int_list& strips_tc,
239 const SGVec2f& tcScale)
241 if (strips_v.size() != strips_n.size()) {
242 // If the normal indices do not match, they should be inmplicitly
243 // the same than the vertex indices. So just call ourselves again
244 // with the matching index vector.
245 addStripGeometry(triangles, vertices, normals, texCoords,
246 strips_v, strips_v, strips_tc, tcScale);
250 for (unsigned i = 2; i < strips_v.size(); ++i) {
252 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
253 v0.normal = normals[strips_n[i-2]];
254 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
256 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
257 v1.normal = normals[strips_n[i-1]];
258 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
260 v2.vertex = toVec3f(vertices[strips_v[i]]);
261 v2.normal = normals[strips_n[i]];
262 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
264 triangles.insert(v1, v0, v2);
266 triangles.insert(v0, v1, v2);
271 addFanGeometry(SGTexturedTriangleBin& triangles,
272 const std::vector<SGVec3d>& vertices,
273 const std::vector<SGVec3f>& normals,
274 const std::vector<SGVec2f>& texCoords,
275 const int_list& fans_v,
276 const int_list& fans_n,
277 const int_list& fans_tc,
278 const SGVec2f& tcScale)
280 if (fans_v.size() != fans_n.size()) {
281 // If the normal indices do not match, they should be implicitly
282 // the same than the vertex indices. So just call ourselves again
283 // with the matching index vector.
284 addFanGeometry(triangles, vertices, normals, texCoords,
285 fans_v, fans_v, fans_tc, tcScale);
290 v0.vertex = toVec3f(vertices[fans_v[0]]);
291 v0.normal = normals[fans_n[0]];
292 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
294 v1.vertex = toVec3f(vertices[fans_v[1]]);
295 v1.normal = normals[fans_n[1]];
296 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
297 for (unsigned i = 2; i < fans_v.size(); ++i) {
299 v2.vertex = toVec3f(vertices[fans_v[i]]);
300 v2.normal = normals[fans_n[i]];
301 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
302 triangles.insert(v0, v1, v2);
307 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
310 return SGVec2f(1, 1);
311 SGMaterial* material = matlib->find(name);
313 return SGVec2f(1, 1);
315 return material->get_tex_coord_scale();
319 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
321 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
322 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
323 SG_LOG(SG_TERRAIN, SG_ALERT,
324 "Group list sizes for triangles do not match!");
328 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
329 std::string materialName = obj.get_tri_materials()[grp];
330 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
331 addTriangleGeometry(materialTriangleMap[materialName],
332 obj.get_wgs84_nodes(), obj.get_normals(),
333 obj.get_texcoords(), obj.get_tris_v()[grp],
334 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
338 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
339 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
340 SG_LOG(SG_TERRAIN, SG_ALERT,
341 "Group list sizes for strips do not match!");
344 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
345 std::string materialName = obj.get_strip_materials()[grp];
346 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
347 addStripGeometry(materialTriangleMap[materialName],
348 obj.get_wgs84_nodes(), obj.get_normals(),
349 obj.get_texcoords(), obj.get_strips_v()[grp],
350 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
354 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
355 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
356 SG_LOG(SG_TERRAIN, SG_ALERT,
357 "Group list sizes for fans do not match!");
360 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
361 std::string materialName = obj.get_fan_materials()[grp];
362 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
363 addFanGeometry(materialTriangleMap[materialName],
364 obj.get_wgs84_nodes(), obj.get_normals(),
365 obj.get_texcoords(), obj.get_fans_v()[grp],
366 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
372 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
374 if (materialTriangleMap.empty())
378 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
379 //osg::Geode* geode = new osg::Geode;
380 SGMaterialTriangleMap::const_iterator i;
381 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
382 osg::Geometry* geometry = i->second.buildGeometry();
385 mat = matlib->find(i->first);
386 eg = new EffectGeode;
388 eg->setEffect(mat->get_effect(i->second));
389 eg->addDrawable(geometry);
390 eg->runGenerators(geometry); // Generate extra data needed by effect
400 void computeRandomSurfaceLights(SGMaterialLib* matlib)
402 SGMaterialTriangleMap::iterator i;
404 // generate a repeatable random seed
406 mt_init(&seed, unsigned(123));
408 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
409 SGMaterial *mat = matlib->find(i->first);
413 float coverage = mat->get_light_coverage();
416 if (coverage < 10000.0) {
417 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
418 << coverage << ", pushing up to 10000");
422 std::vector<SGVec3f> randomPoints;
423 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
424 std::vector<SGVec3f>::iterator j;
425 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
426 float zombie = mt_rand(&seed);
427 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
428 float factor = mt_rand(&seed);
433 if ( zombie > 0.5 ) {
434 // 50% chance of yellowish
435 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
436 } else if (zombie > 0.15f) {
437 // 35% chance of whitish
438 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
439 } else if (zombie > 0.05f) {
440 // 10% chance of orangish
441 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
443 // 5% chance of redish
444 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
446 randomTileLights.insert(*j, color);
451 void computeRandomBuildings(SGMaterialLib* matlib, float building_density)
453 SGMaterialTriangleMap::iterator i;
455 // generate a repeatable random seed
457 mt_init(&seed, unsigned(123));
459 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
460 SGMaterial *mat = matlib->find(i->first);
461 SGTexturedTriangleBin triangleBin = i->second;
466 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
468 float coverage = mat->get_building_coverage();
470 // Minimum spacing needs to include the maximum footprint of a building.
471 // As the 0,0,0 point is the center of the front of the building, we need
472 // to consider the full depth, but only half the possible width.
473 float min_spacing = mat->get_building_spacing();
479 SGBuildingBin* bin = NULL;
481 BOOST_FOREACH(bin, randomBuildings)
483 if (bin->texture == mat->get_building_texture()) {
490 bin = new SGBuildingBin();
491 bin->texture = mat->get_building_texture();
492 SG_LOG(SG_INPUT, SG_DEBUG, "Building texture " << bin->texture);
493 randomBuildings.push_back(bin);
496 std::vector<std::pair<SGVec3f, float> > randomPoints;
498 unsigned num = i->second.getNumTriangles();
499 int triangle_dropped = 0;
500 int building_dropped = 0;
501 int random_dropped = 0;
503 for (unsigned i = 0; i < num; ++i) {
504 SGBuildingBin::BuildingList triangle_buildings;
505 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
507 SGVec3f v0 = triangleBin.getVertex(triangleRef[0]).vertex;
508 SGVec3f v1 = triangleBin.getVertex(triangleRef[1]).vertex;
509 SGVec3f v2 = triangleBin.getVertex(triangleRef[2]).vertex;
510 SGVec2f t0 = triangleBin.getVertex(triangleRef[0]).texCoord;
511 SGVec2f t1 = triangleBin.getVertex(triangleRef[1]).texCoord;
512 SGVec2f t2 = triangleBin.getVertex(triangleRef[2]).texCoord;
513 SGVec3f normal = cross(v1 - v0, v2 - v0);
516 float area = 0.5f*length(normal);
517 if (area <= SGLimitsf::min())
520 // for partial units of area, use a zombie door method to
521 // create the proper random chance of an object being created
522 // for this triangle.
523 double num = area / coverage + mt_rand(&seed);
526 num = num * building_density;
528 // place an object each unit of area
529 while ( num > 1.0 ) {
530 float a = mt_rand(&seed);
531 float b = mt_rand(&seed);
538 SGVec3f randomPoint = a*v0 + b*v1 + c*v2;
539 float rotation = mt_rand(&seed);
541 if (object_mask != NULL) {
542 SGVec2f texCoord = a*t0 + b*t1 + c*t2;
543 osg::Image* img = object_mask->getImage();
544 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
545 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
547 if (mt_rand(&seed) < img->getColor(x, y).b()) {
548 // Object passes mask. Rotation is taken from the red channel
549 rotation = img->getColor(x,y).r();
551 // Fails mask test - try again.
557 // Now create the building, so we have an idea of its footprint
558 // and therefore appropriate spacing.
559 SGBuildingBin::BuildingType buildingtype;
566 // Determine the building type, and hence dimensions.
567 float type = mt_rand(&seed);
569 if (type < mat->get_building_small_fraction()) {
571 buildingtype = SGBuildingBin::SMALL;
572 width = mat->get_building_small_min_width() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_small_max_width() - mat->get_building_small_min_width());
573 depth = mat->get_building_small_min_depth() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_small_max_depth() - mat->get_building_small_min_depth());
574 floors = round(mat->get_building_small_min_floors() + mt_rand(&seed) * (mat->get_building_small_max_floors() - mat->get_building_small_min_floors()));
575 height = floors * (2.8 + mt_rand(&seed));
577 if (depth > width) { depth = width; }
579 pitched = (mt_rand(&seed) < mat->get_building_small_pitch());
580 } else if (type < (mat->get_building_small_fraction() + mat->get_building_medium_fraction())) {
581 buildingtype = SGBuildingBin::MEDIUM;
582 width = mat->get_building_medium_min_width() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_medium_max_width() - mat->get_building_medium_min_width());
583 depth = mat->get_building_medium_min_depth() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_medium_max_depth() - mat->get_building_medium_min_depth());
584 floors = round(mat->get_building_medium_min_floors() + mt_rand(&seed) * (mat->get_building_medium_max_floors() - mat->get_building_medium_min_floors()));
585 height = floors * (2.8 + mt_rand(&seed));
586 pitched = (mt_rand(&seed) < mat->get_building_medium_pitch());
588 buildingtype = SGBuildingBin::LARGE;
589 width = mat->get_building_large_min_width() + mt_rand(&seed) * (mat->get_building_large_max_width() - mat->get_building_large_min_width());
590 depth = mat->get_building_large_min_depth() + mt_rand(&seed) * (mat->get_building_large_max_depth() - mat->get_building_large_min_depth());
591 floors = round(mat->get_building_large_min_floors() + mt_rand(&seed) * (mat->get_building_large_max_floors() - mat->get_building_large_min_floors()));
592 height = floors * (2.8 + mt_rand(&seed));
593 pitched = (mt_rand(&seed) < mat->get_building_large_pitch());
596 // Determine an appropriate minimum spacing for the object. Note that the
597 // origin of the building model is the center of the front face, hence we
598 // consider the full depth. We choose _not_ to use the diagonal distance
599 // to one of the rear corners, as we assume that terrain masking will
600 // make the buildings place in some sort of grid.
601 float radius = std::max(depth, 0.5f*width);
603 // Check that the point is sufficiently far from
604 // the edge of the triangle by measuring the distance
605 // from the three lines that make up the triangle.
606 if (((length(cross(randomPoint - v0, randomPoint - v1)) / length(v1 - v0)) < radius) ||
607 ((length(cross(randomPoint - v1, randomPoint - v2)) / length(v2 - v1)) < radius) ||
608 ((length(cross(randomPoint - v2, randomPoint - v0)) / length(v0 - v2)) < radius) )
615 // Check against the generic random objects. TODO - make this more efficient by
616 // masking ahead of time objects outside of the triangle.
617 bool too_close = false;
618 for (unsigned int i = 0; i < randomModels.getNumModels(); ++i) {
619 float min_dist = randomModels.getMatModel(i).model->get_spacing_m() + radius + min_spacing;
620 min_dist = min_dist * min_dist;
622 if (distSqr(randomModels.getMatModel(i).position, randomPoint) < min_dist) {
630 // Too close to a random model - drop and try again
635 SGBuildingBin::BuildingList::iterator l;
637 // Check that the building is sufficiently far from any other building within the triangle.
638 for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
640 float min_dist = l->radius + radius + min_spacing;
641 min_dist = min_dist * min_dist;
643 if (distSqr(randomPoint, l->position) < min_dist) {
651 // Too close to another building - drop and try again
656 // If we've passed all of the above tests we have a valid
657 // building, so create it!
658 SGBuildingBin::Building building =
659 SGBuildingBin::Building(buildingtype,
667 triangle_buildings.push_back(building);
671 // Add the buildings from this triangle to the overall list.
672 SGBuildingBin::BuildingList::iterator l;
674 for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
679 SG_LOG(SG_INPUT, SG_DEBUG, "Random Buildings: " << bin->getNumBuildings());
680 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to triangle edge: " << triangle_dropped);
681 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to random object: " << random_dropped);
682 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to other building: " << building_dropped);
686 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
688 SGMaterialTriangleMap::iterator i;
690 // generate a repeatable random seed
692 mt_init(&seed, unsigned(586));
694 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
695 SGMaterial *mat = matlib->find(i->first);
699 float wood_coverage = mat->get_wood_coverage();
700 if (wood_coverage <= 0)
703 // Attributes that don't vary by tree but do vary by material
707 BOOST_FOREACH(bin, randomForest)
709 if ((bin->texture == mat->get_tree_texture() ) &&
710 (bin->texture_varieties == mat->get_tree_varieties()) &&
711 (bin->range == mat->get_tree_range() ) &&
712 (bin->width == mat->get_tree_width() ) &&
713 (bin->height == mat->get_tree_height() ) ) {
721 bin->texture = mat->get_tree_texture();
722 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
723 bin->range = mat->get_tree_range();
724 bin->width = mat->get_tree_width();
725 bin->height = mat->get_tree_height();
726 bin->texture_varieties = mat->get_tree_varieties();
727 randomForest.push_back(bin);
730 std::vector<SGVec3f> randomPoints;
731 i->second.addRandomTreePoints(wood_coverage,
732 mat->get_object_mask(i->second),
736 std::vector<SGVec3f>::iterator k;
737 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
743 void computeRandomObjects(SGMaterialLib* matlib)
745 SGMaterialTriangleMap::iterator i;
747 // generate a repeatable random seed
749 mt_init(&seed, unsigned(123));
751 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
752 SGMaterial *mat = matlib->find(i->first);
756 int group_count = mat->get_object_group_count();
760 for (int j = 0; j < group_count; j++)
762 SGMatModelGroup *object_group = mat->get_object_group(j);
763 int nObjects = object_group->get_object_count();
767 // For each of the random models in the group, determine an appropriate
768 // number of random placements and insert them.
769 for (int k = 0; k < nObjects; k++) {
770 SGMatModel * object = object_group->get_object(k);
772 std::vector<std::pair<SGVec3f, float> > randomPoints;
774 i->second.addRandomPoints(object->get_coverage_m2(),
775 object->get_spacing_m(),
776 mat->get_object_mask(i->second),
779 std::vector<std::pair<SGVec3f, float> >::iterator l;
780 for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
781 // Only add the model if it is sufficiently far from the
785 for (unsigned i = 0; i < randomModels.getNumModels(); i++) {
786 float spacing = randomModels.getMatModel(i).model->get_spacing_m() + object->get_spacing_m();
787 spacing = spacing * spacing;
789 if (distSqr(randomModels.getMatModel(i).position, l->first) < spacing) {
796 randomModels.insert(l->first, object, (int)object->get_randomized_range_m(&seed), l->second);
806 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
808 if (!insertPtGeometry(obj, matlib))
810 if (!insertSurfaceGeometry(obj, matlib))
816 typedef std::pair<osg::Node*, int> ModelLOD;
817 struct MakeQuadLeaf {
818 osg::LOD* operator() () const { return new osg::LOD; }
821 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
823 leaf->addChild(mlod.first, 0, mlod.second);
826 struct GetModelLODCoord {
827 GetModelLODCoord() {}
828 GetModelLODCoord(const GetModelLODCoord& rhs)
830 osg::Vec3 operator() (const ModelLOD& mlod) const
832 return mlod.first->getBound().center();
836 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
837 GetModelLODCoord> RandomObjectsQuadtree;
840 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
843 if (!tile.read_bin(path))
846 SGMaterialLib* matlib = 0;
847 bool use_random_objects = false;
848 bool use_random_vegetation = false;
849 bool use_random_buildings = false;
850 float vegetation_density = 1.0f;
851 float building_density = 1.0f;
853 matlib = options->getMaterialLib();
854 SGPropertyNode* propertyNode = options->getPropertyNode().get();
857 = propertyNode->getBoolValue("/sim/rendering/random-objects",
859 use_random_vegetation
860 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
861 use_random_vegetation);
863 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
866 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
867 use_random_buildings);
869 = propertyNode->getFloatValue("/sim/rendering/building-density",
874 SGVec3d center = tile.get_gbs_center();
875 SGGeod geodPos = SGGeod::fromCart(center);
876 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
878 // rotate the tiles so that the bounding boxes get nearly axis aligned.
879 // this will help the collision tree's bounding boxes a bit ...
880 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
881 for (unsigned i = 0; i < nodes.size(); ++i)
882 nodes[i] = hlOr.transform(nodes[i]);
883 tile.set_wgs84_nodes(nodes);
885 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
886 std::vector<SGVec3f> normals = tile.get_normals();
887 for (unsigned i = 0; i < normals.size(); ++i)
888 normals[i] = hlOrf.transform(normals[i]);
889 tile.set_normals(normals);
891 SGTileGeometryBin tileGeometryBin;
892 if (!tileGeometryBin.insertBinObj(tile, matlib))
896 GroundLightManager* lightManager = GroundLightManager::instance();
898 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
899 osg::ref_ptr<osg::Group> randomObjects;
900 osg::ref_ptr<osg::Group> forestNode;
901 osg::ref_ptr<osg::Group> buildingNode;
902 osg::Group* terrainGroup = new osg::Group;
904 osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
906 terrainGroup->addChild(node);
908 if (use_random_objects && matlib) {
909 tileGeometryBin.computeRandomObjects(matlib);
911 if (tileGeometryBin.randomModels.getNumModels() > 0) {
912 // Generate a repeatable random seed
914 mt_init(&seed, unsigned(123));
916 std::vector<ModelLOD> models;
917 for (unsigned int i = 0;
918 i < tileGeometryBin.randomModels.getNumModels(); i++) {
919 SGMatModelBin::MatModel obj
920 = tileGeometryBin.randomModels.getMatModel(i);
922 SGPropertyNode* root = options->getPropertyNode()->getRootNode();
923 osg::Node* node = obj.model->get_random_model(root, &seed);
925 // Create a matrix to place the object in the correct
926 // location, and then apply the rotation matrix created
927 // above, with an additional random (or taken from
928 // the object mask) heading rotation if appropriate.
929 osg::Matrix transformMat;
930 transformMat = osg::Matrix::translate(toOsg(obj.position));
931 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
932 // Rotate the object around the z axis.
933 double hdg = mt_rand(&seed) * M_PI * 2;
934 transformMat.preMult(osg::Matrix::rotate(hdg,
935 osg::Vec3d(0.0, 0.0, 1.0)));
938 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
939 // Rotate the object around the z axis.
940 double hdg = - obj.rotation * M_PI * 2;
941 transformMat.preMult(osg::Matrix::rotate(hdg,
942 osg::Vec3d(0.0, 0.0, 1.0)));
945 osg::MatrixTransform* position =
946 new osg::MatrixTransform(transformMat);
947 position->addChild(node);
948 models.push_back(ModelLOD(position, obj.lod));
950 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
951 quadtree.buildQuadTree(models.begin(), models.end());
952 randomObjects = quadtree.getRoot();
953 randomObjects->setName("random objects");
957 if (use_random_vegetation && matlib) {
958 // Now add some random forest.
959 tileGeometryBin.computeRandomForest(matlib, vegetation_density);
961 if (tileGeometryBin.randomForest.size() > 0) {
962 forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
964 forestNode->setName("Random trees");
968 if (use_random_buildings && matlib) {
969 tileGeometryBin.computeRandomBuildings(matlib, building_density);
970 if (tileGeometryBin.randomBuildings.size() > 0) {
971 buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
973 buildingNode->setName("Random buildings");
977 // FIXME: ugly, has a side effect
979 tileGeometryBin.computeRandomSurfaceLights(matlib);
981 if (tileGeometryBin.tileLights.getNumLights() > 0
982 || tileGeometryBin.randomTileLights.getNumLights() > 0) {
983 osg::Group* groundLights0 = new osg::Group;
984 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
985 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
986 osg::Geode* geode = new osg::Geode;
987 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
988 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
989 groundLights0->addChild(geode);
990 lightGroup->addChild(groundLights0);
993 if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
994 osg::Group* groundLights1 = new osg::Group;
995 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
996 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
997 osg::Group* groundLights2 = new osg::Group;
998 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
999 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1000 osg::Geode* geode = new osg::Geode;
1001 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1002 groundLights1->addChild(geode);
1003 lightGroup->addChild(groundLights1);
1004 geode = new osg::Geode;
1005 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1006 groundLights2->addChild(geode);
1007 lightGroup->addChild(groundLights2);
1010 if (!tileGeometryBin.vasiLights.empty()) {
1011 EffectGeode* vasiGeode = new EffectGeode;
1013 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1014 vasiGeode->setEffect(vasiEffect);
1015 SGVec4f red(1, 0, 0, 1);
1016 SGMaterial* mat = 0;
1018 mat = matlib->find("RWY_RED_LIGHTS");
1020 red = mat->get_light_color();
1021 SGVec4f white(1, 1, 1, 1);
1024 mat = matlib->find("RWY_WHITE_LIGHTS");
1026 white = mat->get_light_color();
1027 SGDirectionalLightListBin::const_iterator i;
1028 for (i = tileGeometryBin.vasiLights.begin();
1029 i != tileGeometryBin.vasiLights.end(); ++i) {
1030 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1032 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1033 lightGroup->addChild(vasiGeode);
1036 Effect* runwayEffect = 0;
1037 if (tileGeometryBin.runwayLights.getNumLights() > 0
1038 || !tileGeometryBin.rabitLights.empty()
1039 || !tileGeometryBin.reilLights.empty()
1040 || !tileGeometryBin.odalLights.empty()
1041 || tileGeometryBin.taxiLights.getNumLights() > 0)
1042 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1043 if (tileGeometryBin.runwayLights.getNumLights() > 0
1044 || !tileGeometryBin.rabitLights.empty()
1045 || !tileGeometryBin.reilLights.empty()
1046 || !tileGeometryBin.odalLights.empty()) {
1047 osg::Group* rwyLights = new osg::Group;
1048 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1049 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1050 if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1051 EffectGeode* geode = new EffectGeode;
1052 geode->setEffect(runwayEffect);
1053 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1055 rwyLights->addChild(geode);
1057 SGDirectionalLightListBin::const_iterator i;
1058 for (i = tileGeometryBin.rabitLights.begin();
1059 i != tileGeometryBin.rabitLights.end(); ++i) {
1060 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1062 for (i = tileGeometryBin.reilLights.begin();
1063 i != tileGeometryBin.reilLights.end(); ++i) {
1064 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1066 SGLightListBin::const_iterator j;
1067 for (j = tileGeometryBin.odalLights.begin();
1068 j != tileGeometryBin.odalLights.end(); ++j) {
1069 rwyLights->addChild(SGLightFactory::getOdal(*j));
1071 lightGroup->addChild(rwyLights);
1074 if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1075 osg::Group* taxiLights = new osg::Group;
1076 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1077 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1078 EffectGeode* geode = new EffectGeode;
1079 geode->setEffect(runwayEffect);
1080 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1081 taxiLights->addChild(geode);
1082 lightGroup->addChild(taxiLights);
1085 // The toplevel transform for that tile.
1086 osg::MatrixTransform* transform = new osg::MatrixTransform;
1087 transform->setName(path);
1088 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1089 osg::Matrix::translate(toOsg(center)));
1090 transform->addChild(terrainGroup);
1091 if (lightGroup->getNumChildren() > 0) {
1092 osg::LOD* lightLOD = new osg::LOD;
1093 lightLOD->addChild(lightGroup.get(), 0, 30000);
1094 // VASI is always on, so doesn't use light bits.
1095 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT);
1096 transform->addChild(lightLOD);
1099 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1101 // Add a LoD node, so we don't try to display anything when the tile center
1102 // is more than 20km away.
1103 osg::LOD* objectLOD = new osg::LOD;
1105 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1106 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1107 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1109 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1110 objectLOD->setNodeMask(nodeMask);
1111 transform->addChild(objectLOD);