be32c771c226a3c8ad608624afe5bb7ce93493d0
[freeglut] / progs / demos / Lorenz / lorenz.c
1 /*
2  * Lorenz Strange Attractor
3  *
4  * Written by John F. Fay in honor of the "freeglut" 2.0.0 release in July 2003
5  *
6  * What it does:
7  *  This program starts with two particles right next to each other.  The particles
8  *  move through a three-dimensional phase space governed by the following equations:
9  *       dx/dt = sigma * ( y - x )
10  *       dy/dt = r * x - y + x * z
11  *       dz/dt = x * y + b * z
12  *  These are the Lorenz equations and define the "Lorenz Attractor."  Any two particles
13  *  arbitrarily close together will move apart as time increases, but their tracks are
14  *  confined within a region of the space.
15  *
16  * Commands:
17  *  Arrow keys:  Rotate the view
18  *  PgUp, PgDn:  Zoom in and out
19  *  Mouse click:  Center on the nearest point on a particle trajectory
20  *
21  *  'r'/'R':  Reset the simulation
22  *  'm'/'M':  Modify the Lorenz parameters (in the text window)
23  *  's'/'S':  Stop (the advancement in time)
24  *  'g'/'G':  Go
25  *  <spacebar>:  Single-step
26  *  <Escape>:  Quit
27  */
28
29 /* Include Files */
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <math.h>
34 #include <time.h>
35 #include <GL/freeglut.h>
36 #ifdef WIN32
37 /* DUMP MEMORY LEAKS */
38 #include <crtdbg.h>
39 #endif
40
41
42 /************************************** Defined Constants ***************************************/
43 /* Number of points to draw in the curves */
44 #define NUM_POINTS    512
45
46 /* Angle to rotate when the user presses an arrow key */
47 #define ROTATION_ANGLE  5.0
48
49 /* Amount to scale bu when the user presses PgUp or PgDn */
50 #define SCALE_FACTOR     0.8
51
52
53 /*************************************** Global Variables ***************************************/
54 /* Lorenz Attractor variables */
55 double s0 = 10.0, r0 = 28.0, b0 = 8.0/3.0 ;   /* Default Lorenz attactor parameters */
56 double time_step = 0.03 ;                     /* Time step in the simulation */
57 double sigma = 10.0, r = 28.0, b = 8.0/3.0 ;  /* Lorenz attactor parameters */
58 double red_position[NUM_POINTS][3] ;          /* Path of the red point */
59 double grn_position[NUM_POINTS][3] ;          /* Path of the green point */
60 int array_index ;                             /* Position in *_position arrays of most recent point */
61 double distance = 0.0 ;                       /* Distance between the two points */
62
63 /* GLUT variables */
64 double yaw = 0.0, pit = 0.0 ;                 /* Euler angles of the viewing rotation */
65 double scale = 1.0 ;                          /* Scale factor */
66 double xcen = 0.0, ycen = 0.0, zcen = 0.0 ;   /* Coordinates of the point looked at */
67
68 int animate = 1 ;                             /* 0 - stop, 1 = go, 2 = single-step */
69
70
71 /******************************************* Functions ******************************************/
72
73 /* The Lorenz Attractor */
74 void calc_deriv ( double position[3], double deriv[3] )
75 {
76   /* Calculate the Lorenz attractor derivatives */
77   deriv[0] = sigma * ( position[1] - position[0] ) ;
78   deriv[1] = ( r + position[2] ) * position[0] - position[1] ;
79   deriv[2] = -position[0] * position[1] - b * position[2] ;
80 }
81
82 void advance_in_time ( double time_step, double position[3], double new_position[3] )
83 {
84   /* Move a point along the Lorenz attractor */
85   double deriv0[3], deriv1[3], deriv2[3], deriv3[3] ;
86   int i ;
87   memcpy ( new_position, position, 3 * sizeof(double) ) ;  /* Save the present values */
88
89   /* First pass in a Fourth-Order Runge-Kutta integration method */
90   calc_deriv ( position, deriv0 ) ;
91   for ( i = 0; i < 3; i++ )
92     new_position[i] = position[i] + 0.5 * time_step * deriv0[i] ;
93
94   /* Second pass */
95   calc_deriv ( new_position, deriv1 ) ;
96   for ( i = 0; i < 3; i++ )
97     new_position[i] = position[i] + 0.5 * time_step * deriv1[i] ;
98
99   /* Third pass */
100   calc_deriv ( position, deriv2 ) ;
101   for ( i = 0; i < 3; i++ )
102     new_position[i] = position[i] + time_step * deriv2[i] ;
103
104   /* Second pass */
105   calc_deriv ( new_position, deriv3 ) ;
106   for ( i = 0; i < 3; i++ )
107     new_position[i] = position[i] + 0.1666666666666666667 * time_step *
108                       ( deriv0[i] + 2.0 * ( deriv1[i] + deriv2[i] ) + deriv3[i] ) ;
109 }
110
111 /* GLUT callbacks */
112
113 #define INPUT_LINE_LENGTH 80
114
115 void key_cb ( unsigned char key, int x, int y )
116 {
117   int i ;
118   char inputline [ INPUT_LINE_LENGTH ] ;
119
120   switch ( key )
121   {
122   case 'r' :  case 'R' :  /* Reset the simulation */
123     /* Reset the Lorenz parameters */
124     sigma = s0 ;
125     b = b0 ;
126     r = r0 ;
127     /* Set an initial position */
128     red_position[0][0] = (double)rand() / (double)RAND_MAX ;
129     red_position[0][1] = (double)rand() / (double)RAND_MAX ;
130     red_position[0][2] = (double)rand() / (double)RAND_MAX ;
131     grn_position[0][0] = (double)rand() / (double)RAND_MAX ;
132     grn_position[0][1] = (double)rand() / (double)RAND_MAX ;
133     grn_position[0][2] = (double)rand() / (double)RAND_MAX ;
134     array_index = 0 ;
135     /* Initialize the arrays */
136     for ( i = 1; i < NUM_POINTS; i++ )
137     {
138       memcpy ( red_position[i], red_position[0], 3 * sizeof(double) ) ;
139       memcpy ( grn_position[i], grn_position[0], 3 * sizeof(double) ) ;
140     }
141
142     break ;
143
144   case 'm' :  case 'M' :  /* Modify the Lorenz parameters */
145     printf ( "Please enter new value for <sigma> (default %f, currently %f): ", s0, sigma ) ;
146     fgets ( inputline, INPUT_LINE_LENGTH-1, stdin ) ;
147     sscanf ( inputline, "%lf", &sigma ) ;
148
149     printf ( "Please enter new value for <b> (default %f, currently %f): ", b0, b ) ;
150     fgets ( inputline, INPUT_LINE_LENGTH-1, stdin ) ;
151     sscanf ( inputline, "%lf", &b ) ;
152
153     printf ( "Please enter new value for <r> (default %f, currently %f): ", r0, r ) ;
154     fgets ( inputline, INPUT_LINE_LENGTH-1, stdin ) ;
155     sscanf ( inputline, "%lf", &r ) ;
156
157     break ;
158
159   case 's' :  case 'S' :  /* Stop the animation */
160     animate = 0 ;
161     break ;
162
163   case 'g' :  case 'G' :  /* Start the animation */
164     animate = 1 ;
165     break ;
166
167   case ' ' :  /* Spacebar:  Single step */
168     animate = 2 ;
169     break ;
170
171   case 27 :  /* Escape key */
172     glutLeaveMainLoop () ;
173     break ;
174   }
175 }
176
177 void special_cb ( int key, int x, int y )
178 {
179   switch ( key )
180   {
181   case GLUT_KEY_UP :  /* Rotate up a little */
182     glRotated ( ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
183     break ;
184
185   case GLUT_KEY_DOWN :  /* Rotate down a little */
186     glRotated ( -ROTATION_ANGLE, 0.0, 1.0, 0.0 ) ;
187     break ;
188
189   case GLUT_KEY_LEFT :  /* Rotate left a little */
190     glRotated ( ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
191     break ;
192
193   case GLUT_KEY_RIGHT :  /* Rotate right a little */
194     glRotated ( -ROTATION_ANGLE, 0.0, 0.0, 1.0 ) ;
195     break ;
196
197   case GLUT_KEY_PAGE_UP :  /* Zoom in a little */
198     glScaled ( 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR, 1.0 / SCALE_FACTOR ) ;
199     break ;
200
201   case GLUT_KEY_PAGE_DOWN :  /* Zoom out a little */
202     glScaled ( SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR ) ;
203     break ;
204   }
205
206   glutPostRedisplay () ;
207 }
208
209 void mouse_cb ( int button, int updown, int x, int y )
210 {
211   if ( updown == GLUT_DOWN )
212   {
213     double dist = 1.0e20 ;  /* A very large number */
214     dist = 0.0 ;  /* so we don't get "unused variable" compiler warning */
215     /* The idea here is that we go into "pick" mode and pick the nearest point
216        to the mouse click position.  Unfortunately I don't have the time to implement
217        it at the moment. */
218   }
219 }
220
221 void draw_curve ( int index, double position [ NUM_POINTS ][3] )
222 {
223   int i = index ;
224
225   glBegin ( GL_LINE_STRIP ) ;
226   do
227   {
228     i = ( i == NUM_POINTS-1 ) ? 0 : i + 1 ;
229     glVertex3dv ( position[i] ) ;
230   }
231   while ( i != index ) ;
232
233   glEnd () ;
234 }
235
236 void display_cb ( void )
237 {
238   char string [ 80 ] ;
239
240   glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;
241
242   glColor3d ( 1.0, 1.0, 1.0 ) ;  /* White */
243   /* Draw some axes */
244   glBegin ( GL_LINES ) ;
245   glVertex3d ( 0.0, 0.0, 0.0 ) ;
246   glVertex3d ( 2.0, 0.0, 0.0 ) ;
247   glVertex3d ( 0.0, 0.0, 0.0 ) ;
248   glVertex3d ( 0.0, 1.0, 0.0 ) ;
249   glVertex3d ( 0.0, 0.0, 0.0 ) ;
250   glVertex3d ( 0.0, 0.0, 1.0 ) ;
251   glEnd () ;
252
253   glColor3d ( 1.0, 0.0, 0.0 ) ;  /* Red */
254   draw_curve ( array_index, red_position ) ;
255
256   glColor3d ( 0.0, 1.0, 0.0 ) ;  /* Green */
257   draw_curve ( array_index, grn_position ) ;
258
259   /* Print the distance between the two points */
260   glColor3d ( 1.0, 1.0, 1.0 ) ;  /* White */
261   sprintf ( string, "Distance: %10.6f", distance ) ;
262   glRasterPos2i ( 10, 10 ) ;
263   glutBitmapString ( GLUT_BITMAP_HELVETICA_12, (unsigned char*)string ) ;
264
265   glutSwapBuffers();
266 }
267
268 void reshape_cb ( int width, int height )
269 {
270   float ar;
271   glViewport ( 0, 0, width, height ) ;
272   glMatrixMode ( GL_PROJECTION ) ;
273   glLoadIdentity () ;
274   ar = (float) width / (float) height ;
275   glFrustum ( -ar, ar, -1.0, 1.0, 10.0, 100.0 ) ;
276   glMatrixMode ( GL_MODELVIEW ) ;
277   glLoadIdentity () ;
278   xcen = 0.0 ;
279   ycen = 0.0 ;
280   zcen = 0.0 ;
281   glTranslated ( xcen, ycen, zcen - 50.0 ) ;
282 }
283
284
285 void timer_cb ( int value )
286 {
287   /* Function called at regular intervals to update the positions of the points */
288   double deltax, deltay, deltaz ;
289   int new_index = array_index + 1 ;
290
291   /* Set the next timed callback */
292   glutTimerFunc ( 30, timer_cb, 0 ) ;
293
294   if ( animate > 0 )
295   {
296     if ( new_index == NUM_POINTS ) new_index = 0 ;
297     advance_in_time ( time_step, red_position[array_index], red_position[new_index] ) ;
298     advance_in_time ( time_step, grn_position[array_index], grn_position[new_index] ) ;
299     array_index = new_index ;
300
301     deltax = red_position[array_index][0] - grn_position[array_index][0] ;
302     deltay = red_position[array_index][1] - grn_position[array_index][1] ;
303     deltaz = red_position[array_index][2] - grn_position[array_index][2] ;
304     distance = sqrt ( deltax * deltax + deltay * deltay + deltaz * deltaz ) ;
305
306     if ( animate == 2 ) animate = 0 ;
307   }
308
309   glutPostRedisplay () ;
310 }
311
312
313
314 /* The Main Program */
315
316 int main ( int argc, char *argv[] )
317 {
318   int pargc = argc ;
319
320   /* Initialize the random number generator */
321   srand ( 1023 ) ;
322
323   /* Set up the OpenGL parameters */
324   glEnable ( GL_DEPTH_TEST ) ;
325   glClearColor ( 0.0, 0.0, 0.0, 0.0 ) ;
326   glClearDepth ( 1.0 ) ;
327
328   /* Initialize GLUT */
329   glutInitWindowSize ( 600, 600 ) ;
330   glutInit ( &pargc, argv ) ;
331   glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ) ;
332
333   /* Create the window */
334   glutCreateWindow ( "Lorenz Attractor" ) ;
335   glutKeyboardFunc ( key_cb ) ;
336   glutMouseFunc ( mouse_cb ) ;
337   glutSpecialFunc ( special_cb ) ;
338   glutDisplayFunc ( display_cb ) ;
339   glutReshapeFunc ( reshape_cb ) ;
340   glutTimerFunc ( 30, timer_cb, 0 ) ;
341
342   /* Initialize the attractor:  The easiest way is to call the keyboard callback with an
343    * argument of 'r' for Reset.
344    */
345   key_cb ( 'r', 0, 0 ) ;
346
347   /* Enter the GLUT main loop */
348   glutMainLoop () ;
349
350 #ifdef WIN32
351   /* DUMP MEMORY LEAK INFORMATION */
352   _CrtDumpMemoryLeaks () ;
353 #endif
354
355   return 0 ;
356 }
357