Hello. I am trying to reproduce native camera.WorldToViewportPoint function, for projecting mesh vertices to viewport. I write colors to texture for visualisation. So, here is what i’ve tried:
- Transform vertex position to worldspace using TransformPoint, then use WorldToViewport
Vector3 v = goTransform.TransformPoint(vertices[i]);
Vector3 pos = mCamera.WorldToViewportPoint(v);
texture.SetPixel((int)(pos.x*textureSizeW), (int)(pos.y*textureSizeH), Color.white);
And as result, everithing is fine:
2) Calculate ModelViewProjection matrix and multiply it with vertex position.
Matrix4x4 M = goTransform.localToWorldMatrix;
Matrix4x4 V = mCamera.worldToCameraMatrix;
Matrix4x4 P = mCamera.projectionMatrix;
Matrix4x4 MVP = P*V*M;
Vector3 pos = MVP.MultiplyPoint(vertices[j]);
texture.SetPixel((int)(pos.x*textureSizeW), (int)(pos.y*textureSizeH), Color.white);
But result is wrong:
3) After reading this answer, I’ve changed my code to:
Matrix4x4 M = goTransform.localToWorldMatrix;
Matrix4x4 V = mCamera.worldToCameraMatrix;
Matrix4x4 P = mCamera.projectionMatrix;
if (d3d) {
// Invert Y for rendering to a render texture
for (int i = 0; i < 4; i++) {
P[1,i] = -P[1,i];
}
// Scale and bias from OpenGL -> D3D depth range
for (int i = 0; i < 4; i++) {
P[2,i] = P[2,i]*0.5f + P[3,i]*0.5f;
}
}
Matrix4x4 MVP =P*V*M;
Vector3 pos = MVP.MultiplyPoint(vertices[j]);
texture.SetPixel((int)(pos.x*textureSizeW), (int)(pos.y*textureSizeH), Color.white);
But result are still wrong:
Could you help me to understand what am I missing? Thanks