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->findCached(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->findCached(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->findCached(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->findCached(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->findCached(i->first);
486 SGTexturedTriangleBin triangleBin = i->second;
491 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
493 int group_count = mat->get_object_group_count();
494 float building_coverage = mat->get_building_coverage();
495 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
496 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
498 if (building_coverage == 0)
501 SGBuildingBin* bin = NULL;
503 if (building_coverage > 0) {
504 bin = new SGBuildingBin(mat);
505 randomBuildings.push_back(bin);
508 unsigned num = i->second.getNumTriangles();
509 int random_dropped = 0;
510 int mask_dropped = 0;
511 int building_dropped = 0;
512 int triangle_dropped = 0;
514 for (unsigned i = 0; i < num; ++i) {
515 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
517 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
518 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
519 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
520 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
521 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
522 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
523 SGVec3f normal = cross(v0, v1);
525 // Ensure the slope isn't too steep by checking the
526 // cos of the angle between the slope normal and the
527 // vertical (conveniently the z-component of the normalized
528 // normal) and values passed in.
529 float cos = normalize(normal).z();
530 float slope_density = 1.0;
531 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
532 if (cos < cos_max_density_angle) {
534 (cos - cos_zero_density_angle) /
535 (cos_max_density_angle - cos_zero_density_angle);
538 // Containers to hold the random buildings and objects generated
539 // for this triangle for collision detection purposes.
540 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
541 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
544 float area = 0.5f*length(normal);
545 if (area <= SGLimitsf::min())
548 // Generate any random objects
549 if (use_random_objects && (group_count > 0))
551 for (int j = 0; j < group_count; j++)
553 SGMatModelGroup *object_group = mat->get_object_group(j);
554 int nObjects = object_group->get_object_count();
556 if (nObjects == 0) continue;
558 // For each of the random models in the group, determine an appropriate
559 // number of random placements and insert them.
560 for (int k = 0; k < nObjects; k++) {
561 SGMatModel * object = object_group->get_object(k);
563 // Determine the number of objecst to place, taking into account
564 // the slope density factor.
565 double n = slope_density * area / object->get_coverage_m2();
567 // Use the zombie door method to determine fractional object placement.
568 n = n + mt_rand(&seed);
570 // place an object each unit of area
572 float a = mt_rand(&seed);
573 float b = mt_rand(&seed);
579 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
580 float rotation = static_cast<float>(mt_rand(&seed));
582 // Check that the point is sufficiently far from
583 // the edge of the triangle by measuring the distance
584 // from the three lines that make up the triangle.
585 float spacing = object->get_spacing_m();
587 SGVec3f p = randomPoint - vorigin;
588 float edges[] = { length(cross(p , p - v0)) / length(v0),
589 length(cross(p - v0, p - v1)) / length(v1 - v0),
590 length(cross(p - v1, p )) / length(v1) };
591 float edge_dist = *std::min_element(edges, edges + 3);
593 if (edge_dist < spacing) {
598 if (object_mask != NULL) {
599 SGVec2f texCoord = torigin + a*t0 + b*t1;
601 // Check this random point against the object mask
602 // blue (for buildings) channel.
603 osg::Image* img = object_mask->getImage();
604 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
605 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
607 if (mt_rand(&seed) > img->getColor(x, y).b()) {
608 // Failed object mask check
613 rotation = img->getColor(x,y).r();
618 // Check it isn't too close to any other random objects in the triangle
619 std::vector<std::pair<SGVec3f, float> >::iterator l;
620 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
621 float min_dist2 = (l->second + object->get_spacing_m()) *
622 (l->second + object->get_spacing_m());
624 if (distSqr(l->first, randomPoint) > min_dist2) {
631 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
632 randomModels.insert(randomPoint,
634 (int)object->get_randomized_range_m(&seed),
642 // Random objects now generated. Now generate the random buildings (if any);
643 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
645 // Calculate the number of buildings, taking into account building density (which is linear)
646 // and the slope density factor.
647 double num = building_density * building_density * slope_density * area / building_coverage;
649 // For partial units of area, use a zombie door method to
650 // create the proper random chance of an object being created
651 // for this triangle.
652 num = num + mt_rand(&seed);
658 // Cosine of the angle between the two vectors.
659 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
661 // Determine a grid spacing in each vector such that the correct
662 // coverage will result.
663 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
664 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
666 stepv0 = std::min(stepv0, 1.0f);
667 stepv1 = std::min(stepv1, 1.0f);
669 // Start at a random point. a will be immediately incremented below.
670 float a = -mt_rand(&seed) * stepv0;
671 float b = mt_rand(&seed) * stepv1;
673 // Place an object each unit of area
677 // Set the next location to place a building
680 if ((a + b) > 1.0f) {
681 // Reached the end of the scan-line on v0. Reset and increment
683 a = mt_rand(&seed) * stepv0;
688 // In a degenerate case of a single point, we might be outside the
689 // scanline. Note that we need to still ensure that a+b < 1.
690 b = mt_rand(&seed) * stepv1 * (1.0f - a);
693 if ((a + b) > 1.0f ) {
694 // Truly degenerate case - simply choose a random point guaranteed
695 // to fulfil the constraing of a+b < 1.
697 b = mt_rand(&seed) * (1.0f - a);
700 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
701 float rotation = mt_rand(&seed);
703 if (object_mask != NULL) {
704 SGVec2f texCoord = torigin + a*t0 + b*t1;
705 osg::Image* img = object_mask->getImage();
706 int x = (int) (img->s() * texCoord.x()) % img->s();
707 int y = (int) (img->t() * texCoord.y()) % img->t();
709 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
710 while (x < 0) x += img->s();
711 while (y < 0) y += img->t();
713 if (mt_rand(&seed) < img->getColor(x, y).b()) {
714 // Object passes mask. Rotation is taken from the red channel
715 rotation = img->getColor(x,y).r();
717 // Fails mask test - try again.
723 // Check building isn't too close to the triangle edge.
724 float type_roll = mt_rand(&seed);
725 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
726 float radius = bin->getBuildingMaxRadius(buildingtype);
728 // Determine the actual center of the building, by shifting from the
729 // center of the front face to the true center.
730 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
731 osg::Vec3f(0.0, 0.0, 1.0));
732 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
734 SGVec3f p = buildingCenter - vorigin;
735 float edges[] = { length(cross(p , p - v0)) / length(v0),
736 length(cross(p - v0, p - v1)) / length(v1 - v0),
737 length(cross(p - v1, p )) / length(v1) };
738 float edge_dist = *std::min_element(edges, edges + 3);
740 if (edge_dist < radius) {
745 // Check building isn't too close to random objects and other buildings.
747 std::vector<std::pair<SGVec3f, float> >::iterator iter;
749 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
750 float min_dist = iter->second + radius;
751 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
762 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
763 float min_dist = iter->second + radius;
764 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
775 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
776 triangleBuildingList.push_back(pt);
777 bin->insert(randomPoint, rotation, buildingtype);
781 triangleObjectsList.clear();
782 triangleBuildingList.clear();
785 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
786 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
787 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
788 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
792 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
794 SGMaterialTriangleMap::iterator i;
796 // generate a repeatable random seed
799 mt_init(&seed, unsigned(586));
801 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
802 SGMaterial *mat = matlib->findCached(i->first);
806 float wood_coverage = mat->get_wood_coverage();
807 if ((wood_coverage <= 0) || (vegetation_density <= 0))
810 // Attributes that don't vary by tree but do vary by material
814 BOOST_FOREACH(bin, randomForest)
816 if ((bin->texture == mat->get_tree_texture() ) &&
817 (bin->texture_varieties == mat->get_tree_varieties()) &&
818 (bin->range == mat->get_tree_range() ) &&
819 (bin->width == mat->get_tree_width() ) &&
820 (bin->height == mat->get_tree_height() ) ) {
828 bin->texture = mat->get_tree_texture();
829 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
830 bin->range = mat->get_tree_range();
831 bin->width = mat->get_tree_width();
832 bin->height = mat->get_tree_height();
833 bin->texture_varieties = mat->get_tree_varieties();
834 randomForest.push_back(bin);
837 std::vector<SGVec3f> randomPoints;
838 i->second.addRandomTreePoints(wood_coverage,
839 mat->get_object_mask(i->second),
841 mat->get_cos_tree_max_density_slope_angle(),
842 mat->get_cos_tree_zero_density_slope_angle(),
845 std::vector<SGVec3f>::iterator k;
846 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
852 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
854 if (!insertPtGeometry(obj, matlib))
856 if (!insertSurfaceGeometry(obj, matlib))
862 typedef std::pair<osg::Node*, int> ModelLOD;
863 struct MakeQuadLeaf {
864 osg::LOD* operator() () const { return new osg::LOD; }
867 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
869 leaf->addChild(mlod.first, 0, mlod.second);
872 struct GetModelLODCoord {
873 GetModelLODCoord() {}
874 GetModelLODCoord(const GetModelLODCoord& rhs)
876 osg::Vec3 operator() (const ModelLOD& mlod) const
878 return mlod.first->getBound().center();
882 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
883 GetModelLODCoord> RandomObjectsQuadtree;
885 class RandomObjectCallback : public OptionsReadFileCallback {
887 virtual osgDB::ReaderWriter::ReadResult
888 readNode(const std::string&, const osgDB::Options*)
890 osg::ref_ptr<osg::Group> group = new osg::Group;
891 group->setName("Random Object and Lighting Group");
892 group->setDataVariance(osg::Object::STATIC);
894 osg::LOD* lightLOD = generateLightingTileObjects();
896 group->addChild(lightLOD);
898 osg::LOD* objectLOD = generateRandomTileObjects();
900 group->addChild(objectLOD);
902 return group.release();
905 // Generate all the lighting objects for the tile.
906 osg::LOD* generateLightingTileObjects()
908 SGMaterialLib* matlib = NULL;
911 matlib = _options->getMaterialLib();
913 // FIXME: ugly, has a side effect
915 _tileGeometryBin->computeRandomSurfaceLights(matlib);
917 GroundLightManager* lightManager = GroundLightManager::instance();
918 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
921 if (_tileGeometryBin->tileLights.getNumLights() > 0
922 || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
923 osg::Group* groundLights0 = new osg::Group;
924 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
925 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
926 osg::Geode* geode = new osg::Geode;
927 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
928 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
929 groundLights0->addChild(geode);
930 lightGroup->addChild(groundLights0);
933 if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
934 osg::Group* groundLights1 = new osg::Group;
935 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
936 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
937 osg::Group* groundLights2 = new osg::Group;
938 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
939 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
940 osg::Geode* geode = new osg::Geode;
941 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
942 groundLights1->addChild(geode);
943 lightGroup->addChild(groundLights1);
944 geode = new osg::Geode;
945 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
946 groundLights2->addChild(geode);
947 lightGroup->addChild(groundLights2);
950 if (!_tileGeometryBin->vasiLights.empty()) {
951 EffectGeode* vasiGeode = new EffectGeode;
953 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
954 vasiGeode->setEffect(vasiEffect);
955 SGVec4f red(1, 0, 0, 1);
958 mat = matlib->findCached("RWY_RED_LIGHTS");
960 red = mat->get_light_color();
961 SGVec4f white(1, 1, 1, 1);
964 mat = matlib->findCached("RWY_WHITE_LIGHTS");
966 white = mat->get_light_color();
967 SGDirectionalLightListBin::const_iterator i;
968 for (i = _tileGeometryBin->vasiLights.begin();
969 i != _tileGeometryBin->vasiLights.end(); ++i) {
970 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
972 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
973 lightGroup->addChild(vasiGeode);
976 Effect* runwayEffect = 0;
977 if (_tileGeometryBin->runwayLights.getNumLights() > 0
978 || !_tileGeometryBin->rabitLights.empty()
979 || !_tileGeometryBin->reilLights.empty()
980 || !_tileGeometryBin->odalLights.empty()
981 || _tileGeometryBin->taxiLights.getNumLights() > 0)
982 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
983 if (_tileGeometryBin->runwayLights.getNumLights() > 0
984 || !_tileGeometryBin->rabitLights.empty()
985 || !_tileGeometryBin->reilLights.empty()
986 || !_tileGeometryBin->odalLights.empty()
987 || !_tileGeometryBin->holdshortLights.empty()
988 || !_tileGeometryBin->guardLights.empty()) {
989 osg::Group* rwyLights = new osg::Group;
990 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
991 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
992 if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
993 EffectGeode* geode = new EffectGeode;
994 geode->setEffect(runwayEffect);
995 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
996 rwyLights->addChild(geode);
998 SGDirectionalLightListBin::const_iterator i;
999 for (i = _tileGeometryBin->rabitLights.begin();
1000 i != _tileGeometryBin->rabitLights.end(); ++i) {
1001 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1003 for (i = _tileGeometryBin->reilLights.begin();
1004 i != _tileGeometryBin->reilLights.end(); ++i) {
1005 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1007 for (i = _tileGeometryBin->holdshortLights.begin();
1008 i != _tileGeometryBin->holdshortLights.end(); ++i) {
1009 rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1011 for (i = _tileGeometryBin->guardLights.begin();
1012 i != _tileGeometryBin->guardLights.end(); ++i) {
1013 rwyLights->addChild(SGLightFactory::getGuard(*i));
1015 SGLightListBin::const_iterator j;
1016 for (j = _tileGeometryBin->odalLights.begin();
1017 j != _tileGeometryBin->odalLights.end(); ++j) {
1018 rwyLights->addChild(SGLightFactory::getOdal(*j));
1020 lightGroup->addChild(rwyLights);
1023 if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1024 osg::Group* taxiLights = new osg::Group;
1025 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1026 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1027 EffectGeode* geode = new EffectGeode;
1028 geode->setEffect(runwayEffect);
1029 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1030 taxiLights->addChild(geode);
1031 lightGroup->addChild(taxiLights);
1034 osg::LOD* lightLOD = NULL;
1036 if (lightGroup->getNumChildren() > 0) {
1037 lightLOD = new osg::LOD;
1038 lightLOD->addChild(lightGroup.get(), 0, 60000);
1039 // VASI is always on, so doesn't use light bits.
1040 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1046 // Generate all the random forest, objects and buildings for the tile
1047 osg::LOD* generateRandomTileObjects()
1049 SGMaterialLib* matlib = NULL;
1050 bool use_random_objects = false;
1051 bool use_random_vegetation = false;
1052 bool use_random_buildings = false;
1053 float vegetation_density = 1.0f;
1054 float building_density = 1.0f;
1056 osg::ref_ptr<osg::Group> randomObjects;
1057 osg::ref_ptr<osg::Group> forestNode;
1058 osg::ref_ptr<osg::Group> buildingNode;
1061 matlib = _options->getMaterialLib();
1062 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1065 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1066 use_random_objects);
1067 use_random_vegetation
1068 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1069 use_random_vegetation);
1071 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1072 vegetation_density);
1073 use_random_buildings
1074 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1075 use_random_buildings);
1077 = propertyNode->getFloatValue("/sim/rendering/building-density",
1084 if (matlib && (use_random_objects || use_random_buildings)) {
1085 _tileGeometryBin->computeRandomObjectsAndBuildings(matlib,
1088 use_random_buildings);
1092 if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1093 // Generate a repeatable random seed
1095 mt_init(&seed, unsigned(123));
1097 std::vector<ModelLOD> models;
1098 for (unsigned int i = 0;
1099 i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1100 SGMatModelBin::MatModel obj
1101 = _tileGeometryBin->randomModels.getMatModel(i);
1103 SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1104 osg::Node* node = obj.model->get_random_model(root, &seed);
1106 // Create a matrix to place the object in the correct
1107 // location, and then apply the rotation matrix created
1108 // above, with an additional random (or taken from
1109 // the object mask) heading rotation if appropriate.
1110 osg::Matrix transformMat;
1111 transformMat = osg::Matrix::translate(toOsg(obj.position));
1112 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1113 // Rotate the object around the z axis.
1114 double hdg = mt_rand(&seed) * M_PI * 2;
1115 transformMat.preMult(osg::Matrix::rotate(hdg,
1116 osg::Vec3d(0.0, 0.0, 1.0)));
1119 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1120 // Rotate the object around the z axis.
1121 double hdg = - obj.rotation * M_PI * 2;
1122 transformMat.preMult(osg::Matrix::rotate(hdg,
1123 osg::Vec3d(0.0, 0.0, 1.0)));
1126 osg::MatrixTransform* position =
1127 new osg::MatrixTransform(transformMat);
1128 position->setName("positionRandomModel");
1129 position->addChild(node);
1130 models.push_back(ModelLOD(position, obj.lod));
1132 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1133 quadtree.buildQuadTree(models.begin(), models.end());
1134 randomObjects = quadtree.getRoot();
1135 randomObjects->setName("Random objects");
1138 if (! _tileGeometryBin->randomBuildings.empty()) {
1139 buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1141 buildingNode->setName("Random buildings");
1142 _tileGeometryBin->randomBuildings.clear();
1145 if (use_random_vegetation && matlib) {
1146 // Now add some random forest.
1147 _tileGeometryBin->computeRandomForest(matlib, vegetation_density);
1149 if (! _tileGeometryBin->randomForest.empty()) {
1150 forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1152 forestNode->setName("Random trees");
1156 osg::LOD* objectLOD = NULL;
1158 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1159 objectLOD = new osg::LOD;
1161 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1162 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1163 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1165 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1166 objectLOD->setNodeMask(nodeMask);
1172 /// The original options to use for this bunch of models
1173 osg::ref_ptr<SGReaderWriterOptions> _options;
1174 osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1178 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1181 if (!tile.read_bin(path))
1184 SGMaterialLib* matlib = 0;
1187 matlib = options->getMaterialLib();
1190 SGVec3d center = tile.get_gbs_center();
1191 SGGeod geodPos = SGGeod::fromCart(center);
1192 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1194 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1195 // this will help the collision tree's bounding boxes a bit ...
1196 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1197 for (unsigned i = 0; i < nodes.size(); ++i)
1198 nodes[i] = hlOr.transform(nodes[i]);
1199 tile.set_wgs84_nodes(nodes);
1201 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1202 std::vector<SGVec3f> normals = tile.get_normals();
1203 for (unsigned i = 0; i < normals.size(); ++i)
1204 normals[i] = hlOrf.transform(normals[i]);
1205 tile.set_normals(normals);
1207 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1209 if (!tileGeometryBin->insertBinObj(tile, matlib))
1212 osg::Group* terrainGroup = new osg::Group;
1213 terrainGroup->setName("BTGTerrainGroup");
1215 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib);
1217 terrainGroup->addChild(node);
1219 // The toplevel transform for that tile.
1220 osg::MatrixTransform* transform = new osg::MatrixTransform;
1221 transform->setName(path);
1222 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1223 osg::Matrix::translate(toOsg(center)));
1224 transform->addChild(terrainGroup);
1226 // PagedLOD for the random objects so we don't need to generate
1227 // them all on tile loading.
1228 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1229 pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1230 pagedLOD->setName("pagedObjectLOD");
1232 // we just need to know about the read file callback that itself holds the data
1233 osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1234 randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1235 randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1237 osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1238 callbackOptions->setReadFileCallback(randomObjectCallback.get());
1239 pagedLOD->setDatabaseOptions(callbackOptions.get());
1241 pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1242 pagedLOD->setRange(pagedLOD->getNumChildren(), 0, 35000);
1243 transform->addChild(pagedLOD);
1244 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );