Thursday, October 20, 2011

Unity 3D (Pro): View matrix (separately) for CG shaders

As Unity's shader support is largely based on Open GL, there isn't, by default design, access to separate model and view matrices in shader code. Occasionally you might want access to this and to use it you'll need to pass this information in yourself.

Just a quick summary of what Unity does provide in Shader code.


  • UNITY_MATRIX_MVP - Current model * view * project matrix

  • UNITY_MATRIX_MV - Current mode * view matrix

  • UNITY_MATRIX_P - Current project matrix

  • _Object2World - Current model matrix

  • _World2Object - Inverse of current world matrix



Very occasionally I wish there was a UNITY_MATRIX_M and UNITY_MATRIX_V but there isn't - at least - not yet. (Same limitation in GLSL)

In C# we can get the view matrix from Camera.mainCamera.worldToCameraMatrix and for GameObjects the model matrix can be generated by using Matrix4x4.TRS( transform.position, transform.rotation, transform.localScale).

If we wanted to pass in our own modelView matrix we could do


Matrix4x4 modelViewMatrix = Camera.mainCamera.worldToCameraMatrix * Matrix4x4.TRS( transform.position, transform.rotation, transform.localScale);



Then at the appropriate point we can do


material.SetMatrix("modelView", modelViewMatrix);



To pass this model view matrix into our shader.

In our shader, presumably in the vertex shader we can then use this value like so


v2f vert(appdata_base v) 
{
v2f o;
o.pos = mul( mul(UNITY_MATRIX_P, modelView), v.vertex );
return o;
}



The result of the above code is exactly the same as


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



So now knowing this you can manipulate and/or use the model and view matrices separately in your shaders if you so choose, by first passing them in from script code.

2 comments:

  1. D'oh! I'll try to add this for some future Unity release (will probably be after Unity 3.5, since we're feature complete for that one already)

    ReplyDelete
  2. Thank NeARAZ. It's great to know you guys are out seeing what the community is doing. I look forward to that addition and keep up the good work!

    ReplyDelete