/*
Copyright (C) 1996-2001 Id Software, Inc.
Copyright (C) 2002-2009 John Fitzgibbons and others
Copyright (C) 2007-2008 Kristian Duske
Copyright (C) 2010-2014 QuakeSpasm developers

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 (at your option) 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.
*/
//gl_fog.c -- global and volumetric fog

#include <sstream>

#include "quakedef.hpp"

//==============================================================================
//
//  GLOBAL FOG
//
//==============================================================================

#define DEFAULT_DENSITY 0.0
#define DEFAULT_GRAY 0.3

static float fog_density;
static float fog_red;
static float fog_green;
static float fog_blue;

static float old_density;
static float old_red;
static float old_green;
static float old_blue;

static float fade_time; //duration of fade
static float fade_done; //time when fade will be done

/*
=============
Fog_Update

update internal variables
=============
*/
void Fog_Update(float density, float red, float green, float blue, float time) {
    //save previous settings for fade
    if (time > 0) {
        //check for a fade in progress
        if (fade_done > cl.time) {
            float f;

            f = (fade_done - cl.time) / fade_time;
            old_density = f * old_density + (1.0 - f) * fog_density;
            old_red = f * old_red + (1.0 - f) * fog_red;
            old_green = f * old_green + (1.0 - f) * fog_green;
            old_blue = f * old_blue + (1.0 - f) * fog_blue;
        } else {
            old_density = fog_density;
            old_red = fog_red;
            old_green = fog_green;
            old_blue = fog_blue;
        }
    }

    fog_density = density;
    fog_red = red;
    fog_green = green;
    fog_blue = blue;
    fade_time = time;
    fade_done = cl.time + time;
}

/*
=============
Fog_ParseServerMessage

handle an SVC_FOG message from server
=============
*/
void Fog_ParseServerMessage(void) {
    float density, red, green, blue, time;

    density = net_message.read_byte().value() / 255.0;
    red = net_message.read_byte().value() / 255.0;
    green = net_message.read_byte().value() / 255.0;
    blue = net_message.read_byte().value() / 255.0;
    time = net_message.read_short().value() / 100.0;
    if (time < 0.0f) time = 0.0f;

    Fog_Update(density, red, green, blue, time);
}

/*
=============
Fog_FogCommand_f

handle the 'fog' console command
=============
*/
void Fog_FogCommand_f(void) {
    float d, r, g, b, t;

    switch (command::argc()) {
        default:
        case 1:
            console::info("usage:\n");
            console::info("   fog <density>\n");
            console::info("   fog <red> <green> <blue>\n");
            console::info("   fog <density> <red> <green> <blue>\n");
            console::info("current values:\n");
            console::info("   \"density\" is \"%f\"\n", fog_density);
            console::info("   \"red\" is \"%f\"\n", fog_red);
            console::info("   \"green\" is \"%f\"\n", fog_green);
            console::info("   \"blue\" is \"%f\"\n", fog_blue);
            return;
        case 2:
            d = std::atof(command::argv(1)->c_str());
            t = 0.0f;
            r = fog_red;
            g = fog_green;
            b = fog_blue;
            break;
        case 3: //TEST
            d = std::atof(command::argv(1)->c_str());
            t = std::atof(command::argv(2)->c_str());
            r = fog_red;
            g = fog_green;
            b = fog_blue;
            break;
        case 4:
            d = fog_density;
            t = 0.0f;
            r = std::atof(command::argv(1)->c_str());
            g = std::atof(command::argv(2)->c_str());
            b = std::atof(command::argv(3)->c_str());
            break;
        case 5:
            d = std::atof(command::argv(1)->c_str());
            r = std::atof(command::argv(2)->c_str());
            g = std::atof(command::argv(3)->c_str());
            b = std::atof(command::argv(4)->c_str());
            t = 0.0f;
            break;
        case 6: //TEST
            d = std::atof(command::argv(1)->c_str());
            r = std::atof(command::argv(2)->c_str());
            g = std::atof(command::argv(3)->c_str());
            b = std::atof(command::argv(4)->c_str());
            t = std::atof(command::argv(5)->c_str());
            break;
    }

    if (d < 0.0f) d = 0.0f;
    if (r < 0.0f) r = 0.0f;
    else if (r > 1.0f) r = 1.0f;
    if (g < 0.0f) g = 0.0f;
    else if (g > 1.0f) g = 1.0f;
    if (b < 0.0f) b = 0.0f;
    else if (b > 1.0f) b = 1.0f;
    Fog_Update(d, r, g, b, t);
}

/*
=============
Fog_ParseWorldspawn

called at map load
=============
*/
void Fog_ParseWorldspawn() {
    std::string key{};
    std::string value{};

    //initially no fog
    fog_density = DEFAULT_DENSITY;
    fog_red = DEFAULT_GRAY;
    fog_green = DEFAULT_GRAY;
    fog_blue = DEFAULT_GRAY;

    old_density = DEFAULT_DENSITY;
    old_red = DEFAULT_GRAY;
    old_green = DEFAULT_GRAY;
    old_blue = DEFAULT_GRAY;

    fade_time = 0.0;
    fade_done = 0.0;

    std::istringstream ss{cl.worldmodel->entities};

    auto token = common::parse_token(ss);
    if (!token.has_value()) {
        return; // error
    }
    if (token->front() != '{') {
        return; // error
    }
    while (true) {
        token = common::parse_token(ss);
        if (!token.has_value()) {
            return; // error
        }
        if (token->front() == '}') {
            break; // end of worldspawn
        }
        if (token->front() == '_') {
            key = token->substr(1);
        } else {
            key = token.value();
        }

        while (!key.empty() && key.back() == ' ') {
            key.pop_back();
        }

        token = common::parse_token(ss);
        if (!token.has_value()) {
            return; // error
        }
       value = token.value();

        if (key == "fog") {
            std::sscanf(value.c_str(), "%f %f %f %f", &fog_density, &fog_red, &fog_green, &fog_blue);
        }
    }
}

/*
=============
Fog_GetColor

calculates fog color for this frame, taking into account fade times
=============
*/
float *Fog_GetColor(void) {
    static float c[4];
    float f;
    int i;

    if (fade_done > cl.time) {
        f = (fade_done - cl.time) / fade_time;
        c[0] = f * old_red + (1.0 - f) * fog_red;
        c[1] = f * old_green + (1.0 - f) * fog_green;
        c[2] = f * old_blue + (1.0 - f) * fog_blue;
        c[3] = 1.0;
    } else {
        c[0] = fog_red;
        c[1] = fog_green;
        c[2] = fog_blue;
        c[3] = 1.0;
    }

    for (i = 0; i < 3; i++) {
        c[i] = std::clamp(c[i], 0.f, 1.f);
    }

    //find closest 24-bit RGB value, so solid-colored sky can match the fog perfectly
    for (i = 0; i < 3; i++) {
        c[i] = (float) (Q_rint(c[i] * 255)) / 255.0f;
    }

    return c;
}

/*
=============
Fog_GetDensity

returns current density of fog
=============
*/
float Fog_GetDensity(void) {
    float f;

    if (fade_done > cl.time) {
        f = (fade_done - cl.time) / fade_time;
        return f * old_density + (1.0 - f) * fog_density;
    } else
        return fog_density;
}

/*
=============
Fog_SetupFrame

called at the beginning of each frame
=============
*/
void Fog_SetupFrame(void) {
    glFogfv(GL_FOG_COLOR, Fog_GetColor());
    glFogf(GL_FOG_DENSITY, Fog_GetDensity() / 64.0);
}

/*
=============
Fog_EnableGFog

called before drawing stuff that should be fogged
=============
*/
void Fog_EnableGFog(void) {
    if (Fog_GetDensity() > 0)
        glEnable(GL_FOG);
}

/*
=============
Fog_DisableGFog

called after drawing stuff that should be fogged
=============
*/
void Fog_DisableGFog(void) {
    if (Fog_GetDensity() > 0)
        glDisable(GL_FOG);
}

/*
=============
Fog_StartAdditive

called before drawing stuff that is additive blended -- sets fog color to black
=============
*/
void Fog_StartAdditive(void) {
    vec3_t color = {0, 0, 0};

    if (Fog_GetDensity() > 0)
        glFogfv(GL_FOG_COLOR, color);
}

/*
=============
Fog_StopAdditive

called after drawing stuff that is additive blended -- restores fog color
=============
*/
void Fog_StopAdditive(void) {
    if (Fog_GetDensity() > 0)
        glFogfv(GL_FOG_COLOR, Fog_GetColor());
}

//==============================================================================
//
//  VOLUMETRIC FOG
//
//==============================================================================

convar r_vfog{"r_vfog", "1"};

void Fog_DrawVFog(void) {
}

void Fog_MarkModels(void) {
}

//==============================================================================
//
//  INIT
//
//==============================================================================

/*
=============
Fog_NewMap

called whenever a map is loaded
=============
*/
void Fog_NewMap(void) {
    Fog_ParseWorldspawn(); //for global fog
    Fog_MarkModels(); //for volumetric fog
}

/*
=============
Fog_Init

called when quake initializes
=============
*/
void Fog_Init(void) {
    command::add("fog", Fog_FogCommand_f);

    //r_vfog.inscribe();

    //set up global fog
    fog_density = DEFAULT_DENSITY;
    fog_red = DEFAULT_GRAY;
    fog_green = DEFAULT_GRAY;
    fog_blue = DEFAULT_GRAY;

    Fog_SetupState();
}

/*
=============
Fog_SetupState

ericw -- moved from Fog_Init, state that needs to be setup when a new context is created
=============
*/
void Fog_SetupState(void) {
    glFogi(GL_FOG_MODE, GL_EXP2);
}
