From http://www.jwz.org/xscreensaver/xscreensaver-5.30.tar.gz
[xscreensaver] / hacks / distort.c
1 /* -*- mode: C; tab-width: 4 -*-
2  * xscreensaver, Copyright (c) 1992-2014 Jamie Zawinski <jwz@jwz.org>
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and its
5  * documentation for any purpose is hereby granted without fee, provided that
6  * the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation.  No representations are made about the suitability of this
9  * software for any purpose.  It is provided "as is" without express or 
10  * implied warranty.
11  */
12
13 /* distort
14  * by Jonas Munsin (jmunsin@iki.fi) and Jamie Zawinski <jwz@jwz.org>
15  * TODO:
16  *      -check the allocations in init_round_lense again, maybe make it possible again
17  *       to use swamp without pre-allocating/calculating (although that
18  *       makes it slower) - -swamp is memory hungry
19  *      -more distortion matrices (fortunately, I'm out of ideas :)
20  * Stuff that would be cool but probably too much of a resource hog:
21  *      -some kind of interpolation to avoid jaggies
22  *    -large speed values leaves the image distorted
23  * program idea borrowed from a screensaver on a non-*NIX OS,
24  *
25  * 28 Sep 1999 Jonas Munsin (jmunsin@iki.fi)
26  *    Added about 10x faster algortim for 8, 16 and 32 bpp (modifies pixels
27  *    directly avoiding costly XPutPixle(XGetPixel()) calls, inspired by
28  *    xwhirl made by horvai@clipper.ens.fr (Peter Horvai) and the XFree86
29  *    Xlib sources.
30  *    This piece of code is really horrible, but it works, and at the moment
31  *    I don't have time or inspiration to fix something that works (knock
32  *    on wood).
33  * 08 Oct 1999 Jonas Munsin (jmunsin@iki.fi)
34  *      Corrected several bugs causing references beyond allocated memory.
35  */
36
37 #include <math.h>
38 #include "screenhack.h"
39 /*#include <X11/Xmd.h>*/
40
41 #ifdef HAVE_XSHM_EXTENSION
42 # include "xshm.h"
43 #endif /* HAVE_XSHM_EXTENSION */
44
45 #define CARD32 unsigned int
46 #define CARD16 unsigned short
47 #define CARD8  unsigned char
48
49
50 struct coo {
51         int x;
52         int y;
53         int r, r_change;
54         int xmove, ymove;
55 };
56
57 struct state {
58   Display *dpy;
59   Window window;
60
61   struct coo xy_coo[10];
62
63   int delay, radius, speed, number, blackhole, vortex, magnify, reflect, slow;
64   int duration;
65   time_t start_time;
66
67   XWindowAttributes xgwa;
68   GC gc;
69   unsigned long black_pixel;
70
71   XImage *orig_map, *buffer_map;
72   unsigned long *buffer_map_cache;
73
74   int ***from;
75   int ****from_array;
76   int *fast_from;
77
78   int bpp_size;
79
80 #ifdef HAVE_XSHM_EXTENSION
81   Bool use_shm;
82   XShmSegmentInfo shm_info;
83 #endif /* HAVE_XSHM_EXTENSION */
84
85   void (*effect) (struct state *, int);
86   void (*draw) (struct state *, int);
87   void (*draw_routine) (struct state *st, XImage *, XImage *, int, int, int *);
88
89   async_load_state *img_loader;
90 };
91
92
93 static void move_lense(struct state *, int);
94 static void swamp_thing(struct state *, int);
95 static void new_rnd_coo(struct state *, int);
96 static void init_round_lense(struct state *st);
97 static void reflect_draw(struct state *, int);
98 static void plain_draw(struct state *, int);
99
100 static void fast_draw_8 (struct state *st, XImage *, XImage *, int, int, int *);
101 static void fast_draw_16(struct state *st, XImage *, XImage *, int, int, int *);
102 static void fast_draw_32(struct state *st, XImage *, XImage *, int, int, int *);
103 static void generic_draw(struct state *st, XImage *, XImage *, int, int, int *);
104
105
106 static void distort_finish_loading (struct state *);
107
108 static void
109 distort_reset (struct state *st)
110 {
111     char *s;
112     int i;
113
114     st->start_time = 0;
115
116         XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
117
118         st->delay = get_integer_resource(st->dpy, "delay", "Integer");
119     st->duration = get_integer_resource (st->dpy, "duration", "Seconds");
120         st->radius = get_integer_resource(st->dpy, "radius", "Integer");
121         st->speed = get_integer_resource(st->dpy, "speed", "Integer");
122         st->number = get_integer_resource(st->dpy, "number", "Integer");
123
124         st->blackhole = get_boolean_resource(st->dpy, "blackhole", "Boolean");
125         st->vortex = get_boolean_resource(st->dpy, "vortex", "Boolean");
126         st->magnify = get_boolean_resource(st->dpy, "magnify", "Boolean");
127         st->reflect = get_boolean_resource(st->dpy, "reflect", "Boolean");
128         st->slow = get_boolean_resource(st->dpy, "slow", "Boolean");
129         
130     if (st->delay < 0) st->delay = 0;
131     if (st->duration < 1) st->duration = 1;
132
133     st->effect = NULL;
134     s = get_string_resource(st->dpy, "effect", "String");
135         if (s && !strcasecmp(s,"swamp"))
136       st->effect = &swamp_thing;
137     else if (s && !strcasecmp(s,"bounce"))
138       st->effect = &move_lense;
139     else if (s && !strcasecmp(s,"none"))
140       ;
141     else if (s && *s)
142       fprintf(stderr,"%s: bogus effect: %s\n", progname, s);
143
144         if (st->effect == NULL && st->radius == 0 && st->speed == 0 && st->number == 0
145                 && !st->blackhole && !st->vortex && !st->magnify && !st->reflect) {
146 /* if no cmdline options are given, randomly choose one of:
147  * -radius 125 -number 4 -speed 1 -bounce
148  * -radius 125 -number 4 -speed 1 -blackhole
149  * -radius 125 -number 4 -speed 1 -vortex
150  * -radius 125 -number 4 -speed 1 -vortex -magnify
151  * -radius 125 -number 4 -speed 1 -vortex -magnify -blackhole
152  * -radius 250 -number 1 -speed 2 -bounce
153  * -radius 250 -number 1 -speed 2 -blackhole
154  * -radius 250 -number 1 -speed 2 -vortex
155  * -radius 250 -number 1 -speed 2 -vortex -magnify
156  * -radius 250 -number 1 -speed 2 -vortex -magnify -blackhole
157  * -radius 80 -number 1 -speed 2 -reflect
158  * -radius 125 -number 3 -speed 2 -reflect
159  * jwz: not these
160  *   -radius 125 -number 4 -speed 2 -swamp
161  *   -radius 125 -number 4 -speed 2 -swamp -blackhole
162  *   -radius 125 -number 4 -speed 2 -swamp -vortex
163  *   -radius 125 -number 4 -speed 2 -swamp -vortex -magnify
164  *   -radius 125 -number 4 -speed 2 -swamp -vortex -magnify -blackhole
165  */
166                 
167                 i = (random() % 12 /* 17 */);
168
169                 st->draw = &plain_draw;
170
171                 switch (i) {
172                         case 0:
173                                 st->radius=125;st->number=4;st->speed=1;
174                                 st->effect=&move_lense;break;
175                         case 1:
176                                 st->radius=125;st->number=4;st->speed=1;st->blackhole=1;
177                                 st->effect=&move_lense;break;
178                         case 2:
179                                 st->radius=125;st->number=4;st->speed=1;st->vortex=1;
180                                 st->effect=&move_lense;break;
181                         case 3:
182                                 st->radius=125;st->number=4;st->speed=1;st->vortex=1;st->magnify=1;
183                                 st->effect=&move_lense;break;
184                         case 4:
185                                 st->radius=125;st->number=4;st->speed=1;st->vortex=1;st->magnify=1;st->blackhole=1;
186                                 st->effect=&move_lense;break;
187                         case 5:
188                                 st->radius=250;st->number=1;st->speed=2;
189                                 st->effect=&move_lense;break;
190                         case 6:
191                                 st->radius=250;st->number=1;st->speed=2;st->blackhole=1;
192                                 st->effect=&move_lense;break;
193                         case 7:
194                                 st->radius=250;st->number=1;st->speed=2;st->vortex=1;
195                                 st->effect=&move_lense;break;
196                         case 8:
197                                 st->radius=250;st->number=1;st->speed=2;st->vortex=1;st->magnify=1;
198                                 st->effect=&move_lense;break;
199                         case 9:
200                                 st->radius=250;st->number=1;st->speed=2;st->vortex=1;st->magnify=1;st->blackhole=1;
201                                 st->effect=&move_lense;break;
202
203                         case 10:
204                                 st->radius=80;st->number=1;st->speed=2;st->reflect=1;
205                                 st->draw = &reflect_draw;st->effect = &move_lense;break;
206                         case 11:
207                                 st->radius=125;st->number=4;st->speed=2;st->reflect=1;
208                                 st->draw = &reflect_draw;st->effect = &move_lense;break;
209
210 #if 0 /* jwz: not these */
211                         case 12:
212                                 st->radius=125;st->number=4;st->speed=2;
213                                 effect=&swamp_thing;break;
214                         case 13:
215                                 st->radius=125;st->number=4;st->speed=2;st->blackhole=1;
216                                 effect=&swamp_thing;break;
217                         case 14:
218                                 st->radius=125;st->number=4;st->speed=2;st->vortex=1;
219                                 effect=&swamp_thing;break;
220                         case 15:
221                                 st->radius=125;st->number=4;st->speed=2;st->vortex=1;st->magnify=1;
222                                 effect=&swamp_thing;break;
223                         case 16:
224                                 st->radius=125;st->number=4;st->speed=2;st->vortex=1;st->magnify=1;st->blackhole=1;
225                                 effect=&swamp_thing;break;
226 #endif
227
228             default:
229                 abort(); break;
230                 }
231         }
232
233     /* never allow the radius to be too close to the min window dimension
234      */
235     if (st->radius > st->xgwa.width  * 0.3) st->radius = st->xgwa.width  * 0.3;
236     if (st->radius > st->xgwa.height * 0.3) st->radius = st->xgwa.height * 0.3;
237
238
239     /* -swamp mode consumes vast amounts of memory, proportional to radius --
240        so throttle radius to a small-ish value (60 => ~30MB.)
241      */
242     if (st->effect == &swamp_thing && st->radius > 60)
243       st->radius = 60;
244
245         if (st->delay < 0)
246                 st->delay = 0;
247         if (st->radius <= 0)
248                 st->radius = 60;
249         if (st->speed <= 0) 
250                 st->speed = 2;
251         if (st->number <= 0)
252                 st->number=1;
253         if (st->number >= 10)
254                 st->number=1;
255         if (st->effect == NULL)
256                 st->effect = &move_lense;
257         if (st->reflect) {
258                 st->draw = &reflect_draw;
259                 st->effect = &move_lense;
260         }
261         if (st->draw == NULL)
262                 st->draw = &plain_draw;
263 }
264
265 static void *
266 distort_init (Display *dpy, Window window)
267 {
268   struct state *st = (struct state *) calloc (1, sizeof(*st));
269         XGCValues gcv;
270         long gcflags;
271
272     st->dpy = dpy;
273     st->window = window;
274
275 #ifdef HAVE_XSHM_EXTENSION
276         st->use_shm = get_boolean_resource(st->dpy, "useSHM", "Boolean");
277 #endif /* HAVE_XSHM_EXTENSION */
278         
279     distort_reset (st);
280
281         st->black_pixel = BlackPixelOfScreen( st->xgwa.screen );
282
283         gcv.function = GXcopy;
284         gcv.subwindow_mode = IncludeInferiors;
285         gcflags = GCFunction;
286         if (use_subwindow_mode_p(st->xgwa.screen, st->window)) /* see grabscreen.c */
287                 gcflags |= GCSubwindowMode;
288         st->gc = XCreateGC (st->dpy, st->window, gcflags, &gcv);
289
290     st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
291                                               st->window, 0, 0);
292     st->start_time = time ((time_t) 0);
293     return st;
294 }
295
296 static void
297 distort_finish_loading (struct state *st)
298 {
299     int i;
300
301     st->start_time = time ((time_t) 0);
302
303         st->buffer_map = 0;
304         st->orig_map = XGetImage(st->dpy, st->window, 0, 0, st->xgwa.width, st->xgwa.height,
305                                                  ~0L, ZPixmap);
306         st->buffer_map_cache = malloc(sizeof(unsigned long)*(2*st->radius+st->speed+2)*(2*st->radius+st->speed+2));
307
308         if (st->buffer_map_cache == NULL) {
309                 perror("distort");
310                 exit(EXIT_FAILURE);
311         }
312
313 # ifdef HAVE_XSHM_EXTENSION
314
315         if (st->use_shm)
316           {
317                 st->buffer_map = create_xshm_image(st->dpy, st->xgwa.visual, st->orig_map->depth,
318                                                                            ZPixmap, 0, &st->shm_info,
319                                                                            2*st->radius + st->speed + 2,
320                                                                            2*st->radius + st->speed + 2);
321                 if (!st->buffer_map)
322                   st->use_shm = False;
323           }
324 # endif /* HAVE_XSHM_EXTENSION */
325
326         if (!st->buffer_map)
327           {
328                 st->buffer_map = XCreateImage(st->dpy, st->xgwa.visual,
329                                                                   st->orig_map->depth, ZPixmap, 0, 0,
330                                                                   2*st->radius + st->speed + 2, 2*st->radius + st->speed + 2,
331                                                                   8, 0);
332                 st->buffer_map->data = (char *)
333                   calloc(st->buffer_map->height, st->buffer_map->bytes_per_line);
334         }
335
336         if ((st->buffer_map->byte_order == st->orig_map->byte_order)
337                         && (st->buffer_map->depth == st->orig_map->depth)
338                         && (st->buffer_map->format == ZPixmap)
339                         && (st->orig_map->format == ZPixmap)
340                         && !st->slow) {
341                 switch (st->orig_map->bits_per_pixel) {
342                         case 32:
343                                 st->draw_routine = &fast_draw_32;
344                                 st->bpp_size = sizeof(CARD32);
345                                 break;
346                         case 16:
347                                 st->draw_routine = &fast_draw_16;
348                                 st->bpp_size = sizeof(CARD16);
349                                 break;
350                         case 8:
351                                 st->draw_routine = &fast_draw_8;
352                                 st->bpp_size = sizeof(CARD8);
353                                 break;
354                         default:
355                                 st->draw_routine = &generic_draw;
356                                 break;
357                 }
358         } else {
359                 st->draw_routine = &generic_draw;
360         }
361         init_round_lense(st);
362
363         for (i = 0; i < st->number; i++) {
364                 new_rnd_coo(st,i);
365                 if (st->number != 1)
366                         st->xy_coo[i].r = (i*st->radius)/(st->number-1); /* "randomize" initial */
367                 else
368                          st->xy_coo[i].r = 0;
369                 st->xy_coo[i].r_change = st->speed + (i%2)*2*(-st->speed);      /* values a bit */
370                 st->xy_coo[i].xmove = st->speed + (i%2)*2*(-st->speed);
371                 st->xy_coo[i].ymove = st->speed + (i%2)*2*(-st->speed);
372         }
373 }
374
375 /* example: initializes a "see-trough" matrix */
376 /* static void make_null_lense(struct state *st)
377 {
378         int i, j;
379         for (i = 0; i < 2*radius+speed+2; i++) {
380                 for (j = 0 ; j < 2*radius+speed+2 ; j++) {
381                         from[i][j][0]=i;
382                         from[i][j][1]=j;
383                 }
384         } 
385 }
386 */
387 static void convert(struct state *st) 
388 {
389         int *p;
390         int i, j;
391         st->fast_from = calloc(1, sizeof(int)*((st->buffer_map->bytes_per_line/st->bpp_size)*(2*st->radius+st->speed+2) + 2*st->radius+st->speed+2));
392         if (st->fast_from == NULL) {
393                 perror("distort");
394                 exit(EXIT_FAILURE);
395         }
396         p = st->fast_from;
397         for (i = 0; i < 2*st->radius+st->speed+2; i++) {
398                 for (j = 0; j < 2*st->radius+st->speed+2; j++) {
399                         *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size)
400                                 = st->from[i][j][0] + st->xgwa.width*st->from[i][j][1];
401                         if (*(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) < 0
402                                         || *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) >= st->orig_map->height*st->orig_map->width) {
403                                 *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) = 0;
404                         }
405                 }
406         }
407 }
408
409 /* makes a lense with the Radius=loop and centred in
410  * the point (radius, radius)
411  */
412 static void make_round_lense(struct state *st, int radius, int loop)
413 {
414         int i, j;
415
416         for (i = 0; i < 2*radius+st->speed+2; i++) {
417                 for(j = 0; j < ((0 == st->bpp_size) ? (2*radius+st->speed+2) : (st->buffer_map->bytes_per_line/st->bpp_size)); j++) {
418                         double r, d;
419                         r = sqrt ((i-radius)*(i-radius)+(j-radius)*(j-radius));
420                         if (loop == 0)
421                           d=0.0;
422                         else
423                           d=r/loop;
424
425                         if (r < loop-1) {
426
427                                 if (st->vortex) { /* vortex-twist effect */
428                                         double angle;
429                 /* this one-line formula for getting a nice rotation angle is borrowed
430                  * (with permission) from the whirl plugin for gimp,
431                  * Copyright (C) 1996 Federico Mena Quintero
432                  */
433                 /* 5 is just a constant used because it looks good :) */
434                                         angle = 5*(1-d)*(1-d);
435
436         /* Avoid atan2: DOMAIN error message */
437                                         if ((radius-j) == 0.0 && (radius-i) == 0.0) {
438                                                 st->from[i][j][0] = radius + cos(angle)*r;
439                                                 st->from[i][j][1] = radius + sin(angle)*r;
440                                         } else {
441                                                 st->from[i][j][0] = radius +
442                                                         cos(angle - atan2(radius-j, -(radius-i)))*r;
443                                                 st->from[i][j][1] = radius +
444                                                         sin(angle - atan2(radius-j, -(radius-i)))*r;
445                                         }
446                                         if (st->magnify) {
447                                                 r = sin(d*M_PI_2);
448                                                 if (st->blackhole && r != 0) /* blackhole effect */
449                                                         r = 1/r;
450                                                 st->from[i][j][0] = radius + (st->from[i][j][0]-radius)*r;
451                                                 st->from[i][j][1] = radius + (st->from[i][j][1]-radius)*r;
452                                         }
453                                 } else { /* default is to magnify */
454                                         r = sin(d*M_PI_2);
455                                 
456         /* raising r to different power here gives different amounts of
457          * distortion, a negative value sucks everything into a black hole
458          */
459                                 /*      r = r*r; */
460                                         if (st->blackhole && r != 0) /* blackhole effect */
461                                                 r = 1/r;
462                                                                         /* bubble effect (and blackhole) */
463                                         st->from[i][j][0] = radius + (i-radius)*r;
464                                         st->from[i][j][1] = radius + (j-radius)*r;
465                                 }
466                         } else { /* not inside loop */
467                                 st->from[i][j][0] = i;
468                                 st->from[i][j][1] = j;
469                         }
470                 }
471         }
472
473         /* this is really just a quick hack to keep both the compability mode with all depths and still
474          * allow the custom optimized draw routines with the minimum amount of work */
475         if (0 != st->bpp_size) {
476                 convert(st);
477         }
478 }
479
480 #ifndef EXIT_FAILURE
481 # define EXIT_FAILURE -1
482 #endif
483
484 static void allocate_lense(struct state *st)
485 {
486         int i, j;
487         int s = ((0 != st->bpp_size) ? (st->buffer_map->bytes_per_line/st->bpp_size) : (2*st->radius+st->speed+2));
488         /* maybe this should be redone so that from[][][] is in one block;
489          * then pointers could be used instead of arrays in some places (and
490          * maybe give a speedup - maybe also consume less memory)
491          */
492         st->from = (int ***)malloc(s*sizeof(int **));
493         if (st->from == NULL) {
494                 perror("distort");
495                 exit(EXIT_FAILURE);
496         }
497         for (i = 0; i < s; i++) {
498                 st->from[i] = (int **)malloc((2*st->radius+st->speed+2) * sizeof(int *));
499                 if (st->from[i] == NULL) {
500                         perror("distort");
501                         exit(EXIT_FAILURE);
502                 }
503                 for (j = 0; j < s; j++) {
504                         st->from[i][j] = (int *)malloc(2 * sizeof(int));
505                         if (st->from[i][j] == NULL) {
506                                 perror("distort");
507                                 exit(EXIT_FAILURE);
508                         }
509                 }
510         }
511 }
512
513 /* from_array in an array containing precalculated from matrices,
514  * this is a double faced mem vs speed trade, it's faster, but eats
515  * _a lot_ of mem for large radius (is there a bug here? I can't see it)
516  */
517 static void init_round_lense(struct state *st)
518 {
519         int k;
520
521         if (st->effect == &swamp_thing) {
522                 st->from_array = (int ****)malloc((st->radius+1)*sizeof(int ***));
523                 for (k=0; k <= st->radius; k++) {
524                         allocate_lense(st);
525                         make_round_lense(st, st->radius, k);
526                         st->from_array[k] = st->from;
527                 }
528         } else { /* just allocate one from[][][] */
529                 allocate_lense(st);
530                 make_round_lense(st, st->radius,st->radius);
531         }
532 }
533
534 /* If fast_draw_8, fast_draw_16 or fast_draw_32 are to be used, the following properties
535  * of the src and dest XImages must hold (otherwise the generic, slooow, method provided
536  * by X is to be used):
537  *      src->byte_order == dest->byte_order
538  *      src->format == ZPixmap && dest->format == ZPixmap
539  *      src->depth == dest->depth == the depth the function in question asumes
540  * x and y is the coordinates in src from where to cut out the image from,
541  * distort_matrix is a precalculated array of how to distort the matrix
542  */
543
544 static void fast_draw_8(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
545 {
546         CARD8 *u = (CARD8 *)dest->data;
547         CARD8 *t = (CARD8 *)src->data + x + y*src->bytes_per_line/sizeof(CARD8);
548
549         while (u < (CARD8 *)(dest->data + sizeof(CARD8)*dest->height
550                                 *dest->bytes_per_line/sizeof(CARD8))) {
551                 *u++ = t[*distort_matrix++];
552         }
553 }
554
555 static void fast_draw_16(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
556 {
557         CARD16 *u = (CARD16 *)dest->data;
558         CARD16 *t = (CARD16 *)src->data + x + y*src->bytes_per_line/sizeof(CARD16);
559
560         while (u < (CARD16 *)(dest->data + sizeof(CARD16)*dest->height
561                                 *dest->bytes_per_line/sizeof(CARD16))) {
562                 *u++ = t[*distort_matrix++];
563         }
564 }
565
566 static void fast_draw_32(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
567 {
568         CARD32 *u = (CARD32 *)dest->data;
569         CARD32 *t = (CARD32 *)src->data + x + y*src->bytes_per_line/sizeof(CARD32);
570
571         while (u < (CARD32 *)(dest->data + sizeof(CARD32)*dest->height
572                                 *dest->bytes_per_line/sizeof(CARD32))) {
573                 *u++ = t[*distort_matrix++];
574         }
575 }
576
577 static void generic_draw(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
578 {
579         int i, j;
580         for (i = 0; i < dest->width; i++)
581                 for (j = 0; j < dest->height; j++)
582                         if (st->from[i][j][0] + x >= 0 &&
583                                         st->from[i][j][0] + x < src->width &&
584                                         st->from[i][j][1] + y >= 0 &&
585                                         st->from[i][j][1] + y < src->height)
586                                 XPutPixel(dest, i, j,
587                                                 XGetPixel(src,
588                                                         st->from[i][j][0] + x,
589                                                         st->from[i][j][1] + y));
590 }
591
592 /* generate an XImage of from[][][] and draw it on the screen */
593 static void plain_draw(struct state *st, int k)
594 {
595         if (st->xy_coo[k].x+2*st->radius+st->speed+2 > st->orig_map->width ||
596                         st->xy_coo[k].y+2*st->radius+st->speed+2 > st->orig_map->height)
597                 return;
598
599         st->draw_routine(st, st->orig_map, st->buffer_map, st->xy_coo[k].x, st->xy_coo[k].y, st->fast_from);
600
601 # ifdef HAVE_XSHM_EXTENSION
602         if (st->use_shm)
603                 XShmPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
604                                 2*st->radius+st->speed+2, 2*st->radius+st->speed+2, False);
605         else
606
607         if (!st->use_shm)
608 # endif
609                 XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
610                                 2*st->radius+st->speed+2, 2*st->radius+st->speed+2);
611
612 }
613
614
615 /* generate an XImage from the reflect algoritm submitted by
616  * Randy Zack <randy@acucorp.com>
617  * draw really got too big and ugly so I split it up
618  * it should be possible to use the from[][] to speed it up
619  * (once I figure out the algorithm used :)
620  */
621 static void reflect_draw(struct state *st, int k)
622 {
623         int i, j;
624         int     cx, cy;
625         int     ly, lysq, lx, ny, dist, rsq = st->radius * st->radius;
626
627         cx = cy = st->radius;
628         if (st->xy_coo[k].ymove > 0)
629                 cy += st->speed;
630         if (st->xy_coo[k].xmove > 0)
631                 cx += st->speed;
632
633         for(i = 0 ; i < 2*st->radius+st->speed+2; i++) {
634                 ly = i - cy;
635                 lysq = ly * ly;
636                 ny = st->xy_coo[k].y + i;
637                 if (ny >= st->orig_map->height) ny = st->orig_map->height-1;
638                 for(j = 0 ; j < 2*st->radius+st->speed+2 ; j++) {
639                         lx = j - cx;
640                         dist = lx * lx + lysq;
641                         if (dist > rsq ||
642                                 ly < -st->radius || ly > st->radius ||
643                                 lx < -st->radius || lx > st->radius)
644                                 XPutPixel( st->buffer_map, j, i,
645                                                    XGetPixel( st->orig_map, st->xy_coo[k].x + j, ny ));
646                         else if (dist == 0)
647                                 XPutPixel( st->buffer_map, j, i, st->black_pixel );
648                         else {
649                                 int     x = st->xy_coo[k].x + cx + (lx * rsq / dist);
650                                 int     y = st->xy_coo[k].y + cy + (ly * rsq / dist);
651                                 if (x < 0 || x >= st->xgwa.width ||
652                                         y < 0 || y >= st->xgwa.height)
653                                         XPutPixel( st->buffer_map, j, i, st->black_pixel );
654                                 else
655                                         XPutPixel( st->buffer_map, j, i,
656                                                            XGetPixel( st->orig_map, x, y ));
657                         }
658                 }
659         }
660
661         XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
662                         2*st->radius+st->speed+2, 2*st->radius+st->speed+2);
663 }
664
665 /* create a new, random coordinate, that won't interfer with any other
666  * coordinates, as the drawing routines would be significantly slowed
667  * down if they were to handle serveral layers of distortions
668  */
669 static void new_rnd_coo(struct state *st, int k)
670 {
671         int i;
672     int loop = 0;
673
674         st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
675         st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
676         
677         for (i = 0; i < st->number; i++) {
678                 if (i != k) {
679                         if ((abs(st->xy_coo[k].x - st->xy_coo[i].x) <= 2*st->radius+st->speed+2)
680                          && (abs(st->xy_coo[k].y - st->xy_coo[i].y) <= 2*st->radius+st->speed+2)) {
681                                 st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
682                                 st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
683                                 i=-1; /* ugly */
684                         } 
685                 }
686         if (loop++ > 1000) return;  /* let's not get stuck */
687         }
688 }
689
690 /* move lens and handle bounces with walls and other lenses */
691 static void move_lense(struct state *st, int k)
692 {
693         int i;
694
695         if (st->xy_coo[k].x + 2*st->radius + st->speed + 2 >= st->xgwa.width)
696                 st->xy_coo[k].xmove = -abs(st->xy_coo[k].xmove);
697         if (st->xy_coo[k].x <= st->speed) 
698                 st->xy_coo[k].xmove = abs(st->xy_coo[k].xmove);
699         if (st->xy_coo[k].y + 2*st->radius + st->speed + 2 >= st->xgwa.height)
700                 st->xy_coo[k].ymove = -abs(st->xy_coo[k].ymove);
701         if (st->xy_coo[k].y <= st->speed)
702                 st->xy_coo[k].ymove = abs(st->xy_coo[k].ymove);
703
704         st->xy_coo[k].x = st->xy_coo[k].x + st->xy_coo[k].xmove;
705         st->xy_coo[k].y = st->xy_coo[k].y + st->xy_coo[k].ymove;
706
707         /* bounce against othe lenses */
708         for (i = 0; i < st->number; i++) {
709                 if ((i != k)
710                 
711 /* This commented test is for rectangular lenses (not currently used) and
712  * the one used is for circular ones
713                 && (abs(xy_coo[k].x - xy_coo[i].x) <= 2*radius)
714                 && (abs(xy_coo[k].y - xy_coo[i].y) <= 2*radius)) { */
715
716                 && ((st->xy_coo[k].x - st->xy_coo[i].x)*(st->xy_coo[k].x - st->xy_coo[i].x)
717                   + (st->xy_coo[k].y - st->xy_coo[i].y)*(st->xy_coo[k].y - st->xy_coo[i].y)
718                         <= 2*st->radius*2*st->radius)) {
719
720                         int x, y;
721                         x = st->xy_coo[k].xmove;
722                         y = st->xy_coo[k].ymove;
723                         st->xy_coo[k].xmove = st->xy_coo[i].xmove;
724                         st->xy_coo[k].ymove = st->xy_coo[i].ymove;
725                         st->xy_coo[i].xmove = x;
726                         st->xy_coo[i].ymove = y;
727                 }
728         }
729
730 }
731
732 /* make xy_coo[k] grow/shrink */
733 static void swamp_thing(struct state *st, int k)
734 {
735         if (st->xy_coo[k].r >= st->radius)
736                 st->xy_coo[k].r_change = -abs(st->xy_coo[k].r_change);
737         
738         if (st->xy_coo[k].r <= 0) {
739                 st->from = st->from_array[0];
740                 st->draw(st,k); 
741                 st->xy_coo[k].r_change = abs(st->xy_coo[k].r_change);
742                 new_rnd_coo(st,k);
743                 st->xy_coo[k].r=st->xy_coo[k].r_change;
744                 return;
745         }
746
747         st->xy_coo[k].r = st->xy_coo[k].r + st->xy_coo[k].r_change;
748
749         if (st->xy_coo[k].r >= st->radius)
750                 st->xy_coo[k].r = st->radius;
751         if (st->xy_coo[k].r <= 0)
752                 st->xy_coo[k].r=0;
753
754         st->from = st->from_array[st->xy_coo[k].r];
755 }
756
757
758 static unsigned long
759 distort_draw (Display *dpy, Window window, void *closure)
760 {
761   struct state *st = (struct state *) closure;
762   int k;
763
764   if (st->img_loader)   /* still loading */
765     {
766       st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0, 0);
767       if (! st->img_loader) {  /* just finished */
768         distort_finish_loading (st);
769       }
770       return st->delay;
771     }
772
773   if (!st->img_loader &&
774       st->start_time + st->duration < time ((time_t) 0)) {
775     st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
776                                               st->window, 0, 0);
777     return st->delay;
778   }
779
780   for (k = 0; k < st->number; k++) {
781     st->effect(st,k);
782     st->draw(st,k);
783   }
784   return st->delay;
785 }
786
787 static void
788 distort_reshape (Display *dpy, Window window, void *closure, 
789                  unsigned int w, unsigned int h)
790 {
791   struct state *st = (struct state *) closure;
792   XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
793   /* XClearWindow (dpy, window); */
794   /* Why doesn't this work? */
795   if (st->orig_map)  /* created in distort_finish_loading, might be early */
796     XPutImage (st->dpy, st->window, st->gc, st->orig_map,
797                0, 0, st->orig_map->width, st->orig_map->height, 0, 0);
798 }
799
800 static Bool
801 distort_event (Display *dpy, Window window, void *closure, XEvent *event)
802 {
803   struct state *st = (struct state *) closure;
804   if (screenhack_event_helper (dpy, window, event))
805     {
806       distort_reset(st);
807       return True;
808     }
809   return False;
810 }
811
812 static void
813 distort_free (Display *dpy, Window window, void *closure)
814 {
815   struct state *st = (struct state *) closure;
816   XFreeGC (st->dpy, st->gc);
817   if (st->orig_map) XDestroyImage (st->orig_map);
818   if (st->buffer_map) XDestroyImage (st->buffer_map);
819   if (st->from) free (st->from);
820   if (st->fast_from) free (st->fast_from);
821   if (st->from_array) free (st->from_array);
822   free (st);
823 }
824
825
826 \f
827
828 static const char *distort_defaults [] = {
829         "*dontClearRoot:                True",
830         "*background:                   Black",
831     "*fpsSolid:                         true",
832 #ifdef __sgi    /* really, HAVE_READ_DISPLAY_EXTENSION */
833         "*visualID:                     Best",
834 #endif
835
836         "*delay:                        20000",
837     "*duration:                 120",
838         "*radius:                       0",
839         "*speed:                        0",
840         "*number:                       0",
841         "*slow:                         False",
842         "*vortex:                       False",
843         "*magnify:                      False",
844         "*reflect:                      False",
845         "*blackhole:            False",
846         "*effect:                   none",
847 #ifdef HAVE_XSHM_EXTENSION
848         "*useSHM:                       False",         /* xshm turns out not to help. */
849 #endif /* HAVE_XSHM_EXTENSION */
850 #ifdef USE_IPHONE
851   "*ignoreRotation:     True",
852   "*rotateImages:       True",
853 #endif
854         0
855 };
856
857 static XrmOptionDescRec distort_options [] = {
858   { "-delay",     ".delay",       XrmoptionSepArg, 0 },
859   { "-duration",  ".duration",    XrmoptionSepArg, 0 },
860   { "-radius",    ".radius",      XrmoptionSepArg, 0 },
861   { "-speed",     ".speed",       XrmoptionSepArg, 0 },
862   { "-number",    ".number",      XrmoptionSepArg, 0 },
863
864   { "-effect",    ".effect",      XrmoptionSepArg, 0 },
865   { "-swamp",     ".effect",      XrmoptionNoArg, "swamp"  },
866   { "-bounce",    ".effect",      XrmoptionNoArg, "bounce" },
867
868   { "-reflect",   ".reflect",     XrmoptionNoArg, "True" },
869   { "-vortex",    ".vortex",      XrmoptionNoArg, "True" },
870   { "-magnify",   ".magnify",     XrmoptionNoArg, "True" },
871   { "-blackhole", ".blackhole",   XrmoptionNoArg, "True" },
872   { "-slow",      ".slow",        XrmoptionNoArg, "True" },
873 #ifdef HAVE_XSHM_EXTENSION
874   { "-shm",       ".useSHM",      XrmoptionNoArg, "True" },
875   { "-no-shm",    ".useSHM",      XrmoptionNoArg, "False" },
876 #endif /* HAVE_XSHM_EXTENSION */
877   { 0, 0, 0, 0 }
878 };
879
880 XSCREENSAVER_MODULE ("Distort", distort)