struct VertexOutput {
  @builtin(position) clip_pos: vec4<f32>,
  @location(0) texture_coords: vec2<f32>,
  @location(1) color: vec4<f32>,
};

struct Sprite {
  top_left: vec2<f32>,
  bottom_right: vec2<f32>,
}

fn rescale_to_sprite(pos: vec2<f32>, sprite_coords: vec4<f32>) -> vec2<f32> {
    let dir = (sprite_coords.zw - sprite_coords.xy);

    return sprite_coords.xy + (dir * pos);
}

struct VmInstance {
  @location(0) mtx_0: vec4<f32>,
  @location(1) mtx_1: vec4<f32>,
  @location(2) mtx_2: vec4<f32>,
  @location(3) mtx_3: vec4<f32>,
  @location(4) sprite: vec4<f32>,
  @location(5) color: vec4<f32>,
  @location(6) offset: vec2<f32>,
}

@group(1) @binding(1)
var<uniform> proj_mtx: mat4x4<f32>;

@vertex
fn vs_main(
    @builtin(vertex_index) in_vertex_index: u32,
    instance: VmInstance,
) -> VertexOutput {
    var out: VertexOutput;
    var vertex_pos = vec2<f32>(
        f32(in_vertex_index & 1),
        f32(in_vertex_index >> 1),
    );
    var in_mtx = mat4x4<f32>(
        instance.mtx_0,
        instance.mtx_1,
        instance.mtx_2,
        instance.mtx_3,
    );
    out.clip_pos = proj_mtx * in_mtx * vec4<f32>(vertex_pos.xy - instance.offset, 0.0, 1.0);
    out.texture_coords = rescale_to_sprite(vertex_pos, instance.sprite);
    out.color = instance.color;
    return out;
}

@group(0) @binding(0)
var t_diffuse: texture_2d<f32>;
@group(1) @binding(0)
var s_diffuse: sampler;

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    return in.color * textureSample(t_diffuse, s_diffuse, in.texture_coords);
}
