webgpu-app/snake.wgsl
2026-08-05 13:20:03 -05:00

91 lines
1.9 KiB
WebGPU Shading Language

struct Configuration {
viewProj: mat4x4f,
lightViewProj: mat4x4f,
lightPosition: vec4f,
eyePosition: vec4f,
aspect: f32,
};
struct Bone {
position: vec4f,
velocity: vec4f,
};
struct BoneConfiguration {
a: vec4f,
};
@group(0) @binding(0) var<uniform> config: Configuration;
@group(1) @binding(0) var<storage> bones: array<Bone>;
@group(1) @binding(1) var<uniform> boneConfig: BoneConfiguration;
struct VertexInput {
@builtin(vertex_index) vertex_index: u32,
};
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) texture: vec2f,
};
const vertices = array(
vec2f(1.0, 0.0),
vec2f(0.0, 1.0),
vec2f(0.0, 0.0),
vec2f(1.0, 1.0),
);
@vertex
fn vertexMain(input: VertexInput) -> VertexOutput
{
let texture = vertices[input.vertex_index];
let position = texture * 2.0 - 1.0;
var output: VertexOutput;
output.position = vec4f(position, 0.0, 1.0);
output.texture = position * vec2f(config.aspect, 1);
return output;
}
fn sdCircle(center: vec2f, sample: vec2f) -> f32
{
let distance = length(center - sample);
return distance;
}
fn sdSegment(p: vec2f, a: vec2f, b: vec2f) -> f32
{
let ba = b - a;
let pa = p - a;
let h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
return length(pa - h * ba);
}
@fragment
fn fragmentMain(input: VertexOutput) -> @location(0) vec4f
{
var color = vec3f(input.texture.xy, 0);
for (var i: u32 = 0; i < u32(boneConfig.a.x); i++) {
if (sdCircle(input.texture.xy, bones[i].position.xy) < 0.01) {
color = vec3f(1, 1, 1);
}
/*
if (sdSegment(input.texture.xy,
bones[i].position.xy,
bones[i].position.xy + bones[i].velocity.xy * 0.05) < 0.002) {
color = vec3(0, 0, 1);
}
*/
/*
if (i == 1 && sdCircle(input.texture.xy, bones[i].velocity.xy) < 0.05) {
color = vec3(0, 0, 1);
}
*/
}
return vec4f(color, 1);
}