Three.js - 基于屏幕上像素位置着色的顶点着色器 [英] Three.js - a vertex shader to color based on location of pixel on screen

查看:138
本文介绍了Three.js - 基于屏幕上像素位置着色的顶点着色器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Three.js,我编写了一个顶点着色器,根据渲染像素的屏幕的象限,为平面中的每个点着色。

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);
}  

jsFiddle的实例: http://jsfiddle.net/Stemkoski/ST4aM/

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

我想修改此着色器以便 x 在屏幕左侧等于0,在屏幕右侧等于1,类似地 y 顶部等于0,底部等于1。我(错误地)认为这会涉及将 x y 的值更改为 x = vx / width y = vy / height (其中 width height 存储窗口的宽度和高度)。但是,通过此更改,在平面上放大和缩小时,每个屏幕像素的颜色似乎都会发生变化。

I would like to modify this shader so that x is equal to 0 on the left side of the screen and 1 on the right side of the screen, and similarly y equal to 0 on the top and 1 on the bottom. I (incorrectly) assumed that this would involve changing the values of x and y to x = v.x / width and y = v.y / height (where width and height store the window's width and height). However, with this change the colors at each screen pixel seem to change when zooming in and out on the plane.

如何修复着色器代码以达到预期效果?

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

推荐答案

您的变量 v 位于剪辑空间中。您需要应用透视分割以将其映射到规范化设备坐标(NDC)空间,该空间采用范围[-1,1]中的值。然后,您需要将该值映射到范围[0,1],如下所示:

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 );

小提琴: http://jsfiddle.net/ST4aM/4/

three.js r.62

three.js r.62

这篇关于Three.js - 基于屏幕上像素位置着色的顶点着色器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆