-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
477 lines (418 loc) · 14.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Graylife</title>
<style>
body {
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
}
#LifeBoard {
box-shadow: 0 2px 3px #333;
margin-bottom: 1em;
}
#LifeControls {
font-size: 12px;
}
#LifeControls > div {
margin-top: 8px;
margin-bottom: 8px;
}
#RunControl, #StepControl {
width: 12em;
height: 4em;
padding-right: 1em;
}
.pickCell {
width: 16px;
height: 16px;
border: 1px solid black;
padding: 1px;
margin: 1px;
display: inline-block;
}
.pickCell.color-picker-selected {
padding: 0;
border: 2px solid yellow;
box-shadow: 0 1px 2px blue;
}
</style>
</head>
<body>
<h1>Graylife</h1>
<h4>An extension of Conway’s Game of Life into grayscale</h4>
<canvas id="LifeBoard"></canvas>
<div id="LifeControls">
<div>
<button id="RunControl">Run</button>
<button id="StepControl">Step</button>
</div>
<div>
<label><input id="GridControl" type="checkbox">Grid</label>
</div>
<div>
<label>Algorithm: <select id="AlgorithmControl"></select></label>
</div>
<div>
<div id="ColorPicker"></div>
</div>
<div>
<button id="FillRandomControl">Fill random</button>
<button id="ClearControl">Clear</button>
</div>
<div>
<label>Preset: <select id="PresetControl"></select></label>
</div>
</div>
<div id="description">
<p>Conway’s Rules</p>
<ul>
<li>Any cell with 3 live neighbors is alive in the next round</li>
<li>A living cell with 2 live neighbors stays alive in the next round</li>
<li>All other cells will be dead.</li>
</ul>
<p>Graylife extensions</p>
<ul>
<li>Rather than live (1) or dead (0), cells may be in a range from 0 to 1</li>
<li><i>If all cells are 0 or 1, the rules are identical to Conway’s.</i></li>
<li>Beyond that, I’m playing around with different interpolations. Check the source code for details.</li>
</ul>
</div>
<div>
<a href="https://github.com/dleppik/graylife">Code repository</a>
</div>
<script>
let boardWidth = 400;
let boardHeight = 200;
let boardScale = 3;
let gridColor = '#eef';
let showGrid = false;
const randomFill = () => Math.random() < 0.75 ? 0 : Math.random();
const presets = [
{name: "Rhino", width: 400, height: 200, scale: 2, image: "Rhino.png"},
{name: "Inverted Jenny", width: 200, height: 200, scale: 2, image: "InvertedJenny.png"},
{name: "Cat Deposit", width: 200, height: 200, scale: 2, image: "CatDeposit-200x200.png"},
{name: "Ptolemaic System", width: 200, height: 200, scale: 2, image: "PtolemaicSystem.png"},
{name: "Small Random", width: 30, height: 30, scale: 10, init: randomFill },
{name: "Large Random", width: 400, height: 200, scale: 2, init: randomFill },
]
let preset = presets.find(it => it.name === 'Small Random');
// Game of Life functions: return (don't set) a new value
const simpleLife = (x, y) => {
const neighbors = cellNeighbors(x, y);
let sum = 0;
neighbors.forEach(value => {sum += Math.round(value);});
if (sum === 3) {
return 1;
}
if (sum === 2 && Math.round(cellValue(x, y)) === 1) {
return 1;
}
return 0;
}
const neighborly = (x, y) => {
function alive(value) {
return value > 0.125;
}
const neighbors = cellNeighbors(x, y);
let livingNeighbors = neighbors.filter(alive);
let value = cellValue(x, y);
if (alive(value)) {
if (livingNeighbors.length === 2) {
return livingNeighbors.sort()[0]; // Choose lowest value (lightest)
}
if (livingNeighbors.length === 3) {
return livingNeighbors.sort()[2]; // Choose highest value (brightest)
}
}
else {
if (livingNeighbors.length === 3) {
return livingNeighbors.sort()[1]; // Choose middle value
}
}
return 0;
}
const smooth = (x, y) => {
const neighbors = cellNeighbors(x, y);
let sum = 0;
neighbors.forEach(value => {sum += value});
let dist;
if (cellValue(x, y) <= 0.0001) {
if (sum < 2.5 || sum > 3.5) {
return 0;
}
dist = Math.abs(sum - 3);
}
else {
if (sum <= 1 || sum >= 4) {
return 0;
}
dist = (sum >= 2 && sum <= 3) ? 0 : Math.abs(sum - 2.5) * 2;
}
const result = Math.max(0, Math.min(1, 1 - Math.abs(dist)));
console.log(`(${x}, ${y}) with`, cellValue(x,y), '->', result, 'dist = ', dist, cellValue(x,y), neighbors);
return result;
}
let algorithms = {
"Neighborly": neighborly,
"Conway's Life": simpleLife,
"Gradient": smooth,
}
let algorithmName = "Neighborly";
let newCellValue = algorithms[algorithmName];
// Simulator
let board = new Float32Array(boardWidth*boardHeight);
let nextBoard = new Float32Array(boardWidth*boardHeight);
function cellIndex(x, y) { return (y * boardWidth) + x; }
function cellValue(x, y) { return board[cellIndex(x, y)] }
function setNextValue(x, y, value) { nextBoard[cellIndex(x, y)] = value }
function setCurrentValue(x, y, value) { board[cellIndex(x, y)] = value }
function cellNeighbor(cellX, cellY, dx, dy) {
const x = mod(cellX + dx, boardWidth);
const y = mod(cellY + dy, boardHeight);
return cellValue(x, y);
}
function mod(n, m) {
return ((n % m) + m) % m;
}
function cellNeighbors(x, y) {
return [
cellNeighbor(x, y, -1, -1),
cellNeighbor(x, y, -1, 0),
cellNeighbor(x, y, -1, 1),
cellNeighbor(x, y, 0, -1),
cellNeighbor(x, y, 0, 1),
cellNeighbor(x, y, 1, -1),
cellNeighbor(x, y, 1, 0),
cellNeighbor(x, y, 1, 1),
];
}
function update(cellFunction) {
if (!cellFunction) {
cellFunction = newCellValue;
}
for (let x=0; x<boardWidth; x++) {
for (let y=0; y<boardHeight; y++) {
setNextValue(x, y, cellFunction(x, y));
}
}
const swap = board;
board = nextBoard;
nextBoard = swap;
}
function fillRandom() { update(randomFill) }
function clearBoard() { update(() => 0) }
function fillImage(url) {
const image = new Image();
image.src = url;
image.onload = function() {
const imageCanvas = document.createElement("canvas");
imageCanvas.width = image.width;
imageCanvas.height = image.height;
const ic = imageCanvas.getContext("2d");
ic.drawImage(image, 0,0);
const data = ic.getImageData(0, 0, imageCanvas.width, imageCanvas.height);
for (let x=0; x < Math.min(imageCanvas.width, boardWidth); x++) {
for (let y=0; y < Math.min(imageCanvas.height, boardHeight); y++) {
const red = data.data[y * (image.width * 4) + x * 4];
const value = 1 - (red / 255);
setCurrentValue(x, y, value);
}
}
drawBoard();
}
}
// UI
let canvas = null;
let context = null;
let boardImage = null;
let boardScalingCanvas = document.createElement("canvas");
let running = null;
let runDelayMillis = 100;
function step() {
update();
drawBoard();
}
function run() {
if (running) {
clearInterval(running);
}
running = setInterval(step, runDelayMillis);
document.getElementById("RunControl").innerText = "Stop";
}
function stop() {
if (running) {
clearInterval(running);
running = null;
}
document.getElementById("RunControl").innerText = "Run";
}
function drawBoard() {
if (boardImage === null) {
boardImage = context.createImageData(boardWidth, boardHeight);
for (let i=0; i< boardImage.data.length; i++) {
boardImage.data[i] = 255;
}
boardScalingCanvas.width = boardWidth;
boardScalingCanvas.height = boardHeight;
}
for (let x=0; x < boardWidth; x++) {
for (let y=0; y < boardHeight; y++) {
drawPixel(cellValue(x, y), x, y);
}
}
boardScalingCanvas.getContext("2d").putImageData(boardImage, 0, 0);
context.imageSmoothingEnabled = false;
context.drawImage(boardScalingCanvas, 0, 0, canvas.width, canvas.height);
if (showGrid) {
context.strokeStyle = gridColor;
context.beginPath();
for (let x=0.5; x< canvas.width; x+= boardScale) { // 0.5: half pixel to avoid antialiasing
context.moveTo(x, 0);
context.lineTo(x, canvas.height);
}
for (let y=0.5; y < canvas.height; y+= boardScale) { // 0.5: half pixel to avoid antialiasing
context.moveTo(0, y);
context.lineTo(canvas.width, y);
}
context.stroke();
}
}
function pixelStyle(value) {
const color = 255 - Math.round(value * 255);
return `rgb(${color}, ${color}, ${color})`;
}
function drawPixel(value, x, y) {
const color = 255 - Math.round(value * 255);
let i = y * (boardWidth * 4) + x * 4;
boardImage.data[i] = color;
boardImage.data[i+1] = color;
boardImage.data[i+2] = color;
}
// Init
function initLife() {
loadPreset(preset.name);
initColorPicker(9);
initAlgorithmSelector();
initPresetControl();
document.getElementById("StepControl").addEventListener('click', () => {
stop();
step();
});
document.getElementById("RunControl").addEventListener('click', () => {
if (running) {
stop();
}
else {
run();
}
});
document.getElementById("FillRandomControl").addEventListener('click', () => {
fillRandom();
drawBoard();
});
document.getElementById("ClearControl").addEventListener('click', () => {
clearBoard();
drawBoard();
});
document.getElementById("GridControl").addEventListener('click', function() {
showGrid = this.checked;
drawBoard();
})
canvas.addEventListener('click', pickColor);
}
function initBoard() {
canvas = document.getElementById("LifeBoard");
canvas.width = boardWidth * boardScale;
canvas.height = boardHeight * boardScale;
context = canvas.getContext('2d');
boardImage = null;
}
function loadPreset(name) {
preset = presets.find(it => it.name === name);
boardWidth = preset.width;
boardHeight = preset.height;
boardScale = preset.scale;
showGrid = boardScale > 2;
const gridControl = document.getElementById("GridControl");
if (gridControl) {
gridControl.checked = showGrid;
}
initBoard();
if (preset.image) {
fillImage(preset.image);
}
if (preset.init) {
update(preset.init);
drawBoard();
}
}
function initPresetControl() {
const control = document.getElementById("PresetControl");
let html = '';
presets.forEach(p => {
const selected = (p.name === preset.name) ? ' selected ' : '';
html += `<option value="${p.name}" ${selected}>${p.name}</option>`
});
control.innerHTML = html;
control.addEventListener('change', (e) => {
clearBoard();
loadPreset(e.target.value);
});
}
function selectAlgorithm(name) {
const a = algorithms[name];
if (!a) {
alert("Unknown algorithm: "+name);
return;
}
algorithmName = name;
newCellValue = a;
const el = document.getElementById("AlgorithmControl");
Array.from(el.children).forEach((opt, i) => {
if (opt.value === name) {
el.selectedIndex = i;
}
});
}
function initAlgorithmSelector() {
let html = "";
Object.keys(algorithms).sort().forEach(name => {
html += `<option value="${name}">${name}</option>`;
});
const el = document.getElementById("AlgorithmControl");
el.innerHTML = html;
el.onchange = (e) => {
selectAlgorithm(e.target.value);
};
selectAlgorithm(algorithmName);
}
function pickColor(event) {
const pickEl = document.getElementsByClassName("color-picker-selected")[0];
const value = Number(pickEl.dataset.value);
const x = Math.floor(event.offsetX / boardScale);
const y = Math.floor(event.offsetY / boardScale);
setCurrentValue(x, y, value);
drawBoard();
}
function initColorPicker(numColors) {
const picker = document.getElementById("ColorPicker");
picker.innerHTML = "";
for (let i=0; i<numColors; i++) {
let value = i / (numColors-1);
picker.innerHTML += `<div class="pickCell" data-value="${value}" style="background: ${pixelStyle(value)}"></div>`;
}
picker.lastElementChild.classList.add("color-picker-selected");
picker.childNodes.forEach(el => {
el.onclick = () => {
Array.from(document.getElementsByClassName("color-picker-selected")).forEach(old => {
old.classList.remove("color-picker-selected");
})
el.classList.add("color-picker-selected");
}
})
}
initLife();
</script>
</body>
</html>