Search across packages, versions, files, declarations, and comments. Use multiple terms to narrow results (AND), and add @vertex, @fragment, or @compute to filter by shader stage.
1// The shader reads the previous frame's state from the `input` texture, and writes the new state of
2// each pixel to the `output` texture. The textures are flipped each step to progress the
3// simulation.
4// Two textures are needed for the game of life as each pixel of step N depends on the state of its
5// neighbors at step N-1.
7@group(0) @binding(0) var input: texture_storage_2d<r32float, read>;
9@group(0) @binding(1) var output: texture_storage_2d<r32float, write>;
11fn hash(value: u32) -> u32 {
12 var state = value;
13 state = state ^ 2747636419u;
14 state = state * 2654435769u;
15 state = state ^ state >> 16u;
16 state = state * 2654435769u;
17 state = state ^ state >> 16u;
18 state = state * 2654435769u;
19 return state;
22fn randomFloat(value: u32) -> f32 {
23 return f32(hash(value)) / 4294967295.0;
26@compute @workgroup_size(8, 8, 1)
27fn init(@builtin(global_invocation_id) invocation_id: vec3<u32>, @builtin(num_workgroups) num_workgroups: vec3<u32>) {
28 let location = vec2<i32>(i32(invocation_id.x), i32(invocation_id.y));
30 let randomNumber = randomFloat(invocation_id.y << 16u | invocation_id.x);
31 let alive = randomNumber > 0.9;
32 let color = vec4<f32>(f32(alive));
34 textureStore(output, location, color);
37fn is_alive(location: vec2<i32>, offset_x: i32, offset_y: i32) -> i32 {
38 let value: vec4<f32> = textureLoad(input, location + vec2<i32>(offset_x, offset_y));
39 return i32(value.x);
42fn count_alive(location: vec2<i32>) -> i32 {
43 return is_alive(location, -1, -1) +
44 is_alive(location, -1, 0) +
45 is_alive(location, -1, 1) +
46 is_alive(location, 0, -1) +
47 is_alive(location, 0, 1) +
48 is_alive(location, 1, -1) +
49 is_alive(location, 1, 0) +
50 is_alive(location, 1, 1);
53@compute @workgroup_size(8, 8, 1)
54fn update(@builtin(global_invocation_id) invocation_id: vec3<u32>) {
55 let location = vec2<i32>(i32(invocation_id.x), i32(invocation_id.y));
57 let n_alive = count_alive(location);
59 var alive: bool;
60 if (n_alive == 3) {
61 alive = true;
62 } else if (n_alive == 2) {
63 let currently_alive = is_alive(location, 0, 0);
64 alive = bool(currently_alive);
65 } else {
66 alive = false;
67 }
68 let color = vec4<f32>(f32(alive));
70 textureStore(output, location, color);
Contents