Getting screen coords in ShaderMaterial shaders

Hi folks,

Can somebody tell me how I can get accurate screen coordinates in a ShaderMaterial fragment shader ?

I’ve tried to create a vec2 vCoords varying like so :

vec4 vPos = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
vCoords = vPos.xy;
vCoords /= vPos.w;
vCoords = vCoords * 0.5 + 0.5;

But the coordinates I get in the fragment shader seem to be off.

When I multiply and print vCoords fractional part, the offset is obvious :

Here is a fiddle : https://jsfiddle.net/felixmariotto/xcnqguy8/32/

I’m sure I’m missing something obvious, there must be a simple way of getting the screen coordinates ? Any help would be appreciated. I need precise viewport coords to sample from a viewport aligned texture.

Hi!
Seems it needs to be done per pixel, instead of per vertex:

const vertexShader = `
	varying vec4 vPos;

	void main() {

		vPos = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		gl_Position = vPos;

	}
`;

const fragmentShader = `
	varying vec4 vPos;
  
  void main() {
  	vec2 vCoords = vPos.xy;
		vCoords /= vPos.w;
		vCoords = vCoords * 0.5 + 0.5;
  
  	vec2 uv = fract( vCoords * 10.0 );
    gl_FragColor = vec4( uv, 0.0, 1.0 );
  }
`;
4 Likes

Ah thank you very much, that’s exactly what I needed !

Working solution for posterity : https://jsfiddle.net/felixmariotto/xcnqguy8/34/

2 Likes

@felixmariotto You’re welcome :slight_smile: :beers: