ftp://ftp.linux.ncsu.edu/mirror/ftp.redhat.com/pub/redhat/linux/enterprise/4/en/os...
[xscreensaver] / hacks / glx / atlantis.c
1 /* atlantis --- Shows moving 3D sea animals */
2
3 #if 0
4 static const char sccsid[] = "@(#)atlantis.c    5.08 2003/04/09 xlockmore";
5 #endif
6
7 /* Copyright (c) E. Lassauge, 1998. */
8
9 /*
10  * Permission to use, copy, modify, and distribute this software and its
11  * documentation for any purpose and without fee is hereby granted,
12  * provided that the above copyright notice appear in all copies and that
13  * both that copyright notice and this permission notice appear in
14  * supporting documentation.
15  *
16  * This file is provided AS IS with no warranties of any kind.  The author
17  * shall have no liability with respect to the infringement of copyrights,
18  * trade secrets or any patents by this file or any part thereof.  In no
19  * event will the author be liable for any lost revenue or profits or
20  * other special, indirect and consequential damages.
21  *
22  * The original code for this mode was written by Mark J. Kilgard
23  * as a demo for openGL programming.
24  * 
25  * Porting it to xlock  was possible by comparing the original Mesa's morph3d 
26  * demo with it's ported version to xlock, so thanks for Marcelo F. Vianna 
27  * (look at morph3d.c) for his indirect help.
28  *
29  * Thanks goes also to Brian Paul for making it possible and inexpensive
30  * to use OpenGL at home.
31  *
32  * My e-mail address is lassauge@users.sourceforge.net
33  *
34  * Eric Lassauge  (May-13-1998)
35  *
36  * REVISION HISTORY:
37  * 
38  * Jamie Zawinski, 2-Apr-01:  - The fishies were inside out!  The back faces
39  *                              were being drawn, not the front faces.
40  *                            - Added a texture to simulate light from the
41  *                              surface, like in the SGI version.
42  *
43  * David A. Bagley - 98/06/17 : Add whalespeed option. Global options to
44  *                              initialize local variables are now:
45  *                              XLock.atlantis.cycles: 100      ! SharkSpeed
46  *                              XLock.atlantis.batchcount: 4    ! SharkNum
47  *                              XLock.atlantis.whalespeed: 250  ! WhaleSpeed
48  *                              XLock.atlantis.size: 6000       ! SharkSize
49  *                              Add random direction for whales/dolphins
50  * 
51  * E.Lassauge - 98/06/16: Use the following global options to initialize
52  *                        local variables :
53  *                              XLock.atlantis.delay: 100       ! SharkSpeed
54  *                              XLock.atlantis.batchcount: 4    ! SharkNum
55  *                              XLock.atlantis.cycles: 250      ! WhaleSpeed
56  *                              XLock.atlantis.size: 6000       ! SharkSize
57  *                        Add support for -/+ wireframe (t'was so easy to do!)
58  *
59  * TODO : 
60  *        - better handling of sizes and speeds
61  *        - test standalone and module modes
62  *        - purify it (!)
63  */
64
65 /* Copyright (c) Mark J. Kilgard, 1994. */
66
67 /**
68  * (c) Copyright 1993, 1994, Silicon Graphics, Inc.
69  * ALL RIGHTS RESERVED
70  * Permission to use, copy, modify, and distribute this software for
71  * any purpose and without fee is hereby granted, provided that the above
72  * copyright notice appear in all copies and that both the copyright notice
73  * and this permission notice appear in supporting documentation, and that
74  * the name of Silicon Graphics, Inc. not be used in advertising
75  * or publicity pertaining to distribution of the software without specific,
76  * written prior permission.
77  *
78  * THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
79  * AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
80  * INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
81  * FITNESS FOR A PARTICULAR PURPOSE.  IN NO EVENT SHALL SILICON
82  * GRAPHICS, INC.  BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
83  * SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
84  * KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
85  * LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
86  * THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC.  HAS BEEN
87  * ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
88  * ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
89  * POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
90  *
91  * US Government Users Restricted Rights
92  * Use, duplication, or disclosure by the Government is subject to
93  * restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
94  * (c)(1)(ii) of the Rights in Technical Data and Computer Software
95  * clause at DFARS 252.227-7013 and/or in similar or successor
96  * clauses in the FAR or the DOD or NASA FAR Supplement.
97  * Unpublished-- rights reserved under the copyright laws of the
98  * United States.  Contractor/manufacturer is Silicon Graphics,
99  * Inc., 2011 N.  Shoreline Blvd., Mountain View, CA 94039-7311.
100  *
101  * OpenGL(TM) is a trademark of Silicon Graphics, Inc.
102  */
103
104 #define DEF_TEXTURE "True"
105 #define DEF_GRADIENT "False"
106 #define DEF_WHALESPEED  "250"
107
108 #ifdef STANDALONE
109 # define PROGCLASS      "Atlantis"
110 # define HACK_INIT      init_atlantis
111 # define HACK_DRAW      draw_atlantis
112 # define HACK_RESHAPE   reshape_atlantis
113 # define atlantis_opts  xlockmore_opts
114 # define DEFAULTS       "*delay:       25000 \n" \
115                          "*count:          4 \n" \
116                          "*showFPS:    False \n" \
117                          "*cycles:       100 \n" \
118                          "*size:        6000 \n" \
119                          "*wireframe:  False \n" \
120                          "*texture:    " DEF_TEXTURE    " \n" \
121                          "*gradient:   " DEF_GRADIENT   " \n" \
122                          "*whalespeed: " DEF_WHALESPEED " \n"
123 # include "xlockmore.h"         /* from the xscreensaver distribution */
124 #else  /* !STANDALONE */
125 # include "xlock.h"             /* from the xlockmore distribution */
126 #include "vis.h"
127 #endif /* !STANDALONE */
128
129 #ifdef USE_GL
130
131 #include "atlantis.h"
132 #include <GL/glu.h>
133
134
135 static int  whalespeed;
136 static int do_texture;
137 static int do_gradient;
138 static XrmOptionDescRec opts[] =
139 {
140      {"-whalespeed", ".atlantis.whalespeed", XrmoptionSepArg, 0},
141      {"-texture",    ".atlantis.texture",    XrmoptionNoArg, "true"},
142      {"+texture",    ".atlantis.texture",    XrmoptionNoArg, "false"},
143      {"-gradient",   ".atlantis.gradient",   XrmoptionNoArg, "true"},
144      {"+gradient",   ".atlantis.gradient",   XrmoptionNoArg, "false"},
145 };
146
147 static argtype vars[] =
148 {
149  {&whalespeed, "whalespeed", "WhaleSpeed", DEF_WHALESPEED, t_Int},
150  {&do_texture,  "texture",    "Texture",    DEF_TEXTURE,   t_Bool},
151  {&do_gradient, "gradient",   "Gradient",   DEF_GRADIENT,  t_Bool},
152 };
153
154 static OptionStruct desc[] =
155 {
156         {"-whalespeed num", "speed of whales and the dolphin"},
157         {"-texture",        "whether to introduce water-like distortion"},
158         {"-gradient",       "whether to introduce gradient-filled background"},
159 };
160
161 ModeSpecOpt atlantis_opts =
162 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
163
164 #ifdef USE_MODULES
165 ModStruct   atlantis_description =
166 {"atlantis", "init_atlantis", "draw_atlantis", "release_atlantis",
167  "refresh_atlantis", "change_atlantis", NULL, &atlantis_opts,
168  1000, NUM_SHARKS, SHARKSPEED, SHARKSIZE, 64, 1.0, "",
169  "Shows moving sharks/whales/dolphin", 0, NULL};
170
171 #endif
172
173 static atlantisstruct *atlantis = NULL;
174
175 #include "xpm-ximage.h"
176
177 #include "../images/sea-texture.xpm"
178
179
180 static void
181 parse_image_data(ModeInfo *mi)
182 {
183   atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
184   ap->texture = xpm_to_ximage (mi->dpy,
185                                mi->xgwa.visual,
186                                mi->xgwa.colormap,
187                                sea_texture);
188 }
189
190 static void
191 InitFishs(atlantisstruct * ap)
192 {
193         int         i;
194
195         for (i = 0; i < ap->num_sharks; i++) {
196                 ap->sharks[i].x = 70000.0 + NRAND(ap->sharksize);
197                 ap->sharks[i].y = NRAND(ap->sharksize);
198                 ap->sharks[i].z = NRAND(ap->sharksize);
199                 ap->sharks[i].psi = NRAND(360) - 180.0;
200                 ap->sharks[i].v = 1.0;
201         }
202
203         /* Random whale direction */
204         ap->whaledir = LRAND() & 1;
205
206         ap->dolph.x = 30000.0;
207         ap->dolph.y = 0.0;
208         ap->dolph.z = (float) (ap->sharksize);
209         ap->dolph.psi = (ap->whaledir) ? 90.0 : -90.0;
210         ap->dolph.theta = 0.0;
211         ap->dolph.v = 6.0;
212
213         ap->momWhale.x = 70000.0;
214         ap->momWhale.y = 0.0;
215         ap->momWhale.z = 0.0;
216         ap->momWhale.psi = (ap->whaledir) ? 90.0 : -90.0;
217         ap->momWhale.theta = 0.0;
218         ap->momWhale.v = 3.0;
219
220         ap->babyWhale.x = 60000.0;
221         ap->babyWhale.y = -2000.0;
222         ap->babyWhale.z = -2000.0;
223         ap->babyWhale.psi = (ap->whaledir) ? 90.0 : -90.0;
224         ap->babyWhale.theta = 0.0;
225         ap->babyWhale.v = 3.0;
226 }
227
228 static void
229 Init(ModeInfo *mi)
230 {
231         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
232
233         static float ambient[] =
234         {0.1, 0.1, 0.1, 1.0};
235         static float diffuse[] =
236         {1.0, 1.0, 1.0, 1.0};
237         static float position[] =
238         {0.0, 1.0, 0.0, 0.0};
239         static float mat_shininess[] =
240         {90.0};
241         static float mat_specular[] =
242         {0.8, 0.8, 0.8, 1.0};
243         static float mat_diffuse[] =
244         {0.46, 0.66, 0.795, 1.0};
245         static float mat_ambient[] =
246         {0.0, 0.1, 0.2, 1.0};
247         static float lmodel_ambient[] =
248         {0.4, 0.4, 0.4, 1.0};
249         static float lmodel_localviewer[] =
250         {0.0};
251         float        fblue = 0.0, fgreen;
252
253         glFrontFace(GL_CCW);
254
255         if (ap->wire)
256           {
257             glDisable(GL_DEPTH_TEST);
258             glDisable(GL_CULL_FACE);
259             glDisable(GL_LIGHTING);
260             glDisable(GL_NORMALIZE);
261           }
262         else
263           {
264             glDepthFunc(GL_LEQUAL);
265             glEnable(GL_DEPTH_TEST);
266             glEnable(GL_CULL_FACE);
267             glEnable(GL_NORMALIZE);
268             glShadeModel(GL_SMOOTH);
269
270             glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
271             glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
272             glLightfv(GL_LIGHT0, GL_POSITION, position);
273             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
274             glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, lmodel_localviewer);
275             glEnable(GL_LIGHTING);
276             glEnable(GL_LIGHT0);
277
278             glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
279             glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
280             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
281             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
282           }
283
284         if (ap->wire || !do_texture)
285           {
286             glDisable(GL_TEXTURE_2D);
287           }
288         else
289           {
290             GLfloat s_plane[] = { 1, 0, 0, 0 };
291             GLfloat t_plane[] = { 0, 0, 1, 0 };
292             GLfloat scale = 0.0005;
293
294             if (!ap->texture)
295               parse_image_data (mi);
296
297             clear_gl_error();
298             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
299                          ap->texture->width, ap->texture->height, 0,
300                          GL_RGBA, GL_UNSIGNED_BYTE,
301                          ap->texture->data);
302             check_gl_error("texture");
303
304             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
305             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
306             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
307             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
308
309             glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
310
311             glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
312             glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
313             glTexGenfv(GL_S, GL_EYE_PLANE, s_plane);
314             glTexGenfv(GL_T, GL_EYE_PLANE, t_plane);
315
316             glEnable(GL_TEXTURE_GEN_S);
317             glEnable(GL_TEXTURE_GEN_T);
318             glEnable(GL_TEXTURE_2D);
319
320             glMatrixMode(GL_TEXTURE);
321             glLoadIdentity();
322             glScalef(scale, scale, 1);
323             glMatrixMode(GL_MODELVIEW);
324           }
325
326         InitFishs(ap);
327
328         /* Add a little randomness */
329         fblue = ((float) (NRAND(30)) / 100.0) + 0.70;
330         fgreen = fblue * 0.56;
331         glClearColor(0.0, fgreen, fblue, 0.0);
332 }
333
334 void
335 reshape_atlantis(ModeInfo * mi, int width, int height)
336 {
337         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
338
339         glViewport(0, 0, ap->WinW = (GLint) width, ap->WinH = (GLint) height);
340
341         glMatrixMode(GL_PROJECTION);
342         glLoadIdentity();
343         gluPerspective(400.0, (GLdouble) width / (GLdouble) height, 1.0, 2000000.0);
344         glMatrixMode(GL_MODELVIEW);
345 }
346
347
348 /* Fill the background with a gradient -- thanks to 
349    Phil Carrig <pod@internode.on.net> for figuring out
350    how to do this more efficiently!
351  */
352 static void
353 clear_tank (atlantisstruct * ap)
354 {
355   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
356
357   if (do_gradient && !ap->wire)
358     {
359       GLfloat top[3] = { 0.00, 0.40, 0.70 };
360       GLfloat bot[3] = { 0.00, 0.05, 0.18 };
361
362       glMatrixMode(GL_PROJECTION);
363       glPushMatrix();
364       {
365         glLoadIdentity();
366         glMatrixMode(GL_MODELVIEW);
367         glPushMatrix();
368         {
369           glLoadIdentity();
370
371           /* save GL_COLOR_MATERIAL, GL_COLOR_MATERIAL_FACE, etc.
372              This stalls the pipeline, so it would be better to do this
373              with explicit enable/disable calls, but I can't figure
374              out how to undo the glEnable() and glColor() calls below!
375              Simply calling glDisable(GL_COLOR_MATERIAL) is insufficient!
376            */
377           glPushAttrib (GL_LIGHTING_BIT);
378           {
379             glEnable (GL_COLOR_MATERIAL);
380
381             glShadeModel(GL_SMOOTH);
382             glBegin(GL_QUADS);
383             glColor3f (bot[0], bot[1], bot[2]); glVertex3f (-1, -1, 1);
384             glColor3f (bot[0], bot[1], bot[2]); glVertex3f ( 1, -1, 1);
385             glColor3f (top[0], top[1], top[2]); glVertex3f ( 1,  1, 1);
386             glColor3f (top[0], top[1], top[2]); glVertex3f (-1,  1, 1);
387             glEnd();
388           }
389           glPopAttrib();
390         }
391         glPopMatrix();
392       }
393       glMatrixMode(GL_PROJECTION);
394       glPopMatrix();
395
396       glMatrixMode(GL_MODELVIEW);
397     }
398 }
399
400
401 static void
402 Animate(atlantisstruct * ap)
403 {
404         int         i;
405
406         for (i = 0; i < ap->num_sharks; i++) {
407                 SharkPilot(&(ap->sharks[i]), ap->sharkspeed);
408                 SharkMiss(ap, i);
409         }
410         WhalePilot(&(ap->dolph), ap->whalespeed, ap->whaledir);
411         ap->dolph.phi++;
412         WhalePilot(&(ap->momWhale), ap->whalespeed, ap->whaledir);
413         ap->momWhale.phi++;
414         WhalePilot(&(ap->babyWhale), ap->whalespeed, ap->whaledir);
415         ap->babyWhale.phi++;
416 }
417
418 static void
419 AllDisplay(atlantisstruct * ap)
420 {
421         int         i;
422
423         clear_tank(ap);
424
425         for (i = 0; i < ap->num_sharks; i++) {
426                 glPushMatrix();
427                 FishTransform(&(ap->sharks[i]));
428                 DrawShark(&(ap->sharks[i]), ap->wire);
429                 glPopMatrix();
430         }
431
432         glPushMatrix();
433         FishTransform(&(ap->dolph));
434         DrawDolphin(&(ap->dolph), ap->wire);
435         glPopMatrix();
436
437         glPushMatrix();
438         FishTransform(&(ap->momWhale));
439         DrawWhale(&(ap->momWhale), ap->wire);
440         glPopMatrix();
441
442         glPushMatrix();
443         FishTransform(&(ap->babyWhale));
444         glScalef(0.45, 0.45, 0.3);
445         DrawWhale(&(ap->babyWhale), ap->wire);
446         glPopMatrix();
447 }
448
449 /*
450  *-----------------------------------------------------------------------------
451  *-----------------------------------------------------------------------------
452  *    Xlock hooks.
453  *-----------------------------------------------------------------------------
454  *-----------------------------------------------------------------------------
455  */
456
457 /*
458  *-----------------------------------------------------------------------------
459  *    Initialize atlantis.  Called each time the window changes.
460  *-----------------------------------------------------------------------------
461  */
462
463 void
464 init_atlantis(ModeInfo * mi)
465 {
466         int         screen = MI_SCREEN(mi);
467         atlantisstruct *ap;
468         Display    *display = MI_DISPLAY(mi);
469         Window      window = MI_WINDOW(mi);
470
471         if (atlantis == NULL) {
472                 if ((atlantis = (atlantisstruct *) calloc(MI_NUM_SCREENS(mi),
473                                            sizeof (atlantisstruct))) == NULL)
474                         return;
475         }
476         ap = &atlantis[screen];
477         ap->num_sharks = MI_COUNT(mi);
478         if (ap->sharks == NULL) {
479                 if ((ap->sharks = (fishRec *) calloc(ap->num_sharks,
480                                                 sizeof (fishRec))) == NULL) {
481                         /* free everything up to now */
482                         (void) free((void *) atlantis);
483                         atlantis = NULL;
484                         return;
485                 }
486         }
487         ap->sharkspeed = MI_CYCLES(mi);         /* has influence on the "width"
488                                                    of the movement */
489         ap->sharksize = MI_SIZE(mi);    /* has influence on the "distance"
490                                            of the sharks */
491         ap->whalespeed = whalespeed;
492         ap->wire = MI_IS_WIREFRAME(mi);
493
494         if (MI_IS_DEBUG(mi)) {
495                 (void) fprintf(stderr,
496                                "%s:\n\tnum_sharks=%d\n\tsharkspeed=%.1f\n\tsharksize=%d\n\twhalespeed=%.1f\n\twireframe=%s\n",
497                                MI_NAME(mi),
498                                ap->num_sharks,
499                                ap->sharkspeed,
500                                ap->sharksize,
501                                ap->whalespeed,
502                                ap->wire ? "yes" : "no"
503                         );
504         }
505         if ((ap->glx_context = init_GL(mi)) != NULL) {
506
507                 reshape_atlantis(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
508                 glDrawBuffer(GL_BACK);
509                 Init(mi);
510                 AllDisplay(ap);
511                 glXSwapBuffers(display, window);
512
513         } else {
514                 MI_CLEARWINDOW(mi);
515         }
516 }
517
518 /*
519  *-----------------------------------------------------------------------------
520  *    Called by the mainline code periodically to update the display.
521  *-----------------------------------------------------------------------------
522  */
523 void
524 draw_atlantis(ModeInfo * mi)
525 {
526         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
527
528         Display    *display = MI_DISPLAY(mi);
529         Window      window = MI_WINDOW(mi);
530
531         MI_IS_DRAWN(mi) = True;
532
533         if (!ap->glx_context)
534                 return;
535
536         glXMakeCurrent(display, window, *(ap->glx_context));
537
538         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
539
540         AllDisplay(ap);
541         Animate(ap);
542
543         if (mi->fps_p) do_fps (mi);
544         glXSwapBuffers(display, window);
545 }
546
547
548 /*
549  *-----------------------------------------------------------------------------
550  *    The display is being taken away from us.  Free up malloc'ed 
551  *      memory and X resources that we've alloc'ed.  Only called
552  *      once, we must zap everything for every screen.
553  *-----------------------------------------------------------------------------
554  */
555
556 void
557 release_atlantis(ModeInfo * mi)
558 {
559         int         screen;
560
561         if (atlantis != NULL) {
562                 for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++) {
563                         atlantisstruct *ap = &atlantis[screen];
564
565                         if (ap->sharks)
566                                 (void) free((void *) ap->sharks);
567                 }
568                 (void) free((void *) atlantis);
569                 atlantis = NULL;
570         }
571         FreeAllGL(mi);
572 }
573
574 void
575 refresh_atlantis(ModeInfo * mi)
576 {
577 }
578
579 void
580 change_atlantis(ModeInfo * mi)
581 {
582         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
583
584         if (!ap->glx_context)
585                 return;
586
587         glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(ap->glx_context));
588         Init(mi);
589 }
590
591 #endif /* USE_GL */