!!ARBfp1.0
#
# Demonstrates per-pixel environment mapping:
#   reflects view direction off surface normal
#
# Orion Sky Lawlor, olawlor@acm.org, 2005/2/7 (Public Domain)
#

# Vertex/fragment communication protocol
ATTRIB world  =fragment.texcoord[4]; # World-coordinates position
ATTRIB worldNi=fragment.texcoord[5]; # World-coordinates normal (interpolated)
ATTRIB albedo =fragment.texcoord[6]; # Material "diffuse color"
ATTRIB viewdir=fragment.texcoord[7]; # Viewing direction (points toward eye)

# Perturb world normal
TEMP worldP,worldS;
MUL worldS,world,20.0; # scaled-up world coordinates (sets noise scale)
TEX worldP,worldS, texture[0],3D; # look up displacement at scaled coordinates
SUB worldS,worldS,0.5; # shift displacement to [-0.5,0.5]
MAD worldP,worldP,0.01, worldNi; # Add in scaled version of displacement to nromal

#  Make world normal have unit length (interpolation shrinks normals)
TEMP L,worldN;
DP3 L,worldP,worldP; # worldN = normalize(worldP)
RSQ L,L.x;
MUL worldN,worldP,L;

# Reflect view direction off geometry normal
#  FIXME: assumes view direction is unit, which isn't true after interpolation
TEMP reflect, reflectLen;
DP3 reflectLen, worldN,viewdir; # length of projection of viewdir onto worldN
MUL reflectLen,reflectLen,2.0; # need twice the length
MAD reflect, worldN,reflectLen, -viewdir; # reflect = -viewdir + 2*normal* dot(normal,viewdir)

TEX result.color, reflect, texture[0], 3D; # 3D texture as environment map
# MOV result.color, worldN;

END
