// Custom shader materials: the tycho_3d equivalent of three.js
// `ShaderMaterial` / `NodeMaterial`. A caller registers a SPIR-V vertex +
// fragment pair once, then any number of scene nodes can use it through
// `MaterialDesc::custom`. The renderer draws those nodes inside the main HDR
// pass (after opaque PBR, before alpha-blended PBR) with the standard scene
// bindings plus a per-shader uniform block and texture slots:
//
//   set 0, binding 0 : FrameUBO   (std140, identical layout to `pbr.frag`)
//   set 0, binding 1 : ObjectBuf  (std430, `ObjectGpu` records, instanced)
//   set 0, binding 2 : UserUBO    (std140, `set_custom_uniforms` floats)
//   set 0, binding 3+: user textures (`set_custom_texture`, slot i -> 3 + i)
//
// The vertex stage must consume the shared 48-byte P3/N3/UV2/T4 layout and
// address objects as `objects[gl_InstanceIndex]` exactly like `pbr.vert`.

///|
/// Renderer-owned custom shader slot. Only `Renderer3D::create_custom_shader`
/// can produce one, so a material can never reference an unregistered slot.
#derive(Eq, Debug)
pub(all) struct CustomShader {
  priv id : Int
}

///|
pub fn CustomShader::id(self : CustomShader) -> Int {
  self.id
}

///|
priv struct CustomShaderState {
  pipe : @rhi.Pipeline
  // Two frame slots so a upload never races the previous frame's read.
  ubo : @rhi.Buffer
  ubo_slot_floats : Int
  ubo_slot_bytes : Int
  ubo_data : FixedArray[Float]
  textures : Array[(@rhi.Texture, @rhi.Sampler)?]
}

///|
/// Register a custom shader pipeline drawn inside the main HDR pass.
///
/// `uniform_floats` is the size of the user uniform block in floats (std140
/// layout is the caller's responsibility; the block is padded to a vec4
/// multiple). `texture_slots` reserves bindings `3 .. 3 + texture_slots - 1`.
/// `blend` selects standard alpha blending (water, decals); `depth_write`
/// defaults to true for opaque custom surfaces. The pipeline matches the
/// renderer's MSAA sample count and the reversed-Z HDR pass format.
pub fn Renderer3D::create_custom_shader(
  self : Renderer3D,
  vert : FixedArray[UInt32],
  frag : FixedArray[UInt32],
  uniform_floats : Int,
  texture_slots? : Int = 0,
  blend? : Bool = false,
  depth_write? : Bool = true,
  cull_mode? : @rhi.CullMode = @rhi.CullMode::Back,
  depth_test? : Bool = true,
) -> CustomShader raise {
  if uniform_floats < 0 || texture_slots < 0 {
    raise Render3DError::InvalidMaterial("create_custom_shader: negative slot count")
  }
  let slot_floats = if uniform_floats == 0 {
    4
  } else {
    ((uniform_floats + 3) / 4) * 4
  }
  // Uniform descriptor offsets must be a multiple of the device's
  // minUniformBufferOffsetAlignment, so stride the two frame slots by that
  // alignment (not merely by the vec4-padded block size). Without this, slot 1
  // of e.g. a 44-float block lands at byte 176 and trips validation on devices
  // with a 64-byte (or 256-byte) alignment requirement.
  let dev_align = self.dev.capabilities().min_uniform_buffer_offset_alignment
  let align = if dev_align > 16 { dev_align } else { 16 }
  let raw_bytes = slot_floats * 4
  let slot_bytes = ((raw_bytes + align - 1) / align) * align
  let samples = if self.msaa {
    @rhi.SampleCount::X4
  } else {
    @rhi.SampleCount::X1
  }
  let mesh_layouts : Array[@rhi.VertexBufferLayout] = [
    @rhi.VertexBufferLayout::new(
      48,
      [
        @rhi.VertexAttribute::new(0, @rhi.VertexFormat::Float3, 0),
        @rhi.VertexAttribute::new(1, @rhi.VertexFormat::Float3, 12),
        @rhi.VertexAttribute::new(2, @rhi.VertexFormat::Float2, 24),
        @rhi.VertexAttribute::new(3, @rhi.VertexFormat::Float4, 32),
      ],
    ),
  ]
  let pipe = create_3d_pipeline(
    self.dev,
    @rhi.PipelineDesc::from_spirv(
      vert,
      frag,
      depth_test=depth_test,
      depth_write=depth_write,
      depth_compare=@rhi.CompareOp::GreaterEqual,
      depth_format=@rhi.TextureFormat::Depth32F,
      cull_mode=cull_mode,
      front_face=@rhi.FrontFace::CounterClockwise,
      blend=blend,
      blend_mode=if blend {
        @rhi.BlendMode::Alpha
      } else {
        @rhi.BlendMode::Opaque
      },
      color_format=@rhi.TextureFormat::RGBA16F,
      vertex_layouts=mesh_layouts,
      samples=samples,
    ),
  )
  let ubo = self.dev.create_buffer_with(
    slot_bytes * 2,
    @rhi.BufferKind::Uniform,
    @rhi.MemoryLocation::CpuToGpu,
  )
  let textures : Array[(@rhi.Texture, @rhi.Sampler)?] = []
  for i = 0; i < texture_slots; i = i + 1 {
    textures.push(None)
  }
  let id = self.custom_shaders.length()
  self.custom_shaders.push({
    pipe,
    ubo,
    ubo_slot_floats: slot_floats,
    ubo_slot_bytes: slot_bytes,
    ubo_data: FixedArray::make(slot_floats, (0.0 : Float)),
    textures,
  })
  { id, }
}

///|
/// Stage the user uniform block for a custom shader. The floats are uploaded
/// to the current frame slot at draw time; the layout must be std140.
/// Extra floats beyond the registered size are ignored.
pub fn Renderer3D::set_custom_uniforms(
  self : Renderer3D,
  shader : CustomShader,
  floats : FixedArray[Float],
) -> Unit raise {
  let id = shader.id()
  if id < 0 || id >= self.custom_shaders.length() {
    raise Render3DError::InvalidMaterial("set_custom_uniforms: unknown custom shader")
  }
  let cs = self.custom_shaders[id]
  let n = if floats.length() < cs.ubo_slot_floats {
    floats.length()
  } else {
    cs.ubo_slot_floats
  }
  for i = 0; i < n; i = i + 1 {
    cs.ubo_data[i] = floats[i]
  }
}

///|
/// Bind a sampled texture into custom-shader slot `slot` (fragment binding
/// `3 + slot`). Passing `None` clears the slot. The default sampler is linear
/// clamp-to-edge; supply a custom sampler for repeat / nearest filtering.
pub fn Renderer3D::set_custom_texture(
  self : Renderer3D,
  shader : CustomShader,
  slot : Int,
  texture : @rhi.Texture?,
  sampler? : @rhi.Sampler,
) -> Unit raise {
  let id = shader.id()
  if id < 0 || id >= self.custom_shaders.length() {
    raise Render3DError::InvalidMaterial("set_custom_texture: unknown custom shader")
  }
  let cs = self.custom_shaders[id]
  if slot < 0 || slot >= cs.textures.length() {
    raise Render3DError::InvalidTexture("set_custom_texture: slot out of range")
  }
  cs.textures[slot] = match texture {
    Some(t) => Some((t, match sampler {
      Some(s) => s
      None => self.linear_sampler
    }))
    None => None
  }
}

///|
/// Number of registered custom shaders (verification helper).
pub fn Renderer3D::custom_shader_count(self : Renderer3D) -> Int {
  self.custom_shaders.length()
}

///|
/// The reference custom-shader pair (`shaders/custom_flat.{vert,frag}`): a
/// flat HDR colour read from the user uniform block (one vec4). Useful as a
/// starting point and as the contract test for the custom pipeline path.
pub fn custom_flat_shader_spv() -> (FixedArray[UInt32], FixedArray[UInt32]) {
  (spv_custom_flat_vert, spv_custom_flat_frag)
}

///|
fn Renderer3D::destroy_custom_shaders(self : Renderer3D) -> Unit {
  for cs in self.custom_shaders {
    cs.pipe.destroy()
    cs.ubo.destroy()
  }
  self.custom_shaders.clear()
}

///|
/// Draw one custom-shader batch inside the main HDR pass. `slot` is the
/// frame-in-flight index used for the frame UBO and the user uniform block.
fn Renderer3D::draw_custom_batch(
  self : Renderer3D,
  pass : @rhi.RenderPass,
  batch : DrawBatch,
  object_offset : Int,
  object_count : Int,
  slot : Int,
) -> Unit {
  let mati = batch.material
  if mati < 0 || mati >= self.materials.length() {
    return
  }
  let ci = match self.materials[mati].shading {
    Custom(c) => c
    _ => -1
  }
  if ci < 0 || ci >= self.custom_shaders.length() {
    return
  }
  let cs = self.custom_shaders[ci]
  try {
    cs.ubo.upload_floats(
      cs.ubo_data,
      slot * cs.ubo_slot_bytes,
      cs.ubo_slot_floats,
    )
  } catch {
    _ => ()
  }
  // RHI bind_* take 0-based slots in reflected-binding order (ascending
  // binding number): uniforms [0, 2] -> slot 0 FrameUBO, slot 1 UserUBO;
  // the only storage buffer (binding 1) -> slot 0; textures (3+) -> slot i.
  pass.bind_pipeline(cs.pipe)
  pass.bind_uniform(
    cs.pipe,
    0,
    self.frame_ubo,
    slot * FRAME_SLOT_BYTES,
    FRAME_BYTES,
  )
  pass.bind_storage(
    cs.pipe,
    0,
    self.object_ring.buffer(),
    object_offset,
    bind_objects_bytes(object_count),
  )
  pass.bind_uniform(
    cs.pipe,
    1,
    cs.ubo,
    slot * cs.ubo_slot_bytes,
    cs.ubo_slot_bytes,
  )
  for i = 0; i < cs.textures.length(); i = i + 1 {
    match cs.textures[i] {
      Some((t, s)) => pass.bind_texture(cs.pipe, i, t, s)
      None => ()
    }
  }
  let mesh = self.meshes[batch.mesh]
  pass.draw_indexed_full(
    mesh.index_count(),
    batch.count,
    mesh.first_index(),
    mesh.first_vertex(),
    batch.first,
  )
  self.stats.draw_calls = self.stats.draw_calls + 1
  self.stats.triangles = self.stats.triangles + mesh.index_count() / 3 * batch.count
}