http://ftp.ksu.edu.tw/FTP/FreeBSD/distfiles/xscreensaver-4.20.tar.gz
[xscreensaver] / hacks / glx / cubenetic.c
1 /* cubenetic, Copyright (c) 2002-2004 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  */
11
12 #include <X11/Intrinsic.h>
13
14 extern XtAppContext app;
15
16 #define PROGCLASS       "Cubenetic"
17 #define HACK_INIT       init_cube
18 #define HACK_DRAW       draw_cube
19 #define HACK_RESHAPE    reshape_cube
20 #define HACK_HANDLE_EVENT cube_handle_event
21 #define EVENT_MASK      PointerMotionMask
22 #define ccs_opts        xlockmore_opts
23
24 #define DEF_SPIN        "XYZ"
25 #define DEF_WANDER      "True"
26 #define DEF_TEXTURE     "True"
27
28 #define DEF_WAVE_COUNT  "3"
29 #define DEF_WAVE_SPEED  "80"
30 #define DEF_WAVE_RADIUS "512"
31
32 #define DEFAULTS        "*delay:        20000       \n" \
33                         "*count:        5           \n" \
34                         "*showFPS:      False       \n" \
35                         "*wireframe:    False       \n" \
36                         "*spin:       " DEF_SPIN   "\n" \
37                         "*wander:     " DEF_WANDER "\n" \
38                         "*texture:    " DEF_TEXTURE"\n" \
39                         "*waves:      " DEF_WAVE_COUNT  "\n" \
40                         "*waveSpeed:  " DEF_WAVE_SPEED  "\n" \
41                         "*waveRadius: " DEF_WAVE_RADIUS "\n" \
42
43 #undef countof
44 #define countof(x) (sizeof((x))/sizeof((*x)))
45
46 #include "xlockmore.h"
47 #include "colors.h"
48 #include "rotator.h"
49 #include "gltrackball.h"
50 #include <ctype.h>
51
52 #ifdef USE_GL /* whole file */
53
54 #include <GL/glu.h>
55
56 typedef struct {
57   int color;
58   GLfloat x, y, z;
59   GLfloat w, h, d;
60   int frame;
61   GLfloat dx, dy, dz;
62   GLfloat dw, dh, dd;
63 } cube;
64
65 typedef struct {
66   int x, y;
67   double xth, yth;
68 } wave_src;
69
70 typedef struct {
71   int nwaves;
72   int radius;
73   int speed;
74   wave_src *srcs;
75   int *heights;
76 } waves;
77
78
79 typedef struct {
80   GLXContext *glx_context;
81   rotator *rot;
82   trackball_state *trackball;
83   Bool button_down_p;
84
85   GLuint cube_list;
86   GLuint texture_id;
87   int ncubes;
88   cube *cubes;
89   waves *waves;
90
91   int texture_width, texture_height;
92   unsigned char *texture;
93
94   int ncolors;
95   XColor *cube_colors;
96   XColor *texture_colors;
97
98 } cube_configuration;
99
100 static cube_configuration *ccs = NULL;
101
102 static char *do_spin;
103 static Bool do_wander;
104 static Bool do_texture;
105
106 static int wave_count;
107 static int wave_speed;
108 static int wave_radius;
109 static int texture_size = 256;
110
111 static XrmOptionDescRec opts[] = {
112   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
113   { "+spin",   ".spin",   XrmoptionNoArg, "" },
114   { "-wander", ".wander", XrmoptionNoArg, "True" },
115   { "+wander", ".wander", XrmoptionNoArg, "False" },
116   {"-texture", ".texture", XrmoptionNoArg, "true" },
117   {"+texture", ".texture", XrmoptionNoArg, "false" },
118   {"-waves",       ".waves",      XrmoptionSepArg, 0 },
119   {"-wave-speed",  ".waveSpeed",  XrmoptionSepArg, 0 },
120   {"-wave-radius", ".waveRadius", XrmoptionSepArg, 0 },
121 };
122
123 static argtype vars[] = {
124   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
125   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
126   {&do_texture, "texture", "Texture", DEF_TEXTURE, t_Bool},
127   {&wave_count, "waves",     "Waves",      DEF_WAVE_COUNT, t_Int},
128   {&wave_speed, "waveSpeed", "WaveSpeed",  DEF_WAVE_SPEED, t_Int},
129   {&wave_radius,"waveRadius","WaveRadius", DEF_WAVE_RADIUS,t_Int},
130 };
131
132 ModeSpecOpt ccs_opts = {countof(opts), opts, countof(vars), vars, NULL};
133
134
135 static void
136 unit_cube (Bool wire)
137 {
138   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* front */
139   glNormal3f (0, 0, 1);
140   glTexCoord2f(1, 0); glVertex3f ( 0.5, -0.5,  0.5);
141   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
142   glTexCoord2f(0, 1); glVertex3f (-0.5,  0.5,  0.5);
143   glTexCoord2f(1, 1); glVertex3f (-0.5, -0.5,  0.5);
144   glEnd();
145
146   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* back */
147   glNormal3f (0, 0, -1);
148   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
149   glTexCoord2f(0, 1); glVertex3f (-0.5,  0.5, -0.5);
150   glTexCoord2f(1, 1); glVertex3f ( 0.5,  0.5, -0.5);
151   glTexCoord2f(1, 0); glVertex3f ( 0.5, -0.5, -0.5);
152   glEnd();
153
154   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* left */
155   glNormal3f (-1, 0, 0);
156   glTexCoord2f(1, 1); glVertex3f (-0.5,  0.5,  0.5);
157   glTexCoord2f(1, 0); glVertex3f (-0.5,  0.5, -0.5);
158   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
159   glTexCoord2f(0, 1); glVertex3f (-0.5, -0.5,  0.5);
160   glEnd();
161
162   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* right */
163   glNormal3f (1, 0, 0);
164   glTexCoord2f(1, 1); glVertex3f ( 0.5, -0.5, -0.5);
165   glTexCoord2f(1, 0); glVertex3f ( 0.5,  0.5, -0.5);
166   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
167   glTexCoord2f(0, 1); glVertex3f ( 0.5, -0.5,  0.5);
168   glEnd();
169
170   if (wire) return;
171
172   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* top */
173   glNormal3f (0, 1, 0);
174   glTexCoord2f(0, 0); glVertex3f ( 0.5,  0.5,  0.5);
175   glTexCoord2f(0, 1); glVertex3f ( 0.5,  0.5, -0.5);
176   glTexCoord2f(1, 1); glVertex3f (-0.5,  0.5, -0.5);
177   glTexCoord2f(1, 0); glVertex3f (-0.5,  0.5,  0.5);
178   glEnd();
179
180   glBegin (wire ? GL_LINE_LOOP : GL_QUADS);     /* bottom */
181   glNormal3f (0, -1, 0);
182   glTexCoord2f(1, 0); glVertex3f (-0.5, -0.5,  0.5);
183   glTexCoord2f(0, 0); glVertex3f (-0.5, -0.5, -0.5);
184   glTexCoord2f(0, 1); glVertex3f ( 0.5, -0.5, -0.5);
185   glTexCoord2f(1, 1); glVertex3f ( 0.5, -0.5,  0.5);
186   glEnd();
187 }
188
189
190
191 /* Window management, etc
192  */
193 void
194 reshape_cube (ModeInfo *mi, int width, int height)
195 {
196   GLfloat h = (GLfloat) height / (GLfloat) width;
197
198   glViewport (0, 0, (GLint) width, (GLint) height);
199
200   glMatrixMode(GL_PROJECTION);
201   glLoadIdentity();
202
203   gluPerspective (30.0, 1/h, 1.0, 100.0);
204   glMatrixMode(GL_MODELVIEW);
205   glLoadIdentity();
206   gluLookAt( 0.0, 0.0, 30.0,
207              0.0, 0.0, 0.0,
208              0.0, 1.0, 0.0);
209
210   glClear(GL_COLOR_BUFFER_BIT);
211 }
212
213
214 \f
215 /* Waves.
216    Adapted from ../hacks/interference.c by Hannu Mallat.
217  */
218
219 static void
220 init_wave (ModeInfo *mi)
221 {
222   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
223   waves *ww;
224   int i;
225   cc->waves = ww = (waves *) calloc (sizeof(*cc->waves), 1);
226   ww->nwaves = wave_count;
227   ww->radius = wave_radius;
228   ww->speed  = wave_speed;
229   ww->heights = (int *) calloc (sizeof(*ww->heights), ww->radius);
230   ww->srcs = (wave_src *) calloc (sizeof(*ww->srcs), ww->nwaves);
231
232   for (i = 0; i < ww->radius; i++)
233     {
234       float max = (cc->ncolors * (ww->radius - i) / (float) ww->radius);
235       ww->heights[i] = ((max + max * cos(i / 50.0)) / 2.0);
236     }
237
238   for (i = 0; i < ww->nwaves; i++)
239     {
240       ww->srcs[i].xth = frand(2.0) * M_PI;
241       ww->srcs[i].yth = frand(2.0) * M_PI;
242     }
243 }
244
245 static void
246 interference (ModeInfo *mi)
247 {
248   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
249   waves *ww = cc->waves;
250   int x, y, i;
251
252   /* Move the wave origins around
253    */
254   for (i = 0; i < ww->nwaves; i++)
255     {
256       ww->srcs[i].xth += (ww->speed / 1000.0);
257       if (ww->srcs[i].xth > 2*M_PI)
258         ww->srcs[i].xth -= 2*M_PI;
259       ww->srcs[i].yth += (ww->speed / 1000.0);
260       if (ww->srcs[i].yth > 2*M_PI)
261         ww->srcs[i].yth -= 2*M_PI;
262
263       ww->srcs[i].x = (cc->texture_width/2 +
264                        (cos (ww->srcs[i].xth) *
265                         cc->texture_width / 2));
266       ww->srcs[i].y = (cc->texture_height/2 +
267                        (cos (ww->srcs[i].yth) *
268                         cc->texture_height / 2));
269     }
270
271   /* Compute the effect of the waves on each pixel,
272      and generate the output map.
273    */
274   for (y = 0; y < cc->texture_height; y++)
275     for (x = 0; x < cc->texture_width; x++)
276       {
277         int result = 0;
278         unsigned char *o;
279         for (i = 0; i < ww->nwaves; i++)
280           {
281             int dx = x - ww->srcs[i].x;
282             int dy = y - ww->srcs[i].y;
283             int dist = sqrt (dx*dx + dy*dy);
284             result += (dist > ww->radius ? 0 : ww->heights[dist]);
285           }
286         result %= cc->ncolors;
287
288         o = cc->texture + (((y * cc->texture_width) + x) << 2);
289         o[0] = (cc->texture_colors[result].red   >> 8);
290         o[1] = (cc->texture_colors[result].green >> 8);
291         o[2] = (cc->texture_colors[result].blue  >> 8);
292      /* o[3] = 0xFF; */
293       }
294 }
295
296 \f
297 /* Textures
298  */
299
300 static void
301 init_texture (ModeInfo *mi)
302 {
303   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
304   int i;
305
306   glEnable(GL_TEXTURE_2D);
307
308   clear_gl_error();
309   glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
310   glGenTextures (1, &cc->texture_id);
311   glBindTexture (GL_TEXTURE_2D, cc->texture_id);
312   check_gl_error("texture binding");
313
314   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
315   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
316   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
317   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
318   glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
319   glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
320   glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
321   check_gl_error("texture initialization");
322
323   cc->texture_width  = texture_size;
324   cc->texture_height = texture_size;
325
326   i = texture_size * texture_size * 4;
327   cc->texture = (unsigned char *) malloc (i);
328   memset (cc->texture, 0xFF, i);
329 }
330
331
332 static void
333 shuffle_texture (ModeInfo *mi)
334 {
335   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
336   interference (mi);
337   clear_gl_error();
338   glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA,
339                 cc->texture_width, cc->texture_height, 0,
340                 GL_RGBA, GL_UNSIGNED_BYTE,
341                 cc->texture);
342   check_gl_error("texture");
343 }
344
345
346 Bool
347 cube_handle_event (ModeInfo *mi, XEvent *event)
348 {
349   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
350
351   if (event->xany.type == ButtonPress &&
352       event->xbutton.button == Button1)
353     {
354       cc->button_down_p = True;
355       gltrackball_start (cc->trackball,
356                          event->xbutton.x, event->xbutton.y,
357                          MI_WIDTH (mi), MI_HEIGHT (mi));
358       return True;
359     }
360   else if (event->xany.type == ButtonRelease &&
361            event->xbutton.button == Button1)
362     {
363       cc->button_down_p = False;
364       return True;
365     }
366   else if (event->xany.type == ButtonPress &&
367            (event->xbutton.button == Button4 ||
368             event->xbutton.button == Button5))
369     {
370       gltrackball_mousewheel (cc->trackball, event->xbutton.button, 10,
371                               !!event->xbutton.state);
372       return True;
373     }
374   else if (event->xany.type == MotionNotify &&
375            cc->button_down_p)
376     {
377       gltrackball_track (cc->trackball,
378                          event->xmotion.x, event->xmotion.y,
379                          MI_WIDTH (mi), MI_HEIGHT (mi));
380       return True;
381     }
382
383   return False;
384 }
385
386
387 void 
388 init_cube (ModeInfo *mi)
389 {
390   int i;
391   cube_configuration *cc;
392   int wire = MI_IS_WIREFRAME(mi);
393
394   if (!ccs) {
395     ccs = (cube_configuration *)
396       calloc (MI_NUM_SCREENS(mi), sizeof (cube_configuration));
397     if (!ccs) {
398       fprintf(stderr, "%s: out of memory\n", progname);
399       exit(1);
400     }
401   }
402
403   cc = &ccs[MI_SCREEN(mi)];
404
405   if ((cc->glx_context = init_GL(mi)) != NULL) {
406     reshape_cube (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
407   }
408
409   if (!wire)
410     {
411       static GLfloat pos[4] = {1.0, 0.5, 1.0, 0.0};
412       static GLfloat amb[4] = {0.2, 0.2, 0.2, 1.0};
413       static GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
414
415       glLightfv(GL_LIGHT0, GL_POSITION, pos);
416       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
417       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
418
419       glEnable(GL_LIGHTING);
420       glEnable(GL_LIGHT0);
421       glEnable(GL_DEPTH_TEST);
422       glEnable(GL_CULL_FACE);
423     }
424
425
426   {
427     Bool spinx=False, spiny=False, spinz=False;
428     double spin_speed   = 1.0;
429     double wander_speed = 0.05;
430
431     char *s = do_spin;
432     while (*s)
433       {
434         if      (*s == 'x' || *s == 'X') spinx = True;
435         else if (*s == 'y' || *s == 'Y') spiny = True;
436         else if (*s == 'z' || *s == 'Z') spinz = True;
437         else
438           {
439             fprintf (stderr,
440          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
441                      progname, do_spin);
442             exit (1);
443           }
444         s++;
445       }
446
447     cc->rot = make_rotator (spinx ? spin_speed : 0,
448                             spiny ? spin_speed : 0,
449                             spinz ? spin_speed : 0,
450                             1.0,
451                             do_wander ? wander_speed : 0,
452                             (spinx && spiny && spinz));
453     cc->trackball = gltrackball_init ();
454   }
455
456   cc->ncolors = 256;
457   cc->texture_colors = (XColor *) calloc(cc->ncolors, sizeof(XColor));
458   cc->cube_colors    = (XColor *) calloc(cc->ncolors, sizeof(XColor));
459
460   {
461     double H[3], S[3], V[3];
462     int shift = 60;
463     H[0] = frand(360.0); 
464     H[1] = ((H[0] + shift) < 360) ? (H[0]+shift) : (H[0] + shift - 360);
465     H[2] = ((H[1] + shift) < 360) ? (H[1]+shift) : (H[1] + shift - 360);
466     S[0] = S[1] = S[2] = 1.0;
467     V[0] = V[1] = V[2] = 1.0;
468     make_color_loop(0, 0,
469                     H[0], S[0], V[0], 
470                     H[1], S[1], V[1], 
471                     H[2], S[2], V[2], 
472                     cc->texture_colors, &cc->ncolors,
473                     False, False);
474
475     make_smooth_colormap (0, 0, 0,
476                           cc->cube_colors, &cc->ncolors, 
477                           False, 0, False);
478   }
479
480   cc->ncubes = MI_COUNT (mi);
481   cc->cubes = (cube *) calloc (sizeof(cube), cc->ncubes);
482   for (i = 0; i < cc->ncubes; i++)
483     {
484       cube *cube = &cc->cubes[i];
485       cube->color = random() % cc->ncolors;
486       cube->w = 1.0;
487       cube->h = 1.0;
488       cube->d = 1.0;
489       cube->dx = frand(0.1);
490       cube->dy = frand(0.1);
491       cube->dz = frand(0.1);
492       cube->dw = frand(0.1);
493       cube->dh = frand(0.1);
494       cube->dd = frand(0.1);
495     }
496
497   if (wire)
498     do_texture = False;
499     
500   if (do_texture)
501     {
502       init_texture (mi);
503       init_wave (mi);
504       shuffle_texture (mi);
505     }
506
507   cc->cube_list = glGenLists (1);
508   glNewList (cc->cube_list, GL_COMPILE);
509   unit_cube (wire);
510   glEndList ();
511 }
512
513
514 static void
515 shuffle_cubes (ModeInfo *mi)
516 {
517   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
518   int i;
519   for (i = 0; i < cc->ncubes; i++)
520     {
521 #     define SINOID(SCALE,FRAME,SIZE) \
522         ((((1 + sin((FRAME * (SCALE)) / 2 * M_PI)) / 2.0) * (SIZE)) - (SIZE)/2)
523
524       cube *cube = &cc->cubes[i];
525       cube->x = SINOID(cube->dx, cube->frame, 0.5);
526       cube->y = SINOID(cube->dy, cube->frame, 0.5);
527       cube->z = SINOID(cube->dz, cube->frame, 0.5);
528       cube->w = SINOID(cube->dw, cube->frame, 0.9) + 1.0;
529       cube->h = SINOID(cube->dh, cube->frame, 0.9) + 1.0;
530       cube->d = SINOID(cube->dd, cube->frame, 0.9) + 1.0;
531       cube->frame++;
532 #     undef SINOID
533     }
534 }
535
536
537 void
538 draw_cube (ModeInfo *mi)
539 {
540   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
541   Display *dpy = MI_DISPLAY(mi);
542   Window window = MI_WINDOW(mi);
543   int i;
544
545   if (!cc->glx_context)
546     return;
547
548   glShadeModel(GL_FLAT);
549
550   glEnable(GL_DEPTH_TEST);
551   glEnable(GL_NORMALIZE);
552   glEnable(GL_CULL_FACE);
553
554   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
555
556   glPushMatrix ();
557
558   glScalef(1.1, 1.1, 1.1);
559
560   {
561     double x, y, z;
562     get_position (cc->rot, &x, &y, &z, !cc->button_down_p);
563     glTranslatef((x - 0.5) * 8,
564                  (y - 0.5) * 6,
565                  (z - 0.5) * 15);
566
567     gltrackball_rotate (cc->trackball);
568
569     get_rotation (cc->rot, &x, &y, &z, !cc->button_down_p);
570     glRotatef (x * 360, 1.0, 0.0, 0.0);
571     glRotatef (y * 360, 0.0, 1.0, 0.0);
572     glRotatef (z * 360, 0.0, 0.0, 1.0);
573   }
574
575   glScalef (2.5, 2.5, 2.5);
576
577   for (i = 0; i < cc->ncubes; i++)
578     {
579       cube *cube = &cc->cubes[i];
580       GLfloat color[4];
581       color[0] = cc->cube_colors[cube->color].red   / 65536.0;
582       color[1] = cc->cube_colors[cube->color].green / 65536.0;
583       color[2] = cc->cube_colors[cube->color].blue  / 65536.0;
584       color[3] = 1.0;
585       cube->color++;
586       if (cube->color >= cc->ncolors) cube->color = 0;
587
588       glPushMatrix ();
589       glTranslatef (cube->x, cube->y, cube->z);
590       glScalef (cube->w, cube->h, cube->d);
591       glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
592       glCallList (cc->cube_list);
593       glPopMatrix ();
594     }
595
596   shuffle_cubes (mi);
597   if (do_texture)
598     shuffle_texture (mi);
599
600   glPopMatrix();
601
602   if (mi->fps_p) do_fps (mi);
603   glFinish();
604
605   glXSwapBuffers(dpy, window);
606 }
607
608 #endif /* USE_GL */