View Matrix for cg shaders in Unity

Hello guys, how can i read/access the view matrix using shaderlab/cg in unity?

i found the world matrix and the projection one, i haven’t found this one.

As most of Unity’s rendering comes from dark corners of OpenGL (back in the day it was the only renderer), there’s no separate view matrix. Just like in OpenGL, model (a.k.a. world) matrix and view matrix are combined into glstate.matrix.modelview[0]

thx

indeed you are correct, i just checked the glstate list in nvidia’s cgfx manual and i didnt find any separate view matrix listed.

k, great, i guess i can’t do much then if i work with imported cgfx files that use the following missing semantics WORLDVIEWPROJECTION, VIEWINVERSE :x

i was thinking of writing an inverse 4x4 function then use it to create VIEWINVERSE then do _Object2World*(view matrix)*glstate.matrix.projection for WORLDVIEWPROJECTION.

oh well

i guess i can’t

You can set this up with a little scripting: calculate the view matrix in the scene (I think it would be Camera.worldToCameraMatrix * Camera.projectionMatrix, but that’s just off the top of my head), then make it available to your shaders with Shader.SetGlobalMatrix(). Put that code in Update() so it recalculates each frame, and you should be good to go.

cool man, thx, i’ll try it and let u know :slight_smile:

ok, i set up the update section of the camera attached script to send to the shader any custom matrix i want, it’s working but i’m still not sure which combinations of matrices i should send to have the correct visual shading effect.

i need this view matrix to import correctly a shader from fxcomposer.

sending camera.worldToCameraMatrix * camera.projectionMatrix is giving way off target results, sending the following gives me much closer visuals to the shader preview i see in fxcomposer :

in the camera script :

function Update () {
var Iview=camera.cameraToWorldMatrix.inverse;

Shader.SetGlobalMatrix(“_MyIview”, Iview.inverse);
}

in the shader cg :

uniform float4x4 _MyIview;

float4x4 wvp = glstate.matrix.mvp;
float4x4 worldI = _World2Object;
float4x4 viewInv = _MyIview;
float4x4 world = _Object2World;


can’t any Unity3d developer clarify if what i’m doing is possible to begin with and if so what do i need to send exactly here to get the view matrix into the shader?

You should try
gl_ProjectionMatrix * camera.worldToCameraMatrix
instead of
camera.worldToCameraMatrix * gl_ProjectionMatrix

@sendel76 , what part of the code are you referencing when you say to try that?

I use UNITY_MATRIX_V and UNITY_MATRIX_P separately in the calculations for DrawProceduralIndirect but they do not correspond to the UNITY_MATRIX_VP multiplication. (Unity5)