#version 410

#include "uniforms.glsl"
#include "hg_sdf.glsl"
#include "material.glsl"
#include "math.glsl"
#include "noise.glsl"

// Textures
uniform sampler2D uFbmSampler;

// Lights
const int NUM_LIGHTS = 1;
vec3      LIGHT_POS[NUM_LIGHTS] = vec3[](vec3(0, 3, 0));
vec3      LIGHT_INT[NUM_LIGHTS] = vec3[](vec3(0));

// Object variables
uniform float uObjScale;
uniform float uObjPosX;
uniform float uObjPosY;
uniform float uObjPosZ;

SceneResult scene(vec3 p)
{
    vec3 pObject = p - vec3(uObjPosX, uObjPosY, uObjPosZ);
    pR(pObject.yz, uGT);
    pR(pObject.xz, uGT);
    vec3 pEdges = pObject;
    float eScale = uObjScale * 0.93;
    float fEdge1 = fBox(pEdges, vec3(eScale + 0.05, eScale, eScale));
    pR(pEdges.xz, PI * 0.5);
    float fEdge2 = fBox(pEdges, vec3(eScale + 0.05, eScale, eScale));
    pR(pEdges.yx, PI * 0.5);
    float fEdge3 = fBox(pEdges, vec3(eScale + 0.05, eScale, eScale));
    SceneResult edges = SceneResult(min(min(fEdge1, fEdge2), fEdge3), 3);
    SceneResult box = SceneResult(fBox(pObject, vec3(uObjScale)), 0);
    SceneResult object = opU(box, edges);
    vec3 pGridZ = p - vec3(0, 0, -uGT * 8);
    pR(pGridZ.yx, PI * 0.5);
    pMod1(pGridZ.z, 2);
    float gridZ = fCylinder(pGridZ, 0.02, 100);
    vec3 pGridX = p;
    pR(pGridX.yz, PI * 0.5);
    pMod1(pGridX.x, 0.5);
    float gridX = fCylinder(pGridX, 0.02, 100);
    SceneResult grid = SceneResult(min(gridX, gridZ), 0);
    SceneResult skySphere = SceneResult(-fSphere(p - vec3(0, -90, 0), 100), 1);
    SceneResult ground = SceneResult(fPlane(p, vec3(0, 1, 0), 0.02), 2);
    return opU(opU(object, grid), opU(ground, skySphere));
}

Material evalMaterial(vec3 p, float matI)
{
    Material mat;
    if (matI < 1) {
        mat = mWhiteLight;
    } else if (matI < 2) {
        mat = mSky(p);
    } else if (matI < 3) {
        mat = mBlueishMirror;
        mat.roughness += saturate(0.6 * fbm((p - vec3(0, 0, uGT * 8)) * 0.4));
    } else {
        mat = mPerfectMirror;
        mat.roughness = 0.05;
    }
    return mat;
}

// Main sphere tracing -stuff
#include "sphere_tracing_end.glsl"
