OpenGL: draw line between two elements

2019-05-07 16:45发布

问题:

I need to draw a line between two meshes I've created. Each mesh is associated with a different model matrix. I've been thinking on how to do this and I thought of this:

glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(first_object_model_matrix);
glBegin(GL_LINES);
glVertex3f(0, 0, 0); // object coord
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(first_object_model_matrix);
glVertex3f(0, 0, 0); // ending point of the line
glEnd( );

But the problem is that I can't call glMatrixMode and glLoadMatrixf between glBegin and glEnd. I'm also using shaders and the programmable pipeline, so the idea of turning back to the fixed pipeline with my scene rendered isn't exciting.

Can you:

  • Suggest me precisely how to draw a line between two meshes (I have their model matrix) with shaders.

or

  • Suggest me how to write code similar to the one above to draw a line having two meshes model matrices.

回答1:

Calculate the line's two points by multiplying each one with one of your model matrices. The following is pseudo-code. Since you're using Qt, you could use its built-in maths libraries to accomplish this effect.

vec3 line_point_1 = model_matrix_object1 * vec4(0, 0, 0, 1);
vec3 line_point_2 = model_matrix_object2 * vec4(0, 0, 0, 1);
// Draw Lines


回答2:

The position of the second point can simply be taken from the w vector of the model_matrix_object2. No need to multiply with (0,0,0,1).

This is because a 4x4 matrix in OpenGL is usually an ortho matrix consisting of a 3x3 rotational part and a translational vector. The last row is then padded with 0,0,0,1. If you want to know where a 4x4 matrix would translate simply get the vector in the right-most column.

See Given a 4x4 homogeneous matrix, how can i get 3D world coords? for more info.