//
// Copyright (C) ANSYS, Inc. and its subsidiaries.  All Rights Reserved.
//
// Author: mgcosta
//

#pragma include("lib/TemplateShader.vert.glsl")

layout( location = 0 ) in vec3 attr_Position;

#if !defined( SYMBOLPLOT_NO_LIGHTING )
layout( location = 1 ) in vec3 attr_Normal;
#endif

#if !defined( SYMBOLPLOT_POINT_MODE )
layout( location = 2 ) in vec3 attr_inst_Translation;
#endif

layout( location = 3 ) in vec4 attr_inst_Orientation;
layout( location = 4 ) in float attr_inst_Result;
layout( location = 5 ) in float attr_inst_Scale;

// TODO: add common matrices to StateTracker
uniform mat4 modelview;
uniform mat4 projection;
uniform mat4 mvp;
uniform mat4 normal;
uniform vec2 resultTransform; // x = min, y = 1.0/range
uniform vec3 scaleTransform;  // x = min, y = 1.0/range, z = attr_inst_Scale ? 0.0 : 1.0
uniform float scaleFactor;
uniform float symbolOffset;

out vec2 var_TexCoord;
noperspective out float var_ResultInRange;
noperspective out float var_ScaleInRange;

vec3 rotate( in vec3 v, in vec4 q )
{
    vec3 u = q.xyz; // extract the vector part of the quaternion
    float s = q.w;  // extract the scalar part of the quaternion

    return 2.0 * dot( u, v ) * u + ( s * s - dot( u, u ) ) * v + 2.0 * s * cross( u, v );
}

void main( void )
{
    // set scale to 1.0 if there's no attr_inst_Scale attribute, leave untouched otherwise
    float scale = ( ( attr_inst_Scale - scaleTransform.x ) * scaleTransform.y ) + scaleTransform.z;
    var_ScaleInRange = ( scale >= 0.0 && scale <= 1.0 ) ? 1.0 : 0.0;

#if defined( SYMBOLPLOT_POINT_MODE )
#if defined( SYMBOLPLOT_HAS_ORIENTATION )
    vec4 instancePos = ( length( attr_inst_Orientation ) == 0.0 ) ? vec4( 0.0 ) : vec4( attr_Position, 1.0 );
#else
    vec4 instancePos = vec4( attr_Position, 1.0 );
#endif
    gl_PointSize = scale * scaleFactor;
#else
    vec3 offset = vec3( 0.0, 0.0, symbolOffset );

#if defined( SYMBOLPLOT_HAS_ORIENTATION )
    vec3 worldPos = ( rotate( attr_Position, attr_inst_Orientation ) + rotate( offset, attr_inst_Orientation ) ) *
                    vec3( scale ) * scaleFactor;
#if !defined( SYMBOLPLOT_NO_LIGHTING )
    vec3 worldNormal = rotate( attr_Normal, attr_inst_Orientation );
#endif
#else
    vec3 worldPos = attr_Position * vec3( scale ) * scaleFactor;
#if !defined( SYMBOLPLOT_NO_LIGHTING )
    vec3 worldNormal = attr_Normal;
#endif
#endif

    vec4 instancePos = vec4( worldPos + attr_inst_Translation, 1.0 );
#endif

#if !defined( SYMBOLPLOT_NO_LIGHTING )
    var_Normal = mat3( normal ) * worldNormal;
#endif

    var_FrontColor = vec4(1.0);
    var_BackColor = vec4(1.0);

    var_EyePosition = (modelview * instancePos).xyz;
    var_TexCoord = vec2( ( attr_inst_Result - resultTransform.x ) * resultTransform.y, 0.5 );
    var_ResultInRange = ( var_TexCoord.x >= 0.0 && var_TexCoord.x <= 1.0 ) ? 1.0 : 0.0;

    gl_Position = mvp * instancePos;
}

