-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathlife.js
83 lines (69 loc) · 1.58 KB
/
life.js
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
/*
tags: fbo, basic
<p>This example implements the game of life in regl.</p>
*/
const regl = require('../regl')()
const RADIUS = 512
const INITIAL_CONDITIONS = (Array(RADIUS * RADIUS * 4)).fill(0).map(
() => Math.random() > 0.9 ? 255 : 0)
const state = (Array(2)).fill().map(() =>
regl.framebuffer({
color: regl.texture({
radius: RADIUS,
data: INITIAL_CONDITIONS,
wrap: 'repeat'
}),
depthStencil: false
}))
const updateLife = regl({
frag: `
precision mediump float;
uniform sampler2D prevState;
varying vec2 uv;
void main() {
float n = 0.0;
for(int dx=-1; dx<=1; ++dx)
for(int dy=-1; dy<=1; ++dy) {
n += texture2D(prevState, uv+vec2(dx,dy)/float(${RADIUS})).r;
}
float s = texture2D(prevState, uv).r;
if(n > 3.0+s || n < 3.0) {
gl_FragColor = vec4(0,0,0,1);
} else {
gl_FragColor = vec4(1,1,1,1);
}
}`,
framebuffer: ({tick}) => state[(tick + 1) % 2]
})
const setupQuad = regl({
frag: `
precision mediump float;
uniform sampler2D prevState;
varying vec2 uv;
void main() {
float state = texture2D(prevState, uv).r;
gl_FragColor = vec4(vec3(state), 1);
}`,
vert: `
precision mediump float;
attribute vec2 position;
varying vec2 uv;
void main() {
uv = 0.5 * (position + 1.0);
gl_Position = vec4(position, 0, 1);
}`,
attributes: {
position: [ -4, -4, 4, -4, 0, 4 ]
},
uniforms: {
prevState: ({tick}) => state[tick % 2]
},
depth: { enable: false },
count: 3
})
regl.frame(() => {
setupQuad(() => {
regl.draw()
updateLife()
})
})