From http://www.jwz.org/xscreensaver/xscreensaver-5.35.tar.gz
[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 "True"
106 #define DEF_WHALESPEED  "250"
107
108 #ifdef STANDALONE
109 # define DEFAULTS       "*delay:       25000 \n" \
110                          "*count:          4 \n" \
111                          "*showFPS:    False \n" \
112                          "*cycles:       100 \n" \
113                          "*size:        6000 \n" \
114                          "*wireframe:  False \n"
115 # define atlantis_handle_event 0
116 # include "xlockmore.h"         /* from the xscreensaver distribution */
117 #else  /* !STANDALONE */
118 # include "xlock.h"             /* from the xlockmore distribution */
119 # include "vis.h"
120 #endif /* !STANDALONE */
121
122 #ifdef USE_GL
123
124 #include "atlantis.h"
125
126
127 static int  whalespeed;
128 static int do_texture;
129 static int do_gradient;
130 static XrmOptionDescRec opts[] =
131 {
132      {"-whalespeed", ".atlantis.whalespeed", XrmoptionSepArg, 0},
133      {"-texture",    ".atlantis.texture",    XrmoptionNoArg, "true"},
134      {"+texture",    ".atlantis.texture",    XrmoptionNoArg, "false"},
135      {"-gradient",   ".atlantis.gradient",   XrmoptionNoArg, "true"},
136      {"+gradient",   ".atlantis.gradient",   XrmoptionNoArg, "false"},
137 };
138
139 static argtype vars[] =
140 {
141  {&whalespeed, "whalespeed", "WhaleSpeed", DEF_WHALESPEED, t_Int},
142  {&do_texture,  "texture",    "Texture",    DEF_TEXTURE,   t_Bool},
143  {&do_gradient, "gradient",   "Gradient",   DEF_GRADIENT,  t_Bool},
144 };
145
146 static OptionStruct desc[] =
147 {
148         {"-whalespeed num", "speed of whales and the dolphin"},
149         {"-texture",        "whether to introduce water-like distortion"},
150         {"-gradient",       "whether to introduce gradient-filled background"},
151 };
152
153 ENTRYPOINT ModeSpecOpt atlantis_opts =
154 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
155
156 #ifdef USE_MODULES
157 ModStruct   atlantis_description =
158 {"atlantis", "init_atlantis", "draw_atlantis", "release_atlantis",
159  "refresh_atlantis", "change_atlantis", NULL, &atlantis_opts,
160  1000, NUM_SHARKS, SHARKSPEED, SHARKSIZE, 64, 1.0, "",
161  "Shows moving sharks/whales/dolphin", 0, NULL};
162
163 #endif
164
165 static atlantisstruct *atlantis = NULL;
166
167 #include "xpm-ximage.h"
168
169 #include "../images/sea-texture.xpm"
170
171
172 static void
173 parse_image_data(ModeInfo *mi)
174 {
175   atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
176   ap->texture = xpm_to_ximage (mi->dpy,
177                                mi->xgwa.visual,
178                                mi->xgwa.colormap,
179                                sea_texture);
180 }
181
182 static void
183 InitFishs(atlantisstruct * ap)
184 {
185         int         i;
186
187         for (i = 0; i < ap->num_sharks; i++) {
188                 ap->sharks[i].x = 70000.0 + NRAND(ap->sharksize);
189                 ap->sharks[i].y = NRAND(ap->sharksize);
190                 ap->sharks[i].z = NRAND(ap->sharksize);
191                 ap->sharks[i].psi = NRAND(360) - 180.0;
192                 ap->sharks[i].v = 1.0;
193         }
194
195         /* Random whale direction */
196         ap->whaledir = LRAND() & 1;
197
198         ap->dolph.x = 30000.0;
199         ap->dolph.y = 0.0;
200         ap->dolph.z = (float) (ap->sharksize);
201         ap->dolph.psi = (ap->whaledir) ? 90.0 : -90.0;
202         ap->dolph.theta = 0.0;
203         ap->dolph.v = 6.0;
204
205         ap->momWhale.x = 70000.0;
206         ap->momWhale.y = 0.0;
207         ap->momWhale.z = 0.0;
208         ap->momWhale.psi = (ap->whaledir) ? 90.0 : -90.0;
209         ap->momWhale.theta = 0.0;
210         ap->momWhale.v = 3.0;
211
212         ap->babyWhale.x = 60000.0;
213         ap->babyWhale.y = -2000.0;
214         ap->babyWhale.z = -2000.0;
215         ap->babyWhale.psi = (ap->whaledir) ? 90.0 : -90.0;
216         ap->babyWhale.theta = 0.0;
217         ap->babyWhale.v = 3.0;
218 }
219
220 static void
221 Init(ModeInfo *mi)
222 {
223         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
224
225         static const float ambient[]        = {0.1, 0.1, 0.1, 1.0};
226         static const float diffuse[]        = {1.0, 1.0, 1.0, 1.0};
227         static const float position[]       = {0.0, 1.0, 0.0, 0.0};
228         static const float mat_shininess[]  = {90.0};
229         static const float mat_specular[]   = {0.8, 0.8, 0.8, 1.0};
230         static const float mat_diffuse[]    = {0.46, 0.66, 0.795, 1.0};
231         static const float mat_ambient[]    = {0.0, 0.1, 0.2, 1.0};
232         static const float lmodel_ambient[] = {0.4, 0.4, 0.4, 1.0};
233         static const float lmodel_localviewer[] = {0.0};
234
235         float        fblue = 0.0, fgreen;
236
237         glFrontFace(GL_CCW);
238
239         if (ap->wire)
240           {
241             glDisable(GL_DEPTH_TEST);
242             glDisable(GL_CULL_FACE);
243             glDisable(GL_LIGHTING);
244             glDisable(GL_NORMALIZE);
245           }
246         else
247           {
248             glDepthFunc(GL_LEQUAL);
249             glEnable(GL_DEPTH_TEST);
250             glEnable(GL_CULL_FACE);
251             glEnable(GL_NORMALIZE);
252             glShadeModel(GL_SMOOTH);
253
254             glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
255             glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
256             glLightfv(GL_LIGHT0, GL_POSITION, position);
257             glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
258             glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, lmodel_localviewer);
259             glEnable(GL_LIGHTING);
260             glEnable(GL_LIGHT0);
261
262             glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
263             glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
264             glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diffuse);
265             glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
266           }
267
268         if (ap->wire || !do_texture)
269           {
270             glDisable(GL_TEXTURE_2D);
271           }
272         else
273           {
274             GLfloat scale = 0.0005;
275
276             if (!ap->texture)
277               parse_image_data (mi);
278
279             clear_gl_error();
280             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
281                          ap->texture->width, ap->texture->height, 0,
282                          GL_RGBA, GL_UNSIGNED_BYTE,
283                          ap->texture->data);
284             check_gl_error("texture");
285
286             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
287             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
288             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
289             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
290
291             glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
292
293 # ifndef HAVE_JWZGLES
294             {
295               GLfloat s_plane[] = { 1, 0, 0, 0 };
296               GLfloat t_plane[] = { 0, 0, 1, 0 };
297               glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
298               glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
299               glTexGenfv(GL_S, GL_EYE_PLANE, s_plane);
300               glTexGenfv(GL_T, GL_EYE_PLANE, t_plane);
301               glEnable(GL_TEXTURE_GEN_S);
302               glEnable(GL_TEXTURE_GEN_T);
303             }
304 # endif
305             glEnable(GL_TEXTURE_2D);
306
307             glMatrixMode(GL_TEXTURE);
308             glLoadIdentity();
309             glScalef(scale, scale, 1);
310             glMatrixMode(GL_MODELVIEW);
311           }
312
313         InitFishs(ap);
314
315         /* Add a little randomness */
316         fblue = ((float) (NRAND(30)) / 100.0) + 0.70;
317         fgreen = fblue * 0.56;
318         glClearColor(0.0, fgreen, fblue, 1.0);
319 }
320
321 ENTRYPOINT void
322 reshape_atlantis(ModeInfo * mi, int width, int height)
323 {
324         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
325
326         glViewport(0, 0, ap->WinW = (GLint) width, ap->WinH = (GLint) height);
327
328         glMatrixMode(GL_PROJECTION);
329         glLoadIdentity();
330         gluPerspective(400.0, (GLdouble) width / (GLdouble) height, 1.0, 2000000.0);
331         glMatrixMode(GL_MODELVIEW);
332 }
333
334
335 /* Fill the background with a gradient -- thanks to 
336    Phil Carrig <pod@internode.on.net> for figuring out
337    how to do this more efficiently!
338  */
339 static void
340 clear_tank (atlantisstruct * ap)
341 {
342   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
343
344   if (do_gradient && !ap->wire)
345     {
346       GLfloat top[4] = { 0.00, 0.40, 0.70, };
347       GLfloat bot[4] = { 0.00, 0.05, 0.18, };
348
349       glMatrixMode(GL_PROJECTION);
350       glPushMatrix();
351       {
352         glLoadIdentity();
353         glMatrixMode(GL_MODELVIEW);
354         glPushMatrix();
355         {
356           glLoadIdentity();
357           /* glRotatef(current_device_rotation(), 0, 0, 1); */
358
359 # ifndef HAVE_JWZGLES
360           glShadeModel (GL_SMOOTH);
361 # endif
362           glDisable (GL_LIGHTING);
363           glBegin (GL_QUADS);
364           glColor3fv (bot);
365           glVertex3f (-1, -1, 1); glVertex3f ( 1, -1, 1);
366           glColor3fv (top);
367           glVertex3f ( 1,  1, 1); glVertex3f (-1,  1, 1);
368           glEnd();
369           glEnable (GL_LIGHTING);
370         }
371         glPopMatrix();
372       }
373       glMatrixMode(GL_PROJECTION);
374       glPopMatrix();
375
376       glMatrixMode(GL_MODELVIEW);
377     }
378 }
379
380
381 static void
382 Animate(atlantisstruct * ap)
383 {
384         int         i;
385
386         for (i = 0; i < ap->num_sharks; i++) {
387                 SharkPilot(&(ap->sharks[i]), ap->sharkspeed);
388                 SharkMiss(ap, i);
389         }
390         WhalePilot(&(ap->dolph), ap->whalespeed, ap->whaledir);
391         ap->dolph.phi++;
392         WhalePilot(&(ap->momWhale), ap->whalespeed, ap->whaledir);
393         ap->momWhale.phi++;
394         WhalePilot(&(ap->babyWhale), ap->whalespeed, ap->whaledir);
395         ap->babyWhale.phi++;
396 }
397
398 static void
399 AllDisplay(atlantisstruct * ap)
400 {
401         int         i;
402
403         clear_tank(ap);
404
405         for (i = 0; i < ap->num_sharks; i++) {
406                 glPushMatrix();
407                 FishTransform(&(ap->sharks[i]));
408                 DrawShark(&(ap->sharks[i]), ap->wire);
409                 glPopMatrix();
410         }
411
412         glPushMatrix();
413         FishTransform(&(ap->dolph));
414         DrawDolphin(&(ap->dolph), ap->wire);
415         glPopMatrix();
416
417         glPushMatrix();
418         FishTransform(&(ap->momWhale));
419         DrawWhale(&(ap->momWhale), ap->wire);
420         glPopMatrix();
421
422         glPushMatrix();
423         FishTransform(&(ap->babyWhale));
424         glScalef(0.45, 0.45, 0.3);
425         DrawWhale(&(ap->babyWhale), ap->wire);
426         glPopMatrix();
427 }
428
429 /*
430  *-----------------------------------------------------------------------------
431  *-----------------------------------------------------------------------------
432  *    Xlock hooks.
433  *-----------------------------------------------------------------------------
434  *-----------------------------------------------------------------------------
435  */
436
437 /*
438  *-----------------------------------------------------------------------------
439  *    Initialize atlantis.  Called each time the window changes.
440  *-----------------------------------------------------------------------------
441  */
442
443 ENTRYPOINT void
444 init_atlantis(ModeInfo * mi)
445 {
446         int         screen = MI_SCREEN(mi);
447         atlantisstruct *ap;
448         Display    *display = MI_DISPLAY(mi);
449         Window      window = MI_WINDOW(mi);
450
451         if (atlantis == NULL) {
452                 if ((atlantis = (atlantisstruct *) calloc(MI_NUM_SCREENS(mi),
453                                            sizeof (atlantisstruct))) == NULL)
454                         return;
455         }
456         ap = &atlantis[screen];
457         ap->num_sharks = MI_COUNT(mi);
458         if (ap->sharks == NULL) {
459                 if ((ap->sharks = (fishRec *) calloc(ap->num_sharks,
460                                                 sizeof (fishRec))) == NULL) {
461                         /* free everything up to now */
462                         (void) free((void *) atlantis);
463                         atlantis = NULL;
464                         return;
465                 }
466         }
467         ap->sharkspeed = MI_CYCLES(mi);         /* has influence on the "width"
468                                                    of the movement */
469         ap->sharksize = MI_SIZE(mi);    /* has influence on the "distance"
470                                            of the sharks */
471         ap->whalespeed = whalespeed;
472         ap->wire = MI_IS_WIREFRAME(mi);
473
474         if (MI_IS_DEBUG(mi)) {
475                 (void) fprintf(stderr,
476                                "%s:\n\tnum_sharks=%d\n\tsharkspeed=%.1f\n\tsharksize=%d\n\twhalespeed=%.1f\n\twireframe=%s\n",
477                                MI_NAME(mi),
478                                ap->num_sharks,
479                                ap->sharkspeed,
480                                ap->sharksize,
481                                ap->whalespeed,
482                                ap->wire ? "yes" : "no"
483                         );
484         }
485         if ((ap->glx_context = init_GL(mi)) != NULL) {
486
487                 reshape_atlantis(mi, MI_WIDTH(mi), MI_HEIGHT(mi));
488                 glDrawBuffer(GL_BACK);
489                 Init(mi);
490                 AllDisplay(ap);
491                 glXSwapBuffers(display, window);
492
493         } else {
494                 MI_CLEARWINDOW(mi);
495         }
496 }
497
498 /*
499  *-----------------------------------------------------------------------------
500  *    Called by the mainline code periodically to update the display.
501  *-----------------------------------------------------------------------------
502  */
503 ENTRYPOINT void
504 draw_atlantis(ModeInfo * mi)
505 {
506         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
507
508         Display    *display = MI_DISPLAY(mi);
509         Window      window = MI_WINDOW(mi);
510
511         MI_IS_DRAWN(mi) = True;
512
513         if (!ap->glx_context)
514                 return;
515
516         glXMakeCurrent(display, window, *(ap->glx_context));
517
518         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
519
520         glPushMatrix();
521         glRotatef(current_device_rotation(), 0, 0, 1);
522         AllDisplay(ap);
523         Animate(ap);
524         glPopMatrix();
525
526         if (mi->fps_p) do_fps (mi);
527         glXSwapBuffers(display, window);
528 }
529
530
531 /*
532  *-----------------------------------------------------------------------------
533  *    The display is being taken away from us.  Free up malloc'ed 
534  *      memory and X resources that we've alloc'ed.  Only called
535  *      once, we must zap everything for every screen.
536  *-----------------------------------------------------------------------------
537  */
538
539 ENTRYPOINT void
540 release_atlantis(ModeInfo * mi)
541 {
542 #if 0
543         int         screen;
544
545         if (atlantis != NULL) {
546                 for (screen = 0; screen < MI_NUM_SCREENS(mi); screen++) {
547                         atlantisstruct *ap = &atlantis[screen];
548
549                         if (ap->sharks)
550                                 (void) free((void *) ap->sharks);
551                 }
552                 (void) free((void *) atlantis);
553                 atlantis = NULL;
554         }
555         FreeAllGL(mi);
556 #endif
557 }
558
559 ENTRYPOINT void
560 refresh_atlantis(ModeInfo * mi)
561 {
562 }
563
564 #ifndef STANDALONE
565 ENTRYPOINT void
566 change_atlantis(ModeInfo * mi)
567 {
568         atlantisstruct *ap = &atlantis[MI_SCREEN(mi)];
569
570         if (!ap->glx_context)
571                 return;
572
573         glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(ap->glx_context));
574         Init(mi);
575 }
576 #endif /* !STANDALONE */
577
578 XSCREENSAVER_MODULE ("Atlantis", atlantis)
579
580 #endif /* USE_GL */