#include src/shaders/basic_structs.wgsl
#include src/shaders/basic_pbr.wgsl
#include src/shaders/tri_sampler.wgsl

[[group(0), binding(0)]]
var<uniform> camera: CameraUniform;

[[group(0), binding(1)]]
var<storage,read> point_lights: PointLightData;

[[group(1), binding(0)]]
var<storage,read> meshes: MeshData;

[[group(2), binding(0)]] var m_sampler: sampler;
[[group(2), binding(1)]] var m_albedo: texture_2d<f32>;
[[group(2), binding(2)]] var m_metallic_roughness: texture_2d<f32>;

[[stage(vertex)]]
fn vs_main(
  [[builtin(instance_index)]] mesh_idx: u32,
  vertex: VertexInput,
) -> VertexOutput {
  let transform = meshes.instances[mesh_idx].transform;
  let world_pos = transform * vec4<f32>(vertex.position, 1.0);
  let world_normal = transform * vec4<f32>(vertex.normal, 0.0);

  var out: VertexOutput;
  out.clip_position = camera.vp * world_pos;
  out.position = world_pos.xyz;
  out.normal = world_normal.xyz;
  out.tex_coords = vertex.tex_coords;
  return out;
}

[[stage(fragment)]]
fn fs_main(
  frag: VertexOutput,
) -> [[location(0)]] vec4<f32> {
  let normal = normalize(frag.normal);
  let view = normalize(camera.eye.xyz - frag.position);

  let albedo = textureSample(m_albedo, m_sampler, frag.tex_coords).xyz;
  // let albedo = TriSampler(m_albedo, m_sampler, frag.position, normal, 10.0);

  let metallic_roughness = textureSample(m_metallic_roughness, m_sampler, frag.tex_coords).bg;
  let metallic = metallic_roughness.x;
  let roughness = metallic_roughness.y;

  var lum = vec3<f32>(0.0);
  for(var i = 0; i < 4; i = i + 1) {
    let light = point_lights.lights[i];
    let light_position = light.center.xyz - frag.position;
    let light_intensity = light.intensity.rgb;
    let light_direction = normalize(light_position);

    let radiance = light_intensity / dot(light_position, light_position);

    let reflected = BRDF(
      light_direction, normal, view,
      albedo, metallic, roughness
    );

    lum = lum + (radiance * reflected);
  }

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