// Software vertex shader generated by Wild Magic.
//
// var float3   kModelPosition      $vin.POSITION
// var float3   kModelNormal        $vin.NORMAL
// var float3   kModelColor         $vin.COLOR
// var float4   kClipPosition       $vout.POSITION
// var float4   kVertexColor        $vout.COLOR
// var float3   kReflectTCoord      $vout.TEXCOORD0
// var float4x4 WVPMatrix           c[0]
// var float4x4 WMatrix             c[4]
// var float3   CameraWorldPosition c[8]

#include "Wm4SoftRenderer.h"
#include "Wm4Matrix4.h"
#include "Wm4Vector3.h"
#include "Wm4ColorRGB.h"
#include "Wm4ColorRGBA.h"

namespace Wm4
{

void v_CubeMap (const float* afRegister, const float* afInVertex,
    float* afOutVertex)
{
    // Get the register items.
    const Matrix4f& rkWVPMatrix = *(const Matrix4f*)&afRegister[0];
    const Matrix4f& rkWMatrix = *(const Matrix4f*)&afRegister[16];
    const Vector3f& rkCameraWorldPosition = *(const Vector3f*)&afRegister[32];

    // Get the input items.
    Vector4f kModelPosition(afInVertex[0],afInVertex[1],afInVertex[2],1.0f);
    Vector4f kModelNormal(afInVertex[3],afInVertex[4],afInVertex[5],0.0f);
    const ColorRGB& rkModelColor = *(const ColorRGB*)&afInVertex[6];

    // Access the output items.
    Vector4f& rkClipPosition = *(Vector4f*)&afOutVertex[0];
    ColorRGBA& rkVertexColor = *(ColorRGBA*)&afOutVertex[4];
    Vector3f& rkReflectTCoord = *(Vector3f*)&afOutVertex[8];

    // *** program ***

    // Transform the position from model space to clip space.
    rkClipPosition = kModelPosition*rkWVPMatrix;

    // Transform the position from model space to world space.
    Vector3f kWorldPosition = (Vector3f)(kModelPosition*rkWMatrix);

    // Transform the normal from model space to world space.  In case the
    // model-to-world matrix has nonunit scales, the resulting vector must
    // be normalized.
    Vector3f kWorldNormal = (Vector3f)(kModelNormal*rkWMatrix);
    kWorldNormal.Normalize();

    // Calculate the incident direction.
    Vector3f kEyeDirection = kWorldPosition - rkCameraWorldPosition;
    kEyeDirection.Normalize();
    
    // Pass through the model color.
    rkVertexColor[0] = rkModelColor[0];
    rkVertexColor[1] = rkModelColor[1];
    rkVertexColor[2] = rkModelColor[2];
    rkVertexColor[3] = 1.0f;

    // Calculate the reflected vector.
    rkReflectTCoord = Reflect(kEyeDirection,kWorldNormal);
}

WM4_IMPLEMENT_VPROGRAM(CubeMap);
WM4_REGISTER_VPROGRAM(CubeMap);

}
