Search code examples
openglcameravertexglpointsize

Determine gl_PointSize from distance of a GL_POINT to the camera


I'm drawing GL_POINTS using glDrawArrays(GL_POINTS, 0, numberOfPoints) The size of each point is set in my vertex shader using gl_PointSize. I get the view matrix from glm::lookAt(origin, eye, up) The xyz position of a point is set using gl_Position = view * proj * vec4(position, 1.0) in the vertex shader. I'd like a point size to increase as its distance to the camera origin decreases, and the size to decrease as the distance from the camera origin increases. Just like normal perspective. How can I determine how large a point will be, from its distance to the camera?


Solution

  • Heres a vertex shader I created recently to achieve this.

    precision mediump float;
    attribute vec3 position;
    
    uniform mat4 model, view, projection;
    uniform float pointsize;
    uniform vec3 cameraeye;
    
    void main(void) {
        gl_Position = projection * view * model * vec4(position.xyz, 1.0);
        gl_PointSize = pointsize - (distance(cameraeye, position.xyz) / pointsize);
    }
    
    • pointsize is the initial and max size of the point
    • cameraeye is the vec3 world position of the camera
    • might be fine to remove the model matrix. I'm using a constant value of identity matrix in my implementation.