-- glslfx version 0.1

//
// Copyright 2021 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

-- configuration
{
    "techniques": {
        "default": {
            "SkydomeFragment": {
                "source": [ "Skydome.Fragment" ]
            }
        }
    }
}

-- glsl Skydome.Fragment

const float PI = 3.1415926535898;
const float farPlane = 1.0;

float wrapSampleValue(float value)
{
    if (value < 0.0) {
        value += 1.0;
    }
    else if (value > 1.0) {
        value -= 1.0;
    }
    return value;
}

// from PreviewSurface.glslfx
vec2 projectToLatLong(vec3 sample3D)
{
    // project spherical coord onto latitude-longitude map with
    // latitude: +y == pi/2 and longitude: +z == 0, +x == pi/2
    float x = (atan(sample3D.z, sample3D.x) + 0.5 * PI) / (2.0 * PI);
    float y = acos(sample3D.y) / PI;

    return vec2(wrapSampleValue(x), wrapSampleValue(y));
}


void main(void)
{
    // Transform the UV coordinates into NDC space and place at the far plane
    // (z = 1) before transforming into view space.
    vec2 uvOut_ndc = (uvOut * vec2(2.0)) - vec2(1.0);
    vec4 uvOut_view = invProjMatrix * vec4(uvOut_ndc, farPlane, 1.0);

    // Normalize to use as the initial sampleDirection
    vec3 sampleDirection = normalize(uvOut_view.xyz);

    // Apply the camera rotation and lightTransform to the sampleDirection
    sampleDirection = 
        ( lightTransform * viewToWorld * vec4(sampleDirection, 0.0) ).xyz;
    
    // Sample Skydome Texture with the sampleDirection
    vec2 sampleCoord = projectToLatLong(sampleDirection);
    hd_FragColor = vec4(HgiGet_skydomeTexture(sampleCoord).xyz, 1.0);
    gl_FragDepth = farPlane;
}
