/////////////////////////////  GPL LICENSE NOTICE  /////////////////////////////

//  crt-royale: A full-featured CRT shader, with cheese.
//  Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
//
//  This program is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License as published by the Free
//  Software Foundation; either version 2 of the License, or any later version.
//
//  This program is distributed in the hope that it will be useful, but WITHOUT
//  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
//  more details.
//
//  You should have received a copy of the GNU General Public License along with
//  this program; if not, write to the Free Software Foundation, Inc., 59 Temple
//  Place, Suite 330, Boston, MA 02111-1307 USA


/////////////////////////////  SETTINGS MANAGEMENT  ////////////////////////////

#include "../user-settings.h"
#include "derived-settings-and-constants.h"
#include "bind-shader-params.h"


//////////////////////////////////  INCLUDES  //////////////////////////////////

#include "../../../../include/gamma-management.h"
#include "../../../../include/blur-functions.h"
#include "phosphor-mask-resizing.h"
#include "scanline-functions.h"
#include "bloom-functions.h"


/////////////////////////////////  STRUCTURES  /////////////////////////////////

struct orig
{
    float2 tex_coord;
    uniform float2 video_size;
    uniform float2 texture_size;
    uniform float2 output_size;
    uniform sampler2D texture;
};

struct input
{
    float2 video_size;
    float2 texture_size;
    float2 output_size;
    float frame_count;
    float frame_direction;
    float frame_rotation;
};

struct out_vertex
{
    float4 position                     : POSITION;
    float2 video_uv                     : TEXCOORD0;
    float2 scanline_tex_uv              : TEXCOORD1;
    float2 blur3x3_tex_uv               : TEXCOORD2;
    float bloom_sigma_runtime           : TEXCOORD3;
};


////////////////////////////////  VERTEX SHADER  ///////////////////////////////

out_vertex main_vertex
(
    float4 position : POSITION,
    float4 color    : COLOR,
    float2 tex_uv   : TEXCOORD0,

    uniform float4x4 modelViewProj,
    uniform input IN,
    uniform orig ORIG_LINEARIZED,
    uniform orig MASKED_SCANLINES,
    uniform orig BLOOM_APPROX
)
{
    out_vertex OUT;
    OUT.position = mul(modelViewProj, position);

    //  Our various input textures use different coords:
    const float2 video_uv = tex_uv * IN.texture_size/IN.video_size;
    OUT.video_uv = video_uv;
    OUT.scanline_tex_uv = video_uv * MASKED_SCANLINES.video_size /
        MASKED_SCANLINES.texture_size;
    OUT.blur3x3_tex_uv = video_uv * BLOOM_APPROX.video_size / BLOOM_APPROX.texture_size;

    //  Calculate a runtime bloom_sigma in case it's needed:
    const float mask_tile_size_x = get_resized_mask_tile_size(
        IN.output_size, IN.output_size * mask_resize_viewport_scale, false).x;
    OUT.bloom_sigma_runtime = get_min_sigma_to_blur_triad(
        mask_tile_size_x / mask_triads_per_tile, bloom_diff_thresh);
    return OUT;
}


///////////////////////////////  FRAGMENT SHADER  //////////////////////////////

float4 main_fragment(in out_vertex VAR, uniform input IN,
    uniform orig MASKED_SCANLINES, uniform orig BLOOM_APPROX) : COLOR
{
    //  Sample the masked scanlines:
    const float3 intensity_dim =
        tex2D_linearize(MASKED_SCANLINES.texture, VAR.scanline_tex_uv).rgb;
    //  Get the full intensity, including auto-undimming, and mask compensation:
    const float auto_dim_factor = levels_autodim_temp;
    const float undim_factor = 1.0/auto_dim_factor;
    const float mask_amplify = get_mask_amplify();
    const float3 intensity = intensity_dim * undim_factor * mask_amplify *
        levels_contrast;

    //  Sample BLOOM_APPROX to estimate what a straight blur of masked scanlines
    //  would look like, so we can estimate how much energy we'll receive from
    //  blooming neighbors:
    const float3 phosphor_blur_approx = levels_contrast * tex2D_linearize(
        BLOOM_APPROX.texture, VAR.blur3x3_tex_uv).rgb;

    //  Compute the blur weight for the center texel and the maximum energy we
    //  expect to receive from neighbors:
    const float bloom_sigma = get_final_bloom_sigma(VAR.bloom_sigma_runtime);
    const float center_weight = get_center_weight(bloom_sigma);
    const float3 max_area_contribution_approx =
        max(float3(0.0), phosphor_blur_approx - center_weight * intensity);
    //  Assume neighbors will blur 100% of their intensity (blur_ratio = 1.0),
    //  because it actually gets better results (on top of being very simple),
    //  but adjust all intensities for the user's desired underestimate factor:
    const float3 area_contrib_underestimate =
        bloom_underestimate_levels * max_area_contribution_approx;
    const float3 intensity_underestimate =
        bloom_underestimate_levels * intensity;
    //  Calculate the blur_ratio, the ratio of intensity we want to blur:
    #ifdef BRIGHTPASS_AREA_BASED
        //  This area-based version changes blur_ratio more smoothly and blurs
        //  more, clipping less but offering less phosphor differentiation:
        const float3 phosphor_blur_underestimate = bloom_underestimate_levels *
            phosphor_blur_approx;
        const float3 soft_intensity = max(intensity_underestimate,
            phosphor_blur_underestimate * mask_amplify);
        const float3 blur_ratio_temp =
            ((float3(1.0) - area_contrib_underestimate) /
            soft_intensity - float3(1.0)) / (center_weight - 1.0);
    #else
        const float3 blur_ratio_temp =
            ((float3(1.0) - area_contrib_underestimate) /
            intensity_underestimate - float3(1.0)) / (center_weight - 1.0);
    #endif
    const float3 blur_ratio = clamp(blur_ratio_temp, 0.0, 1.0);
    //  Calculate the brightpass based on the auto-dimmed, unamplified, masked
    //  scanlines, encode if necessary, and return!
    const float3 brightpass = intensity_dim *
        lerp(blur_ratio, float3(1.0), bloom_excess);
    return encode_output(float4(brightpass, 1.0));
}

