e632cc0380c96755c6a031b00152271ce7e22a79
[xscreensaver] / hacks / glx / cubenetic.c
1 /* cubenetic, Copyright (c) 2002-2006 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     {
353       gltrackball_mousewheel (cc->trackball, event->xbutton.button, 10,
354                               !!event->xbutton.state);
355       return True;
356     }
357   else if (event->xany.type == MotionNotify &&
358            cc->button_down_p)
359     {
360       gltrackball_track (cc->trackball,
361                          event->xmotion.x, event->xmotion.y,
362                          MI_WIDTH (mi), MI_HEIGHT (mi));
363       return True;
364     }
365
366   return False;
367 }
368
369
370 ENTRYPOINT void 
371 init_cube (ModeInfo *mi)
372 {
373   int i;
374   cube_configuration *cc;
375   int wire = MI_IS_WIREFRAME(mi);
376
377   if (!ccs) {
378     ccs = (cube_configuration *)
379       calloc (MI_NUM_SCREENS(mi), sizeof (cube_configuration));
380     if (!ccs) {
381       fprintf(stderr, "%s: out of memory\n", progname);
382       exit(1);
383     }
384   }
385
386   cc = &ccs[MI_SCREEN(mi)];
387
388   if ((cc->glx_context = init_GL(mi)) != NULL) {
389     reshape_cube (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
390   }
391
392   if (!wire)
393     {
394       static const GLfloat pos[4] = {1.0, 0.5, 1.0, 0.0};
395       static const GLfloat amb[4] = {0.2, 0.2, 0.2, 1.0};
396       static const GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
397
398       glLightfv(GL_LIGHT0, GL_POSITION, pos);
399       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
400       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
401
402       glEnable(GL_LIGHTING);
403       glEnable(GL_LIGHT0);
404       glEnable(GL_DEPTH_TEST);
405       glEnable(GL_CULL_FACE);
406     }
407
408
409   {
410     Bool spinx=False, spiny=False, spinz=False;
411     double spin_speed   = 1.0;
412     double wander_speed = 0.05;
413
414     char *s = do_spin;
415     while (*s)
416       {
417         if      (*s == 'x' || *s == 'X') spinx = True;
418         else if (*s == 'y' || *s == 'Y') spiny = True;
419         else if (*s == 'z' || *s == 'Z') spinz = True;
420         else if (*s == '0') ;
421         else
422           {
423             fprintf (stderr,
424          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
425                      progname, do_spin);
426             exit (1);
427           }
428         s++;
429       }
430
431     cc->rot = make_rotator (spinx ? spin_speed : 0,
432                             spiny ? spin_speed : 0,
433                             spinz ? spin_speed : 0,
434                             1.0,
435                             do_wander ? wander_speed : 0,
436                             (spinx && spiny && spinz));
437     cc->trackball = gltrackball_init ();
438   }
439
440   cc->ncolors = 256;
441   cc->texture_colors = (XColor *) calloc(cc->ncolors, sizeof(XColor));
442   cc->cube_colors    = (XColor *) calloc(cc->ncolors, sizeof(XColor));
443
444   {
445     double H[3], S[3], V[3];
446     int shift = 60;
447     H[0] = frand(360.0); 
448     H[1] = ((H[0] + shift) < 360) ? (H[0]+shift) : (H[0] + shift - 360);
449     H[2] = ((H[1] + shift) < 360) ? (H[1]+shift) : (H[1] + shift - 360);
450     S[0] = S[1] = S[2] = 1.0;
451     V[0] = V[1] = V[2] = 1.0;
452     make_color_loop(0, 0,
453                     H[0], S[0], V[0], 
454                     H[1], S[1], V[1], 
455                     H[2], S[2], V[2], 
456                     cc->texture_colors, &cc->ncolors,
457                     False, False);
458
459     make_smooth_colormap (0, 0, 0,
460                           cc->cube_colors, &cc->ncolors, 
461                           False, 0, False);
462   }
463
464   cc->ncubes = MI_COUNT (mi);
465   cc->cubes = (cube *) calloc (sizeof(cube), cc->ncubes);
466   for (i = 0; i < cc->ncubes; i++)
467     {
468       cube *cube = &cc->cubes[i];
469       cube->color = random() % cc->ncolors;
470       cube->w = 1.0;
471       cube->h = 1.0;
472       cube->d = 1.0;
473       cube->dx = frand(0.1);
474       cube->dy = frand(0.1);
475       cube->dz = frand(0.1);
476       cube->dw = frand(0.1);
477       cube->dh = frand(0.1);
478       cube->dd = frand(0.1);
479     }
480
481   if (wire)
482     do_texture = False;
483     
484   if (do_texture)
485     {
486       init_texture (mi);
487       init_wave (mi);
488       shuffle_texture (mi);
489     }
490
491   cc->cube_list = glGenLists (1);
492   glNewList (cc->cube_list, GL_COMPILE);
493   unit_cube (wire);
494   glEndList ();
495 }
496
497
498 static void
499 shuffle_cubes (ModeInfo *mi)
500 {
501   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
502   int i;
503   for (i = 0; i < cc->ncubes; i++)
504     {
505 #     define SINOID(SCALE,FRAME,SIZE) \
506         ((((1 + sin((FRAME * (SCALE)) / 2 * M_PI)) / 2.0) * (SIZE)) - (SIZE)/2)
507
508       cube *cube = &cc->cubes[i];
509       cube->x = SINOID(cube->dx, cube->frame, 0.5);
510       cube->y = SINOID(cube->dy, cube->frame, 0.5);
511       cube->z = SINOID(cube->dz, cube->frame, 0.5);
512       cube->w = SINOID(cube->dw, cube->frame, 0.9) + 1.0;
513       cube->h = SINOID(cube->dh, cube->frame, 0.9) + 1.0;
514       cube->d = SINOID(cube->dd, cube->frame, 0.9) + 1.0;
515       cube->frame++;
516 #     undef SINOID
517     }
518 }
519
520
521 ENTRYPOINT void
522 draw_cube (ModeInfo *mi)
523 {
524   cube_configuration *cc = &ccs[MI_SCREEN(mi)];
525   Display *dpy = MI_DISPLAY(mi);
526   Window window = MI_WINDOW(mi);
527   int i;
528
529   if (!cc->glx_context)
530     return;
531
532   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(cc->glx_context));
533
534   glShadeModel(GL_FLAT);
535
536   glEnable(GL_DEPTH_TEST);
537   glEnable(GL_NORMALIZE);
538   glEnable(GL_CULL_FACE);
539
540   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
541
542   glPushMatrix ();
543
544   glScalef(1.1, 1.1, 1.1);
545
546   {
547     double x, y, z;
548     get_position (cc->rot, &x, &y, &z, !cc->button_down_p);
549     glTranslatef((x - 0.5) * 8,
550                  (y - 0.5) * 6,
551                  (z - 0.5) * 15);
552
553     gltrackball_rotate (cc->trackball);
554
555     get_rotation (cc->rot, &x, &y, &z, !cc->button_down_p);
556     glRotatef (x * 360, 1.0, 0.0, 0.0);
557     glRotatef (y * 360, 0.0, 1.0, 0.0);
558     glRotatef (z * 360, 0.0, 0.0, 1.0);
559   }
560
561   glScalef (2.5, 2.5, 2.5);
562
563   for (i = 0; i < cc->ncubes; i++)
564     {
565       cube *cube = &cc->cubes[i];
566       GLfloat color[4];
567       color[0] = cc->cube_colors[cube->color].red   / 65536.0;
568       color[1] = cc->cube_colors[cube->color].green / 65536.0;
569       color[2] = cc->cube_colors[cube->color].blue  / 65536.0;
570       color[3] = 1.0;
571       cube->color++;
572       if (cube->color >= cc->ncolors) cube->color = 0;
573
574       glPushMatrix ();
575       glTranslatef (cube->x, cube->y, cube->z);
576       glScalef (cube->w, cube->h, cube->d);
577       glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, color);
578       glCallList (cc->cube_list);
579       glPopMatrix ();
580     }
581
582   shuffle_cubes (mi);
583   if (do_texture)
584     shuffle_texture (mi);
585
586   glPopMatrix();
587
588   if (mi->fps_p) do_fps (mi);
589   glFinish();
590
591   glXSwapBuffers(dpy, window);
592 }
593
594 XSCREENSAVER_MODULE_2 ("Cubenetic", cubenetic, cube)
595
596 #endif /* USE_GL */