; constants
.constf const0(0.0, 0.5, 1.0, 2.0)
.constf const1(0.00392156886, 3.05185094e-005, 0.25, 0.00787401574)

.alias ZERO      const0.x
.alias HALF      const0.y
.alias ONE       const0.z
.alias TWO       const0.w
.alias INV_BYTE  const1.x
.alias INV_SHORT const1.y
.alias QUART     const1.z
.alias INV_127   const1.w

; uniforms
.fvec uViewProj[4]
.fvec uBasis[32*2]
.fvec uMaterial
.fvec uViewPos

; in
.alias aCoord    v0
.alias aNormal   v1
.alias aTexCoord v2
.alias aColor    v3
.alias aLight    v4

; variables
.alias lv0    r0
.alias lv1    r1
.alias lv2    r2
.alias lv3    r3
.alias normal r4
.alias refl   r5
.alias view   r6
.alias pos    r7
.alias tmp    r8

; out
.out vPosition position
;.out vTexCoord texcoord0
.out vTexCoord texcoord0.st
.out -         texcoord0w vTexCoord.p
.out vColor    color

.proc main
; joint = int(aCoord.w)
    mova a0.x, aCoord.w

; pos = mulQuatPos(uBasis[joint], aCoord)
    mul pos.xyz, uBasis[a0.x], aCoord.zxyw
    mad pos.xyz, aCoord, uBasis[a0.x].zxyw, -pos
    mad pos.xyz, aCoord.yzxw, uBasis[a0.x].w, pos
    mul tmp.xyz, uBasis[a0.x].zxyw, pos
    mad pos.xyz, pos.yzxw, uBasis[a0.x].yzxw, -tmp
    mad pos.xyz, pos, TWO, aCoord
    add pos.xyz, uBasis[a0.x + 1], pos
    mov pos.w, uBasis[a0.x + 1].w

; vPosition = uViewProj * pos
    mul tmp, uViewProj[0], pos.x
    mad tmp, pos.y, uViewProj[1], tmp
    mad tmp, pos.z, uViewProj[2], tmp
    mad vPosition, pos.w, uViewProj[3], tmp

; view = normalize(uViewPos - pos)
    add view, uViewPos, pos
    dp3 tmp.x, view, view
    rsq tmp.x, tmp.x
    mul view, view, tmp.xxxx

; normal = mulQuat(uBasis[joint], aNormal/127 - 1)
    mul normal, INV_127, aNormal
    add normal, -ONE, normal
    mul pos.xyz, uBasis[a0.x], normal.zxyw
    mad pos.xyz, normal, uBasis[a0.x].zxyw, -pos
    mad pos.xyz, normal.yzxw, uBasis[a0.x].w, pos
    mul tmp.xyz, uBasis[a0.x].zxyw, pos
    mad pos.xyz, pos.yzxw, uBasis[a0.x].yzxw, -tmp
    mad normal, pos, TWO, normal

; refl = reflect(-view, normal)
    dp3 tmp.x, -view, normal
    add tmp.x, tmp.x, tmp.x
    mad refl, -tmp.xxxx, normal, -view

; vTexCoord = lerp(normal, refl, uMaterial.w)
    add tmp, -normal, refl
    mad vTexCoord, tmp, uMaterial.wwww, normal

; vColor = uMaterial
    mov tmp.xyz, uMaterial
    mov tmp.w, ONE
    mul vColor, QUART, tmp
    
    end
.end
