Lee Stemkoski - 1 year ago 157

Javascript Question

Using Three.js, I have written a vertex shader that colors each point in a plane according to which quadrant of the screen a pixel is rendered.

`// vertex shader`

uniform float width;

uniform float height;

varying float x;

varying float y;

void main()

{

vec4 v = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

x = v.x;

y = v.y;

gl_Position = v;

}

// fragment shader

varying float x;

varying float y;

void main()

{

gl_FragColor = vec4(x, y, 0.0, 1.0);

}

Live example at jsFiddle: http://jsfiddle.net/Stemkoski/ST4aM/

I would like to modify this shader so that

`x`

`y`

`x`

`y`

`x = v.x / width`

`y = v.y / height`

`width`

`height`

How can I fix the shader code to have the desired effect?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Your variable `v`

is in clip space. You need to apply the perspective divide to map that to normalized device coordinate ( NDC ) space, which takes values in the range [ -1, 1 ]. Then, you need to map that value to the range [ 0, 1 ] like so:

```
vec4 v = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
x = v.x / v.z;
y = v.y / v.z;
gl_FragColor = vec4( 0.5 * x + 0.5, - 0.5 * y + 0.5, 0.0, 1.0 );
```

fiddle: http://jsfiddle.net/ST4aM/4/

three.js r.62

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**