How to transform world space vertex to camera space position in Cycles OSL I used blender as CG generation tool for Computer Vision research. I tried to render depth (z) value of each surface instead of its color. So I make simple shader, like this

shader depth_shader(
    vector Position = vector(1,0,0),
    output closure color Color = emission())
{
    vector lp = transform("world","camera",Position);
    Color= color(lp[2], lp[2], lp[2]) * emission();    
}


"Position" is input from Geometry node. But when I tried this, It returns odd results, and some pixel has negative value. How to get camera space position, which only applied by rotation, scale and translation? (Before projection matrix multiplication)
for transforming the position you should use point type because according to the OSL Language Specs :


  Depending on the type of the passed point p, different transformation
  semantics will be used. A point will transform as a position, a vector
  as a direction without regard to positioning


just change the type of the Position variable to point or use the P variable that holds the current position then use the transform function as you did ; even after that the whole objects will be bright white, so i have tried to normalize the Z coordinate  using two variables which act as near and far planes that limits the depth range :

shader depth_shader(
    float minZ = 0,
    float maxZ = 1,
    output closure color Color = emission())
{
    point lP = transform("camera", P);
    float Z = lP[2];
    if( (Z&gt;minZ) &amp;&amp; (Z&lt;maxZ))
        Z = (Z-minZ)/(maxZ-minZ);
    else 
        Z = 0;
    Color= color(Z, Z, Z) * emission();    
}