65a7e5cc9598f38ad1256b87a432acd91f9d5b21
[screensavers] / hacks / WolframAutomata / WolframAutomata.c
/* (c) 2021 Aaron Taylor <ataylor at subgeniuskitty dot com> */
/* See LICENSE.txt file for copyright and license details. */
#include "screenhack.h"
/* -------------------------------------------------------------------------- */
/* Data Structures */
/* -------------------------------------------------------------------------- */
struct state {
/* Various X resources */
Display * dpy;
Window win;
GC gc;
/* These hold the pixel value of the foreground and background colors in */
/* the same format as an XColor struct's "pixel" member. */
unsigned long fg, bg;
/* This Pixmap will eventually hold the entire evolution of the CA. The */
/* displayed portion of the CA's evolution is merely a viewport into this */
/* Pixmap. */
Pixmap evolution_history;
/* Together, these three values define the display viewport into the */
/* 'evolution_history' Pixmap. The pair 'dpy_width' and 'dpy_height' are */
/* simply the width and height of the display window. They remain */
/* unchanged during normal operation. However, 'ypos' tracks the location */
/* of the viewport in the 'evolution_history'. It must always keep the */
/* newest generation onscreen and display as much history as possible. */
int dpy_width, dpy_height, ypos;
/* In the 'current_generation' array, the value True means a cell is */
/* alive. We only need to track the current generation since our rulesets */
/* never consider older generations. Anything older can be rendered to */
/* the 'evolution_history' Pixmap and subsequently ignored. */
Bool * current_generation;
/* When randomizing the seed generation, we can specify a population */
/* density, or we can restrict to a single living cell. */
int population_density;
Bool population_single;
/* For more information on the encoding used for rule_number and on the */
/* method used to apply it: https://en.wikipedia.org/wiki/Wolfram_code */
uint8_t rule_number;
/* At the end of the simulation, the user is given time to admire the */
/* output. Delay is available to user as CLI option '-admiration-delay'. */
Bool admiration_in_progress;
size_t admiration_delay; /* ...in seconds. */
/* The following values correspond directly to independent CLI options. */
Bool rule_random;
uint8_t rule_requested; /* Note: Repurposing Rule 0 as null value. */
int cell_size; /* If cell_size=N then draw NxN pixels per cell. */
int delay_microsec; /* ...between calls to WolframAutomata_draw(). */
int num_generations; /* Reset simulation after this many generations. */
/* Not strictly necessary, but makes some code easier to read. */
size_t number_of_cells;
};
enum seed_population {
random_cell,
middle_cell,
edge_cell
};
struct curated_ruleset {
uint8_t rule;
enum seed_population seed;
};
static const struct curated_ruleset curated_ruleset_list[] = {
{ 18, middle_cell},
{ 30, middle_cell},
{ 45, middle_cell},
{ 54, middle_cell},
{ 57, middle_cell},
{ 73, middle_cell},
{105, middle_cell},
{109, middle_cell},
{129, middle_cell},
{133, middle_cell},
{135, middle_cell},
{150, middle_cell},
{ 30, edge_cell},
{ 45, edge_cell},
{ 57, edge_cell},
{ 60, edge_cell},
{ 75, edge_cell},
{107, edge_cell},
{110, edge_cell},
{133, edge_cell},
{137, edge_cell},
{169, edge_cell},
{225, edge_cell},
{ 22, random_cell},
{ 30, random_cell},
{ 54, random_cell},
{ 62, random_cell},
{ 90, random_cell},
{105, random_cell},
{108, random_cell},
{110, random_cell},
{126, random_cell},
{146, random_cell},
{150, random_cell},
{182, random_cell},
{184, random_cell},
{225, random_cell},
{240, random_cell}
};
struct color_pair {
/* The type 'unsigned short' comes from the XColor struct definition, */
/* reproduced below. */
/* */
/* typedef struct { */
/* unsigned long pixel; */
/* unsigned short red, green, blue; */
/* char flags; */
/* char pad; */
/* } XColor; */
/* */
/* The red, green, and blue values are always in the range 0 to 65535 */
/* inclusive, independent of the number of bits actually used in the */
/* display hardware. The server scales these values to the range used */
/* by the hardware. Black is represented by (0,0,0), and white is */
/* represented by (65535,65535,65535). */
unsigned short fg_red, fg_green, fg_blue;
unsigned short bg_red, bg_green, bg_blue;
};
static const struct color_pair color_list[] = {
/* For mapping X11 color names to RGB values: */
/* https://www.ehdp.com/methods/x11-color-names-rgb-values.htm */
/* Remember that our values range from 0-65535 inclusive, so scale the */
/* usual 0-255 range accordingly. */
/* */
/* +---------------------------------------+ */
/* | foreground | | background | */
/* | red,green,blue | | red,green,blue | */
{65535, 0, 0, 0, 0, 0}, /* {"red", "black"}, */
{32767,32767, 0, 0, 0, 0}, /* {"olive", "black"}, */
{ 0,32767,32767, 0, 0, 0}, /* {"teal", "black"}, */
{27524,22937,52428, 0, 0, 0}, /* {"slateblue", "black"}, */
{60947,33422,60947, 0, 0, 0}, /* {"violet", "black"}, */
{41287, 8519,61602, 0, 0, 0}, /* {"purple", "black"}, */
{65535,65535,65535, 0, 0, 0}, /* {"white", "black"}, */
{65535,65535,65535, 0,25558, 0}, /* {"white", "darkgreen"}, */
{65535,65535,65535, 36044, 0,36044}, /* {"white", "darkmagenta"}, */
{65535,65535,65535, 36044, 0, 0}, /* {"white", "darkred"}, */
{65535,65535,65535, 0, 0,36044}, /* {"white", "darkblue"}, */
{11796,20315,20315, 36494,65535,65535}, /* {"darkslategray", "darkslategray1"}, */
{45219,50461,57015, 11796,20315,20315}, /* {"lightsteelblue", "darkslategray"}, */
{10023,16448,35723, 16383,26869,57670}, /* {"royalblue4", "royalblue"}, */
{61166,57311,52428, 35723,33667,30840}, /* {"antiquewhite2", "antiquewhite4"}, */
{51914,65535,28784, 21626,27524,11796}, /* {"darkolivegreen1", "darkolivegreen"}, */
{49601,65535,49601, 26985,35723,26985}, /* {"darkseagreen1", "darkseagreen4"}, */
{65535,49151,52428, 36044, 0, 0}, /* {"pink", "darkred"}, */
{44563,55704,58981, 0,25558, 0}, /* {"lightblue", "darkgreen"}, */
{65535, 0, 0, 0, 0,65535}, /* {"red", "blue"}, */
{65535, 0, 0, 0,25558, 0}, /* {"red", "darkgreen"}, */
{ 0,65535,65535, 0,32767,32767}, /* {"aqua", "teal"}, */
{ 0, 0,36044, 0,32767,32767}, /* {"darkblue", "teal"}, */
{61602,58981,32767, 11796,36044,22281}, /* {"khaki", "seagreen"}, */
{61602,58981,32767, 21626,27524,11796}, /* {"khaki", "darkolivegreen"}, */
{30801,34733,39321, 11796,20315,20315}, /* {"lightslategray", "darkslategray"}, */
{65535,25558,18349, 11796,20315,20315}, /* {"tomato", "darkslategray"}, */
{65535,25558,18349, 0,36044,36044} /* {"tomato", "darkcyan"} */
};
/* -------------------------------------------------------------------------- */
/* Helper Functions */
/* -------------------------------------------------------------------------- */
static void
generate_random_seed(struct state * state)
{
int i;
for (i = 0; i < state->number_of_cells; i++) {
state->current_generation[i] = ((random() % 100) < state->population_density) ? True : False;
}
}
/* This function sanitizes the index used to access cells in a generation. */
/* Specifically, it wraps the index, creating a circular universe for the */
/* cells and ensuring every cell has two neighbors. */
static size_t
sindex(struct state * state, int index)
{
while (index < 0) {
index += state->number_of_cells;
}
while (index >= state->number_of_cells) {
index -= state->number_of_cells;
}
return (size_t) index;
}
/* For more information on the encoding used for state->rule_number and on */
/* the method used to apply it: https://en.wikipedia.org/wiki/Wolfram_code */
static Bool
calculate_cell(struct state * state, int cell_id)
{
uint8_t cell_pattern = 0;
int i;
for (i = -1; i < 2; i++) {
cell_pattern = cell_pattern << 1;
if (state->current_generation[sindex(state, cell_id+i)] == True) {
cell_pattern |= 1;
}
}
if ((state->rule_number >> cell_pattern) & 1) {
return True;
} else {
return False;
}
}
static void
render_current_generation(struct state * state)
{
size_t xpos;
for (xpos = 0; xpos < state->number_of_cells; xpos++) {
if (state->current_generation[xpos] == True) {
XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->cell_size, state->ypos, state->cell_size, state->cell_size);
} else {
XSetForeground(state->dpy, state->gc, state->bg);
XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->cell_size, state->ypos, state->cell_size, state->cell_size);
XSetForeground(state->dpy, state->gc, state->fg);
}
}
}
/* -------------------------------------------------------------------------- */
/* Screenhack API Functions */
/* -------------------------------------------------------------------------- */
static Bool
WolframAutomata_event(Display * dpy, Window win, void * closure, XEvent * event)
{
return False;
}
static void
WolframAutomata_free(Display * dpy, Window win, void * closure)
{
struct state * state = closure;
XFreeGC(state->dpy, state->gc);
XFreePixmap(state->dpy, state->evolution_history);
free(state->current_generation);
free(state);
}
static void *
WolframAutomata_init(Display * dpy, Window win)
{
struct state * state = calloc(1, sizeof(*state));
if (!state) {
fprintf(stderr, "ERROR: Failed to calloc() for state struct in WolframAutomata_init().\n");
exit(EXIT_FAILURE);
}
XGCValues gcv;
XWindowAttributes xgwa;
const struct curated_ruleset * curated_ruleset = NULL;
state->dpy = dpy;
state->win = win;
XGetWindowAttributes(state->dpy, state->win, &xgwa);
state->dpy_width = xgwa.width;
state->dpy_height = xgwa.height;
state->ypos = 0;
state->admiration_delay = get_integer_resource(state->dpy, "admiration-delay", "Integer");
state->admiration_in_progress = False;
/* Set foreground and background colors for active/inactive cells. Either */
/* the user provided an index into the pre-defined color_list[] or a */
/* random entry from that same array should be selected. */
size_t color_index = get_integer_resource(state->dpy, "color-index", "Integer");
if (color_index == -1) {
color_index = random() % sizeof(color_list)/sizeof(color_list[0]);
} else if (color_index >= sizeof(color_list)/sizeof(color_list[0])) {
fprintf(stderr, "WARNING: Color index out of range.\n");
color_index = 0;
}
XColor fg, bg;
fg.red = color_list[color_index].fg_red;
fg.green = color_list[color_index].fg_green;
fg.blue = color_list[color_index].fg_blue;
bg.red = color_list[color_index].bg_red;
bg.green = color_list[color_index].bg_green;
bg.blue = color_list[color_index].bg_blue;
/* TODO: Since I 'alloc', presumably I must also 'free' these colors */
/* at some point. Where/how? I don't want to eventually crash my */
/* X server after months of use. */
XAllocColor(state->dpy, xgwa.colormap, &fg);
XAllocColor(state->dpy, xgwa.colormap, &bg);
state->fg = gcv.foreground = fg.pixel;
state->bg = gcv.background = bg.pixel;
state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
/* Set the size of each simulated cell to NxN pixels for cell_size=N. */
if (get_boolean_resource(state->dpy, "random-pixel-size", "Boolean")) {
/* Although we are choosing the pixel size 'randomly', a truly random */
/* selection would bias toward large numbers since there are more of */
/* them. To avoid this, we select a random number for a bit shift, */
/* resulting in a pixel size of 1, 2, 4, 8, 16 or 32, equally likely. */
state->cell_size = 1 << (random() % 6);
} else {
state->cell_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
}
if (state->cell_size < 1) state->cell_size = 1;
if (state->cell_size > state->dpy_width) state->cell_size = state->dpy_width;
/* Larger cell sizes won't always evenly divide the number of pixels in */
/* our window. In order to avoid a black stripe down the edge, '+1' here */
/* to ensure we are slightly oversize rather than undersize. */
state->number_of_cells = (state->dpy_width / state->cell_size) + 1;
/* Set the delay (in microseconds) between simulation of each generation */
/* of the simulation, also known as the delay between calls to */
/* WolframAutomata_draw(), which simulates one generation per call. */
if (get_boolean_resource(state->dpy, "random-delay", "Boolean")) {
/* When randomly setting the delay, the problem is to avoid being too */
/* fast or too slow, as well as ensuring slower speeds are chosen */
/* with the same likelihood as faster speeds, as perceived by a */
/* human. By empirical observation, we note that for 1x1 up to 4x4 */
/* pixel cell sizes, values for state->delay_microsec between */
/* 2048 (2^11) and 16556 (2^14) produce pleasant scroll rates. To */
/* maintain this appearance, we bitshift state->cell_size down until */
/* it is a maximum of 4x4 pixels in size, record how many bitshifts */
/* took place, and then shift our valid window for */
/* state->delay_microsec up by an equal number of bitshifts. For */
/* example, if state->cell_size=9, then it takes one right shift to */
/* reach state->cell_size=4. Thus, the valid window for */
/* state->delay_microsec becomes 4096 (2^12) up to 32768 (2^15). */
size_t pixel_shift_range = 1;
size_t cell_size_temp = state->cell_size;
while (cell_size_temp > 4) {
cell_size_temp >>= 1;
pixel_shift_range++;
}
/* In the below line, '3' represents the total range, namely '14-11' */
/* from '2^14' and '2^11' as the endpoints. Similarly, the '11' in */
/* the below line represents the starting point of this range, from */
/* the exponent in '2^11'. */
state->delay_microsec = 1 << ((random() % 3) + 11 + pixel_shift_range);
} else {
state->delay_microsec = get_integer_resource(state->dpy, "delay-usec", "Integer");
}
if (state->delay_microsec < 0) state->delay_microsec = 0;
/* Set the number of generations to simulate before wiping the simulation */
/* and re-running with new settings. */
if (get_boolean_resource(state->dpy, "random-num-generations", "Boolean")) {
/* By empirical observation, keep the product */
/* state->num_generations * state->cell_size */
/* below 10,000 to avoid BadAlloc errors from the X server due to */
/* requesting an enormous pixmap. This value works on both a 12 core */
/* Xeon with 108 GiB of RAM and a Sun Ultra 2 with 2 GiB of RAM. */
state->num_generations = random() % (10000 / state->cell_size);
/* Ensure selected value is large enough to at least fill the screen. */
/* Cast to avoid overflow. */
if ((long)state->num_generations * (long)state->cell_size < state->dpy_height) {
state->num_generations = (state->dpy_height / state->cell_size) + 1;
}
} else {
state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
}
/* The minimum number of generations is 2 since we must allocate enough */
/* space to hold the seed generation and at least one pass through */
/* WolframAutomata_draw(), which is where we check whether or not we've */
/* reached the end of the pixmap. */
if (state->num_generations < 0) state->num_generations = 2;
/* The maximum number of generations is cell_size dependent. This is a */
/* soft limit and may be increased if you have plenty of RAM (and a */
/* cooperative X server). The value 10,000 was determined empirically. */
if ((long)state->num_generations * (long)state->cell_size > 10000) {
state->num_generations = 10000 / state->cell_size;
}
/* Time to figure out which rule to use for this simulation. */
/* We ignore any weirdness resulting from the following cast since every */
/* bit pattern is also a valid rule; if the user provides weird input, */
/* then we'll return weird (but well-defined!) output. */
state->rule_requested = (uint8_t) get_integer_resource(state->dpy, "rule-requested", "Integer");
state->rule_random = get_boolean_resource(state->dpy, "rule-random", "Boolean");
/* Through the following set of branches, we enforce CLI flag precedence. */
if (state->rule_random) {
/* If this flag is set, the user wants truly random rules rather than */
/* random rules from a curated list. */
state->rule_number = (uint8_t) random();
} else if (state->rule_requested != 0) {
/* Rule 0 is terribly uninteresting, so we are reusing it as a 'null' */
/* value and hoping nobody notices. Finding a non-zero value means */
/* the user requested a specific rule. Use it. */
state->rule_number = state->rule_requested;
} else {
/* No command-line options were specified, so select rules randomly */
/* from a curated list. */
size_t number_of_array_elements = sizeof(curated_ruleset_list)/sizeof(curated_ruleset_list[0]);
curated_ruleset = &curated_ruleset_list[random() % number_of_array_elements];
state->rule_number = curated_ruleset->rule;
}
/* Time to construct the seed generation for this simulation. */
state->population_single = get_boolean_resource(state->dpy, "population-single", "Boolean");
state->population_density = get_integer_resource(state->dpy, "population-density", "Integer");
if (state->population_density < 0 || state->population_density > 100) state->population_density = 50;
state->current_generation = calloc(1, sizeof(*state->current_generation)*state->number_of_cells);
if (!state->current_generation) {
fprintf(stderr, "ERROR: Failed to calloc() for cell generation in WolframAutomata_init().\n");
exit(EXIT_FAILURE);
}
if (curated_ruleset) {
/* If we're using a curated ruleset, ignore any CLI flags related to */
/* setting the seed generation, instead drawing that information from */
/* the curated ruleset. */
switch (curated_ruleset->seed) {
case random_cell: generate_random_seed(state); break;
case middle_cell: state->current_generation[state->number_of_cells/2] = True; break;
case edge_cell : state->current_generation[0] = True; break;
}
} else {
/* If we're not using a curated ruleset, process any relevant flags */
/* from the user, falling back to a random seed generation if nothing */
/* else is specified. */
if (state->population_single) {
state->current_generation[0] = True;
} else {
generate_random_seed(state);
}
}
state->evolution_history = XCreatePixmap(state->dpy, state->win, state->dpy_width, state->num_generations*state->cell_size, xgwa.depth);
/* Pixmap contents are undefined after creation. Explicitly set a black */
/* background by drawing a black rectangle over the entire pixmap. */
XColor blackx, blacks;
XAllocNamedColor(state->dpy, DefaultColormapOfScreen(DefaultScreenOfDisplay(state->dpy)), "black", &blacks, &blackx);
XSetForeground(state->dpy, state->gc, blacks.pixel);
XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->dpy_width, state->num_generations*state->cell_size);
XSetForeground(state->dpy, state->gc, state->fg);
render_current_generation(state);
state->ypos += state->cell_size;
return state;
}
static unsigned long
WolframAutomata_draw(Display * dpy, Window win, void * closure)
{
struct state * state = closure;
int xpos;
int window_y_offset;
/* Calculate and record new generation. */
Bool new_generation[state->dpy_width];
for (xpos = 0; xpos < state->number_of_cells; xpos++) {
new_generation[xpos] = calculate_cell(state, xpos);
}
for (xpos = 0; xpos < state->number_of_cells; xpos++) {
state->current_generation[xpos] = new_generation[xpos];
}
render_current_generation(state);
/* Check for end of simulation. */
if (state->ypos/state->cell_size < state->num_generations-1) {
/* Life continues. */
state->ypos += state->cell_size;
} else {
/* We have reached the end of this simulation. Give the user a moment */
/* to bask in the glory of our output, then reset. */
if (state->admiration_in_progress) {
WolframAutomata_free(dpy, win, state);
closure = WolframAutomata_init(dpy, win);
} else {
state->admiration_in_progress = True;
return 1000000 * state->admiration_delay;
}
}
/* Calculate vertical offset of current 'window' into the CA's history. */
/* After the CA evolution exceeds our display extents, make window track */
/* current generation, scrolling display to follow newest generation. */
if (state->ypos < state->dpy_height) {
window_y_offset = 0;
} else {
window_y_offset = state->ypos - (state->dpy_height - 1);
}
/* Render a window into the CA history. */
XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->dpy_width, state->dpy_height, 0, 0);
return state->delay_microsec;
}
static const char * WolframAutomata_defaults[] = {
"*delay-usec: 25000",
"*admiration-delay: 5",
"*num-generations: 5000",
"*pixel-size: 2",
"*color-index: -1",
"*population-density: 50",
"*population-single: False",
"*random-cellsize: False",
"*random-delay: False",
"*random-length: False",
"*random-rule: False",
"*rule-requested: 0",
0
};
static XrmOptionDescRec WolframAutomata_options[] = {
{ "-delay-usec", ".delay-usec", XrmoptionSepArg, 0 },
{ "-admiration-delay", ".admiration-delay", XrmoptionSepArg, 0 },
{ "-num-generations", ".num-generations", XrmoptionSepArg, 0 },
{ "-pixel-size", ".pixel-size", XrmoptionSepArg, 0 },
{ "-color-index", ".color-index", XrmoptionSepArg, 0 },
{ "-population-density", ".population-density", XrmoptionSepArg, 0 },
{ "-population-single", ".population-single", XrmoptionNoArg, "True" },
{ "-random-cellsize", ".random-pixel-size", XrmoptionNoArg, "True" },
{ "-random-delay", ".random-delay", XrmoptionNoArg, "True" },
{ "-random-length", ".random-num-generations", XrmoptionNoArg, "True" },
{ "-random-rule", ".rule-random", XrmoptionNoArg, "True" },
{ "-rule", ".rule-requested", XrmoptionSepArg, 0 },
{ 0, 0, 0, 0 }
};
static void
WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
{
struct state * state = closure;
XWindowAttributes xgwa;
XGetWindowAttributes(state->dpy, state->win, &xgwa);
/* Only restart the simulation if the window changed size. */
if (state->dpy_width != xgwa.width || state->dpy_height != xgwa.height) {
WolframAutomata_free(dpy, win, closure);
closure = WolframAutomata_init(dpy, win);
}
}
XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", WolframAutomata)