struct VertexInput {
    @location(0) position: vec3<f32>,
    @location(1) normal: vec3<f32>,
    @location(2) uv: vec2<f32>,
    @location(3) instance_model_0: vec4<f32>,
    @location(4) instance_model_1: vec4<f32>,
    @location(5) instance_model_2: vec4<f32>,
    @location(6) instance_model_3: vec4<f32>,
    @location(7) instance_dissolve: f32,
}

struct VertexOutput {
    @builtin(position) clip_position: vec4<f32>,
    @location(0) world_position: vec3<f32>,
    @location(1) world_normal: vec3<f32>,
    @location(2) dissolve_amount: f32,
    @location(3) uv: vec2<f32>,
}

const MAX_SPOTLIGHTS: u32 = 4u;

struct Spotlight {
    position: vec3<f32>,
    inner_angle: f32,
    direction: vec3<f32>,
    outer_angle: f32,
    range: f32,
    _padding: f32,
    _padding2: f32,
    _padding3: f32,
    _padding4: f32,
    _padding5: f32,
    _padding6: f32,
    _padding7: f32,
}

struct Uniforms {
    model: mat4x4<f32>,
    view: mat4x4<f32>,
    projection: mat4x4<f32>,
    light_view_projections: array<mat4x4<f32>, 4>,
    camera_position: vec3<f32>,
    height_scale: f32,
    player_position: vec3<f32>,
    time: f32,
    shadow_bias: f32,
    tile_scale: f32,
    enable_dissolve: u32,
    enable_snow_light: u32,
    spotlight_count: u32,
    debug_mode: u32,
    _padding2: u32,
    _padding3: u32,
    spotlights: array<Spotlight, 4>,
}

@group(0) @binding(0)
var<uniform> uniforms: Uniforms;

@group(0) @binding(1)
var shadow_map: texture_depth_2d_array;

@group(0) @binding(2)
var shadow_sampler: sampler_comparison;

@group(0) @binding(7)
var blue_noise_texture: texture_2d<f32>;

@group(0) @binding(8)
var blue_noise_sampler: sampler;

@group(0) @binding(9)
var snow_light_texture: texture_2d<f32>;

@group(0) @binding(10)
var snow_light_sampler: sampler;

const PI: f32 = 3.14159265359;
const TERRAIN_BOUNDS: vec2<f32> = vec2<f32>(1000.0, 1000.0);
const LINE_THICKNESS: f32 = 0.1;
const OCTAVE_STEPS: f32 = 4.0;
const STROKE_LENGTH: f32 = 0.8;

fn hash2(p: vec2<f32>) -> f32 {
    let p3 = fract(vec3<f32>(p.x, p.y, p.x) * 0.13);
    let p3_dot = dot(p3, vec3<f32>(p3.y + 3.333, p3.z + 3.333, p3.x + 3.333));
    return fract((p3.x + p3.y) * p3_dot);
}

fn rand(p: vec2f) -> f32 {
    return fract(sin(dot(p, vec2f(12.9898, 78.233))) * 43758.5453);
}

struct StrokeData {
    world_pos_2d: vec2<f32>,
    tile_center: vec2<f32>,
    tile_size: f32,
    direction_to_light: vec2<f32>,
    distance_to_light: f32,
    perpendicular_to_light: vec2<f32>,
    rotation_t: f32,
    line_direction: vec2<f32>,
    perpendicular_to_line: vec2<f32>,
    octave_index: f32,
    offset: vec2<f32>,
    local_pos: vec2<f32>,
}

fn compute_perpendicular(dir: vec2<f32>) -> vec2<f32> {
    return normalize(vec2<f32>(-dir.y, dir.x));
}

fn compute_rotation_t(distance_to_light: f32) -> f32 {
    return pow(min(max(distance_to_light - 1.0 / OCTAVE_STEPS, 0.0) * OCTAVE_STEPS, 1.0), 2.0);
}

fn sample_shadow_map(world_pos: vec3<f32>, spotlight_index: u32) -> f32 {
    let light_space_pos = uniforms.light_view_projections[spotlight_index] * vec4<f32>(world_pos, 1.0);
    let proj_coords = light_space_pos.xyz / light_space_pos.w;
    let ndc_coords = proj_coords * vec3<f32>(0.5, -0.5, 1.0) + vec3<f32>(0.5, 0.5, 0.0);

    if ndc_coords.x < 0.0 || ndc_coords.x > 1.0 || ndc_coords.y < 0.0 || ndc_coords.y > 1.0 || ndc_coords.z < 0.0 || ndc_coords.z > 1.0 {
        return 1.0;
    }

    let depth = ndc_coords.z - uniforms.shadow_bias;
    let shadow = textureSampleCompare(shadow_map, shadow_sampler, ndc_coords.xy, spotlight_index, depth);

    return shadow;
}

fn hatching_lighting(world_pos: vec3<f32>, clip_pos: vec4<f32>, tile_scale: f32, direction: vec2<f32>, distance: f32) -> f32 {
    let octave_index = round((1.0 - pow(distance, 2.0)) * OCTAVE_STEPS);
    let octave_normalized = octave_index / OCTAVE_STEPS;

    if octave_index > 3.0 {
        return 1.0;
    } else if octave_index < 1.0 {
        let screen_pos = clip_pos.xy / clip_pos.w;
        let blue_noise_uv = screen_pos * 0.5 + 0.5;
        let blue_noise = textureSample(blue_noise_texture, blue_noise_sampler, blue_noise_uv * 10.0).r;
        return step(blue_noise, 0.05);
    }


    let world_pos_2d = vec2<f32>(world_pos.x, world_pos.z);
    let tile_size = 1.0 / tile_scale;
    let base_tile_center = floor(world_pos_2d / tile_size) * tile_size + tile_size * 0.5;

    var min_lighting = 1.0;

    for (var tile_y: i32 = -1; tile_y <= 1; tile_y++) {
        for (var tile_x: i32 = -1; tile_x <= 1; tile_x++) {
            let tile_center = base_tile_center + vec2<f32>(f32(tile_x), f32(tile_y)) * tile_size;

            let perpendicular_to_light = compute_perpendicular(direction);
            let t = compute_rotation_t(distance);
            let parallel = mix(perpendicular_to_light, direction, t / 2.0);
            let perpendicular = compute_perpendicular(parallel);

            let spacing = LINE_THICKNESS * 1.5;

            var max_offset: i32;
            switch i32(octave_index) {
                case default {
                    max_offset = 0;
                }
                case 3 {
                    max_offset = 3;
                }
                case 2 {
                    max_offset = 9;
                }
                case 1 {
                    max_offset = 6;
                }
            }
            for (var i: i32 = -max_offset; i <= max_offset; i++) {
                let random = rand(tile_center + vec2<f32>(f32(i), f32(-i)));
                var chance: f32;
                switch i32(octave_index) {
                    case 1, default: {
                        chance = 1.0;
                    }
                    case 2: {
                        chance = 0.5;
                    }
                    case 3: {
                        chance = 0.8;
                    }
                }
                if random > chance {
                    continue;
                }
                let offset = perpendicular * f32(i) * tile_size / f32(max_offset);
                let local_pos = world_pos_2d - tile_center - offset;

                let stroke_data = StrokeData(
                    world_pos_2d,
                    tile_center,
                    tile_size,
                    direction,
                    distance,
                    perpendicular_to_light,
                    t,
                    parallel,
                    perpendicular,
                    octave_index,
                    offset,
                    local_pos,
                );

                let lighting = line_stroke_lighting(stroke_data, clip_pos);
                min_lighting = min(min_lighting, lighting);
            }
        }
    }

    return min_lighting;
}

struct SpotlightData {
    direction_normalized: vec2<f32>,
    combined_distance: f32,
    is_lit: bool,
}

fn calculate_spotlight_data(world_pos: vec3<f32>, normal: vec3<f32>, spotlight: Spotlight, tile_scale: f32, shadow: f32) -> SpotlightData {
    var data: SpotlightData;
    data.is_lit = false;
    data.direction_normalized = vec2<f32>(0.0, 0.0);
    data.combined_distance = 2.0;

    let to_fragment = normalize(world_pos - spotlight.position);
    let angle_to_fragment = acos(dot(to_fragment, spotlight.direction));

    if angle_to_fragment > spotlight.outer_angle {
        return data;
    }

    let cube_size = 1.0 / tile_scale;
    let cube_center = vec3<f32>(
        floor(world_pos.x / cube_size) * cube_size + cube_size * 0.5,
        floor(world_pos.y / cube_size) * cube_size + cube_size * 0.5,
        floor(world_pos.z / cube_size) * cube_size + cube_size * 0.5
    );
    let tile_center = vec2<f32>(cube_center.x, cube_center.z);

    let angular_falloff = smoothstep(spotlight.inner_angle, spotlight.outer_angle, angle_to_fragment);

    let direction_to_point_3d = normalize(spotlight.position - cube_center);
    let diffuse_raw = max(0.0, dot(normalize(normal), direction_to_point_3d));
    let diffuse_res = 4.0;
    let diffuse = floor(diffuse_raw * diffuse_res) / diffuse_res;

    let t = (cube_center.y - spotlight.position.y) / spotlight.direction.y;
    let hit_point = spotlight.position + spotlight.direction * t;
    let hit_point_2d = vec2<f32>(hit_point.x, hit_point.z);
    let direction_to_hit = hit_point_2d - tile_center;
    let distance_to_hit = min(length(direction_to_hit) / spotlight.range, 1.0);
    data.direction_normalized = normalize(direction_to_hit);

    let lighting_intensity = shadow * pow(diffuse, 0.5) * (1.0 - angular_falloff);
    let darkness = 1.0 - lighting_intensity;
    data.combined_distance = distance_to_hit + darkness;

    data.is_lit = data.combined_distance <= 1.0;

    return data;
}

fn all_spotlights_lighting(world_pos: vec3<f32>, clip_pos: vec4<f32>, normal: vec3<f32>, tile_scale: f32) -> f32 {
    var max_lighting = 0.0;

    for (var i = 0u; i < uniforms.spotlight_count; i++) {
        let spotlight = uniforms.spotlights[i];
        let shadow = sample_shadow_map(world_pos, i);
        let data = calculate_spotlight_data(world_pos, normal, spotlight, tile_scale, shadow);

        if data.is_lit {
            let lighting = hatching_lighting(world_pos, clip_pos, tile_scale, data.direction_normalized, data.combined_distance);
            max_lighting = max(max_lighting, lighting);
        }
    }

    return max_lighting;
}

fn line_stroke_lighting(data: StrokeData, clip_pos: vec4<f32>) -> f32 {
    let octave_normalized = data.octave_index / OCTAVE_STEPS;

    let noise = hash2(data.tile_center + data.offset) * 2.0 - 1.0;

    var noise_at_octave = noise;
    var jitter: f32;

    switch i32(data.octave_index) {
        case default {
            noise_at_octave = noise;
            jitter = 1.0;
        }
        case 2 {
            noise_at_octave = noise / 10.0;
            jitter = 1.0;
        }
        case 3 {
            noise_at_octave = noise / 20.0;
            jitter = 0.5;
        }
    }
    let line = mix(data.perpendicular_to_light, data.direction_to_light, data.rotation_t / (2.0 + noise_at_octave));
    let perpendicular_to_line = compute_perpendicular(line);

    let parallel_coord = dot(data.local_pos, line);
    let perpendicular_coord = dot(data.local_pos, perpendicular_to_line);

    let line_half_width = LINE_THICKNESS * (1.0 - octave_normalized * 0.5) * data.tile_size;
    let straight_section_half_length = max(0.0, data.tile_size * 0.4 - line_half_width);

    let parallel_jitter = (rand(data.tile_center + data.offset * 123.456) * 2.0 - 1.0) * data.tile_size * jitter;
    let jittered_parallel_coord = parallel_coord - parallel_jitter;

    let overhang = max(0.0, abs(jittered_parallel_coord) - straight_section_half_length);
    let effective_distance = sqrt(overhang * overhang + perpendicular_coord * perpendicular_coord);

    return step(line_half_width, effective_distance);
}
