Misc 'catchup' commit on WolframAutomata.c.
[screensavers] / hacks / WolframAutomata / WolframAutomata.c
CommitLineData
0c731d4a
AT
1/* (c) 2021 Aaron Taylor <ataylor at subgeniuskitty dot com> */
2/* See LICENSE.txt file for copyright and license details. */
3
4
5/* TODO: Write description explaining that this simulates all 1D NN CAs, and explain briefly what all those terms imply. */
6/* TODO: Explain things like the topology of the space. */
7/* TODO: Explain how the numbering for a CA expands to the actual rules. */
8/* TODO: Briefly explain the four different classes of behavior and their implications. */
9/* TODO: Include a link to Wikipedia. */
10/* TODO: I suppose a lot of this stuff goes in the README instead. */
11/* TODO: Explain the data structures in detail. */
12/* TODO: Explain all the options, like the various starting conditions. */
76b9ae92 13/* TODO: Explain all the dependencies like libXpm. */
0c731d4a
AT
14
15
76b9ae92 16/* TODO: Add a #define for the hack version. */
0c731d4a
AT
17/* TODO: Check manpage for all functions I use and ensure my includes are correct. I don't want to depend on picking up includes via screenhack.h. */
18/* TODO: Verify everything in this file is C89. Get rid of things like '//' comments, pack all my declarations upfront, no stdint, etc. */
0c731d4a 19
d0f3b852 20#include <X11/Intrinsic.h>
0c731d4a
AT
21#include "screenhack.h"
22
d0f3b852
AT
23/*
24 * We do a few manual manipulations of X resources in this hack, like picking
25 * random colors. In order to ensure our manual manipulations always use the
26 * same X resource specification as Xscreensaver, we pass HACKNAME to
27 * Xscreensaver via the XSCREENSAVER_MODULE() line at the bottom of this file,
28 * and then always use HACKNAME or MAKE_STRING(HACKNAME) as the base of the
29 * resource specification when making manual manipulations.
30 */
31#define HACKNAME WolframAutomata
32#define MAKE_STRING_X(s) #s
33#define MAKE_STRING(s) MAKE_STRING_X(s)
34
0c731d4a 35// Command line options
7ce88c8e 36// directory to output XBM files of each run (and call an external command to convert to PNGs?)
2b742550 37// -save-dir STRING
76b9ae92
AT
38// (could use libXpm to save an XPM and then convert to PNG with ImageMagick) (this is a single function call to go from pixmap -> file)
39// (since it depends on an external library, make this whole feature optional at build-time?)
7ce88c8e 40// number of generations to simulate
76b9ae92 41// -random-generations
2b742550 42// -num-generations N
7ce88c8e 43// delay time (speed of simulation)
76b9ae92 44// -random-delay
2b742550 45// -delay-usec N
7ce88c8e 46// foreground and background color
d0f3b852
AT
47// -random-colors (highest precedence)
48// -foreground "COLORNAME"
49// -background "COLORNAME"
50// (default is black and white)
51// (mention sample color combinations in manpage, and link to: https://en.wikipedia.org/wiki/X11_color_names)
7ce88c8e 52// display info overlay with CA number and start conditions?
2b742550 53// -overlay
7ce88c8e 54// which ruleset number to use? Or random? Or random from small set of hand-selected interesting examples?
80cfe219 55// In order of precedence:
14d68c5b 56// -rule-random (select a random rule on each run)
80cfe219
AT
57// -rule N (always simulate Rule N on each run)
58// (if neither of the above two are specified, then a random CURATED rule is selected on each run)
14d68c5b
AT
59// which starting population to use, random or one bit? (for random: allow specifying a density)
60// In order of precedence:
61// -population-single
62// -population-random DENSITY
63// (the two options above only apply to the simulation under the -rule-random or -rule N options. in curated mode, starting population is defined in the curation array)
64// TODO: In the future, add the option for user to pass list of cell IDs to turn ON.
2b742550 65// size of pixel square (e.g. 1x1, 2x2, 3x3, etc)
76b9ae92 66// -random-pixel-size
2b742550 67// -pixel-size N
0c731d4a 68
14d68c5b
AT
69/* -------------------------------------------------------------------------- */
70/* Data Structures */
71/* -------------------------------------------------------------------------- */
72
0c731d4a 73struct state {
7ce88c8e
AT
74 /* Various X resources */
75 Display * dpy;
76 Window win;
77 GC gc;
78
79 // TODO: Explain that this holds the whole evolution of the CA and the actual displayed visualization is simply a snapshot into this pixmap.
80 Pixmap evolution_history;
7ce88c8e
AT
81
82 // TODO: Explain all of these.
7ce88c8e
AT
83 unsigned long fg, bg;
84 int xlim, ylim, ypos; // explain roughly how and where we use these. Note: I'm not thrilled xlim/ylim since they are actually the width of the display, not the limit of the index (off by one). Change those names.
85 Bool display_info;
7ce88c8e
AT
86
87 Bool * current_generation;
80cfe219
AT
88
89 // TODO: Describe these.
90 uint8_t rule_number; // Note: This is not a CLI option. You're thinking of rule_requested.
91 uint8_t rule_requested; // Note: Repurposing Rule 0 as a null value.
92 Bool rule_random;
c428f3d5 93
14d68c5b
AT
94 // TODO: Describe these.
95 int population_density;
96 Bool population_single;
97
c428f3d5
AT
98 /* Misc Commandline Options */
99 int pixel_size; /* Size of CA cell in pixels (e.g. pixel_size=3 means 3x3 pixels per cell). */
100 int delay_microsec; /* Requested delay to screenhack framework before next call to WolframAutomata_draw(). */
7969381e 101 int num_generations; /* Number of generations of the CA to simulate before restarting. */
c428f3d5
AT
102
103 /* Expository Variables - Not strictly necessary, but makes some code easier to read. */
104 size_t number_of_cells;
0c731d4a
AT
105};
106
14d68c5b
AT
107// TODO: Decorations
108enum seed_population {
1f5d1274
AT
109 random_cell,
110 middle_cell,
111 edge_cell
14d68c5b
AT
112};
113
114// TODO: Decorations
115struct curated_ruleset {
116 uint8_t rule;
117 enum seed_population seed;
118};
119
1f5d1274 120// TODO: Decorations
14d68c5b 121static const struct curated_ruleset curated_ruleset_list[] = {
1f5d1274
AT
122 {18, middle_cell},
123 {30, middle_cell},
124 {45, middle_cell},
125 {54, middle_cell},
126 {57, middle_cell},
127 {73, middle_cell},
128 {105, middle_cell},
129 {109, middle_cell},
130 {129, middle_cell},
131 {133, middle_cell},
132 {135, middle_cell},
133 {150, middle_cell},
134 {30, edge_cell},
135 {45, edge_cell},
136 {57, edge_cell},
137 {60, edge_cell},
138 {75, edge_cell},
139 {107, edge_cell},
140 {110, edge_cell},
141 {133, edge_cell},
142 {137, edge_cell},
143 {169, edge_cell},
144 {225, edge_cell},
145 {22, random_cell},
146 {30, random_cell},
147 {54, random_cell},
148 {62, random_cell},
149 {90, random_cell},
150 {105, random_cell},
151 {108, random_cell},
152 {110, random_cell},
153 {126, random_cell},
154 {146, random_cell},
155 {150, random_cell},
156 {182, random_cell},
157 {184, random_cell},
158 {225, random_cell},
159 {240, random_cell}
80cfe219
AT
160};
161
d0f3b852
AT
162// TODO: Decorations
163struct color_pair {
164 char * fg;
165 char * bg;
166};
167
168// TODO: Decorations
169// TODO: Populate this table with more examples.
170static const struct color_pair color_list[] = {
171 {"white", "black"},
172};
173
14d68c5b
AT
174/* -------------------------------------------------------------------------- */
175/* Helper Functions */
176/* -------------------------------------------------------------------------- */
177
178// TODO: decorations? inline?
179void
180generate_random_seed(struct state * state)
181{
182 int i;
183 for (i = 0; i < state->number_of_cells; i++) {
184 state->current_generation[i] = ((random() % 100) < state->population_density) ? True : False;
185 }
186}
187
188// TODO: function decorations?
189// TODO: Explain why this santizes the index for accessing current_generation (i.e. it creates a circular topology).
190size_t
191sindex(struct state * state, int index)
192{
193 while (index < 0) {
194 index += state->number_of_cells;
195 }
196 while (index >= state->number_of_cells) {
197 index -= state->number_of_cells;
198 }
199 return (size_t) index;
200}
201
202// TODO: function decorations?
203// TODO: At least give a one-sentence explanation of the algorithm since this function is the core of the simulation.
204Bool
205calculate_cell(struct state * state, int cell_id)
206{
207 uint8_t cell_pattern = 0;
208 int i;
209 for (i = -1; i < 2; i++) {
210 cell_pattern = cell_pattern << 1;
211 if (state->current_generation[sindex(state, cell_id+i)] == True) {
212 cell_pattern |= 1;
213 }
214 }
215 if ((state->rule_number >> cell_pattern) & 1) {
216 return True;
217 } else {
218 return False;
219 }
220}
221
222// TODO: function decorations?
223void
224render_current_generation(struct state * state)
225{
226 size_t xpos;
227 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
228 if (state->current_generation[xpos] == True) {
229 XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->pixel_size, state->ypos, state->pixel_size, state->pixel_size);
230 }
231 }
232}
233
234/* -------------------------------------------------------------------------- */
235/* Screenhack API Functions */
236/* -------------------------------------------------------------------------- */
237
0c731d4a
AT
238static void *
239WolframAutomata_init(Display * dpy, Window win)
240{
76b9ae92
AT
241 struct state * state = calloc(1, sizeof(*state));
242 if (!state) {
243 fprintf(stderr, "ERROR: Failed to calloc() for state struct in WolframAutomata_init().\n");
244 exit(EXIT_FAILURE);
245 }
246
7ce88c8e
AT
247 XGCValues gcv;
248 XWindowAttributes xgwa;
14d68c5b 249 const struct curated_ruleset * curated_ruleset = NULL;
7ce88c8e
AT
250
251 state->dpy = dpy;
252 state->win = win;
253
254 XGetWindowAttributes(state->dpy, state->win, &xgwa);
255 state->xlim = xgwa.width;
256 state->ylim = xgwa.height;
257 state->ypos = 0; // TODO: Explain why.
258
d0f3b852
AT
259 if (get_boolean_resource(state->dpy, "random-colors", "Boolean")) {
260 XrmDatabase db = XtDatabase(state->dpy);
261 size_t rand_i = random() % sizeof(color_list)/sizeof(color_list[0]);
262 XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".background", color_list[rand_i].bg);
263 XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".foreground", color_list[rand_i].fg);
264 }
265
7ce88c8e
AT
266 state->fg = gcv.foreground = get_pixel_resource(state->dpy, xgwa.colormap, "foreground", "Foreground");
267 state->bg = gcv.background = get_pixel_resource(state->dpy, xgwa.colormap, "background", "Background");
268 state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
269
c428f3d5 270 state->delay_microsec = get_integer_resource(state->dpy, "delay-usec", "Integer");
7ce88c8e
AT
271 if (state->delay_microsec < 0) state->delay_microsec = 0;
272
c428f3d5
AT
273 state->pixel_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
274 if (state->pixel_size < 1) state->pixel_size = 1;
275 if (state->pixel_size > state->xlim) state->pixel_size = state->xlim;
276
277 state->number_of_cells = state->xlim / state->pixel_size;
14d68c5b 278 // TODO: Do we want to enforce that number_of_cells > 0?
c428f3d5 279
80cfe219
AT
280 /* The minimum number of generations is 2 since we must allocate enough */
281 /* space to hold the seed generation and at least one pass through */
282 /* WolframAutomata_draw(), which is where we check whether or not we've */
283 /* reached the end of the pixmap. */
7969381e
AT
284 state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
285 if (state->num_generations < 0) state->num_generations = 2;
286
80cfe219
AT
287 /* Time to figure out which rule to use for this simulation. */
288 /* We ignore any weirdness resulting from the following cast since every */
289 /* bit pattern is also a valid rule; if the user provides weird input, */
290 /* then we'll return weird (but well-defined!) output. */
291 state->rule_requested = (uint8_t) get_integer_resource(state->dpy, "rule-requested", "Integer");
292 state->rule_random = get_boolean_resource(state->dpy, "rule-random", "Boolean");
293 /* Through the following set of branches, we enforce CLI flag precedence. */
294 if (state->rule_random) {
295 /* If this flag is set, the user wants truly random rules rather than */
296 /* random rules from a curated list. */
297 state->rule_number = (uint8_t) random();
298 } else if (state->rule_requested != 0) {
299 /* Rule 0 is terribly uninteresting, so we are reusing it as a 'null' */
300 /* value and hoping nobody notices. Finding a non-zero value means */
301 /* the user requested a specific rule. Use it. */
302 state->rule_number = state->rule_requested;
303 } else {
304 /* No command-line options were specified, so select rules randomly */
305 /* from a curated list. */
14d68c5b
AT
306 size_t number_of_array_elements = sizeof(curated_ruleset_list)/sizeof(curated_ruleset_list[0]);
307 curated_ruleset = &curated_ruleset_list[random() % number_of_array_elements];
308 state->rule_number = curated_ruleset->rule;
309 }
310
311 /* Time to construct the seed generation for this simulation. */
312 state->population_single = get_boolean_resource(state->dpy, "population-single", "Boolean");
313 state->population_density = get_integer_resource(state->dpy, "population-density", "Integer");
314 if (state->population_density < 0 || state->population_density > 100) state->population_density = 50;
315 state->current_generation = calloc(1, sizeof(*state->current_generation)*state->number_of_cells);
316 if (!state->current_generation) {
76b9ae92 317 fprintf(stderr, "ERROR: Failed to calloc() for cell generation in WolframAutomata_init().\n");
14d68c5b
AT
318 exit(EXIT_FAILURE);
319 }
320 if (curated_ruleset) {
321 /* If we're using a curated ruleset, ignore any CLI flags related to */
322 /* setting the seed generation, instead drawing that information from */
323 /* the curated ruleset. */
324 switch (curated_ruleset->seed) {
1f5d1274
AT
325 case random_cell: generate_random_seed(state); break;
326 case middle_cell: state->current_generation[state->number_of_cells/2] = True; break;
327 case edge_cell : state->current_generation[0] = True; break;
14d68c5b
AT
328 }
329 } else {
330 /* If we're not using a curated ruleset, process any relevant flags */
331 /* from the user, falling back to a random seed generation if nothing */
332 /* else is specified. */
333 if (state->population_single) {
334 state->current_generation[0] = True;
335 } else {
336 generate_random_seed(state);
337 }
80cfe219
AT
338 }
339
7ce88c8e
AT
340 // TODO: These should be command-line options, but I need to learn how the get_integer_resource() and similar functions work first.
341 state->display_info = True;
7ce88c8e 342
c428f3d5 343 state->evolution_history = XCreatePixmap(state->dpy, state->win, state->xlim, state->num_generations*state->pixel_size, xgwa.depth);
7ce88c8e
AT
344 // Pixmap contents are undefined after creation. Explicitly set a black
345 // background by drawing a black rectangle over the entire pixmap.
346 XSetForeground(state->dpy, state->gc, state->bg);
c428f3d5 347 XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->xlim, state->num_generations*state->pixel_size);
7ce88c8e 348 XSetForeground(state->dpy, state->gc, state->fg);
14d68c5b
AT
349 render_current_generation(state);
350 state->ypos += state->pixel_size;
7ce88c8e
AT
351
352 return state;
0c731d4a
AT
353}
354
0c731d4a
AT
355static unsigned long
356WolframAutomata_draw(Display * dpy, Window win, void * closure)
357{
358// TODO: Mark these basic sections of the function
359//draw()
7ce88c8e
AT
360// calculate (and store) new generation
361// draw new generation as line of pixels on pixmap
362// calculate current 'viewport' into pixmap
363// display on screen
0c731d4a
AT
364// check for termination condition
365
366 struct state * state = closure;
367 int xpos;
7ce88c8e 368 int window_y_offset;
0c731d4a 369
7ce88c8e 370 Bool new_generation[state->xlim];
c428f3d5 371 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
372 new_generation[xpos] = calculate_cell(state, xpos);
373 }
c428f3d5 374 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
375 state->current_generation[xpos] = new_generation[xpos];
376 }
377 render_current_generation(state);
378
379 // Was this the final generation of this particular simulation? If so, give
380 // the user a moment to bask in the glory of our output and then start a
381 // new simulation.
c428f3d5
AT
382 if (state->ypos/state->pixel_size < state->num_generations-1) {
383 state->ypos += state->pixel_size;
7ce88c8e
AT
384 } else {
385 // TODO: Wait for a second or two, clear the screen and do a new iteration with suitably changed settings.
386 // Note: Since we can't actually loop or sleep here, we need to add a flag to the state struct to indicate that we're in an 'admiration timewindow' (and indicate when it should end)
c428f3d5 387 printf("infinite hamster wheel\n");
7ce88c8e
AT
388 while (1) continue;
389 }
390
391 // Calculate the vertical offset of the current 'window' into the history
392 // of the CA. After the CA's evolution extends past what we can display, have
393 // the window track the current generation and most recent history.
394 if (state->ypos < state->ylim) {
395 window_y_offset = 0;
396 } else {
397 window_y_offset = state->ypos - (state->ylim - 1);
398 }
399
400 // Render everything to the display.
401 XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->xlim, state->ylim, 0, 0);
402 // TODO: Print info on screen if display_info is true. Will need fonts/etc. Do I want to create a separate pixmap for this during the init() function and then just copy the pixmap each time we draw the screen in draw()?
0c731d4a
AT
403
404 return state->delay_microsec;
405}
406
c428f3d5 407// TODO: Fix formatting
0c731d4a
AT
408static const char * WolframAutomata_defaults[] = {
409 ".background: black",
410 ".foreground: white",
d0f3b852 411 "*random-colors: False",
80cfe219 412 "*delay-usec: 25000",
7969381e
AT
413 // TODO: Difference between dot and asterisk? Presumably the asterisk matches all resouces of attribute "pixelsize"? Apply answer to all new options.
414 "*pixel-size: 2",
415 "*num-generations: 5000",
80cfe219
AT
416 "*rule-requested: 0",
417 "*rule-random: False",
14d68c5b
AT
418 "*population-density: 50",
419 "*population-single: False",
0c731d4a
AT
420 0
421};
422
c428f3d5 423// TODO: Fix formatting
0c731d4a 424static XrmOptionDescRec WolframAutomata_options[] = {
d0f3b852
AT
425 { "-background", ".background", XrmoptionSepArg, 0},
426 { "-foreground", ".foreground", XrmoptionSepArg, 0},
427 { "-random-colors", ".random-colors", XrmoptionNoArg, "True"},
c428f3d5
AT
428 { "-delay-usec", ".delay-usec", XrmoptionSepArg, 0 },
429 { "-pixel-size", ".pixel-size", XrmoptionSepArg, 0 },
7969381e 430 { "-num-generations", ".num-generations", XrmoptionSepArg, 0 },
80cfe219
AT
431 { "-rule", ".rule-requested", XrmoptionSepArg, 0 },
432 { "-rule-random", ".rule-random", XrmoptionNoArg, "True" },
14d68c5b
AT
433 { "-population-density", ".population-density", XrmoptionSepArg, 0 },
434 { "-population-single", ".population-single", XrmoptionNoArg, "True" },
0c731d4a
AT
435 { 0, 0, 0, 0 }
436};
437
438static Bool
439WolframAutomata_event(Display * dpy, Window win, void * closure, XEvent * event)
440{
441 return False;
442}
443
444static void
445WolframAutomata_free(Display * dpy, Window win, void * closure)
446{
447 struct state * state = closure;
448 XFreeGC(state->dpy, state->gc);
7ce88c8e
AT
449 XFreePixmap(state->dpy, state->evolution_history);
450 free(state->current_generation);
0c731d4a
AT
451 free(state);
452}
453
454static void
455WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
456{
7ce88c8e 457 WolframAutomata_free(dpy, win, closure);
b0ea929b 458 closure = WolframAutomata_init(dpy, win);
0c731d4a
AT
459}
460
d0f3b852 461XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", HACKNAME)
0c731d4a 462