From http://www.jwz.org/xscreensaver/xscreensaver-5.23.tar.gz
[xscreensaver] / hacks / glx / quasicrystal.c
1 /* quasicrystal, 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  * Overlapping sine waves create interesting plane-tiling interference
12  * patterns.  Created by jwz, Jul 2013.  Inspired by
13  * http://mainisusuallyafunction.blogspot.com/2011/10/quasicrystals-as-sums-of-waves-in-plane.html
14  */
15
16
17 #define DEFAULTS        "*delay:        30000       \n" \
18                         "*spin:         True        \n" \
19                         "*wander:       True        \n" \
20                         "*symmetric:    True        \n" \
21                         "*count:        17          \n" \
22                         "*contrast:     30          \n" \
23                         "*showFPS:      False       \n" \
24                         "*wireframe:    False       \n" \
25
26 # define refresh_quasicrystal 0
27 # define release_quasicrystal 0
28 #undef countof
29 #define countof(x) (sizeof((x))/sizeof((*x)))
30
31 #include "xlockmore.h"
32 #include "colors.h"
33 #include "rotator.h"
34 #include <ctype.h>
35
36 #ifdef USE_GL /* whole file */
37
38 #define DEF_SPEED  "1.0"
39
40 typedef struct {
41   rotator *rot, *rot2;
42   GLuint texid;
43 } plane;
44
45 typedef struct {
46   GLXContext *glx_context;
47   Bool button_down_p;
48   Bool symmetric_p;
49   GLfloat contrast;
50   int count;
51   int ncolors, ccolor;
52   XColor *colors;
53   plane *planes;
54   int mousex, mousey;
55
56 } quasicrystal_configuration;
57
58 static quasicrystal_configuration *bps = NULL;
59
60 static GLfloat speed;
61
62 static XrmOptionDescRec opts[] = {
63   { "-spin",         ".spin",      XrmoptionNoArg, "True"  },
64   { "+spin",         ".spin",      XrmoptionNoArg, "False" },
65   { "-wander",       ".wander",    XrmoptionNoArg, "True"  },
66   { "+wander",       ".wander",    XrmoptionNoArg, "False" },
67   { "-symmetry",     ".symmetric", XrmoptionNoArg, "True"   },
68   { "-no-symmetry",  ".symmetric", XrmoptionNoArg, "False"  },
69   { "-speed",        ".speed",     XrmoptionSepArg, 0 },
70   { "-contrast",     ".contrast",  XrmoptionSepArg, 0 },
71 };
72
73 static argtype vars[] = {
74   {&speed,     "speed",  "Speed",  DEF_SPEED,  t_Float},
75 };
76
77 ENTRYPOINT ModeSpecOpt quasicrystal_opts = {countof(opts), opts, countof(vars), vars, NULL};
78
79
80
81 /* Window management, etc
82  */
83 ENTRYPOINT void
84 reshape_quasicrystal (ModeInfo *mi, int width, int height)
85 {
86   GLfloat h = (GLfloat) height / (GLfloat) width;
87
88   glViewport (0, 0, (GLint) width, (GLint) height);
89
90   glMatrixMode(GL_PROJECTION);
91   glLoadIdentity();
92   glOrtho (0, 1, 1, 0, -1, 1);
93
94   glMatrixMode(GL_MODELVIEW);
95   glLoadIdentity();
96   glTranslatef (0.5, 0.5, 0);
97   glScalef (h, 1, 1);
98   if (width > height)
99     glScalef (1/h, 1/h, 1);
100   glTranslatef (-0.5, -0.5, 0);
101   glClear(GL_COLOR_BUFFER_BIT);
102 }
103
104
105 ENTRYPOINT Bool
106 quasicrystal_handle_event (ModeInfo *mi, XEvent *event)
107 {
108   quasicrystal_configuration *bp = &bps[MI_SCREEN(mi)];
109
110   if (event->xany.type == ButtonPress &&
111       event->xbutton.button == Button1)
112     {
113       bp->button_down_p = True;
114       bp->mousex = event->xbutton.x;
115       bp->mousey = event->xbutton.y;
116       return True;
117     }
118   else if (event->xany.type == ButtonRelease &&
119            event->xbutton.button == Button1)
120     {
121       bp->button_down_p = False;
122       return True;
123     }
124   else if (event->xany.type == MotionNotify &&
125            bp->button_down_p)
126     {
127       /* Dragging up and down tweaks contrast */
128
129       int dx = event->xmotion.x - bp->mousex;
130       int dy = event->xmotion.y - bp->mousey;
131
132       if (abs(dy) > abs(dx))
133         {
134           bp->contrast += dy / 40.0;
135           if (bp->contrast < 0)   bp->contrast = 0;
136           if (bp->contrast > 100) bp->contrast = 100;
137         }
138
139       bp->mousex = event->xmotion.x;
140       bp->mousey = event->xmotion.y;
141       return True;
142     }
143
144   return False;
145 }
146
147
148
149 ENTRYPOINT void 
150 init_quasicrystal (ModeInfo *mi)
151 {
152   quasicrystal_configuration *bp;
153   int wire = MI_IS_WIREFRAME(mi);
154   unsigned char *tex_data = 0;
155   int tex_width;
156   int i;
157
158   if (!bps) {
159     bps = (quasicrystal_configuration *)
160       calloc (MI_NUM_SCREENS(mi), sizeof (quasicrystal_configuration));
161     if (!bps) {
162       fprintf(stderr, "%s: out of memory\n", progname);
163       exit(1);
164     }
165   }
166
167   bp = &bps[MI_SCREEN(mi)];
168
169   bp->glx_context = init_GL(mi);
170
171   reshape_quasicrystal (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
172
173   glDisable (GL_DEPTH_TEST);
174   glEnable (GL_CULL_FACE);
175
176   bp->count = MI_COUNT(mi);
177   if (bp->count < 1) bp->count = 1;
178
179   if (! wire)
180     {
181       unsigned char *o;
182
183       tex_width = 4096;
184       glGetIntegerv (GL_MAX_TEXTURE_SIZE, &tex_width);
185       if (tex_width > 4096) tex_width = 4096;
186
187       tex_data = (unsigned char *) calloc (4, tex_width);
188       o = tex_data;
189       for (i = 0; i < tex_width; i++)
190         {
191           unsigned char y = 255 * (1 + sin (i * M_PI * 2 / tex_width)) / 2;
192           *o++ = y;
193           *o++ = y;
194           *o++ = y;
195           *o++ = 255;
196         }
197     }
198
199   bp->symmetric_p =
200     get_boolean_resource (MI_DISPLAY (mi), "symmetry", "Symmetry");
201
202   bp->contrast = get_float_resource (MI_DISPLAY (mi), "contrast", "Contrast");
203   if (bp->contrast < 0 || bp->contrast > 100) 
204     {
205       fprintf (stderr, "%s: contrast must be between 0 and 100%%.\n", progname);
206       bp->contrast = 0;
207     }
208
209   {
210     Bool spinp   = get_boolean_resource (MI_DISPLAY (mi), "spin", "Spin");
211     Bool wanderp = get_boolean_resource (MI_DISPLAY (mi), "wander", "Wander");
212     double spin_speed   = 0.01;
213     double wander_speed = 0.0001;
214     double spin_accel   = 10.0;
215     double scale_speed  = 0.005;
216
217     bp->planes = (plane *) calloc (sizeof (*bp->planes), bp->count);
218
219     bp->ncolors = 256;  /* ncolors affects color-cycling speed */
220     bp->colors = (XColor *) calloc (bp->ncolors, sizeof(XColor));
221     make_smooth_colormap (0, 0, 0, bp->colors, &bp->ncolors,
222                           False, 0, False);
223     bp->ccolor = 0;
224
225     for (i = 0;  i < bp->count; i++)
226       {
227         plane *p = &bp->planes[i];
228         p->rot = make_rotator (0, 0,
229                                spinp ? spin_speed : 0,
230                                spin_accel,
231                                wanderp ? wander_speed : 0,
232                                True);
233         p->rot2 = make_rotator (0, 0,
234                                 0, 0,
235                                scale_speed,
236                                True);
237         if (! wire)
238           {
239             clear_gl_error();
240
241             glGenTextures (1, &p->texid);
242             glBindTexture (GL_TEXTURE_1D, p->texid);
243             glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
244             glTexImage1D (GL_TEXTURE_1D, 0, GL_RGBA,
245                           tex_width, 0,
246                           GL_RGBA,
247                           /* GL_UNSIGNED_BYTE, */
248                           GL_UNSIGNED_INT_8_8_8_8_REV,
249                           tex_data);
250             check_gl_error("texture");
251
252             glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_REPEAT);
253             glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_REPEAT);
254
255             glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
256             glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
257
258             glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
259           }
260       }
261   }
262
263   if (tex_data) free (tex_data);
264
265   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
266 }
267
268
269 ENTRYPOINT void
270 draw_quasicrystal (ModeInfo *mi)
271 {
272   quasicrystal_configuration *bp = &bps[MI_SCREEN(mi)];
273   Display *dpy = MI_DISPLAY(mi);
274   Window window = MI_WINDOW(mi);
275   int wire = MI_IS_WIREFRAME(mi);
276   double r, ps;
277   int i;
278
279   if (!bp->glx_context)
280     return;
281
282   glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(bp->glx_context));
283
284   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
285
286   mi->polygon_count = 0;
287
288   glShadeModel(GL_FLAT);
289   glDisable(GL_DEPTH_TEST);
290   glDisable(GL_CULL_FACE);
291   glDisable (GL_LIGHTING);
292
293   glEnable (GL_BLEND);
294   glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
295
296   glPushMatrix ();
297   glTranslatef (0.5, 0.5, 0);
298   glScalef (3, 3, 3);
299
300   if (wire) glScalef (0.2, 0.2, 0.2);
301
302   for (i = 0;  i < bp->count; i++)
303     {
304       plane *p = &bp->planes[i];
305       double x, y, z;
306       double scale = (wire ? 10 : 700.0 / bp->count);
307       double pscale;
308
309       glPushMatrix();
310
311       get_position (p->rot, &x, &y, &z, !bp->button_down_p);
312       glTranslatef((x - 0.5) * 0.3333,
313                    (y - 0.5) * 0.3333,
314                    0);
315
316       /* With -symmetry, keep the planes' scales in sync.
317          Otherwise, they scale independently.
318        */
319       if (bp->symmetric_p && i > 0)
320         pscale = ps;
321       else
322         {
323           get_position (p->rot2, &x, &y, &z, !bp->button_down_p);
324           pscale = 1 + (4 * z);
325           ps = pscale;
326         }
327
328       scale *= pscale;
329
330
331       /* With -symmetry, evenly distribute the planes' rotation.
332          Otherwise, they rotate independently.
333        */
334       if (bp->symmetric_p && i > 0)
335         z = r + (i * M_PI * 2 / bp->count);
336       else
337         {
338           get_rotation (p->rot, &x, &y, &z, !bp->button_down_p);
339           r = z;
340         }
341
342
343       glRotatef (z * 360, 0, 0, 1);
344       glTranslatef (-0.5, -0.5, 0);
345
346       glColor4f (1, 1, 1, (wire ? 0.5 : 1.0 / bp->count));
347
348       if (!wire)
349         {
350           glEnable (GL_TEXTURE_1D);
351           glBindTexture (GL_TEXTURE_1D, p->texid);
352         }
353
354       glBegin (wire ? GL_LINE_LOOP : GL_QUADS);
355       glNormal3f (0, 0, 1);
356       glTexCoord2f (-scale/2,  scale/2); glVertex3f (0, 1, 0);
357       glTexCoord2f ( scale/2,  scale/2); glVertex3f (1, 1, 0);
358       glTexCoord2f ( scale/2, -scale/2); glVertex3f (1, 0, 0);
359       glTexCoord2f (-scale/2, -scale/2); glVertex3f (0, 0, 0);
360       glEnd();
361
362       if (wire)
363         {
364           float j;
365           glDisable (GL_TEXTURE_1D);
366           glColor4f (1, 1, 1, 1.0 / bp->count);
367           for (j = 0; j < 1; j += (1 / scale))
368             {
369               glBegin (GL_LINES);
370               glVertex3f (j, 0, 0);
371               glVertex3f (j, 1, 0);
372               mi->polygon_count++;
373               glEnd();
374             }
375         }
376
377       glPopMatrix();
378
379       mi->polygon_count++;
380     }
381
382   /* Colorize the grayscale image. */
383   {
384     GLfloat c[4];
385     c[0] = bp->colors[bp->ccolor].red   / 65536.0;
386     c[1] = bp->colors[bp->ccolor].green / 65536.0;
387     c[2] = bp->colors[bp->ccolor].blue  / 65536.0;
388     c[3] = 1;
389
390     /* Brighten the colors. */
391     c[0] = (0.6666 + c[0]/3);
392     c[1] = (0.6666 + c[1]/3);
393     c[2] = (0.6666 + c[2]/3);
394
395     glBlendFunc (GL_DST_COLOR, GL_SRC_COLOR);
396     glDisable (GL_TEXTURE_1D);
397     glColor4fv (c);
398     glTranslatef (-0.5, -0.5, 0);
399     glBegin (GL_QUADS);
400     glVertex3f (0, 1, 0);
401     glVertex3f (1, 1, 0);
402     glVertex3f (1, 0, 0);
403     glVertex3f (0, 0, 0);
404     glEnd();
405     mi->polygon_count++;
406   }
407
408   /* Clip the colors to simulate contrast. */
409
410   if (bp->contrast > 0)
411     {
412       /* If c > 0, map 0 - 100 to 0.5 - 1.0, and use (s & ~d) */
413       GLfloat c = 1 - (bp->contrast / 2 / 100.0);
414       glDisable (GL_TEXTURE_1D);
415       glDisable (GL_BLEND);
416       glEnable (GL_COLOR_LOGIC_OP);
417       glLogicOp (GL_AND_REVERSE);
418       glColor4f (c, c, c, 1);
419       glBegin (GL_QUADS);
420       glVertex3f (0, 1, 0);
421       glVertex3f (1, 1, 0);
422       glVertex3f (1, 0, 0);
423       glVertex3f (0, 0, 0);
424       glEnd();
425       mi->polygon_count++;
426       glDisable (GL_COLOR_LOGIC_OP);
427     }
428
429   /* Rotate colors. */
430   bp->ccolor++;
431   if (bp->ccolor >= bp->ncolors)
432     bp->ccolor = 0;
433
434
435   glPopMatrix ();
436
437   if (mi->fps_p) do_fps (mi);
438   glFinish();
439
440   glXSwapBuffers(dpy, window);
441 }
442
443 XSCREENSAVER_MODULE ("QuasiCrystal", quasicrystal)
444
445 #endif /* USE_GL */