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