Last active
March 8, 2017 12:02
-
-
Save sakrist/23aa866cbd61dc33b520 to your computer and use it in GitHub Desktop.
GLKMathProject and GLKMathUnproject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
GLKVector3 GLKMathProject(GLKVector3 object, GLKMatrix4 model, GLKMatrix4 projection, int *viewport) { | |
assert(viewport); | |
GLKVector4 v4 = GLKVector4MakeWithVector3(object, 1.0); | |
GLKVector4 v = GLKMatrix4MultiplyVector4(model, v4); | |
v = GLKMatrix4MultiplyVector4(projection, v); | |
v.v[3] = 1.0/v.v[3]; | |
v.v[0] *= v.v[3]; | |
v.v[1] *= v.v[3]; | |
v.v[2] *= v.v[3]; | |
float x = (v.v[0] * 0.5 + 0.5) * viewport[2] + viewport[0]; | |
float y = (v.v[1] * 0.5 + 0.5) * viewport[3] + viewport[1]; | |
float z = (1.0 + v.v[2])*0.5; | |
return GLKVector3Make(x, y, z); | |
} | |
GLKVector3 GLKMathUnproject(GLKVector3 window, GLKMatrix4 model, GLKMatrix4 projection, int *viewport, bool *success) { | |
assert(viewport); | |
bool canInvert = false; | |
GLKMatrix4 inverted = GLKMatrix4Invert(GLKMatrix4Multiply(projection, model), &canInvert); | |
if (success) { | |
*success = canInvert; | |
} | |
if (!canInvert) { | |
return GLKVector3Make(0.0f, 0.0f, 0.0f); | |
} | |
GLKVector4 normalisedVector = GLKVector4Make((2 * window.x / viewport[2] - 1), | |
(2 * (window.y - viewport[1]) / viewport[3] - 1), | |
2*window.z - 1, | |
1); | |
GLKVector4 _point = GLKMatrix4MultiplyVector4(inverted, normalisedVector); | |
_point.v[3] = 1.0/_point.v[3]; | |
GLKVector3 vec = GLKVector3Make(_point.v[0]*_point.v[3], _point.v[1]*_point.v[3], _point.v[2]*_point.v[3]); | |
return vec; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment