import { GLSL3, RawShaderMaterial } from "three";


// Debug visualisation: viewport depth of each voxel as grayscale.
// Same world-space-sized camera-facing quad as the other shaders.
const shader_vx = `
    in vec3 position;
    in vec2 uv;
    in vec3 iPosition;
    in vec3 iNormal;

    out vec2 vUv;

    uniform mat4 modelMatrix;
    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;
    uniform float uPointDiameter;

    void main() {
        vUv = uv;

        float model_scale = length(modelMatrix[0].xyz);
        float world_diameter = uPointDiameter * model_scale;
        float radius_OS = uPointDiameter * 0.5;

        // Inward-shift; see VoxelImpostorShaderV0 for rationale.
        vec3 centre_OS = iPosition - iNormal * radius_OS;
        vec4 centre_view = modelViewMatrix * vec4(centre_OS, 1.0);
        vec2 corner = position.xy * world_diameter;
        gl_Position = projectionMatrix * (centre_view + vec4(corner, 0.0, 0.0));
    }
`;

const shader_fg = `
    precision highp float;
    precision highp int;

    in vec2 vUv;

    out vec4 color_out;

    uniform bool uDiscMask;

    void main() {
        if (uDiscMask) {
            vec2 c = vUv - 0.5;
            if (dot(c, c) > 0.25) {
                discard;
            }
        }
        float d = 1.0 - gl_FragCoord.z;
        color_out = vec4(d, d, d, 1.0);
    }
`;

export class VoxelImpostorShaderViewportDepthV0 extends RawShaderMaterial {
    constructor() {
        super({
            vertexShader: shader_vx,
            fragmentShader: shader_fg,
            glslVersion: GLSL3,
            uniforms: {
                uPointDiameter: { value: 0.05 },
                uDiscMask: { value: false }
            }
        });
    }
}
