1 /* epicycle --- The motion of a body with epicycles, as in the pre-Copernican
4 * Copyright (c) 1998 James Youngman <jay@gnu.org>
6 * Permission to use, copy, modify, distribute, and sell this software and its
7 * documentation for any purpose is hereby granted without fee, provided that
8 * the above copyright notice appear in all copies and that both that
9 * copyright notice and this permission notice appear in supporting
10 * documentation. No representations are made about the suitability of this
11 * software for any purpose. It is provided "as is" without express or
15 /* Standard C headers; screenhack.h assumes that these have already
16 * been included if required -- for example, it defines M_PI if not
23 #include "screenhack.h"
26 /* MIT-SHM headers omitted; this screenhack doesn't use it */
30 /*********************************************************/
31 /******************** MAGIC CONSTANTS ********************/
32 /*********************************************************/
33 #define MIN_RADIUS (5) /* smallest allowable circle radius */
34 #define FILL_PROPORTION (0.9) /* proportion of screen to fill by scaling. */
35 /*********************************************************/
36 /***************** END OF MAGIC CONSTANTS ****************/
37 /*********************************************************/
41 #define FULLCIRCLE (2.0 * M_PI) /* radians in a circle. */
44 /* Some of these resource values here are hand-tuned to give a
45 * pleasing variety of interesting shapes. These are not the only
46 * good settings, but you may find you need to change some as a group
47 * to get pleasing figures.
49 static const char *epicycle_defaults [] = {
64 "*timestepCoarseFactor: 1.0", /* no option for this resource. */
65 "*divisorPoisson: 0.4",
66 "*sizeFactorMin: 1.05",
67 "*sizeFactorMax: 2.05",
71 /* options passed to this program */
72 static XrmOptionDescRec epicycle_options [] = {
73 { "-color0", ".color0", XrmoptionSepArg, 0 },
74 { "-colors", ".colors", XrmoptionSepArg, 0 },
75 { "-colours", ".colors", XrmoptionSepArg, 0 },
76 { "-foreground", ".foreground", XrmoptionSepArg, 0 },
77 { "-delay", ".delay", XrmoptionSepArg, 0 },
78 { "-holdtime", ".holdtime", XrmoptionSepArg, 0 },
79 { "-linewidth", ".lineWidth", XrmoptionSepArg, 0 },
80 { "-min_circles", ".minCircles", XrmoptionSepArg, 0 },
81 { "-max_circles", ".maxCircles", XrmoptionSepArg, 0 },
82 { "-min_speed", ".minSpeed", XrmoptionSepArg, 0 },
83 { "-max_speed", ".maxSpeed", XrmoptionSepArg, 0 },
84 { "-harmonics", ".harmonics", XrmoptionSepArg, 0 },
85 { "-timestep", ".timestep", XrmoptionSepArg, 0 },
86 { "-divisor_poisson",".divisorPoisson",XrmoptionSepArg, 0 },
87 { "-size_factor_min", ".sizeFactorMin", XrmoptionSepArg, 0 },
88 { "-size_factor_max", ".sizeFactorMax", XrmoptionSepArg, 0 },
93 /* Each circle is centred on a point on the rim of another circle.
97 long radius; /* in pixels */
98 double w; /* position (radians ccw from x-axis) */
99 double initial_w; /* starting position */
100 double wdot; /* rotation rate (change in w per iteration) */
103 struct tagCircle *pchild;
105 typedef struct tagCircle Circle;
108 struct tagBody /* a body that moves on a system of circles. */
110 int x_origin, y_origin;
113 int current_color; /* pixel index into colors[] */
114 Circle *epicycles; /* system of circles on which it moves. */
115 struct tagBody *next; /* next in list. */
117 typedef struct tagBody Body;
125 int x_offset, y_offset;
133 int color_shift_pos; /* how far we are towards that. */
134 double colour_cycle_rate;
136 double divisorPoisson;
137 double sizeFactorMin;
138 double sizeFactorMax;
145 double T, timestep, circle, timestep_coarse;
149 int xmax, xmin, ymax, ymin;
152 eraser_state *eraser;
157 /* Determine the GCD of two numbers using Euclid's method. The other
158 * possible algorighm is Stein's method, but it's probably only going
159 * to be much faster on machines with no divide instruction, like the
160 * ARM and the Z80. The former is very fast anyway and the latter
161 * probably won't run X clients; in any case, this calculation is not
162 * the bulk of the computational expense of the program. I originally
163 * tried using Stein's method, but I wanted to remove the gotos. Not
164 * wanting to introduce possible bugs, I plumped for Euclid's method
165 * instead. Lastly, Euclid's algorithm is preferred to the
166 * generalisation for N inputs.
168 * See Knuth, section 4.5.2.
171 gcd(int u, int v) /* Euclid's Method */
173 /* If either operand of % is negative, the sign of the result is
174 * implementation-defined. See section 6.3.5 "Multiplicative
175 * Operators" of the ANSI C Standard (page 46 [LEFT HAND PAGE!] of
176 * "Annotated C Standard", Osborne, ISBN 0-07-881952-0).
191 /* Determine the Lowest Common Multiple of two integers, using
192 * Euclid's Proposition 34, as explained in Knuth's The Art of
193 * Computer Programming, Vol 2, section 4.5.2.
198 return u / gcd(u,v) * v;
202 random_radius(struct state *st, double scale)
206 r = frand(scale) * st->unit_pixels/2; /* for frand() see utils/yarandom.h */
214 random_divisor(struct state *st)
219 while (frand(1.0) < st->divisorPoisson && divisor <= st->harmonics)
223 sign = (frand(1.0) < 0.5) ? +1 : -1;
224 return sign * divisor;
229 oom(struct state *st)
231 fprintf(stderr, "Failed to allocate memory!\n");
236 /* Construct a circle or die.
239 new_circle(struct state *st, double scale)
241 Circle *p = malloc(sizeof(Circle));
243 p->radius = random_radius(st, scale);
244 p->w = p->initial_w = 0.0;
245 p->divisor = random_divisor(st);
246 p->wdot = st->wdot_max / p->divisor;
252 static void delete_circle(Circle *p)
258 delete_circle_chain(Circle *p)
262 Circle *q = p->pchild;
269 new_circle_chain(struct state *st)
272 double scale = 1.0, factor;
275 /* Parent circles are larger than their children by a factor of at
276 * least FACTOR_MIN and at most FACTOR_MAX.
278 factor = st->sizeFactorMin + frand(st->sizeFactorMax - st->sizeFactorMin);
280 /* There are between minCircles and maxCircles in each figure.
282 if (st->maxCircles == st->minCircles)
283 n = st->minCircles; /* Avoid division by zero. */
285 n = st->minCircles + random() % (st->maxCircles - st->minCircles);
290 Circle *p = new_circle(st, scale);
300 assign_random_common_w(Circle *p)
302 double w_common = frand(FULLCIRCLE); /* anywhere on the circle */
305 p->initial_w = w_common;
311 new_body(struct state *st)
313 Body *p = malloc(sizeof(Body));
316 p->epicycles = new_circle_chain(st);
317 p->current_color = 0; /* ?? start them all on different colors? */
320 p->old_x = p->old_y = 0;
321 p->x_origin = p->y_origin = 0;
323 /* Start all the epicycles at the same w value to make it easier to
324 * figure out at what T value the cycle is closed. We don't just fix
325 * the initial W value because that makes all the patterns tend to
326 * be symmetrical about the X axis.
328 assign_random_common_w(p->epicycles);
335 delete_circle_chain(p->epicycles);
341 draw_body(struct state *st, Body *pb, GC gc)
343 XDrawLine(st->dpy, st->window, gc, pb->old_x, pb->old_y, pb->x, pb->y);
347 compute_divisor_lcm(Circle *p)
353 l = lcm(l, p->divisor);
362 * Calculate the position for the body at time T. We work in double
363 * rather than int to avoid the cumulative errors that would be caused
364 * by the rounding implicit in an assignment to int.
367 move_body(Body *pb, double t)
378 for (p=pb->epicycles; NULL != p; p=p->pchild)
380 /* angular pos = initial_pos + time * angular speed */
381 /* but this is an angular position, so modulo FULLCIRCLE. */
382 p->w = fmod(p->initial_w + (t * p->wdot), FULLCIRCLE);
384 x += (p->radius * cos(p->w));
385 y += (p->radius * sin(p->w));
393 colour_init(struct state *st, XWindowAttributes *pxgwa)
398 int H = random() % 360; /* colour choice from attraction.c. */
401 double V = frand(0.25) + 0.75;
406 unsigned long valuemask = 0L;
409 /* Free any already allocated colors...
413 free_colors(st->dpy, st->cmap, st->colors, st->ncolors);
418 st->ncolors = get_integer_resource (st->dpy, "colors", "Colors");
419 if (0 == st->ncolors) /* English spelling? */
420 st->ncolors = get_integer_resource (st->dpy, "colours", "Colors");
424 if (st->ncolors <= 2)
430 st->colors = (XColor *) malloc(sizeof(*st->colors) * (st->ncolors+1));
434 make_smooth_colormap (st->dpy, pxgwa->visual, st->cmap, st->colors, &st->ncolors,
436 False, /* not writable */
437 True); /* verbose (complain about failure) */
438 if (st->ncolors <= 2)
448 st->bg = get_pixel_resource (st->dpy, st->cmap, "background", "Background");
450 /* Set the line width
452 gcv.line_width = get_integer_resource (st->dpy, "lineWidth", "Integer");
455 valuemask |= GCLineWidth;
457 gcv.join_style = JoinRound;
458 gcv.cap_style = CapRound;
460 valuemask |= (GCCapStyle | GCJoinStyle);
464 /* Set the drawing function.
466 gcv.function = GXcopy;
467 valuemask |= GCFunction;
469 /* Set the foreground.
472 fg = get_pixel_resource (st->dpy, st->cmap, "foreground", "Foreground");
475 fg = st->bg ^ get_pixel_resource (st->dpy, st->cmap, ("color0"), "Foreground");
478 valuemask |= GCForeground;
480 /* Actually create the GC.
482 st->color0 = XCreateGC (st->dpy, st->window, valuemask, &gcv);
491 setup(struct state *st)
493 XWindowAttributes xgwa;
495 XGetWindowAttributes (st->dpy, st->window, &xgwa);
496 st->cmap = xgwa.colormap;
498 st->width = xgwa.width;
499 st->height = xgwa.height;
500 st->x_offset = st->width / 2;
501 st->y_offset = st->height / 2;
502 st->unit_pixels = st->width < st->height ? st->width : st->height;
507 colour_init(st, &xgwa);
515 color_step(struct state *st, Body *pb, double frac)
519 int newshift = st->ncolors * fmod(frac * st->colour_cycle_rate, 1.0);
520 if (newshift != st->color_shift_pos)
522 pb->current_color = newshift;
523 XSetForeground (st->dpy, st->color0, st->colors[pb->current_color].pixel);
524 st->color_shift_pos = newshift;
532 distance(long x1, long y1, long x2, long y2)
538 return dx*dx + dy*dy;
541 static int poisson_irand(double p)
544 while (fabs(frand(1.0)) < p)
546 return r < 1 ? 1 : r;
551 precalculate_figure(Body *pb,
552 double this_xtime, double step,
553 int *x_max, int *y_max,
554 int *x_min, int *y_min)
558 move_body(pb, 0.0); /* move once to avoid initial line from origin */
559 *x_min = *x_max = pb->x;
560 *y_min = *y_max = pb->y;
562 for (t=0.0; t<this_xtime; t += step)
564 move_body(pb, t); /* move once to avoid initial line from origin */
576 static int i_max(int a, int b)
578 return (a>b) ? a : b;
581 static void rescale_circles(struct state *st, Body *pb,
582 int x_max, int y_max,
583 int x_min, int y_min)
585 double xscale, yscale, scale;
588 x_max -= st->x_offset;
589 x_min -= st->x_offset;
590 y_max -= st->y_offset;
591 y_min -= st->y_offset;
593 x_max = i_max(x_max, -x_min);
594 y_max = i_max(y_max, -y_min);
597 xm = st->width / 2.0;
598 ym = st->height / 2.0;
608 if (xscale < yscale) /* wider than tall */
609 scale = xscale; /* ensure width fits onscreen */
611 scale = yscale; /* ensure height fits onscreen */
614 scale *= FILL_PROPORTION; /* only fill FILL_PROPORTION of screen */
615 if (scale < 1.0) /* only reduce, don't enlarge. */
618 for (p=pb->epicycles; p; p=p->pchild)
625 printf("enlarge by x%.2f skipped...\n", scale);
630 /* angular speeds of the circles are harmonics of a fundamental
631 * value. That should please the Pythagoreans among you... :-)
634 random_wdot_max(struct state *st)
636 /* Maximum and minimum values for the choice of wdot_max. Possible
637 * epicycle speeds vary from wdot_max to (wdot_max * harmonics).
639 double minspeed, maxspeed;
640 minspeed = get_float_resource(st->dpy, "minSpeed", "Double");
641 maxspeed = get_float_resource(st->dpy, "maxSpeed", "Double");
642 return st->harmonics * (minspeed + FULLCIRCLE * frand(maxspeed-minspeed));
647 epicycle_init (Display *disp, Window win)
649 struct state *st = (struct state *) calloc (1, sizeof(*st));
653 st->holdtime = get_integer_resource (st->dpy, "holdtime", "Integer");
655 st->circle = FULLCIRCLE;
657 XClearWindow(st->dpy, st->window);
661 st->delay = get_integer_resource (st->dpy, "delay", "Integer");
662 st->harmonics = get_integer_resource(st->dpy, "harmonics", "Integer");
663 st->divisorPoisson = get_float_resource(st->dpy, "divisorPoisson", "Double");
665 st->timestep = get_float_resource(st->dpy, "timestep", "Double");
666 st->timestep_coarse = st->timestep *
667 get_float_resource(st->dpy, "timestepCoarseFactor", "Double");
669 st->sizeFactorMin = get_float_resource(st->dpy, "sizeFactorMin", "Double");
670 st->sizeFactorMax = get_float_resource(st->dpy, "sizeFactorMax", "Double");
672 st->minCircles = get_integer_resource (st->dpy, "minCircles", "Integer");
673 st->maxCircles = get_integer_resource (st->dpy, "maxCircles", "Integer");
675 st->xtime = 0; /* is this right? */
681 epicycle_draw (Display *dpy, Window window, void *closure)
683 struct state *st = (struct state *) closure;
684 int this_delay = st->delay;
687 st->eraser = erase_window (st->dpy, st->window, st->eraser);
696 /* Flush any outstanding events; this has the side effect of
697 * reducing the number of "false restarts"; resdtarts caused by
698 * one event (e.g. ConfigureNotify) followed by another
702 st->wdot_max = random_wdot_max(st);
706 delete_body(st->pb0);
709 st->pb0 = new_body(st);
710 st->pb0->x_origin = st->pb0->x = st->x_offset;
711 st->pb0->y_origin = st->pb0->y = st->y_offset;
715 st->eraser = erase_window (st->dpy, st->window, st->eraser);
719 precalculate_figure(st->pb0, st->xtime, st->timestep_coarse,
720 &st->xmax, &st->ymax, &st->xmin, &st->ymin);
722 rescale_circles(st, st->pb0, st->xmax, st->ymax, st->xmin, st->ymin);
724 move_body(st->pb0, 0.0); /* move once to avoid initial line from origin */
725 move_body(st->pb0, 0.0); /* move once to avoid initial line from origin */
728 st->T = 0.0; /* start at time zero. */
730 st->L = compute_divisor_lcm(st->pb0->epicycles);
732 st->colour_cycle_rate = fabs(st->L);
734 st->xtime = fabs(st->L * st->circle / st->wdot_max);
736 if (st->colors) /* (colors==NULL) if mono_p */
737 XSetForeground (st->dpy, st->color0, st->colors[st->pb0->current_color].pixel);
741 color_step(st, st->pb0, st->T/st->xtime );
742 draw_body(st, st->pb0, st->color0);
746 /* Check if the figure is complete...*/
747 if (st->T > st->xtime)
749 this_delay = st->holdtime * 1000000;
750 st->restart = 1; /* begin new figure. */
755 st->T += st->timestep;
756 move_body(st->pb0, st->T);
762 epicycle_reshape (Display *dpy, Window window, void *closure,
763 unsigned int w, unsigned int h)
765 struct state *st = (struct state *) closure;
770 epicycle_event (Display *dpy, Window window, void *closure, XEvent *e)
772 struct state *st = (struct state *) closure;
773 if (e->type == ButtonPress)
783 epicycle_free (Display *dpy, Window window, void *closure)
785 struct state *st = (struct state *) closure;
789 XSCREENSAVER_MODULE ("Epicycle", epicycle)