ftp://ftp.krokus.ru/pub/OpenBSD/distfiles/xscreensaver-5.01.tar.gz
[xscreensaver] / hacks / goop.c
1 /* xscreensaver, Copyright (c) 1997, 2006 Jamie Zawinski <jwz@jwz.org>
2  *
3  * Permission to use, copy, modify, distribute, and sell this software and its
4  * documentation for any purpose is hereby granted without fee, provided that
5  * the above copyright notice appear in all copies and that both that
6  * copyright notice and this permission notice appear in supporting
7  * documentation.  No representations are made about the suitability of this
8  * software for any purpose.  It is provided "as is" without express or 
9  * implied warranty.
10  */
11
12 #include <math.h>
13 #include "screenhack.h"
14 #include "spline.h"
15 #include "alpha.h"
16
17
18 /* This is pretty compute-intensive, probably due to the large number of
19    polygon fills.  I tried introducing a scaling factor to make the spline
20    code emit fewer line segments, but that made the edges very rough.
21    However, tuning *maxVelocity, *elasticity and *delay can result in much
22    smoother looking animation.  I tuned these for a 1280x1024 Indy display,
23    but I don't know whether these values will be reasonable for a slower
24    machine...
25
26    The more planes the better -- SGIs have a 12-bit pseudocolor display
27    (4096 colormap cells) which is mostly useless, except for this program,
28    where it means you can have 11 or 12 mutually-transparent objects instead
29    of only 7 or 8.  But, if you are using the 12-bit visual, you should crank
30    down the velocity and elasticity, or server slowness will cause the
31    animation to look jerky (yes, it's sad but true, SGI's X server is
32    perceptibly slower when using plane masks on a 12-bit visual than on an
33    8-bit visual.)  Using -max-velocity 0.5 -elasticity 0.9 seems to work ok
34    on my Indy R5k with visual 0x27 and the bottom-of-the-line 24-bit graphics
35    board.
36
37    It might look better if each blob had an outline, which was a *slightly*
38    darker color than the center, to give them a bit more definition -- but
39    that would mean using two planes per blob.  (Or maybe allocating the
40    outline colors outside of the plane-space?  Then the outlines wouldn't be
41    transparent, but maybe that wouldn't be so noticeable?)
42
43    Oh, for an alpha channel... maybe I should rewrite this in GL.  Then the
44    blobs could have thickness, and curved edges with specular reflections...
45  */
46
47 #define SCALE       10000  /* fixed-point math, for sub-pixel motion */
48 #define DEF_COUNT   12     /* When planes and count are 0, how many blobs. */
49
50
51 #define RAND(n) ((long) ((random() & 0x7fffffff) % ((long) (n))))
52 #define RANDSIGN() ((random() & 1) ? 1 : -1)
53
54 struct blob {
55   long x, y;            /* position of midpoint */
56   long dx, dy;          /* velocity and direction */
57   double torque;        /* rotational speed */
58   double th;            /* angle of rotation */
59   long elasticity;      /* how fast they deform */
60   long max_velocity;    /* speed limit */
61   long min_r, max_r;    /* radius range */
62   int npoints;          /* control points */
63   long *r;              /* radii */
64   spline *spline;
65 };
66
67 struct layer {
68   int nblobs;
69   struct blob **blobs;
70   Pixmap pixmap;
71   unsigned long pixel;
72   GC gc;
73 };
74
75 enum goop_mode {
76   transparent,
77   opaque,
78   xor,
79   outline
80 };
81
82 struct goop {
83   enum goop_mode mode;
84   int width, height;
85   int nlayers;
86   struct layer **layers;
87   unsigned long background;
88   Pixmap pixmap;
89   GC pixmap_gc;
90   GC window_gc;
91   Bool additive_p;
92   Bool cmap_p;
93   int delay;
94 };
95
96
97 static struct blob *
98 make_blob (Display *dpy, int maxx, int maxy, int size)
99 {
100   struct blob *b = (struct blob *) calloc(1, sizeof(*b));
101   int i;
102   int mid;
103
104   maxx *= SCALE;
105   maxy *= SCALE;
106   size *= SCALE;
107
108   b->max_r = size/2;
109   b->min_r = size/10;
110
111   if (b->min_r < (5*SCALE)) b->min_r = (5*SCALE);
112   mid = ((b->min_r + b->max_r) / 2);
113
114   b->torque       = get_float_resource (dpy, "torque", "Torque");
115   b->elasticity   = SCALE * get_float_resource (dpy, "elasticity", "Elasticity");
116   b->max_velocity = SCALE * get_float_resource (dpy, "maxVelocity", "MaxVelocity");
117
118   b->x = RAND(maxx);
119   b->y = RAND(maxy);
120
121   b->dx = RAND(b->max_velocity) * RANDSIGN();
122   b->dy = RAND(b->max_velocity) * RANDSIGN();
123   b->th = frand(M_PI+M_PI) * RANDSIGN();
124   b->npoints = (random() % 5) + 5;
125
126   b->spline = make_spline (b->npoints);
127   b->r = (long *) malloc (sizeof(*b->r) * b->npoints);
128   for (i = 0; i < b->npoints; i++)
129     b->r[i] = ((random() % mid) + (mid/2)) * RANDSIGN();
130   return b;
131 }
132
133 static void 
134 throb_blob (struct blob *b)
135 {
136   int i;
137   double frac = ((M_PI+M_PI) / b->npoints);
138
139   for (i = 0; i < b->npoints; i++)
140     {
141       long r = b->r[i];
142       long ra = (r > 0 ? r : -r);
143       double th = (b->th > 0 ? b->th : -b->th);
144       long x, y;
145
146       /* place control points evenly around perimiter, shifted by theta */
147       x = b->x + ra * cos (i * frac + th);
148       y = b->y + ra * sin (i * frac + th);
149
150       b->spline->control_x[i] = x / SCALE;
151       b->spline->control_y[i] = y / SCALE;
152
153       /* alter the radius by a random amount, in the direction in which
154          it had been going (the sign of the radius indicates direction.) */
155       ra += (RAND(b->elasticity) * (r > 0 ? 1 : -1));
156       r = ra * (r >= 0 ? 1 : -1);
157
158       /* If we've reached the end (too long or too short) reverse direction. */
159       if ((ra > b->max_r && r >= 0) ||
160           (ra < b->min_r && r < 0))
161         r = -r;
162       /* And reverse direction in mid-course once every 50 times. */
163       else if (! (random() % 50))
164         r = -r;
165
166       b->r[i] = r;
167     }
168 }
169
170 static void
171 move_blob (struct blob *b, int maxx, int maxy)
172 {
173   maxx *= SCALE;
174   maxy *= SCALE;
175
176   b->x += b->dx;
177   b->y += b->dy;
178
179   /* If we've reached the edge of the box, reverse direction. */
180   if ((b->x > maxx && b->dx >= 0) ||
181       (b->x < 0    && b->dx < 0))
182     {
183       b->dx = -b->dx;
184     }
185   if ((b->y > maxy && b->dy >= 0) ||
186       (b->y < 0    && b->dy < 0))
187     {
188       b->dy = -b->dy;
189     }
190
191   /* Alter velocity randomly. */
192   if (! (random() % 10))
193     {
194       b->dx += (RAND(b->max_velocity/2) * RANDSIGN());
195       b->dy += (RAND(b->max_velocity/2) * RANDSIGN());
196
197       /* Throttle velocity */
198       if (b->dx > b->max_velocity || b->dx < -b->max_velocity)
199         b->dx /= 2;
200       if (b->dy > b->max_velocity || b->dy < -b->max_velocity)
201         b->dy /= 2;
202     }
203
204   {
205     double th = b->th;
206     double d = (b->torque == 0 ? 0 : frand(b->torque));
207     if (th < 0)
208       th = -(th + d);
209     else
210       th += d;
211
212     if (th > (M_PI+M_PI))
213       th -= (M_PI+M_PI);
214     else if (th < 0)
215       th += (M_PI+M_PI);
216
217     b->th = (b->th > 0 ? th : -th);
218   }
219
220   /* Alter direction of rotation randomly. */
221   if (! (random() % 100))
222     b->th *= -1;
223 }
224
225 static void
226 draw_blob (Display *dpy, Drawable drawable, GC gc, struct blob *b,
227            Bool fill_p)
228 {
229   compute_closed_spline (b->spline);
230 #ifdef DEBUG
231   {
232     int i;
233     for (i = 0; i < b->npoints; i++)
234       XDrawLine (dpy, drawable, gc, b->x/SCALE, b->y/SCALE,
235                  b->spline->control_x[i], b->spline->control_y[i]);
236   }
237 #else
238   if (fill_p)
239     XFillPolygon (dpy, drawable, gc, b->spline->points, b->spline->n_points,
240                   Nonconvex, CoordModeOrigin);
241   else
242 #endif
243     XDrawLines (dpy, drawable, gc, b->spline->points, b->spline->n_points,
244                 CoordModeOrigin);
245 }
246
247
248 static struct layer *
249 make_layer (Display *dpy, Window window, int width, int height, int nblobs)
250 {
251   int i;
252   struct layer *layer = (struct layer *) calloc(1, sizeof(*layer));
253   int blob_min, blob_max;
254   XGCValues gcv;
255   layer->nblobs = nblobs;
256
257   layer->blobs = (struct blob **) malloc(sizeof(*layer->blobs)*layer->nblobs);
258
259   blob_max = (width < height ? width : height) / 2;
260   blob_min = (blob_max * 2) / 3;
261   for (i = 0; i < layer->nblobs; i++){
262     int j = blob_max - blob_min;
263     layer->blobs[i] = make_blob (dpy, width, height,
264                                  (j ? random() % j : 0) + blob_min);
265   }
266
267   layer->pixmap = XCreatePixmap (dpy, window, width, height, 1);
268   layer->gc = XCreateGC (dpy, layer->pixmap, 0, &gcv);
269
270 # ifdef HAVE_COCOA
271   jwxyz_XSetAlphaAllowed (dpy, layer->gc, True);
272 # endif /* HAVE_COCOA */
273
274   return layer;
275 }
276
277
278 #ifndef HAVE_COCOA
279 static void
280 draw_layer_plane (Display *dpy, struct layer *layer, int width, int height)
281 {
282   int i;
283   for (i = 0; i < layer->nblobs; i++)
284     {
285       throb_blob (layer->blobs[i]);
286       move_blob (layer->blobs[i], width, height);
287       draw_blob (dpy, layer->pixmap, layer->gc, layer->blobs[i], True);
288     }
289 }
290 #endif /* !HAVE_COCOA */
291
292
293 static void
294 draw_layer_blobs (Display *dpy, Drawable drawable, GC gc,
295                   struct layer *layer, int width, int height,
296                   Bool fill_p)
297 {
298   int i;
299   for (i = 0; i < layer->nblobs; i++)
300     {
301       draw_blob (dpy, drawable, gc, layer->blobs[i], fill_p);
302       throb_blob (layer->blobs[i]);
303       move_blob (layer->blobs[i], width, height);
304     }
305 }
306
307
308 static struct goop *
309 make_goop (Screen *screen, Visual *visual, Window window, Colormap cmap,
310            int width, int height, long depth)
311 {
312   Display *dpy = DisplayOfScreen (screen);
313   int i;
314   struct goop *goop = (struct goop *) calloc(1, sizeof(*goop));
315   XGCValues gcv;
316   int nblobs = get_integer_resource (dpy, "count", "Count");
317
318   unsigned long *plane_masks = 0;
319 # ifndef HAVE_COCOA
320   unsigned long base_pixel = 0;
321 # endif
322   char *s;
323
324   s = get_string_resource (dpy, "mode", "Mode");
325   goop->mode = transparent;
326   if (!s || !*s || !strcasecmp (s, "transparent"))
327     ;
328   else if (!strcasecmp (s, "opaque"))
329     goop->mode = opaque;
330   else if (!strcasecmp (s, "xor"))
331     goop->mode = xor;
332   else
333     fprintf (stderr, "%s: bogus mode: \"%s\"\n", progname, s);
334
335   goop->delay = get_integer_resource (dpy, "delay", "Integer");
336
337   goop->width = width;
338   goop->height = height;
339
340   goop->nlayers = get_integer_resource (dpy, "planes", "Planes");
341   if (goop->nlayers <= 0)
342     goop->nlayers = (random() % (depth-2)) + 2;
343   goop->layers = (struct layer **) malloc(sizeof(*goop->layers)*goop->nlayers);
344
345   goop->additive_p = get_boolean_resource (dpy, "additive", "Additive");
346   goop->cmap_p = has_writable_cells (screen, visual);
347
348   if (mono_p && goop->mode == transparent)
349     goop->mode = opaque;
350
351 # ifndef HAVE_COCOA
352   /* Try to allocate some color planes before committing to nlayers.
353    */
354   if (goop->mode == transparent)
355     {
356       int nplanes = goop->nlayers;
357       allocate_alpha_colors (screen, visual, cmap,
358                              &nplanes, goop->additive_p, &plane_masks,
359                              &base_pixel);
360       if (nplanes > 1)
361         goop->nlayers = nplanes;
362       else
363         {
364           fprintf (stderr,
365          "%s: couldn't allocate any color planes; turning transparency off.\n",
366                    progname);
367           goop->mode = opaque;
368         }
369     }
370 # endif /* !HAVE_COCOA */
371
372   {
373     int lblobs[32];
374     int total = DEF_COUNT;
375     memset (lblobs, 0, sizeof(lblobs));
376     if (nblobs <= 0)
377       while (total)
378         for (i = 0; total && i < goop->nlayers; i++)
379           lblobs[i]++, total--;
380     for (i = 0; i < goop->nlayers; i++)
381       goop->layers[i] = make_layer (dpy, window, width, height, 
382                                     (nblobs > 0 ? nblobs : lblobs[i]));
383   }
384
385 # ifndef HAVE_COCOA
386   if (goop->mode == transparent && plane_masks)
387     {
388       for (i = 0; i < goop->nlayers; i++)
389         goop->layers[i]->pixel = base_pixel | plane_masks[i];
390       goop->background = base_pixel;
391     }
392 # endif /* !HAVE_COCOA */
393
394   if (plane_masks)
395     free (plane_masks);
396
397 # ifndef HAVE_COCOA
398   if (goop->mode != transparent)
399 # endif /* !HAVE_COCOA */
400     {
401       XColor color;
402       color.flags = DoRed|DoGreen|DoBlue;
403
404       goop->background =
405         get_pixel_resource (dpy,cmap, "background", "Background");
406
407       for (i = 0; i < goop->nlayers; i++)
408         {
409           int H = random() % 360;                          /* range 0-360    */
410           double S = ((double) (random()%70) + 30)/100.0;  /* range 30%-100% */
411           double V = ((double) (random()%34) + 66)/100.0;  /* range 66%-100% */
412           hsv_to_rgb (H, S, V, &color.red, &color.green, &color.blue);
413           if (XAllocColor (dpy, cmap, &color))
414             goop->layers[i]->pixel = color.pixel;
415           else
416             goop->layers[i]->pixel =
417               WhitePixelOfScreen(DefaultScreenOfDisplay(dpy));
418 # ifdef HAVE_COCOA
419           if (goop->mode == transparent)
420             {
421               /* give a non-opaque alpha to the color */
422               unsigned long pixel = goop->layers[i]->pixel;
423               unsigned long amask = BlackPixelOfScreen (0);
424               unsigned long a = (0xBBBBBBBB & amask);
425               pixel = (pixel & (~amask)) | a;
426               goop->layers[i]->pixel = pixel;
427             }
428 # endif /* HAVE_COCOA */
429         }
430     }
431
432   goop->pixmap = XCreatePixmap (dpy, window, width, height,
433                                 (goop->mode == xor ? 1L : depth));
434
435   gcv.background = goop->background;
436   gcv.foreground = get_pixel_resource (dpy, cmap, "foreground", "Foreground");
437   gcv.line_width = get_integer_resource (dpy, "thickness","Thickness");
438   goop->pixmap_gc = XCreateGC (dpy, goop->pixmap, GCLineWidth, &gcv);
439   goop->window_gc = XCreateGC (dpy, window, GCForeground|GCBackground, &gcv);
440
441 # ifdef HAVE_COCOA
442   jwxyz_XSetAlphaAllowed (dpy, goop->pixmap_gc, True);
443 # endif /* HAVE_COCOA */
444   
445   return goop;
446 }
447
448 static void *
449 goop_init (Display *dpy, Window window)
450 {
451   XWindowAttributes xgwa;
452   XGetWindowAttributes (dpy, window, &xgwa);
453   return make_goop (xgwa.screen, xgwa.visual, window, xgwa.colormap,
454                     xgwa.width, xgwa.height, xgwa.depth);
455 }
456
457 static unsigned long
458 goop_draw (Display *dpy, Window window, void *closure)
459 {
460   struct goop *goop = (struct goop *) closure;
461   int i;
462
463   switch (goop->mode)
464     {
465 # ifndef HAVE_COCOA
466     case transparent:
467
468       for (i = 0; i < goop->nlayers; i++)
469         draw_layer_plane (dpy, goop->layers[i], goop->width, goop->height);
470
471       XSetForeground (dpy, goop->pixmap_gc, goop->background);
472       XSetFunction (dpy, goop->pixmap_gc, GXcopy);
473       XSetPlaneMask (dpy, goop->pixmap_gc, AllPlanes);
474       XFillRectangle (dpy, goop->pixmap, goop->pixmap_gc, 0, 0,
475                       goop->width, goop->height);
476
477       XSetForeground (dpy, goop->pixmap_gc, ~0L);
478
479       if (!goop->cmap_p && !goop->additive_p)
480         {
481           int j;
482           for (i = 0; i < goop->nlayers; i++)
483             for (j = 0; j < goop->layers[i]->nblobs; j++)
484               draw_blob (dpy, goop->pixmap, goop->pixmap_gc,
485                          goop->layers[i]->blobs[j], True);
486           XSetFunction (dpy, goop->pixmap_gc, GXclear);
487         }
488
489       for (i = 0; i < goop->nlayers; i++)
490         {
491           XSetPlaneMask (dpy, goop->pixmap_gc, goop->layers[i]->pixel);
492           draw_layer_blobs (dpy, goop->pixmap, goop->pixmap_gc,
493                             goop->layers[i], goop->width, goop->height,
494                             True);
495         }
496       XCopyArea (dpy, goop->pixmap, window, goop->window_gc, 0, 0,
497                  goop->width, goop->height, 0, 0);
498       break;
499 #endif /* !HAVE_COCOA */
500
501     case xor:
502       XSetFunction (dpy, goop->pixmap_gc, GXcopy);
503       XSetForeground (dpy, goop->pixmap_gc, 0);
504       XFillRectangle (dpy, goop->pixmap, goop->pixmap_gc, 0, 0,
505                       goop->width, goop->height);
506       XSetFunction (dpy, goop->pixmap_gc, GXxor);
507       XSetForeground (dpy, goop->pixmap_gc, 1);
508       for (i = 0; i < goop->nlayers; i++)
509         draw_layer_blobs (dpy, goop->pixmap, goop->pixmap_gc,
510                           goop->layers[i], goop->width, goop->height,
511                           (goop->mode != outline));
512       XCopyPlane (dpy, goop->pixmap, window, goop->window_gc, 0, 0,
513                   goop->width, goop->height, 0, 0, 1L);
514       break;
515
516 # ifdef HAVE_COCOA
517     case transparent:
518 # endif
519     case opaque:
520     case outline:
521       XSetForeground (dpy, goop->pixmap_gc, goop->background);
522       XFillRectangle (dpy, goop->pixmap, goop->pixmap_gc, 0, 0,
523                       goop->width, goop->height);
524       for (i = 0; i < goop->nlayers; i++)
525         {
526           XSetForeground (dpy, goop->pixmap_gc, goop->layers[i]->pixel);
527           draw_layer_blobs (dpy, goop->pixmap, goop->pixmap_gc,
528                             goop->layers[i], goop->width, goop->height,
529                             (goop->mode != outline));
530         }
531       XCopyArea (dpy, goop->pixmap, window, goop->window_gc, 0, 0,
532                  goop->width, goop->height, 0, 0);
533       break;
534
535     default:
536       abort ();
537       break;
538     }
539   return goop->delay;
540 }
541
542 static void
543 goop_reshape (Display *dpy, Window window, void *closure, 
544                  unsigned int w, unsigned int h)
545 {
546   /* #### write me */
547 }
548
549 static Bool
550 goop_event (Display *dpy, Window window, void *closure, XEvent *event)
551 {
552   return False;
553 }
554
555 static void
556 goop_free (Display *dpy, Window window, void *closure)
557 {
558 }
559
560
561 \f
562
563 static const char *goop_defaults [] = {
564   ".background:         black",
565   ".foreground:         yellow",
566   "*delay:              12000",
567   "*additive:           true",
568   "*mode:               transparent",
569   "*count:              0",
570   "*planes:             0",
571   "*thickness:          5",
572   "*torque:             0.0075",
573   "*elasticity:         0.9",
574   "*maxVelocity:        0.5",
575   0
576 };
577
578 static XrmOptionDescRec goop_options [] = {
579   { "-delay",           ".delay",       XrmoptionSepArg, 0 },
580   { "-count",           ".count",       XrmoptionSepArg, 0 },
581   { "-planes",          ".planes",      XrmoptionSepArg, 0 },
582   { "-mode",            ".mode",        XrmoptionSepArg, 0 },
583   { "-xor",             ".mode",        XrmoptionNoArg, "xor" },
584   { "-transparent",     ".mode",        XrmoptionNoArg, "transparent" },
585   { "-opaque",          ".mode",        XrmoptionNoArg, "opaque" },
586   { "-additive",        ".additive",    XrmoptionNoArg, "True" },
587   { "-subtractive",     ".additive",    XrmoptionNoArg, "false" },
588   { "-thickness",       ".thickness",   XrmoptionSepArg, 0 },
589   { "-torque",          ".torque",      XrmoptionSepArg, 0 },
590   { "-elasticity",      ".elasticity",  XrmoptionSepArg, 0 },
591   { "-max-velocity",    ".maxVelocity", XrmoptionSepArg, 0 },
592   { 0, 0, 0, 0 }
593 };
594
595 XSCREENSAVER_MODULE ("Goop", goop)