0

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!

clamp
  • 33,000
  • 75
  • 203
  • 299

1 Answers1

1

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.

Bahbar
  • 17,760
  • 43
  • 62
  • thanks! so i tried assigning the normal like this: o.Normal = mul(UNITY_MATRIX_IT_MV, float4(v.normal,1)); but it still gives me strange results when i move the camera around. – clamp Apr 07 '11 at 10:12
  • @clamp: well... "strange" is not very descriptive. – Bahbar Apr 07 '11 at 10:59
  • well, the lighting intensity changes when i move the camera around. i think it should not. – clamp Apr 07 '11 at 11:32
  • also it seems the problem is with the lightpos. because if i visualize only the light as color on the model, it also changes when the camera is moved. – clamp Apr 07 '11 at 11:34
  • @clamp: well, that makes sense. The light direction is view dependent if the light stays in the same location world-space. Same for the normal. Only n.l stays the same. – Bahbar Apr 07 '11 at 12:07
  • ok, that makes sense. still even after n dot l the lighting changes if the camera is moved. – clamp Apr 07 '11 at 12:45