http://ftp.x.org/contrib/applications/xscreensaver-3.23.tar.gz
[xscreensaver] / hacks / ripples.c
1 /* ripples, Copyright (c) 1999 Ian McConnell <ian@emit.demon.co.uk>
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 /*
13  * "Water" ripples that can cross and interfere with each other.
14  *
15  * I can't remember where I got this idea from, but it's been around for a
16  * while in various demos. Some inspiration from
17  *      water.txt by Tom Hammersley,tomh@globalnet.co.uk
18  *
19  * Options
20  * -delay       usleep every iteration
21  * -rate        Add one drop every "rate" iterations
22  * -box         Add big square splash every "box" iters (not very good)
23  * -water       Ripples on a grabbed background image
24  * -foreground  Interpolate ripples between these two colors
25  * -background
26  * -oily        Psychedelic colours like man
27  * -stir        Add a regular pattern of drops
28  * -fluidity    Between 0 and 16. 16 = big drops
29  * -light       Hack to add lighting effect
30  *
31  * Code mainly hacked from xflame and decayscreen.
32  */
33
34 /* Version history:
35  * 13 Oct 1999: Initial hack
36  * 30 Oct 1999: Speeded up graphics with dirty buffer. Returned to using
37  *              putpixel for greater portability
38  *              Added a variety of methods for splashing screen.
39  * 31 Oct 1999: Added in lighting hack
40  * 13 Nov 1999: Speed up tweaks
41  *              Adjust "light" for different bits per colour (-water only)
42  *
43  */
44
45
46 #include <math.h>
47 #include "screenhack.h"
48 #include <X11/Xutil.h>
49
50 typedef enum {ripple_drop, ripple_blob, ripple_box, ripple_stir} ripple_mode;
51
52 #ifdef HAVE_XSHM_EXTENSION
53 #include "xshm.h"
54 static Bool use_shm;
55 static XShmSegmentInfo shm_info;
56 #endif /* HAVE_XSHM_EXTENSION */
57
58 static Window window;
59 static Display *display;
60 static GC gc;
61 static Visual *visual;
62
63 static XImage *orig_map, *buffer_map;
64 static int ctab[256];
65 static Colormap colormap;
66 static int ncolors;
67 static int light;
68
69 static int width, height; /* ripple size */
70 static int bigwidth, bigheight; /* screen size */
71
72 static Bool transparent;
73 static short *bufferA, *bufferB, *temp;
74 static char *dirty_buffer;
75
76 #define TABLE 256
77 static double cos_tab[TABLE];
78
79 /* Distribution of drops: many little ones and a few big ones. */
80 static double drop_dist[] =
81 {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.6};
82
83 static void (*draw_transparent)(short *src);
84
85 /* How hard to hit the water */
86 #define SPLASH 512
87 #undef  MIN
88 #define MIN(x, y) ((x) < (y) ? (x) : (y))
89 #undef  MAX
90 #define MAX(x, y) ((x) > (y) ? (x) : (y))
91 #undef  DIRTY
92 #define DIRTY 3 /* dirty >= 2, 1 = restore original pixel, 0 = leave alone */
93
94 /* From fortune(6) */
95 /* -- really weird C code to count the number of bits in a word */
96 #define BITCOUNT(x)     (((BX_(x)+(BX_(x)>>4)) & 0x0F0F0F0F) % 255)
97 #define BX_(x)          ((x) - (((x)>>1)&0x77777777) \
98                              - (((x)>>2)&0x33333333) \
99                              - (((x)>>3)&0x11111111))
100
101
102 /*      -------------------------------------------             */
103
104
105 static int
106 map_color(int grey)
107 {
108   /* Clip it */
109   grey = ncolors * abs(grey) / (SPLASH/4);
110   if (grey > ncolors)
111     grey = ncolors;
112
113   /* Display it */
114   return ctab[grey];
115 }
116
117
118 static void
119 draw_ripple(short *src)
120 {
121   int across, down;
122   char *dirty = dirty_buffer;
123
124   for (down = 0; down < height - 1; down++, src += 1, dirty += 1)
125     for (across = 0; across < width - 1; across++, src++, dirty++) {
126       int v1, v2, v3, v4;
127       v1 = (int)*src;
128       v2 = (int)*(src + 1);
129       v3 = (int)*(src + width);
130       v4 = (int)*(src + width + 1);
131       if ((v1 == 0 && v2 == 0 && v3 == 0 && v4 == 0)) {
132         if (*dirty > 0)
133           (*dirty)--;
134       } else
135         *dirty = DIRTY;
136
137       if (*dirty > 0) {
138         int dx;
139         if (light > 0) {
140           dx = ((v3 - v1) + (v4 - v2)) << light; /* light from top */
141         } else
142           dx = 0;
143         XPutPixel(buffer_map,(across<<1),  (down<<1),  map_color(dx + v1));
144         XPutPixel(buffer_map,(across<<1)+1,(down<<1),  map_color(dx + ((v1 + v2) >> 1)));
145         XPutPixel(buffer_map,(across<<1),  (down<<1)+1,map_color(dx + ((v1 + v3) >> 1)));
146         XPutPixel(buffer_map,(across<<1)+1,(down<<1)+1,map_color(dx + ((v1 + v4) >> 1)));
147       }
148     }
149 }
150
151
152 /*      -------------------------------------------             */
153
154
155 /* Uses the horizontal gradient as an offset to create a warp effect  */
156 static void
157 draw_transparent_vanilla(short *src)
158 {
159   int across, down, pixel;
160   char *dirty = dirty_buffer;
161
162   pixel = 0;
163   for (down = 0; down < height - 2; down++, pixel += 2)
164     for (across = 0; across < width-2; across++, pixel++) {
165       int gradx, grady, gradx1, grady1;
166       int x0, x1, x2, y1, y2;
167
168       x0 = src[pixel];
169       x1 = src[pixel + 1];
170       x2 = src[pixel + 2];
171       y1 = src[pixel + width];
172       y2 = src[pixel + 2*width];
173
174       gradx = (x1 - x0);
175       grady = (y1 - x0);
176       gradx1= (x2 - x1);
177       grady1= (y2 - y1);
178       gradx1 = 1 + (gradx + gradx1) / 2;
179       grady1 = 1 + (grady + grady1) / 2;
180
181       if ((2*across+MIN(gradx,gradx1) < 0) ||
182           (2*across+MAX(gradx,gradx1) >= bigwidth)) {
183         gradx = 0;
184         gradx1= 1;
185       }
186       if ((2*down+MIN(grady,grady1) < 0) ||
187           (2*down+MAX(grady,grady1) >= bigheight)) {
188         grady = 0;
189         grady1 = 1;
190       }
191
192       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
193         if (dirty[pixel] > 0)
194           dirty[pixel]--;
195       } else
196         dirty[pixel] = DIRTY;
197
198       if (dirty[pixel] > 0) {
199         XPutPixel(buffer_map, (across<<1),  (down<<1),
200                   XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady));
201         XPutPixel(buffer_map, (across<<1)+1,(down<<1),
202                   XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady));
203         XPutPixel(buffer_map, (across<<1),  (down<<1)+1,
204                   XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady1));
205         XPutPixel(buffer_map, (across<<1)+1,(down<<1)+1,
206                   XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady1));
207       }
208     }
209 }
210
211
212 /*      -------------------------------------------             */
213
214
215 /* This builds on the above warp effect by adding in a lighting effect: */
216 /* brighten pixels by an amount corresponding to the vertical gradient */
217 static unsigned long rmask;
218 static unsigned long gmask;
219 static unsigned long bmask;
220 static int rshift;
221 static int gshift;
222 static int bshift;
223
224
225 static void
226 set_mask(unsigned long color, unsigned long *mask, int *shift)
227 {
228   *shift = 0;
229   while (color != 0 && (color & 1) == 0) {
230     (*shift)++;
231     color >>= 1;
232   }
233   *mask = color;
234 }
235
236
237 static unsigned long
238 cadd(unsigned long color, int dx, unsigned long mask, int shift)
239 {
240   int x;
241   color >>= shift;
242   x = (color & mask);
243   x += dx;
244   if (x < 0) x = 0;
245   else if (x > (int)mask) x = mask;
246   color = x;
247   return color << shift;
248 }
249
250
251 static unsigned long
252 bright(int dx, unsigned long color)
253 {
254   return (cadd(color, dx, rmask, rshift) |
255           cadd(color, dx, gmask, gshift) |
256           cadd(color, dx, bmask, bshift));
257 }
258
259
260 static void
261 draw_transparent_light(short *src)
262 {
263   int across, down, pixel;
264   char *dirty = dirty_buffer;
265
266   pixel = 0;
267   for (down = 0; down < height - 2; down++, pixel += 2)
268     for (across = 0; across < width-2; across++, pixel++) {
269       int gradx, grady, gradx1, grady1;
270       int x0, x1, x2, y1, y2;
271
272       x0 = src[pixel];
273       x1 = src[pixel + 1];
274       x2 = src[pixel + 2];
275       y1 = src[pixel + width];
276       y2 = src[pixel + 2*width];
277
278       gradx = (x1 - x0);
279       grady = (y1 - x0);
280       gradx1= (x2 - x1);
281       grady1= (y2 - y1);
282       gradx1 = 1 + (gradx + gradx1) / 2;
283       grady1 = 1 + (grady + grady1) / 2;
284
285       if ((2*across+MIN(gradx,gradx1) < 0) ||
286           (2*across+MAX(gradx,gradx1) >= bigwidth)) {
287         gradx = 0;
288         gradx1= 1;
289       }
290       if ((2*down+MIN(grady,grady1) < 0) ||
291           (2*down+MAX(grady,grady1) >= bigheight)) {
292         grady = 0;
293         grady1 = 1;
294       }
295
296       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
297         if (dirty[pixel] > 0)
298           dirty[pixel]--;
299       } else
300         dirty[pixel] = DIRTY;
301
302       if (dirty[pixel] > 0) {
303         int dx;
304
305         /* light from top */
306         if (4-light >= 0)
307           dx = (grady + (src[pixel+width+1]-x1)) >> (4-light);
308         else
309           dx = (grady + (src[pixel+width+1]-x1)) << (light-4);
310
311         if (dx != 0) {
312           XPutPixel(buffer_map, (across<<1),  (down<<1),
313                     bright(dx, XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady)));
314           XPutPixel(buffer_map, (across<<1)+1,(down<<1),
315                     bright(dx, XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady)));
316           XPutPixel(buffer_map, (across<<1),  (down<<1)+1,
317                     bright(dx, XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady1)));
318           XPutPixel(buffer_map, (across<<1)+1,(down<<1)+1,
319                     bright(dx, XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady1)));
320         } else {
321           /* Could use XCopyArea, but XPutPixel is faster */
322           XPutPixel(buffer_map, (across<<1),  (down<<1),
323                     XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady));
324           XPutPixel(buffer_map, (across<<1)+1,(down<<1),
325                     XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady));
326           XPutPixel(buffer_map, (across<<1),  (down<<1)+1,
327                     XGetPixel(orig_map, (across<<1) + gradx, (down<<1) + grady1));
328           XPutPixel(buffer_map, (across<<1)+1,(down<<1)+1,
329                     XGetPixel(orig_map, (across<<1) + gradx1,(down<<1) + grady1));
330         }
331       }
332     }
333 }
334
335
336 /*      -------------------------------------------             */
337
338
339 #if 0
340 /* Doesn't go any faster and doesn't work at all colour depths */
341 static void
342 draw_transparent16l(short *src)
343 {
344   int across, down, bigpix, pixel;
345   char *dirty = dirty_buffer;
346   unsigned short *buffer, *orig;
347
348   buffer = (unsigned short *) buffer_map->data;
349   orig = (unsigned short *) orig_map->data;
350
351   for (pixel = bigpix = down = 0;
352        down < height - 2;
353        down++, pixel += 2, bigpix += bigwidth+4)
354     for (across = 0; across < width-2; across++, pixel++, bigpix+=2) {
355       int gradx, grady, gradx1, grady1;
356       int x0, x1, x2, y1, y2;
357
358       x0 = src[pixel];
359       x1 = src[pixel + 1];
360       x2 = src[pixel + 2];
361       y1 = src[pixel + width];
362       y2 = src[pixel + 2*width];
363
364       gradx = (x1 - x0);
365       grady = (y1 - x0);
366       gradx1= (x2 - x1);
367       grady1= (y2 - y1);
368       gradx1 = 1 + (gradx + gradx1) / 2;
369       grady1 = 1 + (grady + grady1) / 2;
370
371       if ((2*across+MIN(gradx,gradx1) < 0) ||
372           (2*across+MAX(gradx,gradx1) >= bigwidth)) {
373         gradx = 0;
374         gradx1= 1;
375       }
376       if ((2*down+MIN(grady,grady1) < 0) ||
377           (2*down+MAX(grady,grady1) >= bigheight)) {
378         grady = 0;
379         grady1 = 1;
380       }
381
382       if ((gradx == 0 && gradx1 == 1 && grady == 0 && grady1 == 1)) {
383         if (dirty[pixel] > 0)
384           dirty[pixel]--;
385       } else
386         dirty[pixel] = DIRTY;
387
388       if (dirty[pixel] > 0) {
389         unsigned short *dest = buffer + bigpix;
390         unsigned short *image = orig + bigpix;
391         int dx;
392
393         /* light from top */
394         if (4-light >= 0)
395           dx = (grady + (src[pixel+width+1]-x1)) >> (4-light);
396         else
397           dx = (grady + (src[pixel+width+1]-x1)) << (light-4);
398
399         grady *= bigwidth;
400         grady1*= bigwidth;
401
402         if (dx != 0) {
403           *dest++ = dobright(dx, *(image + gradx  + grady));
404           *dest   = dobright(dx, *(image + gradx1 + grady));
405           dest   += bigwidth - 1;
406           *dest++ = dobright(dx, *(image + gradx  + grady1));
407           *dest   = dobright(dx, *(image + gradx1 + grady1));
408         } else {
409           *dest++ = *(image + gradx  + grady);
410           *dest   = *(image + gradx1 + grady);
411           dest   += bigwidth - 1;
412           *dest++ = *(image + gradx  + grady1);
413           *dest   = *(image + gradx1 + grady1);
414         }
415       }
416     }
417 }
418 #endif
419
420
421 /*      -------------------------------------------             */
422
423
424 static void
425 setup_X(Display * disp, Window win)
426 {
427   XWindowAttributes xwa;
428   int depth;
429
430   XGetWindowAttributes(disp, win, &xwa);
431   window = win;
432   display = disp;
433   depth = xwa.depth;
434   colormap = xwa.colormap;
435   bigwidth = xwa.width;
436   bigheight = xwa.height;
437   visual = xwa.visual;
438
439 #if 1 /* I'm not entirely sure if I need this */
440   if (bigwidth % 2)
441     bigwidth++;
442   if (bigheight % 2)
443     bigheight++;
444 #endif
445   width = bigwidth / 2;
446   height = bigheight / 2;
447
448   if (transparent) {
449     XGCValues gcv;
450     long gcflags;
451
452     gcv.function = GXcopy;
453     gcv.subwindow_mode = IncludeInferiors;
454
455     gcflags = GCForeground | GCFunction;
456     if (use_subwindow_mode_p(xwa.screen, window))       /* see grabscreen.c */
457       gcflags |= GCSubwindowMode;
458
459     gc = XCreateGC(display, window, gcflags, &gcv);
460
461     grab_screen_image(xwa.screen, window);
462
463     orig_map = XGetImage(display, window, 0, 0, xwa.width, xwa.height,
464                          ~0L, ZPixmap);
465   } else {
466     XGCValues gcv;
467
468     gc = XCreateGC(display, window, 0, &gcv);
469     orig_map = 0;
470   }
471
472   if (!gc) {
473     fprintf(stderr, "XCreateGC failed\n");
474     exit(1);
475   }
476
477   buffer_map = 0;
478
479 #ifdef HAVE_XSHM_EXTENSION
480   if (use_shm) {
481     buffer_map = create_xshm_image(display, xwa.visual, depth,
482                                    ZPixmap, 0, &shm_info, bigwidth, bigheight);
483     if (!buffer_map) {
484       use_shm = False;
485       fprintf(stderr, "create_xshm_image failed\n");
486     }
487   }
488 #endif /* HAVE_XSHM_EXTENSION */
489
490   if (!buffer_map) {
491     buffer_map = XCreateImage(display, xwa.visual,
492                               depth, ZPixmap, 0, 0,
493                               bigwidth, bigheight, 8, 0);
494     buffer_map->data = (char *)
495       calloc(buffer_map->height, buffer_map->bytes_per_line);
496   }
497 }
498
499
500 static void
501 DisplayImage(void)
502 {
503 #ifdef HAVE_XSHM_EXTENSION
504   if (use_shm)
505     XShmPutImage(display, window, gc, buffer_map, 0, 0, 0, 0,
506                  bigwidth, bigheight, False);
507   else
508 #endif /* HAVE_XSHM_EXTENSION */
509     XPutImage(display, window, gc, buffer_map, 0, 0, 0, 0,
510               bigwidth, bigheight);
511
512   XSync(display,False);
513   screenhack_handle_events(display);
514 }
515
516
517 /*      -------------------------------------------             */
518
519
520 static int
521 cinterp(double a, int bg, int fg)
522 {
523   int result;
524   result = (int)((1-a) * bg + a * fg + 0.5);
525   if (result < 0) result = 0;
526   if (result > 255) result = 255;
527   return result;
528 }
529
530
531 /* Interpolate the ripple colours between the background colour and
532    foreground colour */
533 static void
534 init_linear_colors(void)
535 {
536   int i, j, red, green, blue, bred, bgreen, bblue;
537   XColor fg, bg;
538
539   if (ncolors < 2 || mono_p)
540     ncolors = 2;
541   if (ncolors <= 2)
542     mono_p = True;
543
544   /* Make it possible to set the color of the ripples,
545      Based on work by Raymond Medeiros <ray@stommel.marine.usf.edu> and jwz.
546    */
547   fg.pixel = get_pixel_resource("foreground", "Foreground",
548                                 display, colormap);
549   XQueryColor(display, colormap, &fg);
550   red = (fg.red >> 8);
551   green = (fg.green >> 8);
552   blue = (fg.blue >> 8);
553
554   bg.pixel = get_pixel_resource("background", "Background",
555                                 display, colormap);
556   XQueryColor(display, colormap, &bg);
557   bred = (bg.red >> 8);
558   bgreen = (bg.green >> 8);
559   bblue = (bg.blue >> 8);
560
561   j = 0;
562   for (i = 0; i < ncolors+1; i++) {
563     XColor xcl;
564     double a = (double)i / ncolors;
565     int r = cinterp(a, bred, red);
566     int g = cinterp(a, bgreen, green);
567     int b = cinterp(a, bblue, blue);
568
569     xcl.red = (unsigned short) ((r << 8) | r);
570     xcl.green = (unsigned short) ((g << 8) | g);
571     xcl.blue = (unsigned short) ((b << 8) | b);
572     xcl.flags = DoRed | DoGreen | DoBlue;
573
574     XAllocColor(display, colormap, &xcl);
575
576     ctab[j++] = (int) xcl.pixel;
577   }
578 }
579
580
581 static void
582 init_oily_colors(void)
583 {
584   XColor *colors = NULL;
585
586   if (ncolors < 2 || mono_p)
587     ncolors = 2;
588   if (ncolors <= 2)
589     mono_p = True;
590   colors = 0;
591
592   if (!mono_p) {
593     colors = (XColor *)malloc(sizeof(*colors) * (ncolors+1));
594     make_smooth_colormap(display, visual, colormap, colors, &ncolors,
595                          True, /* allocate */
596                          False, /* not writable */
597                          True); /* verbose (complain about failure) */
598     if (ncolors <= 2) {
599       if (colors)
600         free (colors);
601       colors = 0;
602       mono_p = True;
603     }
604   }
605   if (!mono_p) {
606     int i, j = 0;
607     for (i = 0; i < ncolors+1; i++) {
608       XAllocColor(display, colormap, colors+i);
609       ctab[j++] = (int) colors[i].pixel;
610     }
611     free (colors);
612   } else {
613     ncolors = 2;
614     ctab[1] = get_pixel_resource("foreground", "Foreground", display, colormap);
615     ctab[0] = get_pixel_resource("background", "Background", display, colormap);
616   }
617 }
618
619
620 /*      -------------------------------------------             */
621
622
623 static void
624 init_cos_tab(void)
625 {
626   int i;
627   for (i = 0; i < TABLE; i++)
628     cos_tab[i] = cos(i * M_PI/2 / TABLE);
629 }
630
631
632 /* Shape of drop to add */
633 static double
634 sinc(double x)
635 {
636 #if 1
637   /* cosine hump */
638   int i;
639   i = (int)(x * TABLE + 0.5);
640   if (i >= TABLE) i = (TABLE-1) - (i-(TABLE-1));
641   return cos_tab[i];
642 #elif 0
643   return cos(x * M_PI/2);
644 #else
645   if (fabs(x) < 0.1)
646     return 1 - x*x;
647   else
648     return sin(x) / x;
649 #endif
650 }
651
652
653 static void
654 add_circle_drop(int x, int y, int radius, int dheight)
655 {
656   int i, r2, cx, cy;
657   short *buf = (random()&1) ? bufferA : bufferB;
658
659   i = y * width + x;
660   r2 = radius * radius;
661
662   for (cy = -radius; cy <= radius; cy++)
663     for (cx = -radius; cx <= radius; cx++) {
664       int r = cx*cx + cy*cy;
665       if (r <= r2) {
666         buf[i + cx + cy*width] =
667           (short)(dheight * sinc(sqrt(r)/radius));
668       }
669     }
670 }
671
672
673 static void
674 add_drop(ripple_mode mode, int drop)
675 {
676   int newx, newy, dheight;
677   int radius = MIN(width, height) / 50;
678   /* Don't put drops too near the edge of the screen or they get stuck */
679   int border = 8;
680
681   switch (mode) {
682   default:
683   case ripple_drop: {
684     int x;
685
686     dheight = 1 + (random() % drop);
687     newx = border + (random() % (width - 2*border));
688     newy = border + (random() % (height - 2*border));
689     x = newy * width + newx;
690     bufferA[x + 1] = bufferA[x] = bufferA[x + width] = bufferA[x + width + 1] =
691       bufferB[x + 1] = bufferB[x] = bufferB[x + width] = bufferB[x + width + 1] =
692       dheight;
693   }
694   break;
695   case ripple_blob: {
696     double power;
697
698     power = drop_dist[random() % (sizeof(drop_dist)/sizeof(drop_dist[0]))]; /* clumsy */
699     dheight = (int)(drop * (power + 0.01));
700     newx = radius + border + (random() % (int)(width - 2*border - 2*radius*power));
701     newy = radius + border + (random() % (int)(height - 2*border - 2*radius*power));
702     add_circle_drop(newx, newy, radius, dheight);
703   }
704   break;
705   /* Adding too many boxes too quickly (-box 1) doesn't give the waves time
706      to disperse and the waves build up (and overflow) */
707   case ripple_box: {
708     int x;
709     int cx, cy;
710     short *buf = (random()&1) ? bufferA : bufferB;
711
712     radius = (1 + (random() % 5)) * (1 + (random() % 5));
713     dheight = drop / 128;
714     if (random() & 1) dheight = -dheight;
715     newx = radius + border + (random() % (width - 2*border - 2*radius));
716     newy = radius + border + (random() % (height - 2*border - 2*radius));
717     x = newy * width + newx;
718     for (cy = -radius; cy <= radius; cy++)
719       for (cx = -radius; cx <= radius; cx++)
720         buf[x + cx + cy*width] = (short)(dheight);
721   }
722   break;
723   case ripple_stir: {
724     static double ang = 0;
725     border += radius;
726     newx = border + (int)((width-2*border) * (1+cos(3*ang)) / 2);
727     newy = border + (int)((height-2*border) * (1+sin(2*ang)) / 2);
728     add_circle_drop(newx, newy, radius, drop / 10);
729     ang += 0.02;
730     if (ang > 12*M_PI) ang = 0;
731   }
732   break;
733   }
734 }
735
736
737 static void
738 init_ripples(int ndrops, int splash)
739 {
740   int i;
741
742   bufferA = (short *)calloc(width * height, sizeof(*bufferA));
743   bufferB = (short *)calloc(width * height, sizeof(*bufferB));
744   temp = (short *)calloc(width * height, sizeof(*temp));
745
746   dirty_buffer = (char *)calloc(width * height, sizeof(*dirty_buffer));
747
748   for (i = 0; i < ndrops; i++)
749     add_drop(ripple_blob, splash);
750
751   if (transparent) {
752     /* There's got to be a better way of doing this  XCopyArea? */
753     memcpy(buffer_map->data, orig_map->data,
754            bigheight * buffer_map->bytes_per_line);
755   } else {
756     int across, down, color;
757
758     color = map_color(0); /* background colour */
759     for (down = 0; down < bigheight; down++)
760       for (across = 0; across < bigwidth; across++)
761         XPutPixel(buffer_map,across,  down,  color);
762   }
763
764   DisplayImage();
765 }
766
767
768 /*
769  Explanation from hq_water.zip (Arturo R Montesinos (ARM) arami@fi.upm.es)
770
771  Differential equation is:  u  = a ( u  + u  )
772                              tt       xx   yy
773
774  Where a = tension * gravity / surface_density.
775
776  Approximating second derivatives by central differences:
777
778   [ u(t+1)-2u(t)+u(t-1) ] / dt = a [ u(x+1)+u(x-1)+u(y+1)+u(y-1)-4u ] / h
779
780  where dt = time step squared, h = dx*dy = mesh resolution squared.
781
782  From where u(t+1) may be calculated as:
783
784             dt  |   1   |                   dt
785  u(t+1) = a --  | 1 0 1 |u - u(t-1) + (2-4a --)u
786             h   |   1   |                    h
787
788  When a*dt/h = 1/2 last term vanishes, giving:
789
790                  1 |   1   |
791         u(t+1) = - | 1 0 1 |u - u(t-1)
792                  2 |   1   |
793
794  (note that u(t-1,x,y) is only used to calculate u(t+1,x,y) so
795   we can use the same array for both t-1 and t+1, needing only
796   two arrays, U[0] and U[1])
797
798  Dampening is simulated by subtracting 1/2^n of result.
799  n=4 gives best-looking result
800  n<4 (eg 2 or 3) thicker consistency, waves die out immediately
801  n>4 (eg 8 or 12) more fluid, waves die out slowly
802  */
803
804 static void
805 ripple(int fluidity)
806 {
807   int across, down, pixel;
808   static int toggle;
809   static int count;
810   short *src, *dest;
811
812   if (toggle == 0) {
813     src = bufferA;
814     dest = bufferB;
815     toggle = 1;
816   } else {
817     src = bufferB;
818     dest = bufferA;
819     toggle = 0;
820   }
821
822   switch (count) {
823   case 0: case 1:
824     pixel = 1 * width + 1;
825     for (down = 1; down < height - 1; down++, pixel += 2 * 1)
826       for (across = 1; across < width - 1; across++, pixel++) {
827         temp[pixel] =
828           (((src[pixel - 1] + src[pixel + 1] +
829              src[pixel - width] + src[pixel + width]) / 2)) - dest[pixel];
830       }
831
832     /* Smooth the output */
833     pixel = 1 * width + 1;
834     for (down = 1; down < height - 1; down++, pixel += 2 * 1)
835       for (across = 1; across < width - 1; across++, pixel++) {
836         if (temp[pixel] != 0) { /* Close enough for government work */
837           int damp =
838             (temp[pixel - 1] + temp[pixel + 1] +
839              temp[pixel - width] + temp[pixel + width] +
840              temp[pixel - width - 1] + temp[pixel - width + 1] +
841              temp[pixel + width - 1] + temp[pixel + width + 1] +
842              temp[pixel]) / 9;
843           dest[pixel] = damp - (damp >> fluidity);
844         } else
845           dest[pixel] = 0;
846       }
847     break;
848   case 2: case 3:
849     pixel = 1 * width + 1;
850     for (down = 1; down < height - 1; down++, pixel += 2 * 1)
851       for (across = 1; across < width - 1; across++, pixel++) {
852         int damp =
853           (((src[pixel - 1] + src[pixel + 1] +
854              src[pixel - width] + src[pixel + width]) / 2)) - dest[pixel];
855         dest[pixel] = damp - (damp >> fluidity);
856       }
857     break;
858   }
859   if (++count > 3) count = 0;
860
861   if (transparent)
862     draw_transparent(dest);
863   else
864     draw_ripple(dest);
865 }
866
867
868 /*      -------------------------------------------             */
869
870
871 char *progclass = "Ripples";
872
873 char *defaults[] =
874 {
875   ".background:         black",
876   ".foreground:         #FFAF5F",
877   "*colors:             200",
878   "*dontClearRoot:      True",
879   "*delay:              50000",
880   "*rate:               5",
881   "*box:                0",
882   "*water:              False",
883   "*oily:               False",
884   "*stir:               False",
885   "*fluidity:           6",
886   "*light:              0",
887 #ifdef HAVE_XSHM_EXTENSION
888   "*useSHM: True",
889 #endif                          /* HAVE_XSHM_EXTENSION */
890   0
891 };
892
893 XrmOptionDescRec options[] =
894 {
895   { "-colors",  ".colors",      XrmoptionSepArg, 0},
896   { "-colours", ".colors",      XrmoptionSepArg, 0},
897   {"-delay",    ".delay",       XrmoptionSepArg, 0},
898   {"-rate",     ".rate",        XrmoptionSepArg, 0},
899   {"-box",      ".box",         XrmoptionSepArg, 0},
900   {"-water",    ".water",       XrmoptionNoArg, "True"},
901   {"-oily",     ".oily",        XrmoptionNoArg, "True"},
902   {"-stir",     ".stir",        XrmoptionNoArg, "True"},
903   {"-fluidity", ".fluidity",    XrmoptionSepArg, 0},
904   {"-light",    ".light",       XrmoptionSepArg, 0},
905 #ifdef HAVE_XSHM_EXTENSION
906   {"-shm",      ".useSHM",      XrmoptionNoArg, "True"},
907   {"-no-shm",   ".useSHM",      XrmoptionNoArg, "False"},
908 #endif                          /* HAVE_XSHM_EXTENSION */
909   {0, 0, 0, 0}
910 };
911
912
913 void screenhack(Display *disp, Window win)
914 {
915   int iterations = 0;
916   int delay = get_integer_resource("delay", "Integer");
917   int rate = get_integer_resource("rate", "Integer");
918   int box = get_integer_resource("box", "Integer");
919   int oily = get_boolean_resource("oily", "Boolean");
920   int stir = get_boolean_resource("stir", "Boolean");
921   int fluidity = get_integer_resource("fluidity", "Integer");
922   transparent = get_boolean_resource("water", "Boolean");
923 #ifdef HAVE_XSHM_EXTENSION
924   use_shm = get_boolean_resource("useSHM", "Boolean");
925 #endif /* HAVE_XSHM_EXTENSION */
926   light = get_integer_resource("light", "Integer");
927
928   if (fluidity <= 1) fluidity = 1;
929   if (fluidity > 16) fluidity = 16; /* 16 = sizeof(short) */
930   if (light < 0) light = 0;
931
932   init_cos_tab();
933   setup_X(disp, win);
934
935   ncolors = get_integer_resource ("colors", "Colors");
936   if (0 == ncolors)             /* English spelling? */
937     ncolors = get_integer_resource ("colours", "Colors");
938
939   if (ncolors > sizeof(ctab)/sizeof(*ctab))
940     ncolors = sizeof(ctab)/sizeof(*ctab);
941
942   if (oily)
943     init_oily_colors();
944   else
945     init_linear_colors();
946
947   if (transparent && light > 0) {
948     int maxbits;
949     draw_transparent = draw_transparent_light;
950     set_mask(visual->red_mask,   &rmask, &rshift);
951     set_mask(visual->green_mask, &gmask, &gshift);
952     set_mask(visual->blue_mask,  &bmask, &bshift);
953     if (rmask == 0) draw_transparent = draw_transparent_vanilla;
954
955     /* Adjust the shift value "light" when we don't have 8 bits per colour */
956     maxbits = MIN(MIN(BITCOUNT(rmask), BITCOUNT(gmask)), BITCOUNT(bmask));
957     light -= 8-maxbits;
958     if (light < 0) light = 0;
959   } else
960     draw_transparent = draw_transparent_vanilla;
961
962   init_ripples(0, -SPLASH); /* Start off without any drops */
963
964   /* Main drawing loop */
965   while (1) {
966     if (rate > 0 && (iterations % rate) == 0)
967       add_drop(ripple_blob, -SPLASH);
968     if (stir)
969       add_drop(ripple_stir, -SPLASH);
970     if (box > 0 && (random() % box) == 0)
971       add_drop(ripple_box, -SPLASH);
972
973     ripple(fluidity);
974     DisplayImage();
975
976     if (delay)
977       usleep(delay);
978
979     iterations++;
980   }
981 }