1 // a layer of 3d clouds
3 // Written by Harald JOHNSEN, started April 2005.
5 // Copyright (C) 2005 Harald JOHNSEN - hjohnsen@evc.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 # include <simgear_config.h>
28 #include <osg/Texture2D>
29 #include <osg/PositionAttitudeTransform>
31 #include <osgSim/Impostor>
33 #include <simgear/compiler.h>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/scene/util/SGSceneUserData.hxx>
47 //#include <simgear/environment/visual_enviro.hxx>
48 #include <simgear/scene/util/RenderConstants.hxx>
49 #include <simgear/scene/util/SGUpdateVisitor.hxx>
51 #include "newcloud.hxx"
52 #include "cloudfield.hxx"
54 #if defined(__MINGW32__)
55 #define isnan(x) _isnan(x)
58 #if defined (__FreeBSD__)
59 # if __FreeBSD_version < 500000
61 inline int isnan(double r) { return !(r <= 0 || r >= 0); }
66 using namespace simgear;
68 float SGCloudField::fieldSize = 50000.0f;
69 double SGCloudField::timer_dt = 0.0;
70 float SGCloudField::view_distance = 20000.0f;
71 bool SGCloudField::wrap = true;
72 float SGCloudField::MAX_CLOUD_DEPTH = 2000.0f;
73 bool SGCloudField::use_impostors = false;
74 float SGCloudField::lod1_range = 8000.0f;
75 float SGCloudField::lod2_range = 4000.0f;
76 float SGCloudField::impostor_distance = 15000.0f;
78 int impostorcount = 0;
82 SGVec3f SGCloudField::view_vec, SGCloudField::view_X, SGCloudField::view_Y;
85 // Reposition the cloud layer at the specified origin and orientation
86 bool SGCloudField::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
87 double dt, int asl, float speed, float direction ) {
88 // Determine any movement of the placed clouds
89 if (placed_root->getNumChildren() == 0) return false;
92 SGGeod new_pos = SGGeod::fromRadFt(lon, lat, 0.0f);
94 SGGeodesy::SGGeodToCart(new_pos, cart);
95 osg::Vec3f osg_pos = toOsg(cart);
96 osg::Quat orient = toOsg(SGQuatd::fromLonLatRad(lon, lat) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
98 // Always update the altitude transform, as this allows
99 // the clouds to rise and fall smoothly depending on environment updates.
100 altitude_transform->setPosition(osg::Vec3f(0.0f, 0.0f, (float) asl));
102 // Similarly, always determine the effects of the wind
103 osg::Vec3f wind = osg::Vec3f(-cos((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
104 sin((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
106 osg::Vec3f windosg = field_transform->getAttitude() * wind;
107 field_transform->setPosition(field_transform->getPosition() + windosg);
110 // If we're not wrapping the cloudfield, then we make no effort to reposition
114 if ((old_pos - osg_pos).length() > fieldSize*2) {
115 // Big movement - reposition centered to current location.
116 field_transform->setPosition(osg_pos);
117 field_transform->setAttitude(orient);
120 osg::Quat fta = field_transform->getAttitude();
121 osg::Quat ftainv = field_transform->getAttitude().inverse();
123 // delta is the vector from the old position to the new position in cloud-coords
124 // osg::Vec3f delta = ftainv * (osg_pos - old_pos);
127 // Check if any of the clouds should be moved.
128 for(CloudHash::const_iterator itr = cloud_hash.begin(), end = cloud_hash.end();
132 osg::ref_ptr<osg::PositionAttitudeTransform> pat = itr->second;
133 osg::Vec3f currpos = field_transform->getPosition() + fta * pat->getPosition();
135 // Determine the vector from the new position to the cloud in cloud-space.
136 osg::Vec3f w = ftainv * (currpos - toOsg(cart));
138 // Determine a course if required. Note that this involves some axis translation.
141 if (w.x() > 0.6*fieldSize) { y = fieldSize; }
142 if (w.x() < -0.6*fieldSize) { y = -fieldSize; }
143 if (w.y() > 0.6*fieldSize) { x = -fieldSize; }
144 if (w.y() < -0.6*fieldSize) { x = fieldSize; }
146 if ((x != 0.0) || (y != 0.0)) {
147 removeCloudFromTree(pat);
148 SGGeod p = SGGeod::fromCart(toSG(field_transform->getPosition() +
149 fta * pat->getPosition()));
150 addCloudToTree(pat, p, x, y);
155 // Render the clouds in order from farthest away layer to nearest one.
156 field_root->getStateSet()->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
160 SGCloudField::SGCloudField() :
161 field_root(new osg::Group),
162 field_transform(new osg::PositionAttitudeTransform),
163 altitude_transform(new osg::PositionAttitudeTransform)
165 old_pos = osg::Vec3f(0.0f, 0.0f, 0.0f);
166 field_root->addChild(field_transform.get());
167 field_root->setName("3D Cloud field root");
168 osg::StateSet *rootSet = field_root->getOrCreateStateSet();
169 rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
170 rootSet->setAttributeAndModes(getFog());
172 field_transform->addChild(altitude_transform.get());
173 placed_root = new osg::Group();
174 altitude_transform->addChild(placed_root);
180 SGCloudField::~SGCloudField() {
184 void SGCloudField::clear(void) {
186 for(CloudHash::const_iterator itr = cloud_hash.begin(), end = cloud_hash.end();
189 removeCloudFromTree(itr->second);
195 void SGCloudField::applyVisAndLoDRange(void)
197 for (unsigned int i = 0; i < placed_root->getNumChildren(); i++) {
198 osg::ref_ptr<osg::LOD> lodnode1 = (osg::LOD*) placed_root->getChild(i);
199 for (unsigned int j = 0; j < lodnode1->getNumChildren(); j++) {
200 lodnode1->setRange(j, 0.0f, lod1_range + lod2_range + view_distance + MAX_CLOUD_DEPTH);
201 osg::ref_ptr<osg::LOD> lodnode2 = (osg::LOD*) lodnode1->getChild(j);
202 for (unsigned int k = 0; k < lodnode2->getNumChildren(); k++) {
203 lodnode2->setRange(k, 0.0f, view_distance + MAX_CLOUD_DEPTH);
209 bool SGCloudField::addCloud(float lon, float lat, float alt, int index, osg::ref_ptr<EffectGeode> geode) {
210 return addCloud(lon, lat, alt, 0.0f, 0.0f, index, geode);
213 bool SGCloudField::addCloud(float lon, float lat, float alt, float x, float y, int index, osg::ref_ptr<EffectGeode> geode) {
214 // If this cloud index already exists, don't replace it.
215 if (cloud_hash[index]) return false;
217 osg::ref_ptr<osg::PositionAttitudeTransform> transform = new osg::PositionAttitudeTransform;
219 transform->addChild(geode.get());
220 addCloudToTree(transform, lon, lat, alt, x, y);
221 cloud_hash[index] = transform;
225 // Remove a give cloud from inside the tree, without removing it from the cloud hash
226 void SGCloudField::removeCloudFromTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform)
233 osg::ref_ptr<osg::Group> lodnode = transform->getParent(0);
234 lodnode->removeChild(transform);
237 if (lodnode->getNumChildren() == 0) {
238 osg::ref_ptr<osg::Group> lodnode1 = lodnode->getParent(0);
239 osg::ref_ptr<osgSim::Impostor> impostornode = (osgSim::Impostor*) lodnode1->getParent(0);
241 lodnode1->removeChild(lodnode);
244 if (lodnode1->getNumChildren() == 0) {
245 impostornode->removeChild(lodnode1);
246 placed_root->removeChild(impostornode);
252 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform,
253 float lon, float lat, float alt, float x, float y) {
255 // Get the base position
256 SGGeod loc = SGGeod::fromDegFt(lon, lat, alt);
257 addCloudToTree(transform, loc, x, y);
261 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform,
262 SGGeod loc, float x, float y) {
264 float alt = loc.getElevationFt();
265 // Determine any shift by x/y
266 if ((x != 0.0f) || (y != 0.0f)) {
267 double crs = 90.0 - SG_RADIANS_TO_DEGREES * atan2(y, x);
268 double dst = sqrt(x*x + y*y);
271 SGGeod base_pos = SGGeod::fromGeodFt(loc, 0.0f);
272 SGGeodesy::direct(base_pos, crs, dst, loc, endcrs);
275 // The direct call provides the position at 0 alt, so adjust as required.
276 loc.setElevationFt(alt);
277 addCloudToTree(transform, loc);
281 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform, SGGeod loc) {
282 // Work out where this cloud should go in OSG coordinates.
284 SGGeodesy::SGGeodToCart(loc, cart);
285 osg::Vec3f pos = toOsg(cart);
288 if (old_pos == osg::Vec3f(0.0f, 0.0f, 0.0f)) {
290 SGVec3<double> fieldcenter;
291 SGGeodesy::SGGeodToCart(SGGeod::fromDegFt(loc.getLongitudeDeg(), loc.getLatitudeDeg(), 0.0f), fieldcenter);
292 // Convert to the scenegraph orientation where we just rotate around
293 // the y axis 180 degrees.
294 osg::Quat orient = toOsg(SGQuatd::fromLonLatDeg(loc.getLongitudeDeg(), loc.getLatitudeDeg()) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
296 osg::Vec3f osg_pos = toOsg(fieldcenter);
298 field_transform->setPosition(osg_pos);
299 field_transform->setAttitude(orient);
303 // Convert position to cloud-coordinates
304 pos = pos - field_transform->getPosition();
305 pos = field_transform->getAttitude().inverse() * pos;
307 // We have a two level dynamic quad tree which the cloud will be added
308 // to. If there are no appropriate nodes in the quad tree, they are
309 // created as required.
311 osg::ref_ptr<osg::LOD> lodnode1;
312 osg::ref_ptr<osg::LOD> lodnode;
313 osg::ref_ptr<osgSim::Impostor> impostornode;
315 for (unsigned int i = 0; (!found) && (i < placed_root->getNumChildren()); i++) {
316 lodnode1 = (osg::LOD*) placed_root->getChild(i);
317 if ((lodnode1->getCenter() - pos).length2() < lod1_range*lod1_range) {
318 // New cloud is within RADIUS_LEVEL_1 of the center of the LOD node.
325 impostornode = new osgSim::Impostor();
326 impostornode->setImpostorThreshold(impostor_distance);
327 //impostornode->setImpostorThresholdToBound();
328 //impostornode->setCenter(pos);
329 placed_root->addChild(impostornode.get());
330 lodnode1 = (osg::ref_ptr<osg::LOD>) impostornode;
332 lodnode1 = new osg::LOD();
333 placed_root->addChild(lodnode1.get());
338 // Now check if there is a second level LOD node at an appropriate distance
341 for (unsigned int j = 0; (!found) && (j < lodnode1->getNumChildren()); j++) {
342 lodnode = (osg::LOD*) lodnode1->getChild(j);
343 if ((lodnode->getCenter() - pos).length2() < lod2_range*lod2_range) {
344 // We've found the right leaf LOD node
350 // No suitable leaf node was found, so we need to add one.
351 lodnode = new osg::LOD();
352 lodnode1->addChild(lodnode, 0.0f, lod1_range + lod2_range + view_distance + MAX_CLOUD_DEPTH);
356 transform->setPosition(pos);
357 lodnode->addChild(transform.get(), 0.0f, view_distance + MAX_CLOUD_DEPTH);
359 SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "Impostors: " << impostorcount <<
360 " LoD: " << lodcount <<
361 " Clouds: " << cloudcount);
363 lodnode->dirtyBound();
364 lodnode1->dirtyBound();
365 field_root->dirtyBound();
368 bool SGCloudField::deleteCloud(int identifier) {
369 osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
370 if (transform == NULL) return false;
372 removeCloudFromTree(transform);
373 cloud_hash.erase(identifier);
378 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt) {
379 return repositionCloud(identifier, lon, lat, alt, 0.0f, 0.0f);
382 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt, float x, float y) {
383 osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
385 if (transform == NULL) return false;
387 removeCloudFromTree(transform);
388 addCloudToTree(transform, lon, lat, alt, x, y);
392 bool SGCloudField::isDefined3D(void) {
393 return (cloud_hash.size() > 0);
396 SGCloudField::CloudFog::CloudFog() {
398 fog->setMode(osg::Fog::EXP2);
399 fog->setDataVariance(osg::Object::DYNAMIC);
402 void SGCloudField::updateFog(double visibility, const osg::Vec4f& color) {
403 const double sqrt_m_log01 = sqrt(-log(0.01));
404 osg::Fog* fog = CloudFog::instance()->fog.get();
405 fog->setColor(color);
406 fog->setDensity(sqrt_m_log01 / visibility);