OpenGL scene coordinates to screen coordinates

给你一囗甜甜゛ 提交于 2019-12-07 02:27:26

The code seems perfectly valid, but you should use 4D vectors for these homogeneous transforms.

So,

GLKVector4 coor = GLKVector4Make(point.x, point.y, 0, 1);

/// I hope those matrices are fine
GLKMatrix4 modelview = GLKMatrix4MakeWithArray(glProjectionMatrix);
GLKMatrix4 projetion = GLKMatrix4MakeWithArray(modelViewMatrix.data);

GLKVector4 eyeCoor = GLKMatrix4MultiplyVector4(modelview, coor);
GLKVector4 ndcCoor = GLKMatrix4MultiplyVector4(projetion,eyeCoor);

float XScr = ndcCoor.x / ndcCoor.w;
float YScr = ndcCoor.y / ndcCoor.w;

CGPoint p = CGPointMake(XScr, YScr);

If you want XScr and YScr to be in [0..1] range, then add

XScr = (XScr + 1.0f) * 0.5f;
YScr = (YScr + 1.0f) * 0.5f;

conversion.

Even easier: use the GLKit Math function GLKMathProject.

GLKVector3 GLKMathProject (
   GLKVector3 object,
   GLKMatrix4 model,
   GLKMatrix4 projection,
   int *viewport
);

So, in your case, e.g.

int viewport[] = {0, 0, 320, 480};
GLKVector3 windowVector = GLKMathProject(coor, modelview, projetion, viewport);
CGPoint p = CGPointMake(windowVector.x, windowVector.y);

Note that the origin is at lower left, so if you're using UIKit coordinates where the origin is at the upper left, then switch the y coordinate, e.g.

CGPoint p = CGPointMake(windowVector.x, window.bounds.size.height - windowVector.y);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!