From http://www.jwz.org/xscreensaver/xscreensaver-5.39.tar.gz
[xscreensaver] / hacks / distort.c
1 /* -*- mode: C; tab-width: 4 -*-
2  * xscreensaver, Copyright (c) 1992-2018 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  * 09 Oct 2016 Dave Odell (dmo2118@gmail.com)
36  *  Updated for new xshm.c.
37  */
38
39 #include <math.h>
40 #include <time.h>
41 #include "screenhack.h"
42 /*#include <X11/Xmd.h>*/
43 # include "xshm.h"
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   XShmSegmentInfo shm_info;
81
82   void (*effect) (struct state *, int);
83   void (*draw) (struct state *, int);
84   void (*draw_routine) (struct state *st, XImage *, XImage *, int, int, int *);
85
86   async_load_state *img_loader;
87   Pixmap pm;
88 };
89
90
91 static void move_lense(struct state *, int);
92 static void swamp_thing(struct state *, int);
93 static void new_rnd_coo(struct state *, int);
94 static void init_round_lense(struct state *st);
95 static void reflect_draw(struct state *, int);
96 static void plain_draw(struct state *, int);
97
98 static void fast_draw_8 (struct state *st, XImage *, XImage *, int, int, int *);
99 static void fast_draw_16(struct state *st, XImage *, XImage *, int, int, int *);
100 static void fast_draw_32(struct state *st, XImage *, XImage *, int, int, int *);
101 static void generic_draw(struct state *st, XImage *, XImage *, int, int, int *);
102
103
104 static void distort_finish_loading (struct state *);
105
106 static void
107 distort_reset (struct state *st)
108 {
109     char *s;
110     int i;
111
112     st->start_time = 0;
113
114         XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
115
116         st->delay = get_integer_resource(st->dpy, "delay", "Integer");
117     st->duration = get_integer_resource (st->dpy, "duration", "Seconds");
118         st->radius = get_integer_resource(st->dpy, "radius", "Integer");
119         st->speed = get_integer_resource(st->dpy, "speed", "Integer");
120         st->number = get_integer_resource(st->dpy, "number", "Integer");
121
122         st->blackhole = get_boolean_resource(st->dpy, "blackhole", "Boolean");
123         st->vortex = get_boolean_resource(st->dpy, "vortex", "Boolean");
124         st->magnify = get_boolean_resource(st->dpy, "magnify", "Boolean");
125         st->reflect = get_boolean_resource(st->dpy, "reflect", "Boolean");
126         st->slow = get_boolean_resource(st->dpy, "slow", "Boolean");
127         
128     if (st->xgwa.width > 2560) st->radius *= 3;  /* Retina displays */
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     distort_reset (st);
276
277         st->black_pixel = BlackPixelOfScreen( st->xgwa.screen );
278
279         gcv.function = GXcopy;
280         gcv.subwindow_mode = IncludeInferiors;
281         gcflags = GCFunction;
282         if (use_subwindow_mode_p(st->xgwa.screen, st->window)) /* see grabscreen.c */
283                 gcflags |= GCSubwindowMode;
284         st->gc = XCreateGC (st->dpy, st->window, gcflags, &gcv);
285
286     /* On MacOS X11, XGetImage on a Window often gets an inexplicable BadMatch,
287        possibly due to the window manager having occluded something?  It seems
288        nondeterministic. Loading the image into a pixmap instead fixes it. */
289     if (st->pm) XFreePixmap (st->dpy, st->pm);
290     st->pm = XCreatePixmap (st->dpy, st->window,
291                             st->xgwa.width, st->xgwa.height, st->xgwa.depth);
292
293     st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
294                                               st->pm, 0, 0);
295     st->start_time = time ((time_t *) 0);
296     return st;
297 }
298
299 static void
300 distort_finish_loading (struct state *st)
301 {
302     int i;
303
304     st->start_time = time ((time_t *) 0);
305
306     if (! st->pm) abort();
307     XClearWindow (st->dpy, st->window);
308     XCopyArea (st->dpy, st->pm, st->window, st->gc, 
309                0, 0, st->xgwa.width, st->xgwa.height, 0, 0);
310         st->orig_map = XGetImage(st->dpy, st->pm, 0, 0,
311                              st->xgwa.width, st->xgwa.height,
312                              ~0L, ZPixmap);
313         st->buffer_map_cache = malloc(sizeof(unsigned long)*(2*st->radius+st->speed+2)*(2*st->radius+st->speed+2));
314
315         if (st->buffer_map_cache == NULL) {
316                 perror("distort");
317                 exit(EXIT_FAILURE);
318         }
319
320         st->buffer_map = create_xshm_image(st->dpy, st->xgwa.visual, st->orig_map->depth,
321                                            ZPixmap, &st->shm_info,
322                                            2*st->radius + st->speed + 2,
323                                            2*st->radius + st->speed + 2);
324
325         if ((st->buffer_map->byte_order == st->orig_map->byte_order)
326                         && (st->buffer_map->depth == st->orig_map->depth)
327                         && (st->buffer_map->format == ZPixmap)
328                         && (st->orig_map->format == ZPixmap)
329                         && !st->slow) {
330                 switch (st->orig_map->bits_per_pixel) {
331                         case 32:
332                                 st->draw_routine = &fast_draw_32;
333                                 st->bpp_size = sizeof(CARD32);
334                                 break;
335                         case 16:
336                                 st->draw_routine = &fast_draw_16;
337                                 st->bpp_size = sizeof(CARD16);
338                                 break;
339                         case 8:
340                                 st->draw_routine = &fast_draw_8;
341                                 st->bpp_size = sizeof(CARD8);
342                                 break;
343                         default:
344                                 st->draw_routine = &generic_draw;
345                                 break;
346                 }
347         } else {
348                 st->draw_routine = &generic_draw;
349         }
350         init_round_lense(st);
351
352         for (i = 0; i < st->number; i++) {
353                 new_rnd_coo(st,i);
354                 if (st->number != 1)
355                         st->xy_coo[i].r = (i*st->radius)/(st->number-1); /* "randomize" initial */
356                 else
357                          st->xy_coo[i].r = 0;
358                 st->xy_coo[i].r_change = st->speed + (i%2)*2*(-st->speed);      /* values a bit */
359                 st->xy_coo[i].xmove = st->speed + (i%2)*2*(-st->speed);
360                 st->xy_coo[i].ymove = st->speed + (i%2)*2*(-st->speed);
361         }
362 }
363
364 /* example: initializes a "see-trough" matrix */
365 /* static void make_null_lense(struct state *st)
366 {
367         int i, j;
368         for (i = 0; i < 2*radius+speed+2; i++) {
369                 for (j = 0 ; j < 2*radius+speed+2 ; j++) {
370                         from[i][j][0]=i;
371                         from[i][j][1]=j;
372                 }
373         } 
374 }
375 */
376 static void convert(struct state *st) 
377 {
378         int *p;
379         int i, j;
380         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));
381         if (st->fast_from == NULL) {
382                 perror("distort");
383                 exit(EXIT_FAILURE);
384         }
385         p = st->fast_from;
386         for (i = 0; i < 2*st->radius+st->speed+2; i++) {
387                 for (j = 0; j < 2*st->radius+st->speed+2; j++) {
388                         *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size)
389                                 = st->from[i][j][0] + st->xgwa.width*st->from[i][j][1];
390                         if (*(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) < 0
391                                         || *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) >= st->orig_map->height*st->orig_map->width) {
392                                 *(p + i + j*st->buffer_map->bytes_per_line/st->bpp_size) = 0;
393                         }
394                 }
395         }
396 }
397
398 /* makes a lense with the Radius=loop and centred in
399  * the point (radius, radius)
400  */
401 static void make_round_lense(struct state *st, int radius, int loop)
402 {
403         int i, j;
404
405         for (i = 0; i < 2*radius+st->speed+2; i++) {
406                 for(j = 0; j < ((0 == st->bpp_size) ? (2*radius+st->speed+2) : (st->buffer_map->bytes_per_line/st->bpp_size)); j++) {
407                         double r, d;
408                         r = sqrt ((i-radius)*(i-radius)+(j-radius)*(j-radius));
409                         if (loop == 0)
410                           d=0.0;
411                         else
412                           d=r/loop;
413
414                         if (r < loop-1) {
415
416                                 if (st->vortex) { /* vortex-twist effect */
417                                         double angle;
418                 /* this one-line formula for getting a nice rotation angle is borrowed
419                  * (with permission) from the whirl plugin for gimp,
420                  * Copyright (C) 1996 Federico Mena Quintero
421                  */
422                 /* 5 is just a constant used because it looks good :) */
423                                         angle = 5*(1-d)*(1-d);
424
425         /* Avoid atan2: DOMAIN error message */
426                                         if ((radius-j) == 0.0 && (radius-i) == 0.0) {
427                                                 st->from[i][j][0] = radius + cos(angle)*r;
428                                                 st->from[i][j][1] = radius + sin(angle)*r;
429                                         } else {
430                                                 st->from[i][j][0] = radius +
431                                                         cos(angle - atan2(radius-j, -(radius-i)))*r;
432                                                 st->from[i][j][1] = radius +
433                                                         sin(angle - atan2(radius-j, -(radius-i)))*r;
434                                         }
435                                         if (st->magnify) {
436                                                 r = sin(d*M_PI_2);
437                                                 if (st->blackhole && r != 0) /* blackhole effect */
438                                                         r = 1/r;
439                                                 st->from[i][j][0] = radius + (st->from[i][j][0]-radius)*r;
440                                                 st->from[i][j][1] = radius + (st->from[i][j][1]-radius)*r;
441                                         }
442                                 } else { /* default is to magnify */
443                                         r = sin(d*M_PI_2);
444                                 
445         /* raising r to different power here gives different amounts of
446          * distortion, a negative value sucks everything into a black hole
447          */
448                                 /*      r = r*r; */
449                                         if (st->blackhole && r != 0) /* blackhole effect */
450                                                 r = 1/r;
451                                                                         /* bubble effect (and blackhole) */
452                                         st->from[i][j][0] = radius + (i-radius)*r;
453                                         st->from[i][j][1] = radius + (j-radius)*r;
454                                 }
455                         } else { /* not inside loop */
456                                 st->from[i][j][0] = i;
457                                 st->from[i][j][1] = j;
458                         }
459                 }
460         }
461
462         /* this is really just a quick hack to keep both the compability mode with all depths and still
463          * allow the custom optimized draw routines with the minimum amount of work */
464         if (0 != st->bpp_size) {
465                 convert(st);
466         }
467 }
468
469 #ifndef EXIT_FAILURE
470 # define EXIT_FAILURE -1
471 #endif
472
473 static void allocate_lense(struct state *st)
474 {
475         int i, j;
476         int s = ((0 != st->bpp_size) ? (st->buffer_map->bytes_per_line/st->bpp_size) : (2*st->radius+st->speed+2));
477         /* maybe this should be redone so that from[][][] is in one block;
478          * then pointers could be used instead of arrays in some places (and
479          * maybe give a speedup - maybe also consume less memory)
480          */
481         st->from = (int ***)malloc(s*sizeof(int **));
482         if (st->from == NULL) {
483                 perror("distort");
484                 exit(EXIT_FAILURE);
485         }
486         for (i = 0; i < s; i++) {
487                 st->from[i] = (int **)malloc((2*st->radius+st->speed+2) * sizeof(int *));
488                 if (st->from[i] == NULL) {
489                         perror("distort");
490                         exit(EXIT_FAILURE);
491                 }
492                 for (j = 0; j < s; j++) {
493                         st->from[i][j] = (int *)malloc(2 * sizeof(int));
494                         if (st->from[i][j] == NULL) {
495                                 perror("distort");
496                                 exit(EXIT_FAILURE);
497                         }
498                 }
499         }
500 }
501
502 /* from_array in an array containing precalculated from matrices,
503  * this is a double faced mem vs speed trade, it's faster, but eats
504  * _a lot_ of mem for large radius (is there a bug here? I can't see it)
505  */
506 static void init_round_lense(struct state *st)
507 {
508         int k;
509
510         if (st->effect == &swamp_thing) {
511                 st->from_array = (int ****)malloc((st->radius+1)*sizeof(int ***));
512                 for (k=0; k <= st->radius; k++) {
513                         allocate_lense(st);
514                         make_round_lense(st, st->radius, k);
515                         st->from_array[k] = st->from;
516                 }
517         } else { /* just allocate one from[][][] */
518                 allocate_lense(st);
519                 make_round_lense(st, st->radius,st->radius);
520         }
521 }
522
523 /* If fast_draw_8, fast_draw_16 or fast_draw_32 are to be used, the following properties
524  * of the src and dest XImages must hold (otherwise the generic, slooow, method provided
525  * by X is to be used):
526  *      src->byte_order == dest->byte_order
527  *      src->format == ZPixmap && dest->format == ZPixmap
528  *      src->depth == dest->depth == the depth the function in question asumes
529  * x and y is the coordinates in src from where to cut out the image from,
530  * distort_matrix is a precalculated array of how to distort the matrix
531  */
532
533 static void fast_draw_8(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
534 {
535         CARD8 *u = (CARD8 *)dest->data;
536         CARD8 *t = (CARD8 *)src->data + x + y*src->bytes_per_line/sizeof(CARD8);
537
538         while (u < (CARD8 *)(dest->data + sizeof(CARD8)*dest->height
539                                 *dest->bytes_per_line/sizeof(CARD8))) {
540                 *u++ = t[*distort_matrix++];
541         }
542 }
543
544 static void fast_draw_16(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
545 {
546         CARD16 *u = (CARD16 *)dest->data;
547         CARD16 *t = (CARD16 *)src->data + x + y*src->bytes_per_line/sizeof(CARD16);
548
549         while (u < (CARD16 *)(dest->data + sizeof(CARD16)*dest->height
550                                 *dest->bytes_per_line/sizeof(CARD16))) {
551                 *u++ = t[*distort_matrix++];
552         }
553 }
554
555 static void fast_draw_32(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
556 {
557         CARD32 *u = (CARD32 *)dest->data;
558         CARD32 *t = (CARD32 *)src->data + x + y*src->bytes_per_line/sizeof(CARD32);
559
560         while (u < (CARD32 *)(dest->data + sizeof(CARD32)*dest->height
561                                 *dest->bytes_per_line/sizeof(CARD32))) {
562                 *u++ = t[*distort_matrix++];
563         }
564 }
565
566 static void generic_draw(struct state *st, XImage *src, XImage *dest, int x, int y, int *distort_matrix)
567 {
568         int i, j;
569         for (i = 0; i < dest->width; i++)
570                 for (j = 0; j < dest->height; j++)
571                         if (st->from[i][j][0] + x >= 0 &&
572                                         st->from[i][j][0] + x < src->width &&
573                                         st->from[i][j][1] + y >= 0 &&
574                                         st->from[i][j][1] + y < src->height)
575                                 XPutPixel(dest, i, j,
576                                                 XGetPixel(src,
577                                                         st->from[i][j][0] + x,
578                                                         st->from[i][j][1] + y));
579 }
580
581 /* generate an XImage of from[][][] and draw it on the screen */
582 static void plain_draw(struct state *st, int k)
583 {
584         if (st->xy_coo[k].x+2*st->radius+st->speed+2 > st->orig_map->width ||
585                         st->xy_coo[k].y+2*st->radius+st->speed+2 > st->orig_map->height)
586                 return;
587
588         st->draw_routine(st, st->orig_map, st->buffer_map, st->xy_coo[k].x, st->xy_coo[k].y, st->fast_from);
589
590         put_xshm_image(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
591                        2*st->radius+st->speed+2, 2*st->radius+st->speed+2, &st->shm_info);
592 }
593
594
595 /* generate an XImage from the reflect algoritm submitted by
596  * Randy Zack <randy@acucorp.com>
597  * draw really got too big and ugly so I split it up
598  * it should be possible to use the from[][] to speed it up
599  * (once I figure out the algorithm used :)
600  */
601 static void reflect_draw(struct state *st, int k)
602 {
603         int i, j;
604         int     cx, cy;
605         int     ly, lysq, lx, ny, dist, rsq = st->radius * st->radius;
606
607         cx = cy = st->radius;
608         if (st->xy_coo[k].ymove > 0)
609                 cy += st->speed;
610         if (st->xy_coo[k].xmove > 0)
611                 cx += st->speed;
612
613         for(i = 0 ; i < 2*st->radius+st->speed+2; i++) {
614                 ly = i - cy;
615                 lysq = ly * ly;
616                 ny = st->xy_coo[k].y + i;
617                 if (ny >= st->orig_map->height) ny = st->orig_map->height-1;
618                 for(j = 0 ; j < 2*st->radius+st->speed+2 ; j++) {
619                         lx = j - cx;
620                         dist = lx * lx + lysq;
621                         if (dist > rsq ||
622                                 ly < -st->radius || ly > st->radius ||
623                                 lx < -st->radius || lx > st->radius)
624                                 XPutPixel( st->buffer_map, j, i,
625                                                    XGetPixel( st->orig_map, st->xy_coo[k].x + j, ny ));
626                         else if (dist == 0)
627                                 XPutPixel( st->buffer_map, j, i, st->black_pixel );
628                         else {
629                                 int     x = st->xy_coo[k].x + cx + (lx * rsq / dist);
630                                 int     y = st->xy_coo[k].y + cy + (ly * rsq / dist);
631                                 if (x < 0 || x >= st->xgwa.width ||
632                                         y < 0 || y >= st->xgwa.height)
633                                         XPutPixel( st->buffer_map, j, i, st->black_pixel );
634                                 else
635                                         XPutPixel( st->buffer_map, j, i,
636                                                            XGetPixel( st->orig_map, x, y ));
637                         }
638                 }
639         }
640
641         XPutImage(st->dpy, st->window, st->gc, st->buffer_map, 0, 0, st->xy_coo[k].x, st->xy_coo[k].y,
642                         2*st->radius+st->speed+2, 2*st->radius+st->speed+2);
643 }
644
645 /* create a new, random coordinate, that won't interfer with any other
646  * coordinates, as the drawing routines would be significantly slowed
647  * down if they were to handle serveral layers of distortions
648  */
649 static void new_rnd_coo(struct state *st, int k)
650 {
651         int i;
652     int loop = 0;
653
654         st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
655         st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
656         
657         for (i = 0; i < st->number; i++) {
658                 if (i != k) {
659                         if ((abs(st->xy_coo[k].x - st->xy_coo[i].x) <= 2*st->radius+st->speed+2)
660                          && (abs(st->xy_coo[k].y - st->xy_coo[i].y) <= 2*st->radius+st->speed+2)) {
661                                 st->xy_coo[k].x = (random() % (st->xgwa.width-2*st->radius));
662                                 st->xy_coo[k].y = (random() % (st->xgwa.height-2*st->radius));
663                                 i=-1; /* ugly */
664                         } 
665                 }
666         if (loop++ > 1000) return;  /* let's not get stuck */
667         }
668 }
669
670 /* move lens and handle bounces with walls and other lenses */
671 static void move_lense(struct state *st, int k)
672 {
673         int i;
674
675         if (st->xy_coo[k].x + 2*st->radius + st->speed + 2 >= st->xgwa.width)
676                 st->xy_coo[k].xmove = -abs(st->xy_coo[k].xmove);
677         if (st->xy_coo[k].x <= st->speed) 
678                 st->xy_coo[k].xmove = abs(st->xy_coo[k].xmove);
679         if (st->xy_coo[k].y + 2*st->radius + st->speed + 2 >= st->xgwa.height)
680                 st->xy_coo[k].ymove = -abs(st->xy_coo[k].ymove);
681         if (st->xy_coo[k].y <= st->speed)
682                 st->xy_coo[k].ymove = abs(st->xy_coo[k].ymove);
683
684         st->xy_coo[k].x = st->xy_coo[k].x + st->xy_coo[k].xmove;
685         st->xy_coo[k].y = st->xy_coo[k].y + st->xy_coo[k].ymove;
686
687         /* bounce against othe lenses */
688         for (i = 0; i < st->number; i++) {
689                 if ((i != k)
690                 
691 /* This commented test is for rectangular lenses (not currently used) and
692  * the one used is for circular ones
693                 && (abs(xy_coo[k].x - xy_coo[i].x) <= 2*radius)
694                 && (abs(xy_coo[k].y - xy_coo[i].y) <= 2*radius)) { */
695
696                 && ((st->xy_coo[k].x - st->xy_coo[i].x)*(st->xy_coo[k].x - st->xy_coo[i].x)
697                   + (st->xy_coo[k].y - st->xy_coo[i].y)*(st->xy_coo[k].y - st->xy_coo[i].y)
698                         <= 2*st->radius*2*st->radius)) {
699
700                         int x, y;
701                         x = st->xy_coo[k].xmove;
702                         y = st->xy_coo[k].ymove;
703                         st->xy_coo[k].xmove = st->xy_coo[i].xmove;
704                         st->xy_coo[k].ymove = st->xy_coo[i].ymove;
705                         st->xy_coo[i].xmove = x;
706                         st->xy_coo[i].ymove = y;
707                 }
708         }
709
710 }
711
712 /* make xy_coo[k] grow/shrink */
713 static void swamp_thing(struct state *st, int k)
714 {
715         if (st->xy_coo[k].r >= st->radius)
716                 st->xy_coo[k].r_change = -abs(st->xy_coo[k].r_change);
717         
718         if (st->xy_coo[k].r <= 0) {
719                 st->from = st->from_array[0];
720                 st->draw(st,k); 
721                 st->xy_coo[k].r_change = abs(st->xy_coo[k].r_change);
722                 new_rnd_coo(st,k);
723                 st->xy_coo[k].r=st->xy_coo[k].r_change;
724                 return;
725         }
726
727         st->xy_coo[k].r = st->xy_coo[k].r + st->xy_coo[k].r_change;
728
729         if (st->xy_coo[k].r >= st->radius)
730                 st->xy_coo[k].r = st->radius;
731         if (st->xy_coo[k].r <= 0)
732                 st->xy_coo[k].r=0;
733
734         st->from = st->from_array[st->xy_coo[k].r];
735 }
736
737
738 static unsigned long
739 distort_draw (Display *dpy, Window window, void *closure)
740 {
741   struct state *st = (struct state *) closure;
742   int k;
743
744   if (st->img_loader)   /* still loading */
745     {
746       st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0, 0);
747       if (! st->img_loader) {  /* just finished */
748         distort_finish_loading (st);
749       }
750       return st->delay;
751     }
752
753   if (!st->img_loader &&
754       st->start_time + st->duration < time ((time_t *) 0)) {
755     if (st->pm) XFreePixmap (st->dpy, st->pm);
756     st->pm = XCreatePixmap (st->dpy, st->window,
757                             st->xgwa.width, st->xgwa.height, st->xgwa.depth);
758     st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
759                                               st->pm, 0, 0);
760     return st->delay;
761   }
762
763   for (k = 0; k < st->number; k++) {
764     st->effect(st,k);
765     st->draw(st,k);
766   }
767   return st->delay;
768 }
769
770 static void
771 distort_reshape (Display *dpy, Window window, void *closure, 
772                  unsigned int w, unsigned int h)
773 {
774   struct state *st = (struct state *) closure;
775   XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
776   /* XClearWindow (dpy, window); */
777   /* Why doesn't this work? */
778   if (st->orig_map)  /* created in distort_finish_loading, might be early */
779     XPutImage (st->dpy, st->window, st->gc, st->orig_map,
780                0, 0, st->orig_map->width, st->orig_map->height, 0, 0);
781 }
782
783 static Bool
784 distort_event (Display *dpy, Window window, void *closure, XEvent *event)
785 {
786   struct state *st = (struct state *) closure;
787   if (screenhack_event_helper (dpy, window, event))
788     {
789       distort_reset(st);
790       return True;
791     }
792   return False;
793 }
794
795 static void
796 distort_free (Display *dpy, Window window, void *closure)
797 {
798   struct state *st = (struct state *) closure;
799   XFreeGC (st->dpy, st->gc);
800   if (st->pm) XFreePixmap (dpy, st->pm);
801   if (st->orig_map) XDestroyImage (st->orig_map);
802   if (st->buffer_map) destroy_xshm_image (st->dpy, st->buffer_map, &st->shm_info);
803   if (st->from) free (st->from);
804   if (st->fast_from) free (st->fast_from);
805   if (st->from_array) free (st->from_array);
806   free (st);
807 }
808
809
810 \f
811
812 static const char *distort_defaults [] = {
813         "*dontClearRoot:                True",
814         "*background:                   Black",
815     "*fpsSolid:                         true",
816 #ifdef __sgi    /* really, HAVE_READ_DISPLAY_EXTENSION */
817         "*visualID:                     Best",
818 #endif
819
820         "*delay:                        20000",
821     "*duration:                 120",
822         "*radius:                       0",
823         "*speed:                        0",
824         "*number:                       0",
825         "*slow:                         False",
826         "*vortex:                       False",
827         "*magnify:                      False",
828         "*reflect:                      False",
829         "*blackhole:            False",
830         "*effect:                   none",
831 #ifdef HAVE_XSHM_EXTENSION
832         "*useSHM:                       False",         /* xshm turns out not to help. */
833 #endif /* HAVE_XSHM_EXTENSION */
834 #ifdef HAVE_MOBILE
835   "*ignoreRotation:     True",
836   "*rotateImages:       True",
837 #endif
838         0
839 };
840
841 static XrmOptionDescRec distort_options [] = {
842   { "-delay",     ".delay",       XrmoptionSepArg, 0 },
843   { "-duration",  ".duration",    XrmoptionSepArg, 0 },
844   { "-radius",    ".radius",      XrmoptionSepArg, 0 },
845   { "-speed",     ".speed",       XrmoptionSepArg, 0 },
846   { "-number",    ".number",      XrmoptionSepArg, 0 },
847
848   { "-effect",    ".effect",      XrmoptionSepArg, 0 },
849   { "-swamp",     ".effect",      XrmoptionNoArg, "swamp"  },
850   { "-bounce",    ".effect",      XrmoptionNoArg, "bounce" },
851
852   { "-reflect",   ".reflect",     XrmoptionNoArg, "True" },
853   { "-vortex",    ".vortex",      XrmoptionNoArg, "True" },
854   { "-magnify",   ".magnify",     XrmoptionNoArg, "True" },
855   { "-blackhole", ".blackhole",   XrmoptionNoArg, "True" },
856   { "-slow",      ".slow",        XrmoptionNoArg, "True" },
857 #ifdef HAVE_XSHM_EXTENSION
858   { "-shm",       ".useSHM",      XrmoptionNoArg, "True" },
859   { "-no-shm",    ".useSHM",      XrmoptionNoArg, "False" },
860 #endif /* HAVE_XSHM_EXTENSION */
861   { 0, 0, 0, 0 }
862 };
863
864 XSCREENSAVER_MODULE ("Distort", distort)