1 /* tessellimage, Copyright (c) 2014 Jamie Zawinski <jwz@jwz.org>
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
12 #include "screenhack.h"
19 # define XK_MISCELLANY
20 # include <X11/keysymdef.h>
24 #define countof(x) (sizeof((x))/sizeof((*x)))
29 XWindowAttributes xgwa;
32 Bool outline_p, cache_p, fill_p;
33 double duration, duration2;
35 double start_time, start_time2;
38 Pixmap image, output, deltap;
39 int nthreshes, threshes[256], vsizes[256];
43 async_load_state *img_loader;
49 /* Returns the current time in seconds as a double.
55 # ifdef GETTIMEOFDAY_TWO_ARGS
57 gettimeofday(&now, &tzp);
62 return (now.tv_sec + ((double) now.tv_usec * 0.000001));
67 tessellimage_init (Display *dpy, Window window)
69 struct state *st = (struct state *) calloc (1, sizeof(*st));
75 XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
76 cmap = st->xgwa.colormap;
78 st->delay = get_integer_resource (st->dpy, "delay", "Integer");
79 if (st->delay < 1) st->delay = 1;
81 st->outline_p = get_boolean_resource (st->dpy, "outline", "Boolean");
82 st->cache_p = get_boolean_resource (st->dpy, "cache", "Boolean");
83 st->fill_p = get_boolean_resource (st->dpy, "fillScreen", "Boolean");
85 st->max_depth = get_integer_resource (st->dpy, "maxDepth", "MaxDepth");
86 if (st->max_depth < 100) st->max_depth = 100;
88 st->duration = get_float_resource (st->dpy, "duration", "Seconds");
89 if (st->duration < 1) st->duration = 1;
91 st->duration2 = get_float_resource (st->dpy, "duration2", "Seconds");
92 if (st->duration2 < 0.001) st->duration = 0.001;
94 XClearWindow(st->dpy, st->window);
100 /* Given a bitmask, returns the position and width of the field.
103 decode_mask (unsigned int mask, unsigned int *pos_ret, unsigned int *size_ret)
106 for (i = 0; i < 32; i++)
107 if (mask & (1L << i))
111 for (; i < 32; i++, j++)
112 if (! (mask & (1L << i)))
121 pixel_distance (Visual *v, unsigned long p1, unsigned long p2)
123 static int initted_p = 0;
124 static unsigned int rmsk=0, gmsk=0, bmsk=0;
125 static unsigned int rpos=0, gpos=0, bpos=0;
126 static unsigned int rsiz=0, gsiz=0, bsiz=0;
128 unsigned char r1, g1, b1;
129 unsigned char r2, g2, b2;
132 if (!p1 && !p2) return 0;
136 gmsk = v->green_mask;
138 decode_mask (rmsk, &rpos, &rsiz);
139 decode_mask (gmsk, &gpos, &gsiz);
140 decode_mask (bmsk, &bpos, &bsiz);
144 r1 = (p1 & rmsk) >> rpos;
145 g1 = (p1 & gmsk) >> gpos;
146 b1 = (p1 & bmsk) >> bpos;
148 r2 = (p2 & rmsk) >> rpos;
149 g2 = (p2 & gmsk) >> gpos;
150 b2 = (p2 & bmsk) >> bpos;
153 /* Compute the distance in linear RGB space.
155 distance = cbrt (((r2 - r1) * (r2 - r1)) +
156 ((g2 - g1) * (g2 - g1)) +
157 ((b2 - b1) * (b2 - b1)));
160 /* Compute the distance in luminance-weighted RGB space.
163 int rd = (r2 - r1) * 0.2989 * (1 / 0.5870);
164 int gd = (g2 - g1) * 0.5870 * (1 / 0.5870);
165 int bd = (b2 - b1) * 0.1140 * (1 / 0.5870);
166 distance = cbrt ((rd * rd) + (gd * gd) + (bd * bd));
169 /* Compute the distance in brightness-weighted HSV space.
170 (Slower, and doesn't seem to look better than luminance RGB.)
176 double hd, sd, vd, dd;
177 rgb_to_hsv (r1, g1, b1, &h1, &s1, &v1);
178 rgb_to_hsv (r2, g2, b2, &h2, &s2, &v2);
181 if (hd >= 180) hd -= 180;
186 /* [hsv]d are now the distance as 0.0 - 1.0. */
187 /* Compute the overall distance, giving more weight to V. */
188 dd = (hd * 0.25 + sd * 0.25 + vd * 0.5);
190 if (dd < 0 || dd > 1.0) abort();
195 if (distance < 0) distance = -distance;
201 flush_cache (struct state *st)
204 for (i = 0; i < countof(st->cache); i++)
207 XFreePixmap (st->dpy, st->cache[i]);
212 XFreePixmap (st->dpy, st->deltap);
218 /* Scale up the bits in st->img so that it fills the screen, centered.
221 scale_image (struct state *st)
223 double scale, s1, s2;
227 if (st->geom.width <= 0 || st->geom.height <= 0)
230 s1 = st->geom.width / (double) st->img->width;
231 s2 = st->geom.height / (double) st->img->height;
232 scale = (s1 < s2 ? s1 : s2);
234 img2 = XCreateImage (st->dpy, st->xgwa.visual, st->img->depth,
236 st->img->width, st->img->height, 8, 0);
238 img2->data = (char *) calloc (img2->height, img2->bytes_per_line);
239 if (! img2->data) abort();
241 cx = st->img->width / 2;
242 cy = st->img->height / 2;
244 if (st->geom.width < st->geom.height) /* portrait: aim toward the top */
245 cy = st->img->height / (2 / scale);
247 for (y = 0; y < img2->height; y++)
248 for (x = 0; x < img2->width; x++)
250 int x2 = cx + ((x - cx) * scale);
251 int y2 = cy + ((y - cy) * scale);
253 if (x2 >= 0 && y2 >= 0 &&
254 x2 < st->img->width && y2 < st->img->height)
255 p = XGetPixel (st->img, x2, y2);
256 XPutPixel (img2, x, y, p);
258 free (st->img->data);
260 XDestroyImage (st->img);
265 st->geom.width = st->img->width;
266 st->geom.height = st->img->height;
272 analyze (struct state *st)
276 unsigned int w, h, bw, d;
277 unsigned long histo[256];
281 /* Convert the loaded pixmap to an XImage.
283 XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
284 XGetGeometry (st->dpy, st->image, &root, &x, &y, &w, &h, &bw, &d);
288 free (st->img->data);
290 XDestroyImage (st->img);
292 st->img = XGetImage (st->dpy, st->image, 0, 0, w, h, ~0L, ZPixmap);
294 if (st->fill_p) scale_image (st);
296 /* Create the delta map: color space distance between each pixel.
297 Maybe doing running a Sobel Filter matrix on this would be a
298 better idea. That might be a bit faster, but I think it would
299 make no visual difference.
303 free (st->delta->data);
305 XDestroyImage (st->delta);
307 st->delta = XCreateImage (st->dpy, st->xgwa.visual, d, ZPixmap, 0, NULL,
309 st->delta->data = (char *)
310 calloc (st->delta->height, st->delta->bytes_per_line);
312 for (y = 0; y < st->delta->height; y++)
314 for (x = 0; x < st->delta->width; x++)
316 unsigned long pixels[5];
319 pixels[i++] = XGetPixel (st->img, x, y);
320 pixels[i++] = (x > 0 && y > 0 ? XGetPixel (st->img, x-1, y-1) : 0);
321 pixels[i++] = ( y > 0 ? XGetPixel (st->img, x, y-1) : 0);
322 pixels[i++] = (x > 0 ? XGetPixel (st->img, x-1, y) : 0);
323 pixels[i++] = (x > 0 && y < h-1 ? XGetPixel (st->img, x-1, y+1) : 0);
325 for (i = 1; i < countof(pixels); i++)
326 distance += pixel_distance (st->xgwa.visual, pixels[0], pixels[i]);
327 distance /= countof(pixels)-1;
328 XPutPixel (st->delta, x, y, distance);
332 /* Collect a histogram of every distance value.
334 memset (histo, 0, sizeof(histo));
335 for (y = 0; y < st->delta->height; y++)
336 for (x = 0; x < st->delta->width; x++)
338 unsigned long p = XGetPixel (st->delta, x, y);
339 if (p > sizeof(histo)) abort();
343 /* Convert that from "occurrences of N" to ">= N".
345 for (i = countof(histo) - 1; i > 0; i--)
346 histo[i-1] += histo[i];
349 fprintf (stderr, "%s: histo: ", progname);
350 for (i = 0; i < countof(histo); i++)
351 fprintf(stderr, "%d:%lu ", i, histo[i]);
352 fprintf(stderr, "\n");
355 /* Collect a useful set of threshold values, ignoring thresholds that
356 result in a very similar number of control points (since those images
357 probably won't look very different).
361 int max_vsize = st->max_depth;
365 if (min_vsize > max_vsize/100)
366 min_vsize = max_vsize/100;
368 if (min_delta > max_vsize/1000)
369 min_delta = max_vsize/1000;
372 for (i = countof(histo)-1; i >= 0; i--)
374 unsigned long vsize = histo[i];
376 /* If this is a different vsize, push it. */
377 if (vsize >= min_vsize &&
378 vsize <= max_vsize &&
379 (st->nthreshes == 0 ||
380 vsize >= st->vsizes[st->nthreshes-1] + min_delta))
382 st->threshes[st->nthreshes] = i;
383 st->vsizes[st->nthreshes] = vsize;
389 st->thresh = 0; /* startup */
390 st->dthresh = 1; /* forward */
394 XFreePixmap (st->dpy, st->output);
400 fprintf (stderr, "%s: threshes:", progname);
401 for (i = 0; i < st->nthreshes; i++)
402 fprintf (stderr, " %d=%d", st->threshes[i], st->vsizes[i]);
403 fprintf (stderr, "\n");
409 /* True if the distance between any two corners is too small for it to
410 make sense to draw an outline around this triangle.
413 small_triangle_p (const XPoint *p)
416 if (abs (p[0].x - p[1].x) < min) return True;
417 if (abs (p[0].y - p[1].y) < min) return True;
418 if (abs (p[1].x - p[2].x) < min) return True;
419 if (abs (p[1].y - p[2].y) < min) return True;
420 if (abs (p[2].x - p[0].x) < min) return True;
421 if (abs (p[2].y - p[0].y) < min) return True;
424 #endif /* DO_VORONOI */
433 static voronoi_polygon *
434 delaunay_to_voronoi (int np, XYZ *p, int nv, ITRIANGLE *v)
442 struct tri_list *vert_to_tri = (struct tri_list *)
443 calloc (np + 1, sizeof(*vert_to_tri));
444 voronoi_polygon *out = (voronoi_polygon *) calloc (np + 1, sizeof(*out));
447 for (i = 0; i < np; i++)
448 printf("# p %d = %d %d\n", i, (int)p[i].x, (int)p[i].y);
450 for (i = 0; i < nv; i++)
451 printf("@ t %d = %d %d %d\n", i, (int)v[i].p1, (int)v[i].p2, (int)v[i].p3);
455 /* Iterate the triangles to construct a map of vertices to the
456 triangles that contain them.
458 for (i = 0; i < nv; i++)
460 for (j = 0; j < 3; j++) /* iterate points in each triangle */
462 int p = *((&v[i].p1) + j);
463 struct tri_list *t = &vert_to_tri[p];
464 if (p < 0 || p >= np) abort();
465 if (t->size <= t->count + 1)
469 t->tri = realloc (t->tri, t->size * sizeof(*t->tri));
470 if (! t->tri) abort();
472 t->tri[t->count++] = i;
477 for (i = 0; i < nv; i++)
479 struct tri_list *t = &vert_to_tri[i];
480 printf("p %d [%d %d]:", i, (int)p[i].x, (int)p[i].y);
481 for (j = 0; j < t->count; j++) {
483 printf(" t %d [%d(%d %d) %d(%d %d) %d(%d %d)]",
486 (int)p[v[tt].p1].x, (int)p[v[tt].p1].y,
488 (int)p[v[tt].p2].x, (int)p[v[tt].p2].y,
490 (int)p[v[tt].p3].x, (int)p[v[tt].p3].y
492 if (tt < 0 || tt >= nv) abort();
498 /* For every vertex, compose a polygon whose corners are the centers
499 of each triangle using that vertex. Skip any with less than 3 points.
501 for (i = 0; i < np; i++)
503 struct tri_list *t = &vert_to_tri[i];
508 ? (XPoint *) calloc (out[i].npoints + 1, sizeof (*out[i].p))
511 for (j = 0; j < out[i].npoints; j++)
513 ITRIANGLE *tt = &v[t->tri[j]];
514 out[i].p[j].x = (p[tt->p1].x + p[tt->p2].x + p[tt->p3].x) / 3;
515 out[i].p[j].y = (p[tt->p1].y + p[tt->p2].y + p[tt->p3].y) / 3;
516 //printf(" [%d: %d %d]", j, out[i].p[j].x, out[i].p[j].y);
525 #endif /* DO_VORONOI */
531 tessellate (struct state *st)
533 Bool ticked_p = False;
535 if (! st->image) return;
540 gcv.function = GXcopy;
541 gcv.subwindow_mode = IncludeInferiors;
542 st->wgc = XCreateGC(st->dpy, st->window, GCFunction, &gcv);
543 st->pgc = XCreateGC(st->dpy, st->image, GCFunction, &gcv);
546 /* If duration2 has expired, switch to the next threshold. */
548 if (! st->button_down_p)
550 double t2 = double_time();
551 if (st->start_time2 + st->duration2 < t2)
553 st->start_time2 = t2;
554 st->thresh += st->dthresh;
556 if (st->thresh >= st->nthreshes)
558 st->thresh = st->nthreshes - 1;
561 else if (st->thresh < 0)
572 /* If we've picked a new threshold, regenerate the output image. */
574 if (ticked_p && st->cache[st->thresh])
577 st->cache[st->thresh],
579 0, 0, st->delta->width, st->delta->height,
584 int threshold = st->threshes[st->thresh];
585 int vsize = st->vsizes[st->thresh];
593 fprintf(stderr, "%s: thresh %d/%d = %d=%d\n",
594 progname, st->thresh, st->nthreshes, threshold, vsize);
597 /* Create a control point at every pixel where the delta is above
598 the current threshold. Triangulate from those. */
600 vsize += 8; /* corners of screen + corners of image */
602 p = (XYZ *) calloc (vsize+4, sizeof(*p));
603 v = (ITRIANGLE *) calloc (3*(vsize+4), sizeof(*v));
606 fprintf (stderr, "%s: out of memory (%d)\n", progname, vsize);
610 /* Add control points for the corners of the screen, and for the
611 corners of the image.
613 if (st->geom.width <= 0) st->geom.width = st->delta->width;
614 if (st->geom.height <= 0) st->geom.height = st->delta->height;
616 for (y = 0; y <= 1; y++)
617 for (x = 0; x <= 1; x++)
619 p[nv].x = x ? st->delta->width-1 : 0;
620 p[nv].y = y ? st->delta->height-1 : 0;
621 p[nv].z = XGetPixel (st->delta, (int) p[nv].x, (int) p[nv].y);
623 p[nv].x = st->geom.x + (x ? st->geom.width-1 : 0);
624 p[nv].y = st->geom.y + (y ? st->geom.height-1 : 0);
625 p[nv].z = XGetPixel (st->delta, (int) p[nv].x, (int) p[nv].y);
629 /* Add control points for every pixel that exceeds the threshold.
631 for (y = 0; y < st->delta->height; y++)
632 for (x = 0; x < st->delta->width; x++)
634 unsigned long px = XGetPixel (st->delta, x, y);
637 if (nv >= vsize) abort();
645 if (nv != vsize) abort();
647 qsort (p, nv, sizeof(*p), delaunay_xyzcompare);
648 if (delaunay (nv, p, v, &ntri))
650 fprintf (stderr, "%s: out of memory\n", progname);
654 /* Create the output pixmap based on that triangulation. */
657 XFreePixmap (st->dpy, st->output);
658 st->output = XCreatePixmap (st->dpy, st->window,
659 st->delta->width, st->delta->height,
661 XFillRectangle (st->dpy, st->output, st->pgc,
662 0, 0, st->delta->width, st->delta->height);
666 voronoi_polygon *polys = delaunay_to_voronoi (nv, p, ntri, v);
667 for (i = 0; i < nv; i++)
669 if (polys[i].npoints >= 3)
671 unsigned long color = XGetPixel (st->img, p[i].x, p[i].y);
672 XSetForeground (st->dpy, st->pgc, color);
673 XFillPolygon (st->dpy, st->output, st->pgc,
674 polys[i].p, polys[i].npoints,
675 Convex, CoordModeOrigin);
682 XQueryColor (st->dpy, st->xgwa.colormap, &bd);
687 /* bd.red = 0xFFFF; bd.green = 0; bd.blue = 0; */
689 XAllocColor (st->dpy, st->xgwa.colormap, &bd);
690 XSetForeground (st->dpy, st->pgc, bd.pixel);
691 XDrawLines (st->dpy, st->output, st->pgc,
692 polys[i].p, polys[i].npoints,
694 XFreeColors (st->dpy, st->xgwa.colormap, &bd.pixel, 1, 0);
697 if (polys[i].p) free (polys[i].p);
702 #else /* !DO_VORONOI */
704 for (i = 0; i < ntri; i++)
708 xp[0].x = p[v[i].p1].x; xp[0].y = p[v[i].p1].y;
709 xp[1].x = p[v[i].p2].x; xp[1].y = p[v[i].p2].y;
710 xp[2].x = p[v[i].p3].x; xp[2].y = p[v[i].p3].y;
712 /* Set the color of this triangle to the pixel at its midpoint. */
713 color = XGetPixel (st->img,
714 (xp[0].x + xp[1].x + xp[2].x) / 3,
715 (xp[0].y + xp[1].y + xp[2].y) / 3);
717 XSetForeground (st->dpy, st->pgc, color);
718 XFillPolygon (st->dpy, st->output, st->pgc, xp, countof(xp),
719 Convex, CoordModeOrigin);
721 if (st->outline_p && !small_triangle_p(xp))
722 { /* Border the triangle with a color that is darker */
726 XQueryColor (st->dpy, st->xgwa.colormap, &bd);
731 /* bd.red = 0xFFFF; bd.green = 0; bd.blue = 0; */
733 XAllocColor (st->dpy, st->xgwa.colormap, &bd);
734 XSetForeground (st->dpy, st->pgc, bd.pixel);
735 XDrawLines (st->dpy, st->output, st->pgc,
736 xp, countof(xp), CoordModeOrigin);
737 XFreeColors (st->dpy, st->xgwa.colormap, &bd.pixel, 1, 0);
740 #endif /* !DO_VORONOI */
745 if (st->cache_p && !st->cache[st->thresh])
747 st->cache[st->thresh] =
748 XCreatePixmap (st->dpy, st->window,
749 st->delta->width, st->delta->height,
751 if (! st->cache[st->thresh])
753 fprintf (stderr, "%s: out of memory\n", progname);
758 st->cache[st->thresh],
760 0, 0, st->delta->width, st->delta->height,
765 if (! st->output) abort();
769 /* Convert the delta map into a displayable pixmap.
772 get_deltap (struct state *st)
775 int w = st->delta->width;
776 int h = st->delta->height;
779 Visual *v = st->xgwa.visual;
780 unsigned int rmsk=0, gmsk=0, bmsk=0;
781 unsigned int rpos=0, gpos=0, bpos=0;
782 unsigned int rsiz=0, gsiz=0, bsiz=0;
784 if (st->deltap) return st->deltap;
787 gmsk = v->green_mask;
789 decode_mask (rmsk, &rpos, &rsiz);
790 decode_mask (gmsk, &gpos, &gsiz);
791 decode_mask (bmsk, &bpos, &bsiz);
793 dimg = XCreateImage (st->dpy, st->xgwa.visual, st->xgwa.depth,
794 ZPixmap, 0, NULL, w, h, 8, 0);
796 dimg->data = (char *) calloc (dimg->height, dimg->bytes_per_line);
797 if (! dimg->data) abort();
799 for (y = 0; y < h; y++)
800 for (x = 0; x < w; x++)
802 unsigned long v = XGetPixel (st->delta, x, y) << 5;
803 unsigned long p = (((v << rpos) & rmsk) |
804 ((v << gpos) & gmsk) |
805 ((v << bpos) & bmsk));
806 XPutPixel (dimg, x, y, p);
809 st->deltap = XCreatePixmap (st->dpy, st->window, w, h, st->xgwa.depth);
810 XPutImage (st->dpy, st->deltap, st->pgc, dimg, 0, 0, 0, 0, w, h);
811 XDestroyImage (dimg);
817 tessellimage_draw (Display *dpy, Window window, void *closure)
819 struct state *st = (struct state *) closure;
821 if (st->img_loader) /* still loading */
823 st->img_loader = load_image_async_simple (st->img_loader, 0, 0, 0, 0,
825 if (! st->img_loader) { /* just finished */
827 st->start_time = double_time();
828 st->start_time2 = st->start_time;
833 if (!st->img_loader &&
834 st->start_time + st->duration < double_time()) {
835 XClearWindow (st->dpy, st->window);
836 if (st->image) XFreePixmap (dpy, st->image);
837 st->image = XCreatePixmap (st->dpy, st->window,
838 st->xgwa.width, st->xgwa.height,
840 st->img_loader = load_image_async_simple (0, st->xgwa.screen, st->window,
841 st->image, 0, &st->geom);
847 XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
848 XClearWindow (st->dpy, st->window);
852 (st->button_down_p ? get_deltap (st) : st->output),
854 0, 0, st->delta->width, st->delta->height,
855 (st->xgwa.width - st->delta->width) / 2,
856 (st->xgwa.height - st->delta->height) / 2);
863 tessellimage_reshape (Display *dpy, Window window, void *closure,
864 unsigned int w, unsigned int h)
866 struct state *st = (struct state *) closure;
867 XGetWindowAttributes (st->dpy, st->window, &st->xgwa);
871 tessellimage_event (Display *dpy, Window window, void *closure, XEvent *event)
873 struct state *st = (struct state *) closure;
874 if (event->xany.type == ButtonPress)
876 st->button_down_p = True;
879 else if (event->xany.type == ButtonRelease)
881 st->button_down_p = False;
884 else if (event->xany.type == KeyPress)
888 if (event->xany.type == KeyPress || event->xany.type == KeyRelease)
889 XLookupString (&event->xkey, &c, 1, &keysym, 0);
896 st->start_time = 0; /* load next image */
915 tessellimage_free (Display *dpy, Window window, void *closure)
917 struct state *st = (struct state *) closure;
919 XFreeGC (dpy, st->wgc);
920 XFreeGC (dpy, st->pgc);
921 if (st->image) XFreePixmap (dpy, st->image);
922 if (st->output) XFreePixmap (dpy, st->output);
923 if (st->delta) XDestroyImage (st->delta);
930 static const char *tessellimage_defaults [] = {
931 ".background: black",
932 ".foreground: white",
933 "*dontClearRoot: True",
943 "*ignoreRotation: True",
948 static XrmOptionDescRec tessellimage_options [] = {
949 { "-delay", ".delay", XrmoptionSepArg, 0 },
950 { "-duration", ".duration", XrmoptionSepArg, 0 },
951 { "-duration2", ".duration2", XrmoptionSepArg, 0 },
952 { "-max-depth", ".maxDepth", XrmoptionSepArg, 0 },
953 { "-outline", ".outline", XrmoptionNoArg, "True" },
954 { "-no-outline", ".outline", XrmoptionNoArg, "False" },
955 { "-fill-screen", ".fillScreen", XrmoptionNoArg, "True" },
956 { "-no-fill-screen", ".fillScreen", XrmoptionNoArg, "False" },
957 { "-cache", ".cache", XrmoptionNoArg, "True" },
958 { "-no-cache", ".cache", XrmoptionNoArg, "False" },
962 XSCREENSAVER_MODULE ("Tessellimage", tessellimage)