]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloudfield.cxx
Merge commit 'refs/merge-requests/11' of git://gitorious.org/fg/simgear into merge...
[simgear.git] / simgear / scene / sky / cloudfield.cxx
1 // a layer of 3d clouds
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
6 //
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.
11 //
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.
16 //
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.
20 //
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <osg/Fog>
28 #include <osg/Texture2D>
29 #include <osg/PositionAttitudeTransform>
30 #include <osg/Vec4f>
31
32 #include <simgear/compiler.h>
33
34 #include <simgear/math/sg_random.h>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/scene/util/SGSceneUserData.hxx>
37
38 #include <algorithm>
39 #include <vector>
40 #include <iostream>
41
42 using namespace std;
43
44 using std::vector;
45
46 //#include <simgear/environment/visual_enviro.hxx>
47 #include <simgear/scene/util/RenderConstants.hxx>
48 #include <simgear/scene/util/SGUpdateVisitor.hxx>
49 #include "sky.hxx"
50 #include "newcloud.hxx"
51 #include "cloudfield.hxx"
52
53 #if defined(__MINGW32__)
54 #define isnan(x) _isnan(x)
55 #endif
56
57 #if defined (__FreeBSD__)
58 #  if __FreeBSD_version < 500000
59      extern "C" {
60        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
61      }
62 #  endif
63 #endif
64
65 using namespace simgear;
66
67 float SGCloudField::fieldSize = 50000.0f;
68 double SGCloudField::timer_dt = 0.0;
69 float SGCloudField::view_distance = 20000.0f;
70 bool SGCloudField::wrap = true;
71 float SGCloudField::RADIUS_LEVEL_1 = 20000.0f;
72 float SGCloudField::RADIUS_LEVEL_2 = 5000.0f;
73
74 SGVec3f SGCloudField::view_vec, SGCloudField::view_X, SGCloudField::view_Y;
75
76
77 // Reposition the cloud layer at the specified origin and orientation
78 bool SGCloudField::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
79                                double dt, int asl, float speed, float direction ) {
80     // Determine any movement of the placed clouds
81     if (placed_root->getNumChildren() == 0) return false;
82
83     SGVec3<double> cart;
84     SGGeodesy::SGGeodToCart(SGGeod::fromRadFt(lon, lat, 0.0f), cart);
85     osg::Vec3f osg_pos = toOsg(cart);
86     osg::Quat orient = toOsg(SGQuatd::fromLonLatRad(lon, lat) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
87     
88     // Always update the altitude transform, as this allows
89     // the clouds to rise and fall smoothly depending on environment updates.
90     altitude_transform->setPosition(osg::Vec3f(0.0f, 0.0f, (float) asl));
91     
92     // Similarly, always determine the effects of the wind
93     osg::Vec3f wind = osg::Vec3f(-cos((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
94                                  sin((direction + 180)* SGD_DEGREES_TO_RADIANS) * speed * dt,
95                                  0.0f);
96     //cout << "Wind: " << direction << "@" << speed << "\n";
97     
98     osg::Vec3f windosg = field_transform->getAttitude() * wind;
99     field_transform->setPosition(field_transform->getPosition() + windosg);
100     
101     if (!wrap) {
102         // If we're not wrapping the cloudfield, then we make no effort to reposition
103         return false;
104     }
105         
106     if ((old_pos - osg_pos).length() > fieldSize*2) {
107         // Big movement - reposition centered to current location.
108         field_transform->setPosition(osg_pos);
109         field_transform->setAttitude(orient);
110         old_pos = osg_pos;
111     } else {
112         // delta is the vector from the old position to the new position in cloud-coords
113         osg::Vec3f delta = field_transform->getAttitude().inverse() * (osg_pos - old_pos);
114         //cout << "Delta: " << delta.length() << "\n";
115
116         for (unsigned int i = 0; i < placed_root->getNumChildren(); i++) {
117             osg::ref_ptr<osg::LOD> lodnode1 = (osg::LOD*) placed_root->getChild(i);
118             osg::Vec3f v = delta - lodnode1->getCenter();
119
120             if ((v.x() < -0.5*fieldSize) ||
121                 (v.x() >  0.5*fieldSize) ||
122                 (v.y() < -0.5*fieldSize) ||
123                 (v.y() >  0.5*fieldSize)   )  {
124                 //cout << "V: " << v.x() << ", " << v.y() << "\n";
125
126                 osg::Vec3f shift = osg::Vec3f(0.0f, 0.0f, 0.0f);
127                 if (v.x() > 0.5*fieldSize) { shift += osg::Vec3f(fieldSize, 0.0f, 0.0f); }
128                 if (v.x() < -0.5*fieldSize) { shift -= osg::Vec3f(fieldSize, 0.0f, 0.0f); }
129
130                 if (v.y() > 0.5*fieldSize) { shift += osg::Vec3f(0.0f, fieldSize, 0.0f); }
131                 if (v.y() < -0.5*fieldSize) { shift -= osg::Vec3f(0.0f, fieldSize, 0.0f); }
132
133                 //cout << "Shift: " << shift.x() << ", " << shift.y() << "\n\n";
134
135                 for (unsigned int j = 0; j < lodnode1->getNumChildren(); j++) {
136                     osg::ref_ptr<osg::LOD> lodnode2 = (osg::LOD*) lodnode1->getChild(j);
137                     for (unsigned int k = 0; k < lodnode2->getNumChildren(); k++) {
138                         osg::ref_ptr<osg::PositionAttitudeTransform> pat =(osg::PositionAttitudeTransform*) lodnode2->getChild(k);
139                         pat->setPosition(pat->getPosition() + shift);
140                     }
141                 }
142             }
143         }
144     }
145     
146     // Render the clouds in order from farthest away layer to nearest one.
147     field_root->getStateSet()->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
148     return true;
149 }
150
151 SGCloudField::SGCloudField() :
152         field_root(new osg::Group),
153         field_transform(new osg::PositionAttitudeTransform),
154         altitude_transform(new osg::PositionAttitudeTransform)
155 {
156     old_pos = osg::Vec3f(0.0f, 0.0f, 0.0f);
157     field_root->addChild(field_transform.get());
158     field_root->setName("3D Cloud field root");
159     osg::StateSet *rootSet = field_root->getOrCreateStateSet();
160     rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
161     rootSet->setAttributeAndModes(getFog());
162     
163     field_transform->addChild(altitude_transform.get());
164     placed_root = new osg::Group();
165     altitude_transform->addChild(placed_root);
166 }
167     
168 SGCloudField::~SGCloudField() {
169         }
170
171
172 void SGCloudField::clear(void) {
173
174     for(CloudHash::const_iterator itr = cloud_hash.begin(), end = cloud_hash.end();
175         itr != end;
176         ++itr) {
177         removeCloudFromTree(itr->second);
178     }
179     
180     cloud_hash.clear();
181 }
182
183 void SGCloudField::applyVisRange(void)
184 {
185     for (unsigned int i = 0; i < placed_root->getNumChildren(); i++) {
186         osg::ref_ptr<osg::LOD> lodnode1 = (osg::LOD*) placed_root->getChild(i);
187         for (unsigned int j = 0; j < lodnode1->getNumChildren(); j++) {
188             osg::ref_ptr<osg::LOD> lodnode2 = (osg::LOD*) lodnode1->getChild(j);
189             for (unsigned int k = 0; k < lodnode2->getNumChildren(); k++) {
190                 lodnode2->setRange(k, 0.0f, view_distance);
191             }
192         }
193     }
194 }
195             
196 bool SGCloudField::addCloud(float lon, float lat, float alt, int index, osg::ref_ptr<EffectGeode> geode) {
197   return addCloud(lon, lat, alt, 0.0f, 0.0f, index, geode);
198         }
199
200 bool SGCloudField::addCloud(float lon, float lat, float alt, float x, float y, int index, osg::ref_ptr<EffectGeode> geode) {
201     // If this cloud index already exists, don't replace it.
202     if (cloud_hash[index]) return false;
203
204     osg::ref_ptr<osg::PositionAttitudeTransform> transform = new osg::PositionAttitudeTransform;
205
206     transform->addChild(geode.get());
207     addCloudToTree(transform, lon, lat, alt, x, y);
208     cloud_hash[index] = transform;
209     return true;
210     }
211     
212 // Remove a give cloud from inside the tree, without removing it from the cloud hash
213 void SGCloudField::removeCloudFromTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform)
214 {
215     osg::ref_ptr<osg::Group> lodnode = transform->getParent(0);
216     lodnode->removeChild(transform);
217
218     // Clean up the LOD nodes if required
219     if (lodnode->getNumChildren() == 0) {
220         osg::ref_ptr<osg::Group> lodnode1 = lodnode->getParent(0);
221             
222         lodnode1->removeChild(lodnode);
223             
224         if (lodnode1->getNumChildren() == 0) {
225             placed_root->removeChild(lodnode1);
226         }
227     }
228 }
229
230 void SGCloudField::addCloudToTree(osg::ref_ptr<osg::PositionAttitudeTransform> transform,
231                                   float lon, float lat, float alt, float x, float y) {
232     
233     // Get the base position
234     SGGeod loc = SGGeod::fromDegFt(lon, lat, alt);
235     
236     // Determine any shift by x/y
237     if ((x != 0.0f) || (y != 0.0f)) {
238         double crs;
239         
240         if (y == 0.0f) {
241             crs = (x < 0.0f) ? -90.0 : 90.0;        
242         } else {
243             crs = SG_RADIANS_TO_DEGREES * tan(x/y); 
244         }
245          
246         double dst = sqrt(x*x + y*y);
247         double endcrs;
248         
249         SGGeod base_pos = SGGeod::fromDegFt(lon, lat, 0.0f);            
250         SGGeodesy::direct(base_pos, crs, dst, loc, endcrs);
251         
252         // The direct call provides the position at 0 alt, so adjust as required.
253         loc.setElevationFt(alt);
254     }
255         
256     // Work out where this cloud should go in OSG coordinates.
257     SGVec3<double> cart;
258     SGGeodesy::SGGeodToCart(loc, cart);
259     osg::Vec3f pos = toOsg(cart);
260
261     // Convert to the scenegraph orientation where we just rotate around
262     // the y axis 180 degrees.
263     osg::Quat orient = toOsg(SGQuatd::fromLonLatDeg(lon, lat) * SGQuatd::fromRealImag(0, SGVec3d(0, 1, 0)));
264
265     if (old_pos == osg::Vec3f(0.0f, 0.0f, 0.0f)) {
266         // First se tup.
267         SGVec3<double> fieldcenter;
268         SGGeodesy::SGGeodToCart(SGGeod::fromDegFt(lon, lat, 0.0f), fieldcenter);
269
270         field_transform->setPosition(toOsg(fieldcenter));
271         field_transform->setAttitude(orient);
272         old_pos = toOsg(fieldcenter);
273     }
274
275     pos = pos - field_transform->getPosition();
276
277     pos = orient.inverse() * pos;
278
279     // We have a two level dynamic quad tree which the cloud will be added
280     // to. If there are no appropriate nodes in the quad tree, they are
281     // created as required.
282     bool found = false;
283     osg::ref_ptr<osg::LOD> lodnode1;
284     osg::ref_ptr<osg::LOD> lodnode;
285
286     for (unsigned int i = 0; (!found) && (i < placed_root->getNumChildren()); i++) {
287         lodnode1 = (osg::LOD*) placed_root->getChild(i);
288         if ((lodnode1->getCenter() - pos).length2() < RADIUS_LEVEL_1*RADIUS_LEVEL_1) {
289             // New cloud is within RADIUS_LEVEL_1 of the center of the LOD node.
290             //cout << "Adding cloud to existing LoD level 1 node. Distance:" << (lodnode1->getCenter() - pos).length() << "\n";
291             found = true;
292         }
293     }
294
295     if (!found) {
296         lodnode1 = new osg::LOD();
297         placed_root->addChild(lodnode1.get());
298         //cout << "Adding cloud to new LoD node\n";
299     }
300
301     // Now check if there is a second level LOD node at an appropriate distance
302     found = false;
303
304     for (unsigned int j = 0; (!found) && (j < lodnode1->getNumChildren()); j++) {
305         lodnode = (osg::LOD*) lodnode1->getChild(j);
306         if ((lodnode->getCenter() - pos).length2() < RADIUS_LEVEL_2*RADIUS_LEVEL_2) {
307             // We've found the right leaf LOD node
308             //cout << "Found existing LOD leaf node. Distance:"<< (lodnode->getCenter() - pos).length() << "\n";
309             found = true;
310             }
311         }
312
313     if (!found) {
314         // No suitable leave node was found, so we need to add one.
315         lodnode = new osg::LOD();
316         lodnode1->addChild(lodnode, 0.0f, 4*RADIUS_LEVEL_1);
317         //cout << "Adding cloud to new LoD node\n";
318 }
319
320     transform->setPosition(pos);
321     lodnode->addChild(transform.get(), 0.0f, view_distance);
322
323     lodnode->dirtyBound();
324     lodnode1->dirtyBound();
325     field_root->dirtyBound();
326 }
327         
328 bool SGCloudField::deleteCloud(int identifier) {
329     osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
330     if (transform == NULL) return false;
331         
332     removeCloudFromTree(transform);
333     cloud_hash.erase(identifier);
334
335     return true;
336 }
337         
338 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt) {
339     return repositionCloud(identifier, lon, lat, alt, 0.0f, 0.0f);
340 }
341
342 bool SGCloudField::repositionCloud(int identifier, float lon, float lat, float alt, float x, float y) {
343     osg::ref_ptr<osg::PositionAttitudeTransform> transform = cloud_hash[identifier];
344     
345     if (transform == NULL) return false;
346
347     removeCloudFromTree(transform);
348     addCloudToTree(transform, lon, lat, alt, x, y);
349     return true;
350     }
351
352 bool SGCloudField::isDefined3D(void) {
353     return (cloud_hash.size() > 0);
354 }
355
356 SGCloudField::CloudFog::CloudFog() {
357     fog = new osg::Fog;
358     fog->setMode(osg::Fog::EXP2);
359     fog->setDataVariance(osg::Object::DYNAMIC);
360 }
361
362 void SGCloudField::updateFog(double visibility, const osg::Vec4f& color) {
363     const double sqrt_m_log01 = sqrt(-log(0.01));
364     osg::Fog* fog = CloudFog::instance()->fog.get();
365     fog->setColor(color);
366     fog->setDensity(sqrt_m_log01 / visibility);
367 }
368