From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / glx / kaleidocycle.c
1 /* kaleidocycle, Copyright (c) 2013-2014 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                         "*suppressRotationAnimation: True\n" \
23
24 # define refresh_kaleidocycle 0
25 # define release_kaleidocycle 0
26 #undef countof
27 #define countof(x) (sizeof((x))/sizeof((*x)))
28
29 #include "xlockmore.h"
30 #include "colors.h"
31 #include "normals.h"
32 #include "rotator.h"
33 #include "gltrackball.h"
34 #include <ctype.h>
35 #include <math.h>
36
37 #ifdef USE_GL /* whole file */
38
39 #define DEF_SPIN        "Z"
40 #define DEF_WANDER      "False"
41 #define DEF_SPEED       "1.0"
42
43 typedef struct {
44   GLXContext *glx_context;
45   rotator *rot, *rot2;
46   trackball_state *trackball;
47   Bool button_down_p;
48
49   int min_count, max_count;
50   Bool startup_p;
51
52   int ncolors;
53   XColor *colors;
54   int ccolor;
55
56   GLfloat count;
57   GLfloat th, dth;
58
59   enum { STATIC, IN, OUT } mode, prev_mode;
60
61 } kaleidocycle_configuration;
62
63 static kaleidocycle_configuration *bps = NULL;
64
65 static char *do_spin;
66 static GLfloat speed;
67 static Bool do_wander;
68
69 static XrmOptionDescRec opts[] = {
70   { "-spin",   ".spin",   XrmoptionSepArg, 0 },
71   { "+spin",   ".spin",   XrmoptionNoArg, "" },
72   { "-wander", ".wander", XrmoptionNoArg, "True" },
73   { "+wander", ".wander", XrmoptionNoArg, "False" },
74   { "-speed",  ".speed",  XrmoptionSepArg, 0 },
75 };
76
77 static argtype vars[] = {
78   {&do_spin,   "spin",   "Spin",   DEF_SPIN,   t_String},
79   {&do_wander, "wander", "Wander", DEF_WANDER, t_Bool},
80   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
81 };
82
83 ENTRYPOINT ModeSpecOpt kaleidocycle_opts = {countof(opts), opts, countof(vars), vars, NULL};
84
85
86
87 /* Window management, etc
88  */
89 ENTRYPOINT void
90 reshape_kaleidocycle (ModeInfo *mi, int width, int height)
91 {
92   GLfloat h = (GLfloat) height / (GLfloat) width;
93
94   glViewport (0, 0, (GLint) width, (GLint) height);
95
96   glMatrixMode(GL_PROJECTION);
97   glLoadIdentity();
98   gluPerspective (30.0, 1/h, 1.0, 100.0);
99
100   glMatrixMode(GL_MODELVIEW);
101   glLoadIdentity();
102   gluLookAt( 0.0, 0.0, 30.0,
103              0.0, 0.0, 0.0,
104              0.0, 1.0, 0.0);
105
106 # ifdef HAVE_MOBILE     /* Keep it the same relative size when rotated. */
107   {
108     int o = (int) current_device_rotation();
109     if (o != 0 && o != 180 && o != -180)
110       glScalef (1/h, 1/h, 1/h);
111   }
112 # endif
113
114   glClear(GL_COLOR_BUFFER_BIT);
115 }
116
117
118 ENTRYPOINT Bool
119 kaleidocycle_handle_event (ModeInfo *mi, XEvent *event)
120 {
121   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
122
123   if (gltrackball_event_handler (event, bp->trackball,
124                                  MI_WIDTH (mi), MI_HEIGHT (mi),
125                                  &bp->button_down_p))
126     return True;
127   else if (event->xany.type == KeyPress)
128     {
129       KeySym keysym;
130       char c = 0;
131       XLookupString (&event->xkey, &c, 1, &keysym, 0);
132       if (c == '+' || c == '.' || c == '>' || c == '=' || c == '+' ||
133           keysym == XK_Right || keysym == XK_Up || keysym == XK_Next)
134         {
135           bp->mode = IN;
136           return True;
137         }
138       else if ((c == '-' || c == ',' || c == '<' || c == '-' || c == '_' ||
139                keysym == XK_Left || keysym == XK_Down || keysym == XK_Prior) &&
140                bp->count > bp->min_count)
141         {
142           bp->mode = OUT;
143           return True;
144         }
145       else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
146         goto DEF;
147     }
148   else if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
149     {
150     DEF:
151       if (bp->count <= bp->min_count)
152         bp->mode = IN;
153       else
154         bp->mode = (random() & 1) ? IN : OUT;
155       return True;
156     }
157
158   return False;
159 }
160
161
162
163 ENTRYPOINT void 
164 init_kaleidocycle (ModeInfo *mi)
165 {
166   kaleidocycle_configuration *bp;
167   int wire = MI_IS_WIREFRAME(mi);
168   int i;
169
170   MI_INIT (mi, bps, NULL);
171
172   bp = &bps[MI_SCREEN(mi)];
173
174   bp->glx_context = init_GL(mi);
175
176   reshape_kaleidocycle (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
177
178   glLineWidth (4);
179
180   if (!wire)
181     {
182       GLfloat pos[4] = {1.0, 1.0, 1.0, 0.0};
183       GLfloat amb[4] = {0.0, 0.0, 0.0, 1.0};
184       GLfloat dif[4] = {1.0, 1.0, 1.0, 1.0};
185       GLfloat spc[4] = {0.0, 1.0, 1.0, 1.0};
186
187       glEnable(GL_LIGHTING);
188       glEnable(GL_LIGHT0);
189       glEnable(GL_DEPTH_TEST);
190       glEnable(GL_CULL_FACE);
191
192       glLightfv(GL_LIGHT0, GL_POSITION, pos);
193       glLightfv(GL_LIGHT0, GL_AMBIENT,  amb);
194       glLightfv(GL_LIGHT0, GL_DIFFUSE,  dif);
195       glLightfv(GL_LIGHT0, GL_SPECULAR, spc);
196
197       glEnable (GL_BLEND);
198       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
199     }
200
201   {
202     Bool spinx = False, spiny = False, spinz = False;
203     double spin_speed   = 0.25;
204     double wander_speed = 0.005;
205     double spin_accel   = 0.2;
206     double twist_speed  = 0.25;
207     double twist_accel  = 1.0;
208
209     char *s = do_spin;
210     while (*s)
211       {
212         if      (*s == 'x' || *s == 'X') spinx = True;
213         else if (*s == 'y' || *s == 'Y') spiny = True;
214         else if (*s == 'z' || *s == 'Z') spinz = True;
215         else if (*s == '0') ;
216         else
217           {
218             fprintf (stderr,
219          "%s: spin must contain only the characters X, Y, or Z (not \"%s\")\n",
220                      progname, do_spin);
221             exit (1);
222           }
223         s++;
224       }
225
226     bp->rot = make_rotator (spinx ? spin_speed : 0,
227                             spiny ? spin_speed : 0,
228                             spinz ? spin_speed : 0,
229                             spin_accel,
230                             do_wander ? wander_speed : 0,
231                             False);
232     bp->rot2 = make_rotator (twist_speed, 0, 0, twist_accel, 0, True);
233
234     bp->trackball = gltrackball_init (True);
235   }
236
237   if (MI_COUNT(mi) < 8) MI_COUNT(mi) = 8;
238   if (MI_COUNT(mi) & 1) MI_COUNT(mi)++;
239
240   bp->min_count = 8;
241   bp->max_count = 12 + MI_COUNT(mi) * 1.3;
242   if (bp->max_count & 1) bp->max_count++;
243   bp->startup_p = True;
244
245   bp->count = 0;
246   bp->mode = IN;
247   bp->prev_mode = IN;
248
249 /*
250   bp->count = MI_COUNT(mi);
251   bp->mode = STATIC;
252 */
253
254   bp->ncolors = 512;
255   if (! bp->colors)
256     bp->colors = (XColor *) calloc(bp->ncolors, sizeof(XColor));
257   make_uniform_colormap (0, 0, 0,
258                          bp->colors, &bp->ncolors,
259                          False, 0, False);
260
261   for (i = 0; i < bp->ncolors; i++)
262     {
263       /* make colors twice as bright */
264       bp->colors[i].red   = (bp->colors[i].red   >> 2) + 0x7FFF;
265       bp->colors[i].green = (bp->colors[i].green >> 2) + 0x7FFF;
266       bp->colors[i].blue  = (bp->colors[i].blue  >> 2) + 0x7FFF;
267     }
268
269   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
270 }
271
272
273
274 /* t = toroidal rotation, a = radial position
275    colors = 4 colors, 4 channels each.
276  */
277 static void
278 draw_tetra (ModeInfo *mi, double t, double a, Bool reflect_p,
279             GLfloat *colors)
280 {
281   int wire = MI_IS_WIREFRAME(mi);
282
283   XYZ v1, v2, v3, P, Q;
284   XYZ verts[4];
285   int i;
286
287   double scale;
288   double sint = sin(t);
289   double cost = cos(t);
290   double tana = tan(a);
291   double sint2 = sint * sint;
292   double tana2 = tana * tana;
293
294   v1.x = cost;
295   v1.y = 0;
296   v1.z = sint;
297
298   scale = 1 / sqrt (1 + sint2 * tana2);
299   v2.x = scale * -sint;
300   v2.y = scale * -sint * tana;
301   v2.z = scale * cost;
302
303   v3.x = scale * -sint2 * tana;
304   v3.y = scale;
305   v3.z = scale * cost * sint * tana;
306
307   P.x = v3.y / tana - v3.x;
308   P.y = 0;
309   P.z = -v3.z / 2;
310
311   Q.x = v3.y / tana;
312   Q.y = v3.y;
313   Q.z = v3.z / 2;
314
315   verts[0] = P;
316   verts[1] = P;
317   verts[2] = Q;
318   verts[3] = Q;
319
320   scale = sqrt(2) / 2;
321   verts[0].x = P.x - scale * v1.x;
322   verts[0].y = P.y - scale * v1.y;
323   verts[0].z = P.z - scale * v1.z;
324
325   verts[1].x = P.x + scale * v1.x;
326   verts[1].y = P.y + scale * v1.y;
327   verts[1].z = P.z + scale * v1.z;
328
329   verts[2].x = Q.x - scale * v2.x;
330   verts[2].y = Q.y - scale * v2.y;
331   verts[2].z = Q.z - scale * v2.z;
332
333   verts[3].x = Q.x + scale * v2.x;
334   verts[3].y = Q.y + scale * v2.y;
335   verts[3].z = Q.z + scale * v2.z;
336
337   for (i = 0; i < 4; i++)
338     {
339       Bool reflect2_p = ((i + (reflect_p != 0)) & 1);
340       XYZ a = verts[(i+1) % 4];
341       XYZ b = verts[(i+2) % 4];
342       XYZ c = verts[(i+3) % 4];
343       XYZ n = ((i & 1)
344                ? calc_normal (b, a, c)
345                : calc_normal (a, b, c));
346       if (wire)
347         glColor4fv (colors + (i * 4));
348       else
349         glMaterialfv (GL_FRONT, GL_AMBIENT_AND_DIFFUSE, colors + (i * 4));
350
351       glFrontFace (reflect2_p ? GL_CW : GL_CCW);
352       glBegin (wire ? GL_LINE_LOOP : GL_TRIANGLES);
353       glNormal3f (n.x, n.y, n.z);
354       glVertex3f (a.x, a.y, a.z);
355       glVertex3f (b.x, b.y, b.z);
356       glVertex3f (c.x, c.y, c.z);
357       glEnd();
358     }
359 }
360
361
362 /* Reflect through the plane normal to the given vector.
363  */
364 static void
365 reflect (double x, double y, double z)
366 {
367   GLfloat m[4][4];
368
369   m[0][0] = 1 - (2 * x * x);
370   m[1][0] = -2 * x * y;
371   m[2][0] = -2 * x * z;
372   m[3][0] = 0;
373
374   m[0][1] = -2 * x * y;
375   m[1][1] = 1 - (2 * y * y);
376   m[2][1] = -2 * y * z;
377   m[3][1] = 0;
378
379   m[0][2] = -2 * x * z;
380   m[1][2] = -2 * y * z;
381   m[2][2] = 1 - (2 * z * z);
382   m[3][2] = 0;
383
384   m[0][3] = 0;
385   m[1][3] = 0;
386   m[2][3] = 0;
387   m[3][3] = 1;
388
389   glMultMatrixf (&m[0][0]);
390 }
391
392
393 ENTRYPOINT void
394 draw_kaleidocycle (ModeInfo *mi)
395 {
396   kaleidocycle_configuration *bp = &bps[MI_SCREEN(mi)];
397   Display *dpy = MI_DISPLAY(mi);
398   Window window = MI_WINDOW(mi);
399   GLfloat colors[4*4];
400   GLfloat count;
401   double t, a;
402   int i;
403
404   GLfloat bspec[4] = {1.0, 1.0, 1.0, 1.0};
405   GLfloat bshiny   = 128.0;
406
407   if (!bp->glx_context)
408     return;
409
410   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
411
412   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
413
414   mi->polygon_count = 0;
415
416   glShadeModel(GL_SMOOTH);
417   glEnable(GL_DEPTH_TEST);
418   glEnable(GL_NORMALIZE);
419   glEnable(GL_CULL_FACE);
420
421   glPushMatrix ();
422
423   {
424     double x, y, z;
425     get_position (bp->rot, &x, &y, &z, !bp->button_down_p);
426     glTranslatef((x - 0.5) * 5,
427                  (y - 0.5) * 5,
428                  (z - 0.5) * 10);
429
430     gltrackball_rotate (bp->trackball);
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 */