]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloudfield.cxx
bdd64aa3286758c22b5f5008c95648b7a9a14e05
[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, 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
20 //
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include <plib/sg.h>
30 #include <plib/ssg.h>
31 #include <simgear/math/sg_geodesy.hxx>
32 #include <simgear/math/polar3d.hxx>
33
34 #include STL_ALGORITHM
35 #include <vector>
36
37 SG_USING_STD(vector);
38
39 #include <simgear/environment/visual_enviro.hxx>
40 #include "newcloud.hxx"
41 #include "cloudfield.hxx"
42
43 static list_of_culledCloud inViewClouds;
44
45 // visibility distance for clouds in meters
46 float SGCloudField::CloudVis = 25000.0f;
47 bool SGCloudField::enable3D = true;
48 // fieldSize must be > CloudVis or we can destroy the impostor cache
49 // a cloud must only be seen once or the impostor will be generated for each of his positions
50 double SGCloudField::fieldSize = 27000.0;
51 float SGCloudField::density = 100.0;
52 static int last_cache_size = 1*1024;
53 static int cacheResolution = 64;
54
55 int SGCloudField::get_CacheResolution(void) {
56         return cacheResolution;
57 }
58
59 void SGCloudField::set_CacheResolution(int resolutionPixels) {
60         if(cacheResolution == resolutionPixels)
61                 return;
62         cacheResolution = resolutionPixels;
63         if(enable3D) {
64                 int count = last_cache_size * 1024 / (cacheResolution * cacheResolution * 4);
65                 if(count == 0)
66                         count = 1;
67                 SGNewCloud::cldCache->setCacheSize(count, cacheResolution);
68         }
69 }
70
71 int SGCloudField::get_CacheSize(void) { 
72         return SGNewCloud::cldCache->queryCacheSize(); 
73 }
74
75 void SGCloudField::set_CacheSize(int sizeKb) {
76         // apply in rendering option dialog
77         if(last_cache_size == sizeKb)
78                 return;
79         if(sizeKb == 0)
80                 return;
81         if(sizeKb)
82                 last_cache_size = sizeKb;
83         if(enable3D) {
84                 int count = last_cache_size * 1024 / (cacheResolution * cacheResolution * 4);
85                 if(count == 0)
86                         count = 1;
87 //              SGNewCloud::cldCache->setCacheSize(sizeKb);
88                 SGNewCloud::cldCache->setCacheSize(count, cacheResolution);
89         }
90 }
91 void SGCloudField::set_CloudVis(float distance) {
92         if( distance <= fieldSize )
93                 SGCloudField::CloudVis = distance;
94 }
95 void SGCloudField::set_density(float density) {
96         SGCloudField::density = density;
97 }
98 void SGCloudField::set_enable3dClouds(bool enable) {
99         if(enable3D == enable)
100                 return;
101         enable3D = enable;
102         if(enable) {
103                 SGNewCloud::cldCache->setCacheSize(last_cache_size);
104         } else {
105                 SGNewCloud::cldCache->setCacheSize(0);
106         }
107 }
108
109 // reposition the cloud layer at the specified origin and orientation
110 void SGCloudField::reposition( sgVec3 p, sgVec3 up, double lon, double lat, double alt, double dt) {
111     sgMat4 T1, LON, LAT;
112     sgVec3 axis;
113
114     sgMakeTransMat4( T1, p );
115
116     sgSetVec3( axis, 0.0, 0.0, 1.0 );
117     sgMakeRotMat4( LON, lon * SGD_RADIANS_TO_DEGREES, axis );
118
119     sgSetVec3( axis, 0.0, 1.0, 0.0 );
120     sgMakeRotMat4( LAT, 90.0 - lat * SGD_RADIANS_TO_DEGREES, axis );
121
122     sgMat4 TRANSFORM;
123
124     sgCopyMat4( TRANSFORM, T1 );
125     sgPreMultMat4( TRANSFORM, LON );
126     sgPreMultMat4( TRANSFORM, LAT );
127
128     sgCoord layerpos;
129     sgSetCoord( &layerpos, TRANSFORM );
130
131         sgMakeCoordMat4( transform, &layerpos );
132
133
134         this->alt = alt;
135
136         // simulate clouds movement from wind
137         double speed = 10.0f;
138         double direction = 45.0;
139     double sp_dist = speed*dt;
140     if (sp_dist > 0) {
141         double bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
142         double by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
143                 relative_position[SG_X] += bx;
144                 relative_position[SG_Y] += by;
145     }
146
147     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
148         Point3D start( last_lon, last_lat, 0.0 );
149         Point3D dest( lon, lat, 0.0 );
150         double course = 0.0, dist = 0.0;
151
152         calc_gc_course_dist( dest, start, &course, &dist );
153         // if start and dest are too close together,
154         // calc_gc_course_dist() can return a course of "nan".  If
155         // this happens, lets just use the last known good course.
156         // This is a hack, and it would probably be better to make
157         // calc_gc_course_dist() more robust.
158         if ( isnan(course) ) {
159             course = last_course;
160         } else {
161             last_course = course;
162         }
163
164         // calculate cloud movement due to external forces
165         double ax = 0.0, ay = 0.0;
166
167         if (dist > 0.0) {
168             ax = cos(course) * dist;
169             ay = sin(course) * dist;
170         }
171
172                 deltax += ax;
173                 deltay += ay;
174
175         last_lon = lon;
176         last_lat = lat;
177     }
178
179
180         // correct the frustum with the right far plane
181         ssgContext *context = ssgGetCurrentContext();
182         frustum = *context->getFrustum();
183         frustum.setFOV(55.0,0);
184         frustum.setNearFar(1.0, CloudVis);
185 }
186
187 SGCloudField::SGCloudField() :
188         last_density(0.0),
189         deltax(0.0),
190         deltay(0.0),
191         last_course(0.0)
192 {
193         sgSetVec3( relative_position, 0,0,0);
194         theField.reserve(200);
195         inViewClouds.reserve(200);
196 }
197
198 SGCloudField::~SGCloudField() {
199         list_of_Cloud::iterator iCloud;
200         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
201                 delete iCloud->aCloud;
202         }
203         theField.clear();
204 }
205
206
207 // use a table or else we see poping when moving the slider...
208 static int densTable[][10] = {
209         {0,0,0,0,0,0,0,0,0,0},
210         {1,0,0,0,0,0,0,0,0,0},
211         {1,0,0,0,1,0,0,0,0,0},
212         {1,0,0,0,1,0,0,1,0,0}, // 30%
213         {1,0,1,0,1,0,0,1,0,0},
214         {1,0,1,0,1,0,1,1,0,0}, // 50%
215         {1,0,1,0,1,0,1,1,0,1},
216         {1,0,1,1,1,0,1,1,0,1}, // 70%
217         {1,1,1,1,1,0,1,1,0,1},
218         {1,1,1,1,1,0,1,1,1,1}, // 90%
219         {1,1,1,1,1,1,1,1,1,1}
220 };
221
222 // set the visible flag depending on density
223 void SGCloudField::applyDensity(void) {
224         int row = (int) (density / 10.0);
225         int col = 0;
226         list_of_Cloud::iterator iCloud;
227         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
228                 if(++col > 9)
229                         col = 0;
230                 if( densTable[row][col] ) {
231                         iCloud->visible = true;
232                 } else
233                         iCloud->visible = false;
234         }
235         last_density = density;
236 }
237
238 // add one cloud, data is not copied, ownership given
239 void SGCloudField::addCloud( sgVec3 pos, SGNewCloud *cloud) {
240         Cloud cl;
241         sgCopyVec3( cl.pos, pos );
242         cl.aCloud = cloud;
243         cl.visible = true;
244         cloud->SetPos( pos );
245         theField.push_back( cl );
246 }
247
248
249 static float Rnd(float n) {
250         return n * (-0.5f + rand() / (float) RAND_MAX);
251 }
252
253 // for debug only
254 // build a field of cloud of size 25x25 km, its a grid of 11x11 clouds
255 void SGCloudField::buildTestLayer(void) {
256
257         const float s = 2250.0f;
258
259         for( int z = -5 ; z <= 5 ; z++) {
260                 for( int x = -5 ; x <= 5 ; x++ ) {
261             SGNewCloud *cloud = new SGNewCloud;
262                         cloud->new_cu();
263                         sgVec3 pos = {(x+Rnd(0.7)) * s, 750.0f, (z+Rnd(0.7)) * s};
264             addCloud(pos, cloud);
265                 }
266         }
267         applyDensity();
268 }
269
270 // cull all clouds of a tiled field
271 void SGCloudField::cullClouds(sgVec3 eyePos, sgMat4 mat) {
272         list_of_Cloud::iterator iCloud;
273
274         // TODO:cull the field before culling the clouds in the field (should eliminate 3 fields)
275         for( iCloud = theField.begin() ; iCloud != theField.end() ; iCloud++ ) {
276                 sgVec3 dist;
277                 sgSphere sphere;
278                 if( ! iCloud->visible )
279                         continue;
280                 sgSubVec3( dist, iCloud->pos, eyePos );
281                 sphere.setCenter(dist[0], dist[2], dist[1]);
282                 float radius = iCloud->aCloud->getRadius();
283                 sphere.setRadius(radius);
284                 sphere.orthoXform(mat);
285                 if( frustum.contains( & sphere ) != SG_OUTSIDE ) {
286                         float squareDist = dist[0]*dist[0] + dist[1]*dist[1] + dist[2]*dist[2];
287                         culledCloud tmp;
288                         tmp.aCloud = iCloud->aCloud;
289                         sgCopyVec3( tmp.eyePos, eyePos ); 
290                         // save distance for later sort, opposite distance because we want back to front
291                         tmp.dist   =  - squareDist;
292                         inViewClouds.push_back(tmp);
293                         if( squareDist - radius*radius < 100*100 )
294                                 sgEnviro.set_view_in_cloud(true);
295                 }
296         }
297
298 }
299
300
301 // Render a cloud field
302 // because no field can have an infinite size (and we don't want to reach his border)
303 // we draw this field and adjacent fields.
304 // adjacent fields are not real, its the same field displaced by some offset
305 void SGCloudField::Render(void) {
306     sgVec3 eyePos;
307         double relx, rely;
308
309         if( ! enable3D )
310                 return;
311
312         if( last_density != density ) {
313                 last_density = density;
314                 applyDensity();
315         }
316
317         // ask the impostor cache to do some cleanup
318         // TODO:don't do that for every field
319         SGNewCloud::cldCache->startNewFrame();
320
321         inViewClouds.clear();
322
323  
324         glPushMatrix();
325  
326         sgMat4 modelview, tmp, invtrans;
327
328         // try to find the sun position
329         sgTransposeNegateMat4( invtrans, transform );
330     sgVec3 lightVec;
331     ssgGetLight( 0 )->getPosition( lightVec );
332     sgXformVec3( lightVec, invtrans );
333         sgCopyVec3( SGNewCloud::modelSunDir, lightVec );
334         sgSetVec3(  SGNewCloud::modelSunDir, lightVec[0], lightVec[2], lightVec[1]);
335         // try to find the lighting data (buggy)
336         sgVec4 diffuse, ambient;
337         ssgGetLight( 0 )->getColour( GL_DIFFUSE, diffuse );
338         ssgGetLight( 0 )->getColour( GL_AMBIENT, ambient );
339         sgScaleVec3 ( SGNewCloud::sunlight, diffuse , 0.70f);
340         sgScaleVec3 ( SGNewCloud::ambLight, ambient , 0.60f);
341
342         // voodoo things on the matrix stack
343     ssgGetModelviewMatrix( modelview );
344         sgCopyMat4( tmp, transform );
345     sgPostMultMat4( tmp, modelview );
346
347         // cloud fields are tiled on the flat earth
348         // compute the position in the tile
349         relx = -fmod( deltax + relative_position[SG_X] + tmp[3][0], fieldSize );
350         rely = -fmod( deltay + relative_position[SG_Y] + tmp[3][1], fieldSize );
351
352         sgSetVec3( eyePos, -relx, alt, -rely);
353
354         tmp[3][2] = 0;
355         tmp[3][0] = 0;
356         tmp[3][1] = 0;
357     ssgLoadModelviewMatrix( tmp );
358  
359 /* flat earth
360
361         ^
362         |
363         |    FFF
364         |    FoF
365         |    FFF
366         |
367         O----------->
368                 o = we are here
369                 F = adjacent fields
370 */
371
372         for(int x = -1 ; x <= 1 ; x++)
373                 for(int y = -1 ; y <= 1 ; y++ ) {
374                         sgVec3 fieldPos;
375                         // pretend we are not where we are
376                         sgSetVec3(fieldPos, eyePos[0] + x*fieldSize, eyePos[1], eyePos[2] + y*fieldSize);
377                         cullClouds(fieldPos, tmp);
378                 }
379         // sort all visible clouds back to front (because of transparency)
380         std::sort( inViewClouds.begin(), inViewClouds.end() );
381  
382         // TODO:push states
383         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
384     glEnable(GL_ALPHA_TEST);
385     glAlphaFunc(GL_GREATER, 0.0f);
386         glDisable(GL_CULL_FACE);
387         glEnable(GL_DEPTH_TEST);
388         glEnable(GL_SMOOTH);
389     glEnable(GL_BLEND);
390         glBlendFunc( GL_DST_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
391         glEnable( GL_TEXTURE_2D );
392         glDisable( GL_FOG );
393     glDisable(GL_LIGHTING);
394
395         // test data: field = 11x11 cloud, 9 fields
396         // depending on position and view direction, perhaps 40 to 60 clouds not culled
397         list_of_culledCloud::iterator iCloud;
398         for( iCloud = inViewClouds.begin() ; iCloud != inViewClouds.end() ; iCloud++ ) {
399 //              iCloud->aCloud->drawContainers();
400                 iCloud->aCloud->Render(iCloud->eyePos);
401         }
402
403         glBindTexture(GL_TEXTURE_2D, 0);
404     glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
405         glEnable( GL_FOG );
406         glEnable(GL_CULL_FACE);
407         glEnable(GL_DEPTH_TEST);
408
409         ssgLoadModelviewMatrix( modelview );
410
411         glPopMatrix();
412
413 }
414