I calculated the screen coordinates of the vertices in the vertex shader, and inversely calculated the screen coordinates back to space coordinates. Then when I adjust the viewing direction, the vertices of the mesh appear very noticeably jittery. Is this caused by the loss of precision when transforming the coordinates? How to avoid it? The relevant code is as follows
void vertex(){
vec2 view_size = vec2(1024, 600);
vec4 p = transform_screen_pos(PROJECTION_MATRIX, INV_CAMERA_MATRIX, VERTEX, view_size);
VERTEX = (inverse(MODELVIEW_MATRIX) * INV_PROJECTION_MATRIX * unproject(p.xy, view_size, p.z, p.w)).xyz;
}
vec4 unproject(vec2 screen, vec2 screen_size, float z, float w) {
vec2 clip_pos = vec2(screen.x / screen_size.x, screen.y / screen_size.y);
vec3 clip_pos_3d = vec3(clip_pos,z);
vec3 device_normal = clip_pos_3d * 2.0 - 1.0;
vec4 res = vec4(device_normal * w, w);
return res;
}
vec4 transform_screen_pos(mat4 project, mat4 MODELVIEW, vec3 coord, vec2 screen_size){
vec4 device = project * MODELVIEW * vec4(coord.xyz, 1.0);
vec3 device_normal = device.xyz / device.w;
vec3 clip_pos_3d = (device_normal * 0.5 + 0.5);
float z = clip_pos_3d.z;
float w = device.w;
vec2 screen_pos = vec2(clip_pos_3d.x * screen_size.x, clip_pos_3d.y * screen_size.y);
vec4 res = vec4(screen_pos, z, w);
return res;
}