Added "number of generations" as a command line flag to WolframAutomata.
[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. */
13
14
15/* 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. */
16/* TODO: Verify everything in this file is C89. Get rid of things like '//' comments, pack all my declarations upfront, no stdint, etc. */
0c731d4a
AT
17
18#include "screenhack.h"
19
20// Command line options
7ce88c8e 21// directory to output XBM files of each run (and call an external command to convert to PNGs?)
2b742550 22// -save-dir STRING
7ce88c8e 23// number of generations to simulate
2b742550 24// -num-generations N
7ce88c8e 25// delay time (speed of simulation)
2b742550 26// -delay-usec N
7ce88c8e 27// foreground and background color
2b742550 28// ??? (strings of some sort, but I need to look up what X resources to interact with)
7ce88c8e 29// display info overlay with CA number and start conditions?
2b742550 30// -overlay
7ce88c8e 31// which ruleset number to use? Or random? Or random from small set of hand-selected interesting examples?
2b742550
AT
32// Options (with precedence): -rule N
33// -rule-curated
34// -rule-random
7ce88c8e 35// which starting population to use? Or random? Or one bit in middle? Or one bit on edge? (For random: Can I allow specifying a density like 25%, 50%, 75%?)
2b742550
AT
36// Options (with precedence): -population STRING (string is a comma separated list of cell IDs to populate, starting from 0)
37// -population-curated
38// -population-random
39// size of pixel square (e.g. 1x1, 2x2, 3x3, etc)
40// -pixel-size N
0c731d4a
AT
41
42struct state {
7ce88c8e
AT
43 /* Various X resources */
44 Display * dpy;
45 Window win;
46 GC gc;
47
48 // TODO: Explain that this holds the whole evolution of the CA and the actual displayed visualization is simply a snapshot into this pixmap.
49 Pixmap evolution_history;
7ce88c8e
AT
50
51 // TODO: Explain all of these.
7ce88c8e
AT
52 unsigned long fg, bg;
53 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.
54 Bool display_info;
7ce88c8e
AT
55
56 Bool * current_generation;
57 uint8_t ruleset;
c428f3d5
AT
58
59 /* Misc Commandline Options */
60 int pixel_size; /* Size of CA cell in pixels (e.g. pixel_size=3 means 3x3 pixels per cell). */
61 int delay_microsec; /* Requested delay to screenhack framework before next call to WolframAutomata_draw(). */
7969381e 62 int num_generations; /* Number of generations of the CA to simulate before restarting. */
c428f3d5
AT
63
64 /* Expository Variables - Not strictly necessary, but makes some code easier to read. */
65 size_t number_of_cells;
0c731d4a
AT
66};
67
68static void *
69WolframAutomata_init(Display * dpy, Window win)
70{
7ce88c8e
AT
71 struct state * state = calloc(1, sizeof(*state)); // TODO: Check calloc() call
72 XGCValues gcv;
73 XWindowAttributes xgwa;
74
75 state->dpy = dpy;
76 state->win = win;
77
78 XGetWindowAttributes(state->dpy, state->win, &xgwa);
79 state->xlim = xgwa.width;
80 state->ylim = xgwa.height;
81 state->ypos = 0; // TODO: Explain why.
82
83 state->fg = gcv.foreground = get_pixel_resource(state->dpy, xgwa.colormap, "foreground", "Foreground");
84 state->bg = gcv.background = get_pixel_resource(state->dpy, xgwa.colormap, "background", "Background");
85 state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
86
c428f3d5 87 state->delay_microsec = get_integer_resource(state->dpy, "delay-usec", "Integer");
7ce88c8e
AT
88 if (state->delay_microsec < 0) state->delay_microsec = 0;
89
c428f3d5
AT
90 state->pixel_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
91 if (state->pixel_size < 1) state->pixel_size = 1;
92 if (state->pixel_size > state->xlim) state->pixel_size = state->xlim;
93
94 state->number_of_cells = state->xlim / state->pixel_size;
95
7969381e
AT
96 /*
97 * The minimum number of generations is 2 since we must allocate enough
98 * space to hold the seed generation and at least one pass through
99 * WolframAutomata_draw(), which is where we check whether or not we've
100 * reached the end of the pixmap.
101 */
102 state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
103 if (state->num_generations < 0) state->num_generations = 2;
104
7ce88c8e
AT
105 // TODO: These should be command-line options, but I need to learn how the get_integer_resource() and similar functions work first.
106 state->display_info = True;
107 state->ruleset = 30;
7ce88c8e 108
c428f3d5 109 state->current_generation = calloc(1, (sizeof(*(state->current_generation))*state->number_of_cells)); // TODO: Check calloc() call TODO: Can't recall precedence; can I eliminate any parenthesis?
7ce88c8e
AT
110 // TODO: Make the starting state a user-configurable option. At least give the user some options like 'random', 'one-middle', 'one edge', etc.
111 // Ideally accept something like a list of integers representing starting pixels to be "on".
c428f3d5 112 state->current_generation[0] = True;
7ce88c8e 113
c428f3d5 114 state->evolution_history = XCreatePixmap(state->dpy, state->win, state->xlim, state->num_generations*state->pixel_size, xgwa.depth);
7ce88c8e
AT
115 // Pixmap contents are undefined after creation. Explicitly set a black
116 // background by drawing a black rectangle over the entire pixmap.
117 XSetForeground(state->dpy, state->gc, state->bg);
c428f3d5 118 XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->xlim, state->num_generations*state->pixel_size);
7ce88c8e
AT
119 XSetForeground(state->dpy, state->gc, state->fg);
120 // TODO: Need to draw starting generation on pixmap and increment state->ypos.
121
122 return state;
0c731d4a
AT
123}
124
125// TODO: function decorations?
126// TODO: Explain why this santizes the index for accessing current_generation (i.e. it creates a circular topology).
127size_t
128sindex(struct state * state, int index)
129{
7ce88c8e 130 while (index < 0) {
c428f3d5 131 index += state->number_of_cells;
7ce88c8e 132 }
c428f3d5
AT
133 while (index >= state->number_of_cells) {
134 index -= state->number_of_cells;
7ce88c8e
AT
135 }
136 return (size_t) index;
0c731d4a
AT
137}
138
139// TODO: function decorations?
140// TODO: At least give a one-sentence explanation of the algorithm since this function is the core of the simulation.
141Bool
142calculate_cell(struct state * state, int cell_id)
143{
7ce88c8e
AT
144 uint8_t cell_pattern = 0;
145 int i;
146 for (i = -1; i < 2; i++) {
147 cell_pattern = cell_pattern << 1;
148 if (state->current_generation[sindex(state, cell_id+i)] == True) {
149 cell_pattern |= 1;
150 }
151 }
152 if ((state->ruleset >> cell_pattern) & 1) {
153 return True;
154 } else {
155 return False;
156 }
0c731d4a
AT
157}
158
159// TODO: function decorations?
160void
161render_current_generation(struct state * state)
162{
7ce88c8e 163 size_t xpos;
c428f3d5 164 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e 165 if (state->current_generation[xpos] == True) {
c428f3d5 166 XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->pixel_size, state->ypos, state->pixel_size, state->pixel_size);
7ce88c8e
AT
167 }
168 }
0c731d4a
AT
169}
170
171static unsigned long
172WolframAutomata_draw(Display * dpy, Window win, void * closure)
173{
174// TODO: Mark these basic sections of the function
175//draw()
7ce88c8e
AT
176// calculate (and store) new generation
177// draw new generation as line of pixels on pixmap
178// calculate current 'viewport' into pixmap
179// display on screen
0c731d4a
AT
180// check for termination condition
181
182 struct state * state = closure;
183 int xpos;
7ce88c8e 184 int window_y_offset;
0c731d4a 185
7ce88c8e 186 Bool new_generation[state->xlim];
c428f3d5 187 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
188 new_generation[xpos] = calculate_cell(state, xpos);
189 }
c428f3d5 190 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
191 state->current_generation[xpos] = new_generation[xpos];
192 }
193 render_current_generation(state);
194
195 // Was this the final generation of this particular simulation? If so, give
196 // the user a moment to bask in the glory of our output and then start a
197 // new simulation.
c428f3d5
AT
198 if (state->ypos/state->pixel_size < state->num_generations-1) {
199 state->ypos += state->pixel_size;
7ce88c8e
AT
200 } else {
201 // TODO: Wait for a second or two, clear the screen and do a new iteration with suitably changed settings.
202 // 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 203 printf("infinite hamster wheel\n");
7ce88c8e
AT
204 while (1) continue;
205 }
206
207 // Calculate the vertical offset of the current 'window' into the history
208 // of the CA. After the CA's evolution extends past what we can display, have
209 // the window track the current generation and most recent history.
210 if (state->ypos < state->ylim) {
211 window_y_offset = 0;
212 } else {
213 window_y_offset = state->ypos - (state->ylim - 1);
214 }
215
216 // Render everything to the display.
217 XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->xlim, state->ylim, 0, 0);
218 // 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
219
220 return state->delay_microsec;
221}
222
c428f3d5 223// TODO: Fix formatting
0c731d4a
AT
224static const char * WolframAutomata_defaults[] = {
225 ".background: black",
226 ".foreground: white",
c428f3d5 227 "*delay-usec: 2500",
7969381e
AT
228 // TODO: Difference between dot and asterisk? Presumably the asterisk matches all resouces of attribute "pixelsize"? Apply answer to all new options.
229 "*pixel-size: 2",
230 "*num-generations: 5000",
0c731d4a
AT
231 0
232};
233
c428f3d5 234// TODO: Fix formatting
0c731d4a 235static XrmOptionDescRec WolframAutomata_options[] = {
c428f3d5
AT
236 { "-delay-usec", ".delay-usec", XrmoptionSepArg, 0 },
237 { "-pixel-size", ".pixel-size", XrmoptionSepArg, 0 },
7969381e 238 { "-num-generations", ".num-generations", XrmoptionSepArg, 0 },
0c731d4a
AT
239 { 0, 0, 0, 0 }
240};
241
242static Bool
243WolframAutomata_event(Display * dpy, Window win, void * closure, XEvent * event)
244{
245 return False;
246}
247
248static void
249WolframAutomata_free(Display * dpy, Window win, void * closure)
250{
251 struct state * state = closure;
252 XFreeGC(state->dpy, state->gc);
7ce88c8e
AT
253 XFreePixmap(state->dpy, state->evolution_history);
254 free(state->current_generation);
0c731d4a
AT
255 free(state);
256}
257
258static void
259WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
260{
7ce88c8e 261 WolframAutomata_free(dpy, win, closure);
b0ea929b 262 closure = WolframAutomata_init(dpy, win);
0c731d4a
AT
263}
264
265XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", WolframAutomata)
266