/****************************************************************************
**
** Copyright (C) 2014 NVIDIA Corporation.
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt 3D Studio.
**
** $QT_BEGIN_LICENSE:GPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef SHADOW_MAPPING_GLSLLIB
#define SHADOW_MAPPING_GLSLLIB

#include "depthpass.glsllib"

float qt_sampleCubemap( in samplerCube shadowCube, in vec4 shadowControls, in mat4 shadowViewMat, in vec3 lightPos, in vec3 worldPos, in vec2 cameraProps )
{
    float dist = length(worldPos - lightPos);
    float shadowMapNear = cameraProps.x;
    float shadowMapFar = cameraProps.y;
    float shadowBias = shadowControls.x;
    float shadowFactor = shadowControls.y;
    float currentDepth = clamp((dist - shadowMapNear) / (shadowMapFar - shadowMapNear), 0.0, 1.0);
    vec3 smpCoord = worldPos - lightPos;

    // reverse Y if shadowControls.w == 1 (not enough on its own, also expects +Y and -Y swapped in shadowCube)
    smpCoord.y = mix(smpCoord.y, -smpCoord.y, shadowControls.w);

    float sampleDepth = texture( shadowCube, smpCoord ).x + shadowBias;
    return min(1.0, exp(shadowFactor * sampleDepth) / exp(shadowFactor * currentDepth));
}

float qt_sampleOrthographic( in sampler2D shadowMap, in vec4 shadowControls, in mat4 shadowMatrix, in vec3 worldPos, in vec2 cameraProps )
{
    vec4 projCoord = shadowMatrix * vec4( worldPos, 1.0 );
    vec3 smpCoord = projCoord.xyz / projCoord.w;
    smpCoord.y = mix(smpCoord.y, 1.0 - smpCoord.y, shadowControls.w);

    float shadowBias = shadowControls.x;
    float shadowFactor = shadowControls.y;
    float sampleDepth = texture( shadowMap, smpCoord.xy ).x + shadowBias;

    return min(1.0, exp(shadowFactor * sampleDepth) / exp(shadowFactor * smpCoord.z));
}

#endif
