http://packetstormsecurity.org/UNIX/admin/xscreensaver-4.01.tar.gz
[xscreensaver] / hacks / interference.c
1 /* interference.c --- colored fields via decaying sinusoidal waves.
2  * An entry for the RHAD Labs Screensaver Contest.
3  *
4  * Author: Hannu Mallat <hmallat@cs.hut.fi>
5  *
6  * Copyright (C) 1998 Hannu Mallat.
7  *
8  * Permission to use, copy, modify, distribute, and sell this software and its
9  * documentation for any purpose is hereby granted without fee, provided that
10  * the above copyright notice appear in all copies and that both that
11  * copyright notice and this permission notice appear in supporting
12  * documentation.  No representations are made about the suitability of this
13  * software for any purpose.  It is provided "as is" without express or 
14  * implied warranty.
15  *
16  * decaying sinusoidal waves, which extend spherically from their
17  * respective origins, move around the plane. a sort of interference
18  * between them is calculated and the resulting twodimensional wave
19  * height map is plotted in a grid, using softly changing colours.
20  *
21  * not physically (or in any sense) accurate, but fun to look at for 
22  * a while. you may tune the speed/resolution/interestingness tradeoff 
23  * with X resources, see below.
24  *
25  * Created      : Wed Apr 22 09:30:30 1998, hmallat
26  * Last modified: Wed Apr 22 09:30:30 1998, hmallat
27  *
28  * TODO:
29  *
30  *    This really needs to be sped up.
31  *
32  *    I've tried making it use XPutPixel/XPutImage instead of XFillRectangle,
33  *    but that doesn't seem to help (it's the same speed at gridsize=1, and
34  *    it actually makes it slower at larger sizes.)
35  *
36  *    I played around with shared memory, but clearly I still don't know how
37  *    to use the XSHM extension properly, because it doesn't work yet.
38  *
39  *    Hannu had put in code to use the double-buffering extension, but that
40  *    code didn't work for me on Irix.  I don't think it would help anyway,
41  *    since it's not the swapping of frames that is the bottleneck (or a source
42  *    of visible flicker.)
43  *
44  *     -- jwz, 4-Jun-98
45  */
46
47 #include <math.h>
48
49 #include "screenhack.h"
50
51 # include <X11/Xutil.h>
52
53 /* I thought it would be faster this way, but it turns out not to be... -jwz */
54 #undef USE_XIMAGE
55
56 #ifndef USE_XIMAGE
57 # undef HAVE_XSHM_EXTENSION  /* only applicable when using XImages */
58 #endif /* USE_XIMAGE */
59
60
61 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
62 # include "xdbe.h"
63 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
64
65 #ifdef HAVE_XSHM_EXTENSION
66 # include "xshm.h"
67 #endif /* HAVE_XSHM_EXTENSION */
68
69 char *progclass="Interference";
70
71 char *defaults [] = {
72   ".background:  black",
73   ".foreground:  white",
74   "*count:       3",     /* number of waves */
75   "*gridsize:    4",     /* pixel size, smaller values for better resolution */
76   "*ncolors:     128",   /* number of colours used */
77   "*speed:       30",    /* speed of wave origins moving around */
78   "*delay:       30000", /* or something */
79   "*color-shift: 60",    /* h in hsv space, smaller values for smaller
80                           * color gradients */
81   "*radius:      800",   /* wave extent */
82   "*gray:        false", /* color or grayscale */
83   "*mono:        false", /* monochrome, not very much fun */
84
85   "*doubleBuffer: True",
86 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
87   "*useDBE:      True", /* use double buffering extension */
88 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
89
90 #ifdef HAVE_XSHM_EXTENSION
91   "*useSHM:      True", /* use shared memory extension */
92 #endif /*  HAVE_XSHM_EXTENSION */
93   0
94 };
95
96 XrmOptionDescRec options [] = {
97   { "-count",       ".count",       XrmoptionSepArg, 0 }, 
98   { "-ncolors",     ".ncolors",     XrmoptionSepArg, 0 }, 
99   { "-gridsize",    ".gridsize",    XrmoptionSepArg, 0 }, 
100   { "-speed",       ".speed",       XrmoptionSepArg, 0 },
101   { "-delay",       ".delay",       XrmoptionSepArg, 0 },
102   { "-color-shift", ".color-shift", XrmoptionSepArg, 0 },
103   { "-radius",      ".radius",      XrmoptionSepArg, 0 },
104   { "-gray",        ".gray",        XrmoptionNoArg,  "True" },
105   { "-mono",        ".mono",        XrmoptionNoArg,  "True" },
106   { "-db",          ".doubleBuffer", XrmoptionNoArg,  "True" },
107   { "-no-db",       ".doubleBuffer", XrmoptionNoArg,  "False" },
108 #ifdef HAVE_XSHM_EXTENSION
109   { "-shm",     ".useSHM",      XrmoptionNoArg, "True" },
110   { "-no-shm",  ".useSHM",      XrmoptionNoArg, "False" },
111 #endif /*  HAVE_XSHM_EXTENSION */
112   { 0, 0, 0, 0 }
113 };
114
115 int options_size = (sizeof (options) / sizeof (XrmOptionDescRec));
116
117 struct inter_source {
118   int x; 
119   int y;
120   double x_theta;
121   double y_theta;
122 };
123
124 struct inter_context {
125   /*
126    * Display-related entries 
127    */
128   Display* dpy;
129   Window   win;
130
131 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
132   XdbeBackBuffer back_buf;
133 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
134   Pixmap   pix_buf;
135
136   GC       copy_gc;
137 #ifdef USE_XIMAGE
138   XImage  *ximage;
139 #endif /* USE_XIMAGE */
140
141 #ifdef HAVE_XSHM_EXTENSION
142   Bool use_shm;
143   XShmSegmentInfo shm_info;
144 #endif /* HAVE_XSHM_EXTENSION */
145
146   /*
147    * Resources
148    */
149   int count;
150   int grid_size;
151   int colors;
152   int speed;
153   int delay;
154   int shift;
155   int radius;
156
157   /*
158    * Drawing-related entries
159    */
160   int w;
161   int h;
162   Colormap cmap;
163   XColor* pal;
164   GC* gcs;
165
166   /*
167    * lookup tables
168    */
169   int* wave_height;
170     
171   /*
172    * Interference sources
173    */
174   struct inter_source* source;
175 };
176
177 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
178 # define TARGET(c) ((c)->back_buf ? (c)->back_buf : \
179                     (c)->pix_buf ? (c)->pix_buf : (c)->win)
180 #else  /* HAVE_DOUBLE_BUFFER_EXTENSION */
181 # define TARGET(c) ((c)->pix_buf ? (c)->pix_buf : (c)->win)
182 #endif /* !HAVE_DOUBLE_BUFFER_EXTENSION */
183
184 void inter_init(Display* dpy, Window win, struct inter_context* c) 
185 {
186   XWindowAttributes xgwa;
187   double H[3], S[3], V[3];
188   int i;
189   int mono;
190   int gray;
191   XGCValues val;
192   unsigned long valmask = 0;
193   Bool dbuf = get_boolean_resource ("doubleBuffer", "Boolean");
194
195   memset (c, 0, sizeof(*c));
196
197   c->dpy = dpy;
198   c->win = win;
199
200   XGetWindowAttributes(c->dpy, c->win, &xgwa);
201   c->w = xgwa.width;
202   c->h = xgwa.height;
203   c->cmap = xgwa.colormap;
204
205 #ifdef HAVE_XSHM_EXTENSION
206   c->use_shm = get_boolean_resource("useSHM", "Boolean");
207 #endif /*  HAVE_XSHM_EXTENSION */
208
209   if (dbuf)
210     {
211 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
212       c->back_buf = xdbe_get_backbuffer (c->dpy, c->win, XdbeUndefined);
213 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
214
215 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
216       if (!c->back_buf)
217 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
218         c->pix_buf = XCreatePixmap (dpy, win, xgwa.width, xgwa.height,
219                                     xgwa.depth);
220     }
221
222   val.function = GXcopy;
223   c->copy_gc = XCreateGC(c->dpy, TARGET(c), GCFunction, &val);
224
225   c->count = get_integer_resource("count", "Integer");
226   if(c->count < 1)
227     c->count = 1;
228   c->grid_size = get_integer_resource("gridsize", "Integer");
229   if(c->grid_size < 1)
230     c->grid_size = 1;
231   mono = get_boolean_resource("mono", "Boolean");
232   if(!mono) {
233     c->colors = get_integer_resource("ncolors", "Integer");
234     if(c->colors < 2)
235       c->colors = 2;
236   }
237   c->speed = get_integer_resource("speed", "Integer");
238   c->shift = get_float_resource("color-shift", "Float");
239   while(c->shift >= 360.0)
240     c->shift -= 360.0;
241   while(c->shift <= -360.0)
242     c->shift += 360.0;
243   c->radius = get_integer_resource("radius", "Integer");;
244   if(c->radius < 1)
245     c->radius = 1;
246
247 #ifdef USE_XIMAGE
248
249   c->ximage = 0;
250
251 # ifdef HAVE_XSHM_EXTENSION
252   if (c->use_shm)
253     {
254       c->ximage = create_xshm_image(dpy, xgwa.visual, xgwa.depth,
255                                     ZPixmap, 0, &c->shm_info,
256                                     xgwa.width, c->grid_size);
257       if (!c->ximage)
258         c->use_shm = False;
259     }
260 # endif /* HAVE_XSHM_EXTENSION */
261
262   if (!c->ximage)
263     {
264       c->ximage =
265         XCreateImage (dpy, xgwa.visual,
266                       xgwa.depth, ZPixmap, 0, 0, /* depth, fmt, offset, data */
267                       xgwa.width, c->grid_size,  /* width, height */
268                       8, 0);                     /* pad, bpl */
269       c->ximage->data = (unsigned char *)
270         calloc(c->ximage->height, c->ximage->bytes_per_line);
271     }
272 #endif /* USE_XIMAGE */
273
274   if(!mono) {
275     c->pal = calloc(c->colors, sizeof(XColor));
276
277     gray = get_boolean_resource("gray", "Boolean");
278     if(!gray) {
279       H[0] = frand(360.0); 
280       H[1] = H[0] + c->shift < 360.0 ? H[0]+c->shift : H[0] + c->shift-360.0; 
281       H[2] = H[1] + c->shift < 360.0 ? H[1]+c->shift : H[1] + c->shift-360.0; 
282       S[0] = S[1] = S[2] = 1.0;
283       V[0] = V[1] = V[2] = 1.0;
284     } else {
285       H[0] = H[1] = H[2] = 0.0;
286       S[0] = S[1] = S[2] = 0.0;
287       V[0] = 1.0; V[1] = 0.5; V[2] = 0.0;
288     }
289
290     make_color_loop(c->dpy, c->cmap, 
291                     H[0], S[0], V[0], 
292                     H[1], S[1], V[1], 
293                     H[2], S[2], V[2], 
294                     c->pal, &(c->colors), 
295                     True, False);
296     if(c->colors < 2) { /* color allocation failure */
297       mono = 1;
298       free(c->pal);
299     }
300   }
301
302   if(mono) { /* DON'T else this with the previous if! */
303     c->colors = 2;
304     c->pal = calloc(2, sizeof(XColor));
305     c->pal[0].pixel = BlackPixel(c->dpy, DefaultScreen(c->dpy));
306     c->pal[1].pixel = WhitePixel(c->dpy, DefaultScreen(c->dpy));
307   }    
308
309   valmask = GCForeground;
310   c->gcs = calloc(c->colors, sizeof(GC));
311   for(i = 0; i < c->colors; i++) {
312     val.foreground = c->pal[i].pixel;    
313     c->gcs[i] = XCreateGC(c->dpy, TARGET(c), valmask, &val);
314   }
315
316   c->wave_height = calloc(c->radius, sizeof(int));
317   for(i = 0; i < c->radius; i++) {
318     float max = 
319       ((float)c->colors) * 
320       ((float)c->radius - (float)i) /
321       ((float)c->radius);
322     c->wave_height[i] = 
323       (int)
324       ((max + max*cos((double)i/50.0)) / 2.0);
325   }
326
327   c->source = calloc(c->count, sizeof(struct inter_source));
328   for(i = 0; i < c->count; i++) {
329     c->source[i].x_theta = frand(2.0)*3.14159;
330     c->source[i].y_theta = frand(2.0)*3.14159;
331   }
332
333 }
334
335 #define source_x(c, i) \
336   (c->w/2 + ((int)(cos(c->source[i].x_theta)*((float)c->w/2.0))))
337 #define source_y(c, i) \
338   (c->h/2 + ((int)(cos(c->source[i].y_theta)*((float)c->h/2.0))))
339
340 /*
341  * this is rather suboptimal. the sqrt() doesn't seem to be a big
342  * performance hit, but all those separate XFillRectangle()'s are.
343  * hell, it's just a quick hack anyway -- if someone wishes to tune
344  * it, go ahead! 
345  */
346
347 void do_inter(struct inter_context* c) 
348 {
349   int i, j, k;
350   int result;
351   int dist;
352   int g;
353
354   int dx, dy;
355
356   for(i = 0; i < c->count; i++) {
357     c->source[i].x_theta += (c->speed/1000.0);
358     if(c->source[i].x_theta > 2.0*3.14159)
359       c->source[i].x_theta -= 2.0*3.14159;
360     c->source[i].y_theta += (c->speed/1000.0);
361     if(c->source[i].y_theta > 2.0*3.14159)
362       c->source[i].y_theta -= 2.0*3.14159;
363     c->source[i].x = source_x(c, i);
364     c->source[i].y = source_y(c, i);
365   }
366
367   g = c->grid_size;
368
369   for(j = 0; j < c->h/g; j++) {
370     for(i = 0; i < c->w/g; i++) {
371       result = 0;
372       for(k = 0; k < c->count; k++) {
373         dx = i*g + g/2 - c->source[k].x;
374         dy = j*g + g/2 - c->source[k].y;
375         dist = sqrt(dx*dx + dy*dy); /* what's the performance penalty here? */
376         result += (dist > c->radius ? 0 : c->wave_height[dist]);
377       }
378       result %= c->colors;
379
380 #ifdef USE_XIMAGE
381       /* Fill in these `gridsize' horizontal bits in the scanline */
382       for(k = 0; k < g; k++)
383         XPutPixel(c->ximage, (g*i)+k, 0, c->pal[result].pixel);
384
385 #else  /* !USE_XIMAGE */
386       XFillRectangle(c->dpy, TARGET(c), c->gcs[result], g*i, g*j, g, g); 
387 #endif /* !USE_XIMAGE */
388     }
389
390 #ifdef USE_XIMAGE
391
392     /* Only the first scanline of the image has been filled in; clone that
393        scanline to the rest of the `gridsize' lines in the ximage */
394     for(k = 0; k < (g-1); k++)
395       memcpy(c->ximage->data + (c->ximage->bytes_per_line * (k + 1)),
396              c->ximage->data + (c->ximage->bytes_per_line * k),
397              c->ximage->bytes_per_line);
398
399     /* Move the bits for this horizontal stripe to the server. */
400 # ifdef HAVE_XSHM_EXTENSION
401     if (c->use_shm)
402       XShmPutImage(c->dpy, TARGET(c), c->copy_gc, c->ximage,
403                    0, 0, 0, g*j, c->ximage->width, c->ximage->height,
404                    False);
405     else
406 # endif /*  HAVE_XSHM_EXTENSION */
407       XPutImage(c->dpy, TARGET(c), c->copy_gc, c->ximage,
408                 0, 0, 0, g*j, c->ximage->width, c->ximage->height);
409
410 #endif /* USE_XIMAGE */
411   }
412
413 #ifdef HAVE_DOUBLE_BUFFER_EXTENSION
414   if (c->back_buf)
415     {
416       XdbeSwapInfo info[1];
417       info[0].swap_window = c->win;
418       info[0].swap_action = XdbeUndefined;
419       XdbeSwapBuffers(c->dpy, info, 1);
420     }
421   else
422 #endif /* HAVE_DOUBLE_BUFFER_EXTENSION */
423     if (c->pix_buf)
424       {
425         XCopyArea (c->dpy, c->pix_buf, c->win, c->copy_gc,
426                    0, 0, c->w, c->h, 0, 0);
427       }
428
429   XSync(c->dpy, False);
430 }
431
432 void screenhack(Display *dpy, Window win) 
433 {
434   struct inter_context c;
435   int delay;
436
437   delay = get_integer_resource("delay", "Integer");
438
439   inter_init(dpy, win, &c);
440   while(1) {
441     do_inter(&c); 
442     screenhack_handle_events (dpy);
443     if(delay) usleep(delay);
444   }
445 }