- Home /
Reproduce WorldToViewportPoint function
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:
1) 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 added this part to my code:
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;
}
}
But result are still wrong. Could you help me to understand what am I missing? Thanks
i am stuck with the same problem. did you solve it?
Answer by Paulius-Liekis · Dec 29, 2014 at 02:49 PM
Maybe you need pos /= pos.z
, i.e. applying projection?
Answer by sirshelley · Feb 05, 2016 at 02:50 AM
When you use Multiplypoint it converts it to clipping space so too correct:
screenpos.x being your (Projection matrix* View matrix)Multiplypoint(vector) //clipping to 1,1 Vector3 scPos= new Vector3(screenPos.x + 1f, screenPos.y + 1f, screenPos.z + 1f) / 2f; // viewport into screen scPos = new Vector3(screenPos.x Screen.width, screenPos.y * Screen.height, screenPos.z);