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