From http://www.jwz.org/xscreensaver/xscreensaver-5.29.tar.gz
[xscreensaver] / hacks / glx / kaleidocycle.c
1 /* kaleidocycle, Copyright (c) 2013 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  * A loop of rotating tetrahedra.  Created by jwz, July 2013.
12  * Inspired by, and some math borrowed from:
13  * http://www.kaleidocycles.de/pdf/kaleidocycles_theory.pdf
14  * http://intothecontinuum.tumblr.com/post/50873970770/an-even-number-of-at-least-8-regular-tetrahedra
15  */
16
17
18 #define DEFAULTS        "*delay:        30000       \n" \
19                         "*count:        16          \n" \
20                         "*showFPS:      False       \n" \
21                         "*wireframe:    False       \n" \
22
23 # define refresh_kaleidocycle 0
24 # define release_kaleidocycle 0
25 #undef countof
26 #define countof(x) (sizeof((x))/sizeof((*x)))
27
28 #include "xlockmore.h"
29 #include "colors.h"
30 #include "normals.h"
31 #include "rotator.h"
32 #include "gltrackball.h"
33 #include <ctype.h>
34 #include <math.h>
35
36 #ifdef USE_GL /* whole file */
37
38 #define DEF_SPIN        "Z"
39 #define DEF_WANDER      "False"
40 #define DEF_SPEED       "1.0"
41
42 typedef struct {
43   GLXContext *glx_context;
44   rotator *rot, *rot2;
45   trackball_state *trackball;
46   Bool button_down_p;
47
48   int min_count, max_count;
49   Bool startup_p;
50
51   int ncolors;
52   XColor *colors;
53   int ccolor;
54
55   GLfloat count;
56   GLfloat th, dth;
57
58   enum { STATIC, IN, OUT } mode, prev_mode;
59
60 } kaleidocycle_configuration;
61
62 static kaleidocycle_configuration *bps = NULL;
63
64 static char *do_spin;
65 static GLfloat speed;
66 static Bool do_wander;
67
68 static XrmOptionDescRec opts[] = {
69   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
70   { "+spin",   ".spin",   XrmoptionNoArg, "" },
71   { "-wander", ".wander", XrmoptionNoArg, "True" },
72   { "+wander", ".wander", XrmoptionNoArg, "False" },
73   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
74 };
75
76 static argtype vars[] = {
77   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
78   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
79   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
80 };
81
82 ENTRYPOINT ModeSpecOpt kaleidocycle_opts = {countof(opts), opts, countof(vars), vars, NULL};
83
84
85
86 /* Window management, etc
87  */
88 ENTRYPOINT void
89 reshape_kaleidocycle (ModeInfo *mi, int width, int height)
90 {
91   GLfloat h = (GLfloat) height / (GLfloat) width;
92
93   glViewport (0, 0, (GLint) width, (GLint) height);
94
95   glMatrixMode(GL_PROJECTION);
96   glLoadIdentity();
97   gluPerspective (30.0, 1/h, 1.0, 100.0);
98
99   glMatrixMode(GL_MODELVIEW);
100   glLoadIdentity();
101   gluLookAt( 0.0, 0.0, 30.0,
102              0.0, 0.0, 0.0,
103              0.0, 1.0, 0.0);
104
105   glClear(GL_COLOR_BUFFER_BIT);
106 }
107
108
109 ENTRYPOINT Bool
110 kaleidocycle_handle_event (ModeInfo *mi, XEvent *event)
111 {
112   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
113
114   if (event->xany.type == ButtonPress &&
115       event->xbutton.button == Button1)
116     {
117       bp->button_down_p = True;
118       gltrackball_start (bp->trackball,
119                          event->xbutton.x, event->xbutton.y,
120                          MI_WIDTH (mi), MI_HEIGHT (mi));
121       return True;
122     }
123   else if (event->xany.type == ButtonRelease &&
124            event->xbutton.button == Button1)
125     {
126       bp->button_down_p = False;
127       return True;
128     }
129   else if (event->xany.type == ButtonPress &&
130            (event->xbutton.button == Button4 ||
131             event->xbutton.button == Button5 ||
132             event->xbutton.button == Button6 ||
133             event->xbutton.button == Button7))
134     {
135       gltrackball_mousewheel (bp->trackball, event->xbutton.button, 5,
136                               !!event->xbutton.state);
137       return True;
138     }
139   else if (event->xany.type == MotionNotify &&
140            bp->button_down_p)
141     {
142       gltrackball_track (bp->trackball,
143                          event->xmotion.x, event->xmotion.y,
144                          MI_WIDTH (mi), MI_HEIGHT (mi));
145       return True;
146     }
147
148   return False;
149 }
150
151
152
153 ENTRYPOINT void 
154 init_kaleidocycle (ModeInfo *mi)
155 {
156   kaleidocycle_configuration *bp;
157   int wire = MI_IS_WIREFRAME(mi);
158   int i;
159
160   if (!bps) {
161     bps = (kaleidocycle_configuration *)
162       calloc (MI_NUM_SCREENS(mi), sizeof (kaleidocycle_configuration));
163     if (!bps) {
164       fprintf(stderr, "%s: out of memory\n", progname);
165       exit(1);
166     }
167   }
168
169   bp = &bps[MI_SCREEN(mi)];
170
171   bp->glx_context = init_GL(mi);
172
173   reshape_kaleidocycle (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
174
175   glLineWidth (4);
176
177   if (!wire)
178     {
179       GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
180       GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
181       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
182       GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};
183
184       glEnable(GL_LIGHTING);
185       glEnable(GL_LIGHT0);
186       glEnable(GL_DEPTH_TEST);
187       glEnable(GL_CULL_FACE);
188
189       glLightfv(GL_LIGHT0, GL_POSITION, pos);
190       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
191       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
192       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
193
194       glEnable (GL_BLEND);
195       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
196     }
197
198   {
199     Bool spinx = False, spiny = False, spinz = False;
200     double spin_speed   = 0.25;
201     double wander_speed = 0.005;
202     double spin_accel   = 0.2;
203     double twist_speed  = 0.25;
204     double twist_accel  = 1.0;
205
206     char *s = do_spin;
207     while (*s)
208       {
209         if      (*s == 'x' || *s == 'X') spinx = True;
210         else if (*s == 'y' || *s == 'Y') spiny = True;
211         else if (*s == 'z' || *s == 'Z') spinz = True;
212         else if (*s == '0') ;
213         else
214           {
215             fprintf (stderr,
216          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
217                      progname, do_spin);
218             exit (1);
219           }
220         s++;
221       }
222
223     bp->rot = make_rotator (spinx ? spin_speed : 0,
224                             spiny ? spin_speed : 0,
225                             spinz ? spin_speed : 0,
226                             spin_accel,
227                             do_wander ? wander_speed : 0,
228                             False);
229     bp->rot2 = make_rotator (twist_speed, 0, 0, twist_accel, 0, True);
230
231     bp->trackball = gltrackball_init ();
232   }
233
234   if (MI_COUNT(mi) < 8) MI_COUNT(mi) = 8;
235   if (MI_COUNT(mi) & 1) MI_COUNT(mi)++;
236
237   bp->min_count = 8;
238   bp->max_count = 12 + MI_COUNT(mi) * 1.3;
239   if (bp->max_count & 1) bp->max_count++;
240   bp->startup_p = True;
241
242   bp->count = 0;
243   bp->mode = IN;
244   bp->prev_mode = IN;
245
246 /*
247   bp->count = MI_COUNT(mi);
248   bp->mode = STATIC;
249 */
250
251   bp->ncolors = 512;
252   if (! bp->colors)
253     bp->colors = (XColor *) calloc(bp->ncolors, sizeof(XColor));
254   make_uniform_colormap (0, 0, 0,
255                          bp->colors, &bp->ncolors,
256                          False, 0, False);
257
258   for (i = 0; i < bp->ncolors; i++)
259     {
260       /* make colors twice as bright */
261       bp->colors[i].red   = (bp->colors[i].red   >> 2) + 0x7FFF;
262       bp->colors[i].green = (bp->colors[i].green >> 2) + 0x7FFF;
263       bp->colors[i].blue  = (bp->colors[i].blue  >> 2) + 0x7FFF;
264     }
265
266   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
267 }
268
269
270
271 /* t = toroidal rotation, a = radial position
272    colors = 4 colors, 4 channels each.
273  */
274 static void
275 draw_tetra (ModeInfo *mi, double t, double a, Bool reflect_p,
276             GLfloat *colors)
277 {
278   int wire = MI_IS_WIREFRAME(mi);
279
280   XYZ v1, v2, v3, P, Q;
281   XYZ verts[4];
282   int i;
283
284   double scale;
285   double sint = sin(t);
286   double cost = cos(t);
287   double tana = tan(a);
288   double sint2 = sint * sint;
289   double tana2 = tana * tana;
290
291   v1.x = cost;
292   v1.y = 0;
293   v1.z = sint;
294
295   scale = 1 / sqrt (1 + sint2 * tana2);
296   v2.x = scale * -sint;
297   v2.y = scale * -sint * tana;
298   v2.z = scale * cost;
299
300   v3.x = scale * -sint2 * tana;
301   v3.y = scale;
302   v3.z = scale * cost * sint * tana;
303
304   P.x = v3.y / tana - v3.x;
305   P.y = 0;
306   P.z = -v3.z / 2;
307
308   Q.x = v3.y / tana;
309   Q.y = v3.y;
310   Q.z = v3.z / 2;
311
312   verts[0] = P;
313   verts[1] = P;
314   verts[2] = Q;
315   verts[3] = Q;
316
317   scale = sqrt(2) / 2;
318   verts[0].x = P.x - scale * v1.x;
319   verts[0].y = P.y - scale * v1.y;
320   verts[0].z = P.z - scale * v1.z;
321
322   verts[1].x = P.x + scale * v1.x;
323   verts[1].y = P.y + scale * v1.y;
324   verts[1].z = P.z + scale * v1.z;
325
326   verts[2].x = Q.x - scale * v2.x;
327   verts[2].y = Q.y - scale * v2.y;
328   verts[2].z = Q.z - scale * v2.z;
329
330   verts[3].x = Q.x + scale * v2.x;
331   verts[3].y = Q.y + scale * v2.y;
332   verts[3].z = Q.z + scale * v2.z;
333
334   for (i = 0; i < 4; i++)
335     {
336       Bool reflect2_p = ((i + (reflect_p != 0)) & 1);
337       XYZ a = verts[(i+1) % 4];
338       XYZ b = verts[(i+2) % 4];
339       XYZ c = verts[(i+3) % 4];
340       XYZ n = ((i & 1)
341                ? calc_normal (b, a, c)
342                : calc_normal (a, b, c));
343       if (wire)
344         glColor4fv (colors + (i * 4));
345       else
346         glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colors + (i * 4));
347
348       glFrontFace (reflect2_p ? GL_CW : GL_CCW);
349       glBegin (wire ? GL_LINE_LOOP : GL_TRIANGLES);
350       glNormal3f (n.x, n.y, n.z);
351       glVertex3f (a.x, a.y, a.z);
352       glVertex3f (b.x, b.y, b.z);
353       glVertex3f (c.x, c.y, c.z);
354       glEnd();
355     }
356 }
357
358
359 /* Reflect through the plane normal to the given vector.
360  */
361 static void
362 reflect (double x, double y, double z)
363 {
364   GLfloat m[4][4];
365
366   m[0][0] = 1 - (2 * x * x);
367   m[1][0] = -2 * x * y;
368   m[2][0] = -2 * x * z;
369   m[3][0] = 0;
370
371   m[0][1] = -2 * x * y;
372   m[1][1] = 1 - (2 * y * y);
373   m[2][1] = -2 * y * z;
374   m[3][1] = 0;
375
376   m[0][2] = -2 * x * z;
377   m[1][2] = -2 * y * z;
378   m[2][2] = 1 - (2 * z * z);
379   m[3][2] = 0;
380
381   m[0][3] = 0;
382   m[1][3] = 0;
383   m[2][3] = 0;
384   m[3][3] = 1;
385
386   glMultMatrixf (&m[0][0]);
387 }
388
389
390 ENTRYPOINT void
391 draw_kaleidocycle (ModeInfo *mi)
392 {
393   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
394   Display *dpy = MI_DISPLAY(mi);
395   Window window = MI_WINDOW(mi);
396   GLfloat colors[4*4];
397   GLfloat count;
398   double t, a;
399   int i;
400
401   GLfloat bspec[4] = {1.0, 1.0, 1.0, 1.0};
402   GLfloat bshiny   = 128.0;
403
404   if (!bp->glx_context)
405     return;
406
407   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
408
409   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
410
411   mi->polygon_count = 0;
412
413   glShadeModel(GL_SMOOTH);
414   glEnable(GL_DEPTH_TEST);
415   glEnable(GL_NORMALIZE);
416   glEnable(GL_CULL_FACE);
417
418   glPushMatrix ();
419
420   {
421     double x, y, z;
422     get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
423     glTranslatef((x - 0.5) * 5,
424                  (y - 0.5) * 5,
425                  (z - 0.5) * 10);
426
427     /* Do it twice because we don't track the device's orientation. */
428     glRotatef( current_device_rotation(), 0, 0, 1);
429     gltrackball_rotate (bp->trackball);
430     glRotatef(-current_device_rotation(), 0, 0, 1);
431
432     get_rotation (bp->rot, &x, &y, &z, !bp->button_down_p);
433     glRotatef (x * 360, 1, 0, 0);
434     glRotatef (y * 360, 0, 1, 0);
435     glRotatef (z * 360, 0, 0, 1);
436
437     get_rotation (bp->rot2, &x, &y, &z, !bp->button_down_p);
438     bp->th = x * 360 * 10 * speed;
439
440     /* Make sure the twist is always in motion.  Without this, the rotator
441        sometimes stops, and for too long, and it's boring looking.
442      */
443     bp->th += speed * bp->dth++;
444     while (bp->dth > 360) bp->dth -= 360;
445     while (bp->th  > 360) bp->th  -= 360;
446   }
447
448   glMaterialfv (GL_FRONT, GL_SPECULAR,  bspec);
449   glMateriali  (GL_FRONT, GL_SHININESS, bshiny);
450
451
452   /* Evenly spread the colors of the faces, and cycle them together.
453    */
454   for (i = 0; i < 4; i++)
455     {
456       int o  = bp->ncolors / 4;
457       int c = (bp->ccolor + (o*i)) % bp->ncolors;
458       colors[i*4+0] = bp->colors[c].red   / 65536.0;
459       colors[i*4+1] = bp->colors[c].green / 65536.0;
460       colors[i*4+2] = bp->colors[c].blue  / 65536.0;
461       colors[i*4+3] = 1;
462     }
463   bp->ccolor++;
464   if (bp->ccolor >= bp->ncolors) bp->ccolor = 0;
465
466
467   count = (int) floor (bp->count);
468   while (count < 8) count++;
469   if (((int) floor (count)) & 1) count++;
470
471   a = 2 * M_PI / (bp->count < 8 ? 8 : bp->count);
472   t = bp->th / (180 / M_PI);
473
474   glScalef (3, 3, 3);
475   glScalef (a, a, a);
476   glRotatef (90, 0, 0, 1);
477 /*  glRotatef (45, 0, 1, 0); */
478
479   for (i = 0; i <= (int) floor (bp->count); i++)
480     {
481       Bool flip_p = (i & 1);
482       glPushMatrix();
483       glRotatef ((i/2) * 4 * 180 / bp->count, 0, 0, 1);
484       if (flip_p) reflect (-sin(a), cos(a), 0);
485
486       if (bp->mode != STATIC && i >= (int) floor (bp->count))
487         {
488           /* Fractional bp->count means the last piece is in transition */
489           GLfloat scale = bp->count - (int) floor (bp->count);
490           GLfloat tick = 0.07 * speed;
491           GLfloat ocount = bp->count;
492           GLfloat alpha;
493
494           /* Fill in faster if we're starting up */
495           if (bp->count < MI_COUNT(mi))
496             tick *= 2;
497
498           glScalef (scale, scale, scale);
499
500           switch (bp->mode) {
501           case IN: break;
502           case OUT: tick = -tick; break;
503           case STATIC: tick = 0; break;
504           }
505
506           bp->count += tick;
507
508           if (bp->mode == IN
509               ? floor (ocount) != floor (bp->count)
510               : ceil  (ocount) != ceil  (bp->count))
511             {
512               if (bp->mode == IN)
513                 bp->count = floor (ocount) + 1;
514               else
515                 bp->count = ceil  (ocount) - 1;
516
517               if (((int) floor (bp->count)) & 1 ||
518                   (bp->mode == IN && 
519                    (bp->count < MI_COUNT(mi) &&
520                     bp->startup_p)))
521                 {
522                   /* keep going if it's odd, or less than 8. */
523                   bp->count = round(bp->count);
524                 }
525               else
526                 {
527                   bp->mode = STATIC;
528                   bp->startup_p = False;
529                 }
530             }
531
532           alpha = (scale * scale * scale * scale);
533           if (alpha < 0.4) alpha = 0.4;
534           colors[3] = colors[7] = colors[11] = colors[15] = alpha;
535         }
536
537       draw_tetra (mi, t, a, flip_p, colors);
538       mi->polygon_count += 4;
539
540       glPopMatrix();
541     }
542
543   if (bp->mode == STATIC && !(random() % 200)) {
544     if (bp->count <= bp->min_count)
545       bp->mode = IN;
546     else if (bp->count >= bp->max_count)
547       bp->mode = OUT;
548     else
549       bp->mode = bp->prev_mode;
550
551     bp->prev_mode = bp->mode;
552   }
553
554
555   mi->recursion_depth = ceil (bp->count);
556
557   glPopMatrix ();
558
559   if (mi->fps_p) do_fps (mi);
560   glFinish();
561
562   glXSwapBuffers(dpy, window);
563 }
564
565 XSCREENSAVER_MODULE ("Kaleidocycle", kaleidocycle)
566
567 #endif /* USE_GL */