正文

OpenGL: 3D坐标到屏幕坐标的转换逻辑(gluProject的实现)2010-11-22 17:36:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/yuqiexing/52048.html

分享到:

遇到需要将3D坐标转换到屏幕坐标的问题,在网上很多朋友也在寻找答案,下面是glu中gluProject函数的实现。(实际上就是mesa的OpenGL实现版本)   // 矩阵按行优先存储 首先说一下opengl中的矩阵表示, 一般在c/c++中定义的矩阵和opengl中的矩阵分别是: /***************************************************************************** We define a 4x4 matrix array, OpenGL linear matrix format: referenced as Row,Column as: | 0,0   0,1   0,2   0,3 |             |a0 a4 a8 a12| | 1,0   1,1   1,2   1,3 |             |a1 a5 a9 a13| | 2,0   2,1   2,2   2,3 |             |a2 a6 a10 a14| | 3,0   3,1   3,2   3,3 |             |a3 a7 a11 a15| */ 两者行和列正好相反,因此,对于一个4×4的矩阵GLdouble m[16], 那么在操作这个矩阵时必须小心     GLint gluProject(GLdouble objx, GLdouble objy, GLdouble objz, const GLdouble model[16], const GLdouble proj[16], const GLint viewport[4], GLdouble * winx, GLdouble * winy, GLdouble * winz) { /* matrice de transformation */ GLdouble in[4], out[4]; /* initilise la matrice et le vecteur a transformer */ in[0] = objx; in[1] = objy; in[2] = objz; in[3] = 1.0; transform_point(out, model, in); transform_point(in, proj, out); /* d’ou le resultat normalise entre -1 et 1 */ if (in[3] == 0.0) return GL_FALSE; in[0] /= in[3]; in[1] /= in[3]; in[2] /= in[3]; /* en coordonnees ecran */ *winx = viewport[0] + (1 + in[0]) * viewport[2] / 2; *winy = viewport[1] + (1 + in[1]) * viewport[3] / 2; /* entre 0 et 1 suivant z */ *winz = (1 + in[2]) / 2; return GL_TRUE; } /* * Transform a point (column vector) by a 4x4 matrix. I.e. out = m * in * Input: m - the 4x4 matrix * in - the 4x1 vector * Output: out - the resulting 4x1 vector. */ static void transform_point(GLdouble out[4], const GLdouble m[16], const GLdouble in[4]) { #define M(row,col) m[col*4+row] out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3]; out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3]; out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3]; out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3]; #undef M } 参考: http://www.soidc.net/articles/1215485053486/20081129/1215945559526_1.html http://sutiany.itpub.net/post/6261/33673 http://www.opengl.org/wiki/GluProject_and_gluUnProject_code

阅读(6842) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册