@group(0) @binding(0) var source_texture: texture_2d<f32>;
@group(0) @binding(1) var source_sampler: sampler;

struct VertexOutput {
    @builtin(position) clip_position: vec4<f32>,
    @location(0) uv: vec2<f32>,
}

@vertex
fn vertex_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
    let uv = vec2<f32>(
        f32((vertex_index << 1u) & 2u),
        f32(vertex_index & 2u)
    );
    let clip_position = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);

    var out: VertexOutput;
    out.clip_position = clip_position;
    out.uv = vec2<f32>(uv.x, 1.0 - uv.y);
    return out;
}

@fragment
fn fragment_main(in: VertexOutput) -> @location(0) vec4<f32> {
    let texture_size = vec2<f32>(textureDimensions(source_texture));
    let texel_size = 1.0 / texture_size;

    let a = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(-1.0, -1.0)).rgb;
    let b = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(0.0, -1.0)).rgb;
    let c = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(1.0, -1.0)).rgb;
    let d = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(-0.5, -0.5)).rgb;
    let e = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(0.5, -0.5)).rgb;
    let f = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(-1.0, 0.0)).rgb;
    let g = textureSample(source_texture, source_sampler, in.uv).rgb;
    let h = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(1.0, 0.0)).rgb;
    let i = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(-0.5, 0.5)).rgb;
    let j = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(0.5, 0.5)).rgb;
    let k = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(-1.0, 1.0)).rgb;
    let l = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(0.0, 1.0)).rgb;
    let m = textureSample(source_texture, source_sampler, in.uv + texel_size * vec2<f32>(1.0, 1.0)).rgb;

    var downsample = (d + e + i + j) * 0.125;
    downsample = downsample + (a + c + k + m) * 0.03125;
    downsample = downsample + (b + f + h + l) * 0.0625;
    downsample = downsample + g * 0.125;

    return vec4<f32>(downsample, 1.0);
}
