From http://www.jwz.org/xscreensaver/xscreensaver-5.37.tar.gz
[xscreensaver] / hacks / drift.c
1 /* -*- Mode: C; tab-width: 4 -*- */
2 /* drift --- drifting recursive fractal cosmic flames */
3
4 #if 0
5 static const char sccsid[] = "@(#)drift.c       5.00 2000/11/01 xlockmore";
6 #endif
7
8 /*-
9  * Copyright (c) 1991 by Patrick J. Naughton.
10  *
11  * Permission to use, copy, modify, and distribute this software and its
12  * documentation for any purpose and without fee is hereby granted,
13  * provided that the above copyright notice appear in all copies and that
14  * both that copyright notice and this permission notice appear in
15  * supporting documentation.
16  *
17  * This file is provided AS IS with no warranties of any kind.  The author
18  * shall have no liability with respect to the infringement of copyrights,
19  * trade secrets or any patents by this file or any part thereof.  In no
20  * event will the author be liable for any lost revenue or profits or
21  * other special, indirect and consequential damages.
22  *
23  * Revision History:
24  * 01-Nov-2000: Allocation checks
25  * 10-May-1997: Jamie Zawinski <jwz@jwz.org> compatible with xscreensaver
26  * 01-Jan-1997: Moved new flame to drift.  Compile time options now run time.
27  * 01-Jun-1995: Updated by Scott Draves.
28  * 27-Jun-1991: vary number of functions used.
29  * 24-Jun-1991: fixed portability problem with integer mod (%).
30  * 06-Jun-1991: Written, received from Scott Draves <spot@cs.cmu.edu>
31  */
32
33 #ifdef STANDALONE
34 # define MODE_drift
35 # define DEFAULTS "*delay: 10000 \n" \
36                                   "*count: 30 \n" \
37                                   "*ncolors: 200 \n" \
38                                   "*fpsSolid: true \n" \
39                                   "*ignoreRotation: True \n" \
40
41 # define SMOOTH_COLORS
42 # define release_drift 0
43 # include "xlockmore.h"         /* in xscreensaver distribution */
44 # include "erase.h"
45 #else /* STANDALONE */
46 # define ENTRYPOINT /**/
47 # include "xlock.h"             /* in xlockmore distribution */
48 #endif /* STANDALONE */
49
50 #ifdef MODE_drift
51
52 #define DEF_GROW "False"        /* Grow fractals instead of animating one at a time,
53                                    would then be like flame */
54 #define DEF_LISS "False"        /* if this is defined then instead of a point
55                                    bouncing around in a high dimensional sphere, we
56                                    use lissojous figures.  Only makes sense if
57                                    grow is false. */
58
59 static Bool grow;
60 static Bool liss;
61
62 static XrmOptionDescRec opts[] =
63 {
64         {"-grow", ".drift.grow", XrmoptionNoArg, "on"},
65         {"+grow", ".drift.grow", XrmoptionNoArg, "off"},
66         {"-liss", ".drift.trail", XrmoptionNoArg, "on"},
67         {"+liss", ".drift.trail", XrmoptionNoArg, "off"}
68 };
69 static argtype vars[] =
70 {
71         {&grow, "grow", "Grow", DEF_GROW, t_Bool},
72         {&liss, "trail", "Trail", DEF_LISS, t_Bool}
73 };
74 static OptionStruct desc[] =
75 {
76         {"-/+grow", "turn on/off growing fractals, else they are animated"},
77         {"-/+liss", "turn on/off using lissojous figures to get points"}
78 };
79
80 ENTRYPOINT ModeSpecOpt drift_opts =
81 {sizeof opts / sizeof opts[0], opts, sizeof vars / sizeof vars[0], vars, desc};
82
83 #ifdef USE_MODULES
84 ModStruct   drift_description =
85 {"drift", "init_drift", "draw_drift", (char *) NULL,
86  "refresh_drift", "init_drift", (char *) NULL, &drift_opts,
87  10000, 30, 1, 1, 64, 1.0, "",
88  "Shows cosmic drifting flame fractals", 0, NULL};
89
90 #endif
91
92 #define MAXBATCH1       200     /* mono */
93 #define MAXBATCH2       20      /* color */
94 #define FUSE            10      /* discard this many initial iterations */
95 #define NMAJORVARS      7
96 #define MAXLEV 10
97
98 typedef struct {
99         /* shape of current flame */
100         int         nxforms;
101         double      f[2][3][MAXLEV];    /* a bunch of non-homogeneous xforms */
102         int         variation[10];      /* for each xform */
103
104         /* Animation */
105         double      df[2][3][MAXLEV];
106
107         /* high-level control */
108         int         mode;       /* 0->slow/single 1->fast/many */
109         int         nfractals;  /* draw this many fractals */
110         int         major_variation;
111         int         fractal_len;        /* pts/fractal */
112         int         color;
113         int         rainbow;    /* more than one color per fractal
114                                    1-> computed by adding dimension to fractal */
115
116         int         width, height;      /* of window */
117         int         timer;
118
119         /* draw info about current flame */
120         int         fuse;       /* iterate this many before drawing */
121         int         total_points;       /* draw this many pts before fractal ends */
122         int         npoints;    /* how many we've computed but not drawn */
123         XPoint      pts[MAXBATCH1];     /* here they are */
124         unsigned long pixcol;
125         /* when drawing in color, we have a buffer per color */
126         int        *ncpoints;
127         XPoint     *cpts;
128
129         double      x, y, c;
130         int         liss_time;
131         Bool        grow, liss;
132
133         short       lasthalf;
134         long        saved_random_bits;
135         int         nbits;
136
137 #ifdef STANDALONE
138   int erase_countdown;
139   eraser_state *eraser;
140 #endif
141 } driftstruct;
142
143 static driftstruct *drifts = (driftstruct *) NULL;
144
145 static short
146 halfrandom(driftstruct * dp, int mv)
147 {
148         unsigned long r;
149
150         if (dp->lasthalf) {
151                 r = dp->lasthalf;
152                 dp->lasthalf = 0;
153         } else {
154                 r = LRAND();
155                 dp->lasthalf = (short) (r >> 16);
156         }
157         r = r % mv;
158         return r;
159 }
160
161 static int
162 frandom(driftstruct * dp, int n)
163 {
164         int         result;
165
166         if (3 > dp->nbits) {
167                 dp->saved_random_bits = LRAND();
168                 dp->nbits = 31;
169         }
170         switch (n) {
171                 case 2:
172                         result = (int) (dp->saved_random_bits & 1);
173                         dp->saved_random_bits >>= 1;
174                         dp->nbits -= 1;
175                         return result;
176
177                 case 3:
178                         result = (int) (dp->saved_random_bits & 3);
179                         dp->saved_random_bits >>= 2;
180                         dp->nbits -= 2;
181                         if (3 == result)
182                                 return frandom(dp, 3);
183                         return result;
184
185                 case 4:
186                         result = (int) (dp->saved_random_bits & 3);
187                         dp->saved_random_bits >>= 2;
188                         dp->nbits -= 2;
189                         return result;
190
191                 case 5:
192                         result = (int) (dp->saved_random_bits & 7);
193                         dp->saved_random_bits >>= 3;
194                         dp->nbits -= 3;
195                         if (4 < result)
196                                 return frandom(dp, 5);
197                         return result;
198                 default:
199                         (void) fprintf(stderr, "bad arg to frandom\n");
200         }
201         return 0;
202 }
203
204 #define DISTRIB_A (halfrandom(dp, 7000) + 9000)
205 #define DISTRIB_B ((frandom(dp, 3) + 1) * (frandom(dp, 3) + 1) * 120000)
206 #define LEN(x) (sizeof(x)/sizeof((x)[0]))
207
208 static void
209 initmode(ModeInfo * mi, int mode)
210 {
211         driftstruct *dp = &drifts[MI_SCREEN(mi)];
212
213 #define VARIATION_LEN 14
214
215         dp->mode = mode;
216
217         dp->major_variation = halfrandom(dp, VARIATION_LEN);
218         /*  0, 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6, 6 */
219         dp->major_variation = ((dp->major_variation >= VARIATION_LEN >> 1) &&
220                                (dp->major_variation < VARIATION_LEN - 1)) ?
221                 (dp->major_variation + 1) >> 1 : dp->major_variation >> 1;
222
223         if (dp->grow) {
224                 dp->rainbow = 0;
225                 if (mode) {
226                         if (!dp->color || halfrandom(dp, 8)) {
227                                 dp->nfractals = halfrandom(dp, 30) + 5;
228                                 dp->fractal_len = DISTRIB_A;
229                         } else {
230                                 dp->nfractals = halfrandom(dp, 5) + 5;
231                                 dp->fractal_len = DISTRIB_B;
232                         }
233                 } else {
234                         dp->rainbow = dp->color;
235                         dp->nfractals = 1;
236                         dp->fractal_len = DISTRIB_B;
237                 }
238         } else {
239                 dp->nfractals = 1;
240                 dp->rainbow = dp->color;
241                 dp->fractal_len = 2000000;
242         }
243         dp->fractal_len = (dp->fractal_len * MI_COUNT(mi)) / 20;
244
245 #ifndef STANDALONE
246         MI_CLEARWINDOW(mi);
247 #endif
248 }
249
250 static void
251 pick_df_coefs(ModeInfo * mi)
252 {
253         driftstruct *dp = &drifts[MI_SCREEN(mi)];
254         int         i, j, k;
255         double      r;
256
257         for (i = 0; i < dp->nxforms; i++) {
258
259                 r = 1e-6;
260                 for (j = 0; j < 2; j++)
261                         for (k = 0; k < 3; k++) {
262                                 dp->df[j][k][i] = ((double) halfrandom(dp, 1000) / 500.0 - 1.0);
263                                 r += dp->df[j][k][i] * dp->df[j][k][i];
264                         }
265                 r = (3 + halfrandom(dp, 5)) * 0.01 / sqrt(r);
266                 for (j = 0; j < 2; j++)
267                         for (k = 0; k < 3; k++)
268                                 dp->df[j][k][i] *= r;
269         }
270 }
271
272 static void
273 free_drift(ModeInfo * mi)
274 {
275         driftstruct *dp = &drifts[MI_SCREEN(mi)];
276         if (dp->ncpoints != NULL) {
277                 (void) free((void *) dp->ncpoints);
278                 dp->ncpoints = (int *) NULL;
279         }
280         if (dp->cpts != NULL) {
281                 (void) free((void *) dp->cpts);
282                 dp->cpts = (XPoint *) NULL;
283         }
284 }
285
286 static void
287 initfractal(ModeInfo * mi)
288 {
289         driftstruct *dp = &drifts[MI_SCREEN(mi)];
290         int         i, j, k;
291
292 #define XFORM_LEN 9
293
294         dp->fuse = FUSE;
295         dp->total_points = 0;
296
297         if (!dp->ncpoints) {
298                 if ((dp->ncpoints = (int *) malloc(sizeof (int) * MI_NCOLORS(mi))) ==
299                         NULL) {
300                         free_drift(mi);
301                         return;
302                 }
303         }
304         if (!dp->cpts) {
305                 if ((dp->cpts = (XPoint *) malloc(MAXBATCH2 * sizeof (XPoint) *
306                          MI_NCOLORS(mi))) == NULL) {
307                         free_drift(mi);
308                         return;
309                 }
310         }
311
312         if (dp->rainbow)
313                 for (i = 0; i < MI_NPIXELS(mi); i++)
314                         dp->ncpoints[i] = 0;
315         else
316                 dp->npoints = 0;
317         dp->nxforms = halfrandom(dp, XFORM_LEN);
318         /* 2, 2, 2, 3, 3, 3, 4, 4, 5 */
319         dp->nxforms = (dp->nxforms >= XFORM_LEN - 1) + dp->nxforms / 3 + 2;
320
321         dp->c = dp->x = dp->y = 0.0;
322         if (dp->liss && !halfrandom(dp, 10)) {
323                 dp->liss_time = 0;
324         }
325         if (!dp->grow)
326                 pick_df_coefs(mi);
327         for (i = 0; i < dp->nxforms; i++) {
328                 if (NMAJORVARS == dp->major_variation)
329                         dp->variation[i] = halfrandom(dp, NMAJORVARS);
330                 else
331                         dp->variation[i] = dp->major_variation;
332                 for (j = 0; j < 2; j++)
333                         for (k = 0; k < 3; k++) {
334                                 if (dp->liss)
335                                         dp->f[j][k][i] = sin(dp->liss_time * dp->df[j][k][i]);
336                                 else
337                                         dp->f[j][k][i] = ((double) halfrandom(dp, 1000) / 500.0 - 1.0);
338                         }
339         }
340         if (dp->color)
341                 dp->pixcol = MI_PIXEL(mi, halfrandom(dp, MI_NPIXELS(mi)));
342         else
343                 dp->pixcol = MI_WHITE_PIXEL(mi);
344
345 }
346
347
348 ENTRYPOINT void
349 init_drift(ModeInfo * mi)
350 {
351         driftstruct *dp;
352
353         MI_INIT (mi, drifts, free_drift);
354         dp = &drifts[MI_SCREEN(mi)];
355
356         dp->width = MI_WIDTH(mi);
357         dp->height = MI_HEIGHT(mi);
358         dp->color = MI_NPIXELS(mi) > 2;
359
360         if (MI_IS_FULLRANDOM(mi)) {
361                 if (NRAND(3) == 0)
362                         dp->grow = True;
363                 else {
364                         dp->grow = False;
365                         dp->liss = (Bool) (LRAND() & 1);
366                 }
367         } else {
368                 dp->grow = grow;
369                 if (dp->grow)
370                         dp->liss = False;
371                 else
372                         dp->liss = liss;
373         }
374         initmode(mi, 1);
375         initfractal(mi);
376 }
377
378 static void
379 iter(driftstruct * dp)
380 {
381         int         i = frandom(dp, dp->nxforms);
382         double      nx, ny, nc;
383
384
385         if (i)
386                 nc = (dp->c + 1.0) / 2.0;
387         else
388                 nc = dp->c / 2.0;
389
390         nx = dp->f[0][0][i] * dp->x + dp->f[0][1][i] * dp->y + dp->f[0][2][i];
391         ny = dp->f[1][0][i] * dp->x + dp->f[1][1][i] * dp->y + dp->f[1][2][i];
392
393
394         switch (dp->variation[i]) {
395                 case 1:
396                         /* sinusoidal */
397                         nx = sin(nx);
398                         ny = sin(ny);
399                         break;
400                 case 2:
401                         {
402                                 /* complex */
403                                 double      r2 = nx * nx + ny * ny + 1e-6;
404
405                                 nx = nx / r2;
406                                 ny = ny / r2;
407                                 break;
408                         }
409                 case 3:
410                         /* bent */
411                         if (nx < 0.0)
412                                 nx = nx * 2.0;
413                         if (ny < 0.0)
414                                 ny = ny / 2.0;
415                         break;
416                 case 4:
417                         {
418                                 /* swirl */
419
420                                 double      r = (nx * nx + ny * ny);    /* times k here is fun */
421                                 double      c1 = sin(r);
422                                 double      c2 = cos(r);
423                                 double      t = nx;
424
425                                 if (nx > 1e4 || nx < -1e4 || ny > 1e4 || ny < -1e4)
426                                         ny = 1e4;
427                                 else
428                                         ny = c2 * t + c1 * ny;
429                                 nx = c1 * nx - c2 * ny;
430                                 break;
431                         }
432                 case 5:
433                         {
434                                 /* horseshoe */
435                                 double      r, c1, c2, t;
436
437                                 /* Avoid atan2: DOMAIN error message */
438                                 if (nx == 0.0 && ny == 0.0)
439                                         r = 0.0;
440                                 else
441                                         r = atan2(nx, ny);      /* times k here is fun */
442                                 c1 = sin(r);
443                                 c2 = cos(r);
444                                 t = nx;
445
446                                 nx = c1 * nx - c2 * ny;
447                                 ny = c2 * t + c1 * ny;
448                                 break;
449                         }
450                 case 6:
451                         {
452                                 /* drape */
453                                 double      t;
454
455                                 /* Avoid atan2: DOMAIN error message */
456                                 if (nx == 0.0 && ny == 0.0)
457                                         t = 0.0;
458                                 else
459                                         t = atan2(nx, ny) / M_PI;
460
461                                 if (nx > 1e4 || nx < -1e4 || ny > 1e4 || ny < -1e4)
462                                         ny = 1e4;
463                                 else
464                                         ny = sqrt(nx * nx + ny * ny) - 1.0;
465                                 nx = t;
466                                 break;
467                         }
468         }
469
470 #if 0
471         /* here are some others */
472         {
473                 /* broken */
474                 if (nx > 1.0)
475                         nx = nx - 1.0;
476                 if (nx < -1.0)
477                         nx = nx + 1.0;
478                 if (ny > 1.0)
479                         ny = ny - 1.0;
480                 if (ny < -1.0)
481                         ny = ny + 1.0;
482                 break;
483         }
484         {
485                 /* complex sine */
486                 double      u = nx, v = ny;
487                 double      ev = exp(v);
488                 double      emv = exp(-v);
489
490                 nx = (ev + emv) * sin(u) / 2.0;
491                 ny = (ev - emv) * cos(u) / 2.0;
492         }
493         {
494
495                 /* polynomial */
496                 if (nx < 0)
497                         nx = -nx * nx;
498                 else
499                         nx = nx * nx;
500
501                 if (ny < 0)
502                         ny = -ny * ny;
503                 else
504                         ny = ny * ny;
505         }
506         {
507                 /* spherical */
508                 double      r = 0.5 + sqrt(nx * nx + ny * ny + 1e-6);
509
510                 nx = nx / r;
511                 ny = ny / r;
512         }
513         {
514                 nx = atan(nx) / M_PI_2
515                         ny = atan(ny) / M_PI_2
516         }
517 #endif
518
519         /* how to check nan too?  some machines don't have finite().
520            don't need to check ny, it'll propogate */
521         if (nx > 1e4 || nx < -1e4) {
522                 nx = halfrandom(dp, 1000) / 500.0 - 1.0;
523                 ny = halfrandom(dp, 1000) / 500.0 - 1.0;
524                 dp->fuse = FUSE;
525         }
526         dp->x = nx;
527         dp->y = ny;
528         dp->c = nc;
529
530 }
531
532 static void
533 draw(ModeInfo * mi, driftstruct * dp, Drawable d)
534 {
535         Display    *display = MI_DISPLAY(mi);
536         GC          gc = MI_GC(mi);
537         double      x = dp->x;
538         double      y = dp->y;
539         int         fixed_x, fixed_y, npix, c, n;
540
541         if (dp->fuse) {
542                 dp->fuse--;
543                 return;
544         }
545         if (!(x > -1.0 && x < 1.0 && y > -1.0 && y < 1.0))
546                 return;
547
548         fixed_x = (int) ((dp->width / 2) * (x + 1.0));
549         fixed_y = (int) ((dp->height / 2) * (y + 1.0));
550
551         if (!dp->rainbow) {
552
553                 dp->pts[dp->npoints].x = fixed_x;
554                 dp->pts[dp->npoints].y = fixed_y;
555                 dp->npoints++;
556                 if (dp->npoints == MAXBATCH1) {
557                         XSetForeground(display, gc, dp->pixcol);
558                         XDrawPoints(display, d, gc, dp->pts, dp->npoints, CoordModeOrigin);
559                         dp->npoints = 0;
560                 }
561         } else {
562
563                 npix = MI_NPIXELS(mi);
564                 c = (int) (dp->c * npix);
565
566                 if (c < 0)
567                         c = 0;
568                 if (c >= npix)
569                         c = npix - 1;
570                 n = dp->ncpoints[c];
571                 dp->cpts[c * MAXBATCH2 + n].x = fixed_x;
572                 dp->cpts[c * MAXBATCH2 + n].y = fixed_y;
573                 if (++dp->ncpoints[c] == MAXBATCH2) {
574                         XSetForeground(display, gc, MI_PIXEL(mi, c));
575                         XDrawPoints(display, d, gc, &(dp->cpts[c * MAXBATCH2]),
576                                     dp->ncpoints[c], CoordModeOrigin);
577                         dp->ncpoints[c] = 0;
578                 }
579         }
580 }
581
582 static void
583 draw_flush(ModeInfo * mi, driftstruct * dp, Drawable d)
584 {
585         Display    *display = MI_DISPLAY(mi);
586         GC          gc = MI_GC(mi);
587
588         if (dp->rainbow) {
589                 int         npix = MI_NPIXELS(mi);
590                 int         i;
591
592                 for (i = 0; i < npix; i++) {
593                         if (dp->ncpoints[i]) {
594                                 XSetForeground(display, gc, MI_PIXEL(mi, i));
595                                 XDrawPoints(display, d, gc, &(dp->cpts[i * MAXBATCH2]),
596                                             dp->ncpoints[i], CoordModeOrigin);
597                                 dp->ncpoints[i] = 0;
598                         }
599                 }
600         } else {
601                 if (dp->npoints)
602                         XSetForeground(display, gc, dp->pixcol);
603                 XDrawPoints(display, d, gc, dp->pts,
604                             dp->npoints, CoordModeOrigin);
605                 dp->npoints = 0;
606         }
607 }
608
609
610 ENTRYPOINT void
611 draw_drift(ModeInfo * mi)
612 {
613         Window      window = MI_WINDOW(mi);
614         driftstruct *dp;
615
616         if (drifts == NULL)
617                 return;
618         dp = &drifts[MI_SCREEN(mi)];
619         if (dp->ncpoints == NULL)
620                 return;
621
622     if (dp->erase_countdown) {
623       if (!--dp->erase_countdown) {
624         dp->eraser = erase_window (MI_DISPLAY(mi), MI_WINDOW(mi), dp->eraser);
625       }
626       return;
627     }
628     if (dp->eraser) {
629       dp->eraser = erase_window (MI_DISPLAY(mi), MI_WINDOW(mi), dp->eraser);
630       return;
631     }
632
633         MI_IS_DRAWN(mi) = True;
634         dp->timer = 3000;
635         while (dp->timer) {
636                 iter(dp);
637                 draw(mi, dp, window);
638                 if (dp->total_points++ > dp->fractal_len) {
639                         draw_flush(mi, dp, window);
640                         if (0 == --dp->nfractals) {
641 #ifdef STANDALONE
642               dp->erase_countdown = 4 * 1000000 / MI_PAUSE(mi);
643 #endif /* STANDALONE */
644                                 initmode(mi, frandom(dp, 2));
645                         }
646                         initfractal(mi);
647                 }
648                 dp->timer--;
649         }
650         if (!dp->grow) {
651                 int         i, j, k;
652
653                 draw_flush(mi, dp, window);
654                 if (dp->liss)
655                         dp->liss_time++;
656                 for (i = 0; i < dp->nxforms; i++)
657                         for (j = 0; j < 2; j++)
658                                 for (k = 0; k < 3; k++) {
659                                         if (dp->liss)
660                                                 dp->f[j][k][i] = sin(dp->liss_time * dp->df[j][k][i]);
661                                         else {
662                                                 double      t = dp->f[j][k][i] += dp->df[j][k][i];
663
664                                                 if (t < -1.0 || 1.0 < t)
665                                                         dp->df[j][k][i] *= -1.0;
666                                         }
667                                 }
668         }
669 }
670
671 ENTRYPOINT void
672 reshape_drift(ModeInfo * mi, int width, int height)
673 {
674   MI_CLEARWINDOW(mi);
675   init_drift (mi);
676 }
677
678 ENTRYPOINT void
679 refresh_drift(ModeInfo * mi)
680 {
681         MI_CLEARWINDOW(mi);
682 }
683
684 ENTRYPOINT Bool
685 drift_handle_event (ModeInfo *mi, XEvent *event)
686 {
687   if (screenhack_event_helper (MI_DISPLAY(mi), MI_WINDOW(mi), event))
688     {
689       reshape_drift (mi, MI_WIDTH(mi), MI_HEIGHT(mi));
690       return True;
691     }
692   return False;
693 }
694
695
696 XSCREENSAVER_MODULE ("Drift", drift)
697
698 #endif /* MODE_drift */