我在OpenGL中有四边形(在两个方向上拉伸[-1 1])。我在它的顶点上执行正交投影,然后像这样旋转和翻译:
glm::Mat4 map_mvp;
glm::quat rotation = glm::quat(glm::vec3(0,0,-yaw));
map_mvp = glm::toMat4(rotation) * map_mvp;
map_mvp = glm::translate(map_mvp,glm::vec3(-translate_x,translate_y,0));
map_mvp = glm::ortho(-width/map_zoom,width/map_zoom,-height/map_zoom,height/map_zoom ) * map_mvp;
glUseProgram(map_program);
glUniformMatrix4fv(glGetUniformLocation(map_program, "mvp"), 1, GL_FALSE, glm::value_ptr(map_mvp));
根据代码的其他部分,上述代码中的各种变量(yaw,translate_x等)随时间而变化。我的目标是知道我用来显示它的GLFW窗口的任何区域的四边形坐标。我假设我可以反转投影,但是当我这样做时,我会得到完全随机且不正确的坐标。我使用的代码是(在鼠标点击的回调中):
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
//Find click position in the same coord system as the vertices
int pixel_width, pixel_height, virtual_width, virtual_height;
glfwGetFramebufferSize(window, &pixel_width, &pixel_height);
glfwGetWindowSize(window, &virtual_width, &virtual_height);
double x_world_pos, y_world_pos, x_virt_to_pix, y_virt_to_pix;
x_world_pos = (2 * xpos / virtual_width - 1);
y_world_pos = - (1 - 2 * ypos / virtual_height);
//Inverse rotation to find map position
glm::mat4 mvp_rev_map;
glm::quat rotation = glm::quat(glm::vec3(0,0,yaw));
mvp_rev_map = glm::inverse(glm::ortho(-v->width/v->map_zoom,v->width/v->map_zoom,-v->height/v->map_zoom,v->height/v->map_zoom)) * mvp_rev_map;
mvp_rev_map = glm::translate(mvp_rev_map,glm::vec3(translate_x,-translate_y,0));
mvp_rev_map = glm::toMat4(rotation) * mvp_rev_map;
// Find z pixel depth
GLfloat zpixel ;
glm::vec2 screen_pos=glm::vec2(xpos, ypos);
glm::vec2 pixel_pos=screen_pos * glm::vec2(pixel_width, pixel_height) / glm::vec2(virtual_width, virtual_height); // note: not necessarily integer
pixel_pos = pixel_pos + glm::vec2(0.5f, 0.5f); // shift to GL's center convention
glReadPixels((GLint)pixel_pos.x,(GLint)pixel_height-1-pixel_pos.y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT, &zpixel);
glm::vec4 quad_pos = mvp_rev_map * glm::vec4(x_world_pos, y_world_pos, (float)zpixel, 1.0);
有人能看到我出错的地方吗?