why _WorldSpaceLightPos0 seems to be affected by the camera position?

I’m writing a shader which uses _WorldSpaceLightPos0 to calculate the surface emission, it works fine, except for the fact that when the camera moves, at certain angles objects suddenly become noticeably brighter. All objects and the (directional) light are fixed in space, only the camera moves. According to this, for directional lights, _WorldSpaceLightPos0 contains the light’s world space direction, so if the light is at a fixed rotation I should not be getting abrupt changes in the surface emission when the camera moves (or rotates). Here is the code:

Shader "Effects/Tint" {
   Properties{
      _Color("Color",Color) = (1,1,1,1)
      _MainTex("Texture", 2D) = "white" {}
   }
      SubShader{
      Tags{ "RenderType" = "Opaque" }
      CGPROGRAM

#pragma surface surf Lambert vertex:vert
#pragma shader_feature BUMP_ON
      struct Input {
      float2 uv_MainTex;
      float  balance;
   };

   float4    _Color;
   sampler2D _MainTex;



   void vert(inout appdata_full v, out Input o) {
      UNITY_INITIALIZE_OUTPUT(Input,o);
      o.balance = dot(v.normal,_WorldSpaceLightPos0.xyz)*0.5 + 0.5;
   }



   void surf(Input IN, inout SurfaceOutput o) {
      o.Albedo   = tex2D(_MainTex, IN.uv_MainTex).rgb*_Color;
      o.Emission = _Color*IN.balance*0.5;
   }

   ENDCG


   }
      Fallback "Diffuse"

}

_WorldSpaceLightPos0.xyz is either the world space direction of directional lights or the world space position of point or spot lights. Because Unity does lighting in multiple passes, and the vertex function is run for each light, it’ll change what that means.

If you don’t need per pixel point lighting you can add noforwardadd to the #pragma surface line and that value should only ever mean the world space direction.

Thank you!!!

Right now I’m only using a directional light, and as far as I can forecast the evolution of the game I probably won’t need more lights, however if I ever need to add more lights, how can I force the shader to take into account only one specific directional light and ignore all the rest?.. is that even possible?

I tested your solution but, I’m still getting abrupt changes in emission, at certain angles, a tiny change in the camera’s position generates a huge change in the light emitted by the object, moving the camera in certain directions makes objects look as it they were flashing. I commented the line that sets the albedo, in order to make sure it wasn’t the source of the problem. This is what I have now.

Shader "Effects/Tint" {
   Properties{
      _Color("Color",Color) = (1,1,1,1)
      _MainTex("Texture", 2D) = "white" {}
   }
      SubShader{
      Tags{ "RenderType" = "Opaque" }
      CGPROGRAM

#pragma surface surf Lambert vertex:vert noforwardadd
#pragma shader_feature BUMP_ON
      struct Input {
      float2 uv_MainTex;
      float  balance;
   };

   float4    _Color;
   sampler2D _MainTex;



   void vert(inout appdata_full v, out Input o) {
      UNITY_INITIALIZE_OUTPUT(Input,o);
      o.balance = dot(v.normal,_WorldSpaceLightPos0.xyz)*0.5 + 0.5;
   }



   void surf(Input IN, inout SurfaceOutput o) {
    //  o.Albedo   = tex2D(_MainTex, IN.uv_MainTex).rgb*_Color;
      o.Emission = _Color*IN.balance*0.5;
   }

   ENDCG


   }
      Fallback "Diffuse"

}

I’m using Unity 5.5.0b10

Hello,

Sorry for my English, I’m french …

You are using a surface shader, which do not care about rendering path mode. There are several ways to use _WorldSpaceLightPos0 depending on both which rendering path mode you are executing and light type you are actually processing. Because of that, you must use the most general computation.

lightDir = _WorldSpaceLightPos0.xyz - worldPos.xyz * _WorldSpaceLightPos0.w

This computation work both for directional and non-directional light.

Generaly, a light ray is normalized, so do not forget to use the normalize method before passing it to your dot computation.

1 Like

Thank you… now it works fine, but now I have to do all the calculations on the surface function, that’s not a problem, but just for curiosity is there a way to make it work on the vertex function?

Vertex function is called one time per vertices - i.e. if you have a triangle, vertex function will be call three times - and the resulting value will be interpolate along them.
Surface function is called one time per pixel.
About your question, it depends on what do you want.

  • if you want a per vertex lighting, you must do your computation in the vertex function.
  • if you want a per pixel lighting, you must do your computation in the surface function.

In another hand, all the vertex data delivered by the appdata struct are in object space coordinate. If you rotate your model, these data change!
Usualy, light direction is in world space coordinate and lighting is computed in the same space. So, you must transform your normal data from object to world space.

I wanted to do the calculations on the vertex function for performance reasons, but I can’t find in the documentation a parameter equivalente to worldPos which is available for the vertex function, so my question is about how to do the same computation on the vertex function… not sure if mul(_Object2World,_WorldSpaceLightPos0.xyz) can be used in this case.

In your appdata struct, you have the vertex position in object coordinate space which is available in the vertex function.

struct appdata_full {
    float4 vertex : POSITION;
    float4 tangent : TANGENT;
    float3 normal : NORMAL;
    float4 texcoord : TEXCOORD0;
    float4 texcoord1 : TEXCOORD1;
    float4 texcoord2 : TEXCOORD2;
    float4 texcoord3 : TEXCOORD3;
#if defined(SHADER_API_XBOX360)
    half4 texcoord4 : TEXCOORD4;
    half4 texcoord5 : TEXCOORD5;
#endif
    fixed4 color : COLOR;
    UNITY_INSTANCE_ID
};

And Unity public API provides us all matrix we need - i.e Unity - Manual: Built-in shader variables - in order to transform our coordinate spaces.

So, to transform the vertex position from model space to world space, you must perform this computation:

float4 worldPos = mul(unity_ObjectToWorld, appdata.vertex);

Note the use of unity_ObjectToWorld instead of _Object2World. It seems it’s the new matrix name. Unity will automatically change the old name by the new one when you will re-open your solution.

_WorldSpaceLightPos0 is already in world space.

Hmmmmm… I’m not using the vertex position but the normal… and there’s no noticeable difference between:

 o.balance = dot(v.normal,_WorldSpaceLightPos0.xyz)*0.5 + 0.5;

and

 o.balance = dot(mul(unity_ObjectToWorld,v.normal),_WorldSpaceLightPos0.xyz)*0.5 + 0.5;

To my eyes it’s exactly the same, and in both cases I have the same problem which is: abrupt changes in the light emitted by the object when the camera moves… So your first solution is the only one that really works, and like I said, as far as I know, it only can be implemented in the surface function. This:

o.balance = dot(v.normal,mul(unity_WorldToObject,_WorldSpaceLightPos0.xyz))*0.5 + 0.5;

doesn’t work either.

The IN.worldPos value is something that’s calculated by the surface shader’s internal vertex function after your custom vertex function is called. So to use the world position you will have to calculate it yourself, like you would if you were doing a vertex/fragment shader. Also if you’re looking for the dot product of the surface normals to the light direction you would need to also transform the normals into world space as the v.normal is in local model space and you’ll get peculiar results there as well.

So, like @Blackhart mentioned, you’ll need to use unity_ObjectToWorld, but his example isn’t quite right, you actually need this:
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;

Then for the vertex normal you would need to do this:
float3 worldNormal = UnityObjectToWorldNormal(v.normal);

Then you’ll also need to normalize the results of the light direction stuff in the case of needing the world position if you want to use it in the dot product, which will give you this:
o.balance = dot(worldNormal, normalize(_WorldSpaceLightDir0.xyz - worldPos * _WorldSpaceLightDir0.w));

The vector returned by UnityObjectToWorldNormal() is already normalized, so nothing addtional has to be done there.

Alternatively you could do what you attempted in transforming the direction into object space, but you still need to normalize the resulting vector before using it in a dot product. The v.normal will also already be normalized so like with the world space dot product nothing additional needs to be done to it, but if you need the world position (in the case of point and spot lights) there’s no optimization to be had as you’re still doing two muls. If you’re using noforwardadd and it’s only ever going to be a directional light then this should work:

o.balance = dot(v.normal, normalize(mul(unity_WorldToObject, _WorldSpaceLightPos0)));

Note I am not using .xyz on the _WorldSpaceLightPos0, but instead the full .xyzw value. Your example might also work, but it is nebulous as unity_WorldToObject is a float4x4 and _WorldSpaceLightPos0.xyz is a float3, and a float4x4 should only every be mul with a float4. Also since this is a direction you really only want the float3x3 of the float4x4 to be applied (a float4x4 has positional translation, a float3x3 is just scale and rotation), but since the w of the _WorldSpaceLightPos0 in the case of a directional light is 0.0 the positional translation won’t be applied. Using .xyz some GPUs will handle that how you want as a direction, and some won’t.

However I’m not entirely sure exactly what your end goal is. If you’re looking for a dot product of the surface normal to the light direction, then that’s already being calculated per pixel since that’s exactly what the Lambert lighting model is, so if you’re calculating it in the vertex you’re just doing it again and not saving any calculation, instead you’re doubling it.

Thank you for the so complete explanation… Ok… even when it is obvious that I need to normalize the vector, I keep forgetting to include it in the code… that’s something I need to remember.

The goal is to make objects to emit light depending on how directly the light is hitting the surface, so the vertices facing the light source should emit no light at all, while the vertices on the oposite side should be fully emissive.

… so based on your explanation what I really need is this:

 o.balance = 1-(dot(UnityObjectToWorldNormal(v.normal),_WorldSpaceLightPos0.xyz)*0.5 + 0.5);

Thank you!