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 <boost/foreach.hpp>
48 #include <simgear/debug/logstream.hxx>
49 #include <simgear/io/sg_binobj.hxx>
50 #include <simgear/math/sg_geodesy.hxx>
51 #include <simgear/math/sg_random.h>
52 #include <simgear/math/SGMisc.hxx>
53 #include <simgear/scene/material/Effect.hxx>
54 #include <simgear/scene/material/EffectGeode.hxx>
55 #include <simgear/scene/material/mat.hxx>
56 #include <simgear/scene/material/matmodel.hxx>
57 #include <simgear/scene/material/matlib.hxx>
58 #include <simgear/scene/model/SGOffsetTransform.hxx>
59 #include <simgear/scene/util/SGUpdateVisitor.hxx>
60 #include <simgear/scene/util/SGNodeMasks.hxx>
61 #include <simgear/scene/util/QuadTreeBuilder.hxx>
62 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
63 #include <simgear/scene/util/OptionsReadFileCallback.hxx>
65 #include "SGTexturedTriangleBin.hxx"
66 #include "SGLightBin.hxx"
67 #include "SGModelBin.hxx"
68 #include "SGBuildingBin.hxx"
69 #include "TreeBin.hxx"
70 #include "SGDirectionalLightBin.hxx"
71 #include "GroundLightManager.hxx"
74 #include "pt_lights.hxx"
76 using namespace simgear;
78 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
79 typedef std::list<SGLightBin> SGLightListBin;
80 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
82 class SGTileGeometryBin : public osg::Referenced {
84 SGMaterialTriangleMap materialTriangleMap;
85 SGLightBin tileLights;
86 SGLightBin randomTileLights;
87 SGTreeBinList randomForest;
88 SGDirectionalLightBin runwayLights;
89 SGDirectionalLightBin taxiLights;
90 SGDirectionalLightListBin vasiLights;
91 SGDirectionalLightListBin rabitLights;
92 SGLightListBin odalLights;
93 SGDirectionalLightListBin holdshortLights;
94 SGDirectionalLightListBin guardLights;
95 SGDirectionalLightListBin reilLights;
96 SGMatModelBin randomModels;
97 SGBuildingBinList randomBuildings;
100 getMaterialLightColor(const SGMaterial* material)
103 return SGVec4f(1, 1, 1, 0.8);
104 return material->get_light_color();
108 addPointGeometry(SGLightBin& lights,
109 const std::vector<SGVec3d>& vertices,
110 const SGVec4f& color,
111 const int_list& pts_v)
113 for (unsigned i = 0; i < pts_v.size(); ++i)
114 lights.insert(toVec3f(vertices[pts_v[i]]), color);
118 addPointGeometry(SGDirectionalLightBin& lights,
119 const std::vector<SGVec3d>& vertices,
120 const std::vector<SGVec3f>& normals,
121 const SGVec4f& color,
122 const int_list& pts_v,
123 const int_list& pts_n)
125 // If the normal indices match the vertex indices, use seperate
126 // normal indices. Else reuse the vertex indices for the normals.
127 if (pts_v.size() == pts_n.size()) {
128 for (unsigned i = 0; i < pts_v.size(); ++i)
129 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
131 for (unsigned i = 0; i < pts_v.size(); ++i)
132 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
137 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
139 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
140 SG_LOG(SG_TERRAIN, SG_ALERT,
141 "Group list sizes for points do not match!");
145 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
146 std::string materialName = obj.get_pt_materials()[grp];
147 SGMaterial* material = 0;
149 material = matlib->find(materialName);
150 SGVec4f color = getMaterialLightColor(material);
152 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
153 // Just plain lights. Not something for the runway.
154 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
155 obj.get_pts_v()[grp]);
156 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
157 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
158 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
159 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
160 } else if (materialName == "RWY_VASI_LIGHTS") {
161 vasiLights.push_back(SGDirectionalLightBin());
162 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
163 obj.get_normals(), color, obj.get_pts_v()[grp],
164 obj.get_pts_n()[grp]);
165 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
166 rabitLights.push_back(SGDirectionalLightBin());
167 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
168 obj.get_normals(), color, obj.get_pts_v()[grp],
169 obj.get_pts_n()[grp]);
170 } else if (materialName == "RWY_ODALS_LIGHTS") {
171 odalLights.push_back(SGLightBin());
172 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
173 color, obj.get_pts_v()[grp]);
174 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
175 holdshortLights.push_back(SGDirectionalLightBin());
176 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
177 obj.get_normals(), color, obj.get_pts_v()[grp],
178 obj.get_pts_n()[grp]);
179 } else if (materialName == "RWY_GUARD_LIGHTS") {
180 guardLights.push_back(SGDirectionalLightBin());
181 addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
182 obj.get_normals(), color, obj.get_pts_v()[grp],
183 obj.get_pts_n()[grp]);
184 } else if (materialName == "RWY_REIL_LIGHTS") {
185 reilLights.push_back(SGDirectionalLightBin());
186 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
187 obj.get_normals(), color, obj.get_pts_v()[grp],
188 obj.get_pts_n()[grp]);
190 // what is left must be runway lights
191 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
192 obj.get_normals(), color, obj.get_pts_v()[grp],
193 obj.get_pts_n()[grp]);
202 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
203 const SGVec2f& tcScale, unsigned i)
207 else if (tc.size() == 1)
208 return mult(texCoords[tc[0]], tcScale);
210 return mult(texCoords[tc[i]], tcScale);
214 addTriangleGeometry(SGTexturedTriangleBin& triangles,
215 const std::vector<SGVec3d>& vertices,
216 const std::vector<SGVec3f>& normals,
217 const std::vector<SGVec2f>& texCoords,
218 const int_list& tris_v,
219 const int_list& tris_n,
220 const int_list& tris_tc,
221 const SGVec2f& tcScale)
223 if (tris_v.size() != tris_n.size()) {
224 // If the normal indices do not match, they should be inmplicitly
225 // the same than the vertex indices. So just call ourselves again
226 // with the matching index vector.
227 addTriangleGeometry(triangles, vertices, normals, texCoords,
228 tris_v, tris_v, tris_tc, tcScale);
232 for (unsigned i = 2; i < tris_v.size(); i += 3) {
234 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
235 v0.normal = normals[tris_n[i-2]];
236 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
238 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
239 v1.normal = normals[tris_n[i-1]];
240 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
242 v2.vertex = toVec3f(vertices[tris_v[i]]);
243 v2.normal = normals[tris_n[i]];
244 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
245 triangles.insert(v0, v1, v2);
250 addStripGeometry(SGTexturedTriangleBin& triangles,
251 const std::vector<SGVec3d>& vertices,
252 const std::vector<SGVec3f>& normals,
253 const std::vector<SGVec2f>& texCoords,
254 const int_list& strips_v,
255 const int_list& strips_n,
256 const int_list& strips_tc,
257 const SGVec2f& tcScale)
259 if (strips_v.size() != strips_n.size()) {
260 // If the normal indices do not match, they should be inmplicitly
261 // the same than the vertex indices. So just call ourselves again
262 // with the matching index vector.
263 addStripGeometry(triangles, vertices, normals, texCoords,
264 strips_v, strips_v, strips_tc, tcScale);
268 for (unsigned i = 2; i < strips_v.size(); ++i) {
270 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
271 v0.normal = normals[strips_n[i-2]];
272 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
274 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
275 v1.normal = normals[strips_n[i-1]];
276 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
278 v2.vertex = toVec3f(vertices[strips_v[i]]);
279 v2.normal = normals[strips_n[i]];
280 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
282 triangles.insert(v1, v0, v2);
284 triangles.insert(v0, v1, v2);
289 addFanGeometry(SGTexturedTriangleBin& triangles,
290 const std::vector<SGVec3d>& vertices,
291 const std::vector<SGVec3f>& normals,
292 const std::vector<SGVec2f>& texCoords,
293 const int_list& fans_v,
294 const int_list& fans_n,
295 const int_list& fans_tc,
296 const SGVec2f& tcScale)
298 if (fans_v.size() != fans_n.size()) {
299 // If the normal indices do not match, they should be implicitly
300 // the same than the vertex indices. So just call ourselves again
301 // with the matching index vector.
302 addFanGeometry(triangles, vertices, normals, texCoords,
303 fans_v, fans_v, fans_tc, tcScale);
308 v0.vertex = toVec3f(vertices[fans_v[0]]);
309 v0.normal = normals[fans_n[0]];
310 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
312 v1.vertex = toVec3f(vertices[fans_v[1]]);
313 v1.normal = normals[fans_n[1]];
314 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
315 for (unsigned i = 2; i < fans_v.size(); ++i) {
317 v2.vertex = toVec3f(vertices[fans_v[i]]);
318 v2.normal = normals[fans_n[i]];
319 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
320 triangles.insert(v0, v1, v2);
325 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
328 return SGVec2f(1, 1);
329 SGMaterial* material = matlib->find(name);
331 return SGVec2f(1, 1);
333 return material->get_tex_coord_scale();
337 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
339 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
340 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
341 SG_LOG(SG_TERRAIN, SG_ALERT,
342 "Group list sizes for triangles do not match!");
346 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
347 std::string materialName = obj.get_tri_materials()[grp];
348 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
349 addTriangleGeometry(materialTriangleMap[materialName],
350 obj.get_wgs84_nodes(), obj.get_normals(),
351 obj.get_texcoords(), obj.get_tris_v()[grp],
352 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
356 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
357 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
358 SG_LOG(SG_TERRAIN, SG_ALERT,
359 "Group list sizes for strips do not match!");
362 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
363 std::string materialName = obj.get_strip_materials()[grp];
364 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
365 addStripGeometry(materialTriangleMap[materialName],
366 obj.get_wgs84_nodes(), obj.get_normals(),
367 obj.get_texcoords(), obj.get_strips_v()[grp],
368 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
372 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
373 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
374 SG_LOG(SG_TERRAIN, SG_ALERT,
375 "Group list sizes for fans do not match!");
378 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
379 std::string materialName = obj.get_fan_materials()[grp];
380 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
381 addFanGeometry(materialTriangleMap[materialName],
382 obj.get_wgs84_nodes(), obj.get_normals(),
383 obj.get_texcoords(), obj.get_fans_v()[grp],
384 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
390 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
392 if (materialTriangleMap.empty())
396 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
397 //osg::Geode* geode = new osg::Geode;
398 SGMaterialTriangleMap::const_iterator i;
399 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
400 osg::Geometry* geometry = i->second.buildGeometry();
403 mat = matlib->find(i->first);
404 eg = new EffectGeode;
405 eg->setName("EffectGeode");
407 eg->setEffect(mat->get_effect(i->second));
408 eg->addDrawable(geometry);
409 eg->runGenerators(geometry); // Generate extra data needed by effect
411 group->setName("surfaceGeometryGroup");
421 void computeRandomSurfaceLights(SGMaterialLib* matlib)
423 SGMaterialTriangleMap::iterator i;
425 // generate a repeatable random seed
427 mt_init(&seed, unsigned(123));
429 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
430 SGMaterial *mat = matlib->find(i->first);
434 float coverage = mat->get_light_coverage();
437 if (coverage < 10000.0) {
438 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
439 << coverage << ", pushing up to 10000");
443 std::vector<SGVec3f> randomPoints;
444 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
445 std::vector<SGVec3f>::iterator j;
446 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
447 float zombie = mt_rand(&seed);
448 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
449 float factor = mt_rand(&seed);
454 if ( zombie > 0.5 ) {
455 // 50% chance of yellowish
456 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
457 } else if (zombie > 0.15f) {
458 // 35% chance of whitish
459 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
460 } else if (zombie > 0.05f) {
461 // 10% chance of orangish
462 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
464 // 5% chance of redish
465 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
467 randomTileLights.insert(*j, color);
472 void computeRandomObjectsAndBuildings(
473 SGMaterialLib* matlib,
474 float building_density,
475 bool use_random_objects,
476 bool use_random_buildings)
478 SGMaterialTriangleMap::iterator i;
480 // generate a repeatable random seed
482 mt_init(&seed, unsigned(123));
484 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
485 SGMaterial *mat = matlib->find(i->first);
486 SGTexturedTriangleBin triangleBin = i->second;
491 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
493 if (object_mask != NULL) {
494 img = object_mask->getImage();
497 int group_count = mat->get_object_group_count();
498 float building_coverage = mat->get_building_coverage();
499 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
500 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
502 if (building_coverage == 0)
507 if (building_coverage > 0) {
508 bin = new SGBuildingBin(mat);
509 randomBuildings.push_back(bin);
512 unsigned num = i->second.getNumTriangles();
513 int random_dropped = 0;
514 int mask_dropped = 0;
515 int building_dropped = 0;
516 int triangle_dropped = 0;
518 for (unsigned i = 0; i < num; ++i) {
519 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
521 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
522 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
523 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
524 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
525 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
526 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
527 SGVec3f normal = cross(v0, v1);
529 // Ensure the slope isn't too steep by checking the
530 // cos of the angle between the slope normal and the
531 // vertical (conveniently the z-component of the normalized
532 // normal) and values passed in.
533 float cos = normalize(normal).z();
534 float slope_density = 1.0;
535 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
536 if (cos < cos_max_density_angle) {
538 (cos - cos_zero_density_angle) /
539 (cos_max_density_angle - cos_zero_density_angle);
542 // Containers to hold the random buildings and objects generated
543 // for this triangle for collision detection purposes.
544 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
545 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
548 float area = 0.5f*length(normal);
549 if (area <= SGLimitsf::min())
552 // Generate any random objects
553 if (use_random_objects && (group_count > 0))
555 for (int j = 0; j < group_count; j++)
557 SGMatModelGroup *object_group = mat->get_object_group(j);
558 int nObjects = object_group->get_object_count();
560 if (nObjects == 0) continue;
562 // For each of the random models in the group, determine an appropriate
563 // number of random placements and insert them.
564 for (int k = 0; k < nObjects; k++) {
565 SGMatModel * object = object_group->get_object(k);
567 // Determine the number of objecst to place, taking into account
568 // the slope density factor.
569 double n = slope_density * area / object->get_coverage_m2();
571 // Use the zombie door method to determine fractional object placement.
572 n = n + mt_rand(&seed);
574 // place an object each unit of area
576 float a = mt_rand(&seed);
577 float b = mt_rand(&seed);
583 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
584 float rotation = static_cast<float>(mt_rand(&seed));
586 // Check that the point is sufficiently far from
587 // the edge of the triangle by measuring the distance
588 // from the three lines that make up the triangle.
589 float spacing = object->get_spacing_m();
591 SGVec3f p = randomPoint - vorigin;
592 float edges[] = { length(cross(p , p - v0)) / length(v0),
593 length(cross(p - v0, p - v1)) / length(v1 - v0),
594 length(cross(p - v1, p )) / length(v1) };
595 float edge_dist = *std::min_element(edges, edges + 3);
597 if (edge_dist < spacing) {
602 if (object_mask != NULL) {
603 SGVec2f texCoord = torigin + a*t0 + b*t1;
605 // Check this random point against the object mask
606 // blue (for buildings) channel.
607 osg::Image* img = object_mask->getImage();
608 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
609 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
611 if (mt_rand(&seed) > img->getColor(x, y).b()) {
612 // Failed object mask check
617 rotation = img->getColor(x,y).r();
622 // Check it isn't too close to any other random objects in the triangle
623 std::vector<std::pair<SGVec3f, float> >::iterator l;
624 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
625 float min_dist2 = (l->second + object->get_spacing_m()) *
626 (l->second + object->get_spacing_m());
628 if (distSqr(l->first, randomPoint) > min_dist2) {
635 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
636 randomModels.insert(randomPoint,
638 (int)object->get_randomized_range_m(&seed),
646 // Random objects now generated. Now generate the random buildings (if any);
647 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
649 // Calculate the number of buildings, taking into account building density (which is linear)
650 // and the slope density factor.
651 double num = building_density * building_density * slope_density * area / building_coverage;
653 // For partial units of area, use a zombie door method to
654 // create the proper random chance of an object being created
655 // for this triangle.
656 num = num + mt_rand(&seed);
662 // Cosine of the angle between the two vectors.
663 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
665 // Determine a grid spacing in each vector such that the correct
666 // coverage will result.
667 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
668 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
670 stepv0 = std::min(stepv0, 1.0f);
671 stepv1 = std::min(stepv1, 1.0f);
673 // Start at a random point. a will be immediately incremented below.
674 float a = -mt_rand(&seed) * stepv0;
675 float b = mt_rand(&seed) * stepv1;
677 // Place an object each unit of area
681 // Set the next location to place a building
684 if ((a + b) > 1.0f) {
685 // Reached the end of the scan-line on v0. Reset and increment
687 a = mt_rand(&seed) * stepv0;
692 // In a degenerate case of a single point, we might be outside the
693 // scanline. Note that we need to still ensure that a+b < 1.
694 b = mt_rand(&seed) * stepv1 * (1.0f - a);
697 if ((a + b) > 1.0f ) {
698 // Truly degenerate case - simply choose a random point guaranteed
699 // to fulfil the constraing of a+b < 1.
701 b = mt_rand(&seed) * (1.0f - a);
704 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
705 float rotation = mt_rand(&seed);
707 if (object_mask != NULL) {
708 SGVec2f texCoord = torigin + a*t0 + b*t1;
709 osg::Image* img = object_mask->getImage();
710 int x = (int) (img->s() * texCoord.x()) % img->s();
711 int y = (int) (img->t() * texCoord.y()) % img->t();
713 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
714 while (x < 0) x += img->s();
715 while (y < 0) y += img->t();
717 if (mt_rand(&seed) < img->getColor(x, y).b()) {
718 // Object passes mask. Rotation is taken from the red channel
719 rotation = img->getColor(x,y).r();
721 // Fails mask test - try again.
727 // Check building isn't too close to the triangle edge.
728 float type_roll = mt_rand(&seed);
729 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
730 float radius = bin->getBuildingMaxRadius(buildingtype);
732 // Determine the actual center of the building, by shifting from the
733 // center of the front face to the true center.
734 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
735 osg::Vec3f(0.0, 0.0, 1.0));
736 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
738 SGVec3f p = buildingCenter - vorigin;
739 float edges[] = { length(cross(p , p - v0)) / length(v0),
740 length(cross(p - v0, p - v1)) / length(v1 - v0),
741 length(cross(p - v1, p )) / length(v1) };
742 float edge_dist = *std::min_element(edges, edges + 3);
744 if (edge_dist < radius) {
749 // Check building isn't too close to random objects and other buildings.
751 std::vector<std::pair<SGVec3f, float> >::iterator iter;
753 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
754 float min_dist = iter->second + radius;
755 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
766 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
767 float min_dist = iter->second + radius;
768 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
779 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
780 triangleBuildingList.push_back(pt);
781 bin->insert(randomPoint, rotation, buildingtype);
785 triangleObjectsList.clear();
786 triangleBuildingList.clear();
789 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
790 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
791 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
792 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
796 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
798 SGMaterialTriangleMap::iterator i;
800 // generate a repeatable random seed
803 mt_init(&seed, unsigned(586));
805 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
806 SGMaterial *mat = matlib->find(i->first);
810 float wood_coverage = mat->get_wood_coverage();
811 if ((wood_coverage <= 0) || (vegetation_density <= 0))
814 // Attributes that don't vary by tree but do vary by material
818 BOOST_FOREACH(bin, randomForest)
820 if ((bin->texture == mat->get_tree_texture() ) &&
821 (bin->texture_varieties == mat->get_tree_varieties()) &&
822 (bin->range == mat->get_tree_range() ) &&
823 (bin->width == mat->get_tree_width() ) &&
824 (bin->height == mat->get_tree_height() ) ) {
832 bin->texture = mat->get_tree_texture();
833 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
834 bin->range = mat->get_tree_range();
835 bin->width = mat->get_tree_width();
836 bin->height = mat->get_tree_height();
837 bin->texture_varieties = mat->get_tree_varieties();
838 randomForest.push_back(bin);
841 std::vector<SGVec3f> randomPoints;
842 i->second.addRandomTreePoints(wood_coverage,
843 mat->get_object_mask(i->second),
845 mat->get_cos_tree_max_density_slope_angle(),
846 mat->get_cos_tree_zero_density_slope_angle(),
849 std::vector<SGVec3f>::iterator k;
850 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
856 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
858 if (!insertPtGeometry(obj, matlib))
860 if (!insertSurfaceGeometry(obj, matlib))
866 typedef std::pair<osg::Node*, int> ModelLOD;
867 struct MakeQuadLeaf {
868 osg::LOD* operator() () const { return new osg::LOD; }
871 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
873 leaf->addChild(mlod.first, 0, mlod.second);
876 struct GetModelLODCoord {
877 GetModelLODCoord() {}
878 GetModelLODCoord(const GetModelLODCoord& rhs)
880 osg::Vec3 operator() (const ModelLOD& mlod) const
882 return mlod.first->getBound().center();
886 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
887 GetModelLODCoord> RandomObjectsQuadtree;
889 class RandomObjectCallback : public OptionsReadFileCallback {
891 virtual osgDB::ReaderWriter::ReadResult
892 readNode(const std::string&, const osgDB::Options*)
894 osg::ref_ptr<osg::Group> group = new osg::Group;
895 group->setName("Random Object and Lighting Group");
896 group->setDataVariance(osg::Object::STATIC);
898 osg::LOD* lightLOD = generateLightingTileObjects();
900 group->addChild(lightLOD);
902 osg::LOD* objectLOD = generateRandomTileObjects();
904 group->addChild(objectLOD);
906 return group.release();
909 // Generate all the lighting objects for the tile.
910 osg::LOD* generateLightingTileObjects()
912 SGMaterialLib* matlib;
915 matlib = _options->getMaterialLib();
917 // FIXME: ugly, has a side effect
919 _tileGeometryBin->computeRandomSurfaceLights(matlib);
921 GroundLightManager* lightManager = GroundLightManager::instance();
922 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
925 if (_tileGeometryBin->tileLights.getNumLights() > 0
926 || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
927 osg::Group* groundLights0 = new osg::Group;
928 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
929 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
930 osg::Geode* geode = new osg::Geode;
931 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
932 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
933 groundLights0->addChild(geode);
934 lightGroup->addChild(groundLights0);
937 if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
938 osg::Group* groundLights1 = new osg::Group;
939 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
940 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
941 osg::Group* groundLights2 = new osg::Group;
942 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
943 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
944 osg::Geode* geode = new osg::Geode;
945 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
946 groundLights1->addChild(geode);
947 lightGroup->addChild(groundLights1);
948 geode = new osg::Geode;
949 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
950 groundLights2->addChild(geode);
951 lightGroup->addChild(groundLights2);
954 if (!_tileGeometryBin->vasiLights.empty()) {
955 EffectGeode* vasiGeode = new EffectGeode;
957 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
958 vasiGeode->setEffect(vasiEffect);
959 SGVec4f red(1, 0, 0, 1);
962 mat = matlib->find("RWY_RED_LIGHTS");
964 red = mat->get_light_color();
965 SGVec4f white(1, 1, 1, 1);
968 mat = matlib->find("RWY_WHITE_LIGHTS");
970 white = mat->get_light_color();
971 SGDirectionalLightListBin::const_iterator i;
972 for (i = _tileGeometryBin->vasiLights.begin();
973 i != _tileGeometryBin->vasiLights.end(); ++i) {
974 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
976 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
977 lightGroup->addChild(vasiGeode);
980 Effect* runwayEffect = 0;
981 if (_tileGeometryBin->runwayLights.getNumLights() > 0
982 || !_tileGeometryBin->rabitLights.empty()
983 || !_tileGeometryBin->reilLights.empty()
984 || !_tileGeometryBin->odalLights.empty()
985 || _tileGeometryBin->taxiLights.getNumLights() > 0)
986 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
987 if (_tileGeometryBin->runwayLights.getNumLights() > 0
988 || !_tileGeometryBin->rabitLights.empty()
989 || !_tileGeometryBin->reilLights.empty()
990 || !_tileGeometryBin->odalLights.empty()
991 || !_tileGeometryBin->holdshortLights.empty()
992 || !_tileGeometryBin->guardLights.empty()) {
993 osg::Group* rwyLights = new osg::Group;
994 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
995 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
996 if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
997 EffectGeode* geode = new EffectGeode;
998 geode->setEffect(runwayEffect);
999 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1000 rwyLights->addChild(geode);
1002 SGDirectionalLightListBin::const_iterator i;
1003 for (i = _tileGeometryBin->rabitLights.begin();
1004 i != _tileGeometryBin->rabitLights.end(); ++i) {
1005 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1007 for (i = _tileGeometryBin->reilLights.begin();
1008 i != _tileGeometryBin->reilLights.end(); ++i) {
1009 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1011 for (i = _tileGeometryBin->holdshortLights.begin();
1012 i != _tileGeometryBin->holdshortLights.end(); ++i) {
1013 rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1015 for (i = _tileGeometryBin->guardLights.begin();
1016 i != _tileGeometryBin->guardLights.end(); ++i) {
1017 rwyLights->addChild(SGLightFactory::getGuard(*i));
1019 SGLightListBin::const_iterator j;
1020 for (j = _tileGeometryBin->odalLights.begin();
1021 j != _tileGeometryBin->odalLights.end(); ++j) {
1022 rwyLights->addChild(SGLightFactory::getOdal(*j));
1024 lightGroup->addChild(rwyLights);
1027 if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1028 osg::Group* taxiLights = new osg::Group;
1029 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1030 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1031 EffectGeode* geode = new EffectGeode;
1032 geode->setEffect(runwayEffect);
1033 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1034 taxiLights->addChild(geode);
1035 lightGroup->addChild(taxiLights);
1038 osg::LOD* lightLOD = NULL;
1040 if (lightGroup->getNumChildren() > 0) {
1041 lightLOD = new osg::LOD;
1042 lightLOD->addChild(lightGroup.get(), 0, 60000);
1043 // VASI is always on, so doesn't use light bits.
1044 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1050 // Generate all the random forest, objects and buildings for the tile
1051 osg::LOD* generateRandomTileObjects()
1053 SGMaterialLib* matlib;
1054 bool use_random_objects = false;
1055 bool use_random_vegetation = false;
1056 bool use_random_buildings = false;
1057 float vegetation_density = 1.0f;
1058 float building_density = 1.0f;
1060 osg::ref_ptr<osg::Group> randomObjects;
1061 osg::ref_ptr<osg::Group> forestNode;
1062 osg::ref_ptr<osg::Group> buildingNode;
1065 matlib = _options->getMaterialLib();
1066 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1069 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1070 use_random_objects);
1071 use_random_vegetation
1072 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1073 use_random_vegetation);
1075 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1076 vegetation_density);
1077 use_random_buildings
1078 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1079 use_random_buildings);
1081 = propertyNode->getFloatValue("/sim/rendering/building-density",
1088 if (matlib && (use_random_objects || use_random_buildings)) {
1089 _tileGeometryBin->computeRandomObjectsAndBuildings(matlib,
1092 use_random_buildings);
1096 if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1097 // Generate a repeatable random seed
1099 mt_init(&seed, unsigned(123));
1101 std::vector<ModelLOD> models;
1102 for (unsigned int i = 0;
1103 i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1104 SGMatModelBin::MatModel obj
1105 = _tileGeometryBin->randomModels.getMatModel(i);
1107 SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1108 osg::Node* node = obj.model->get_random_model(root, &seed);
1110 // Create a matrix to place the object in the correct
1111 // location, and then apply the rotation matrix created
1112 // above, with an additional random (or taken from
1113 // the object mask) heading rotation if appropriate.
1114 osg::Matrix transformMat;
1115 transformMat = osg::Matrix::translate(toOsg(obj.position));
1116 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1117 // Rotate the object around the z axis.
1118 double hdg = mt_rand(&seed) * M_PI * 2;
1119 transformMat.preMult(osg::Matrix::rotate(hdg,
1120 osg::Vec3d(0.0, 0.0, 1.0)));
1123 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1124 // Rotate the object around the z axis.
1125 double hdg = - obj.rotation * M_PI * 2;
1126 transformMat.preMult(osg::Matrix::rotate(hdg,
1127 osg::Vec3d(0.0, 0.0, 1.0)));
1130 osg::MatrixTransform* position =
1131 new osg::MatrixTransform(transformMat);
1132 position->setName("positionRandomModel");
1133 position->addChild(node);
1134 models.push_back(ModelLOD(position, obj.lod));
1136 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1137 quadtree.buildQuadTree(models.begin(), models.end());
1138 randomObjects = quadtree.getRoot();
1139 randomObjects->setName("Random objects");
1142 if (! _tileGeometryBin->randomBuildings.empty()) {
1143 buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1145 buildingNode->setName("Random buildings");
1146 _tileGeometryBin->randomBuildings.clear();
1149 if (use_random_vegetation && matlib) {
1150 // Now add some random forest.
1151 _tileGeometryBin->computeRandomForest(matlib, vegetation_density);
1153 if (! _tileGeometryBin->randomForest.empty()) {
1154 forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1156 forestNode->setName("Random trees");
1160 osg::LOD* objectLOD = NULL;
1162 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1163 objectLOD = new osg::LOD;
1165 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1166 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1167 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1169 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1170 objectLOD->setNodeMask(nodeMask);
1176 /// The original options to use for this bunch of models
1177 osg::ref_ptr<SGReaderWriterOptions> _options;
1178 osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1182 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1185 if (!tile.read_bin(path))
1188 SGMaterialLib* matlib = 0;
1191 matlib = options->getMaterialLib();
1194 SGVec3d center = tile.get_gbs_center();
1195 SGGeod geodPos = SGGeod::fromCart(center);
1196 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1198 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1199 // this will help the collision tree's bounding boxes a bit ...
1200 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1201 for (unsigned i = 0; i < nodes.size(); ++i)
1202 nodes[i] = hlOr.transform(nodes[i]);
1203 tile.set_wgs84_nodes(nodes);
1205 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1206 std::vector<SGVec3f> normals = tile.get_normals();
1207 for (unsigned i = 0; i < normals.size(); ++i)
1208 normals[i] = hlOrf.transform(normals[i]);
1209 tile.set_normals(normals);
1211 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1213 if (!tileGeometryBin->insertBinObj(tile, matlib))
1216 osg::Group* terrainGroup = new osg::Group;
1217 terrainGroup->setName("BTGTerrainGroup");
1219 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib);
1221 terrainGroup->addChild(node);
1223 // The toplevel transform for that tile.
1224 osg::MatrixTransform* transform = new osg::MatrixTransform;
1225 transform->setName(path);
1226 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1227 osg::Matrix::translate(toOsg(center)));
1228 transform->addChild(terrainGroup);
1230 // PagedLOD for the random objects so we don't need to generate
1231 // them all on tile loading.
1232 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1233 pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1234 pagedLOD->setName("pagedObjectLOD");
1236 // we just need to know about the read file callback that itself holds the data
1237 osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1238 randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1239 randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1241 osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1242 callbackOptions->setReadFileCallback(randomObjectCallback.get());
1243 pagedLOD->setDatabaseOptions(callbackOptions.get());
1245 pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1246 pagedLOD->setRange(pagedLOD->getNumChildren(), 0, 35000);
1247 transform->addChild(pagedLOD);
1248 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );