Search code examples
directxpixel-shadercg

CG: what's wrong with my per-pixel lighting?


i try to do basic n-dot-l lighting in unity and CG.

to my understanding the lighting should not change depending from where you look at the object with your camera. but in my situation it does.

        struct v2f {
            float4 pos : SV_POSITION;
            float3 LightDirection:   TEXCOORD2;
         float3 Normal:   TEXCOORD3;
        };

        uniform float4 _LightPos;

        v2f vert (appdata_tan v)
        {
            v2f o;

            o.pos = mul (UNITY_MATRIX_MVP, v.vertex);
            o.Texcoord = v.texcoord;

            float3 p = mul(UNITY_MATRIX_MV, v.vertex);

            o.LightDirection = _LightPos.xyz - p;

            o.Normal = v.normal;

            return o;
        }

        half4 frag (v2f i) : COLOR
        {
            float3 l = normalize(i.LightDirection);
            float3 n = normalize(i.Normal);
            float x = dot(n,l);
            return float4(x,x,x,1);
        }

so what am i missing in this code?

do i need to transform the lights position with the modelview matrix as well?

thanks!


Solution

  • v.normal is in object space while i.LightDirection is in view space.

    Pick a space and stick to it. Transforming normals to view space is one way to go. It requires to multiply by the inverse-transpose of the modelview. Depending on your model-view model, it can be as simple as the 3x3 upper part of the modelview.