【问题标题】:get current pixel position on webGL2 fragment shader获取 webGL2 片段着色器上的当前像素位置
【发布时间】:2019-11-19 02:53:25
【问题描述】:

我创建了一个简单的 webGL 脚本,它根据 (x,y) 像素位置应用像素颜色

我得到了什么:

这就是我所做的:

#ifdef GL_ES
precision mediump float;
#endif

uniform float width;
uniform float height;
uniform float time;

void main() {
  vec2 u_resolution = vec2(width, height);
    vec2 st = gl_FragCoord.xy / u_resolution;
    gl_FragColor = vec4(st.x, st.y, 0.5, 1.0);
}

Codepen: Hello WebGL

我正在尝试将其转换为 webGL2,但我不知道如何获取当前像素位置。

这是我尝试过的:

#version 300 es
#ifdef GL_ES
precision mediump float;
#endif

uniform float width;
uniform float height;
uniform float time;
out vec4 color;

void main() {
  vec2 u_resolution = vec2(width, height);
    vec2 st = color.xy / u_resolution;
    color = vec4(st.x, st.y, 0.5, 1.0);
}

Codepen: Hello WebGL2

如何在 webgl2 中获取当前像素位置?

【问题讨论】:

  • 您在 WebGL2 版本中从 gl_FragCoord 更改为 color 有什么原因吗?我会尝试仍然使用vec2 st = gl_FragCoord.xy / u_resolution;
  • gl_FragCoord 在 WebGL 2.0 和 GLSL ES 3.00 中仍然有效

标签: webgl webgl2


【解决方案1】:

gl_FragCoord 在 WebGL2 中仍然是正确的方式

var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var gl = canvas.getContext("webgl2");

//************** Shader sources **************
var vertexSource = `
#version 300 es
in vec2 position;
void main() {
  gl_Position = vec4(position, 0.0, 1.0);
}
`;

var fragmentSource = `
#version 300 es
#ifdef GL_ES
precision mediump float;
#endif

uniform float width;
uniform float height;
uniform float time;
out vec4 color;

void main() {
  vec2 u_resolution = vec2(width, height);
	vec2 st = gl_FragCoord.xy / u_resolution;
	color = vec4(st.x, st.y, 0.5, 1.0);
}`;

window.addEventListener("resize", onWindowResize, false);

function onWindowResize() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  gl.viewport(0, 0, canvas.width, canvas.height);
  gl.uniform1f(widthHandle, window.innerWidth);
  gl.uniform1f(heightHandle, window.innerHeight);
}

//Compile shader and combine with source
function compileShader(shaderSource, shaderType) {
  var shader = gl.createShader(shaderType);
  gl.shaderSource(shader, shaderSource);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    throw "Shader compile failed with: " + gl.getShaderInfoLog(shader);
  }
  return shader;
}

//From https://codepen.io/jlfwong/pen/GqmroZ
//Utility to complain loudly if we fail to find the attribute/uniform
function getAttribLocation(program, name) {
  var attributeLocation = gl.getAttribLocation(program, name);
  if (attributeLocation === -1) {
    throw "Cannot find attribute " + name + ".";
  }
  return attributeLocation;
}

function getUniformLocation(program, name) {
  var attributeLocation = gl.getUniformLocation(program, name);
  if (attributeLocation === -1) {
    throw "Cannot find uniform " + name + ".";
  }
  return attributeLocation;
}

//************** Create shaders **************

//Create vertex and fragment shaders
var vertexShader = compileShader(vertexSource.trim(), gl.VERTEX_SHADER);
var fragmentShader = compileShader(fragmentSource.trim(), gl.FRAGMENT_SHADER);

//Create shader programs
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);

gl.useProgram(program);

//Set up rectangle covering entire canvas
var vertexData = new Float32Array([
  -1.0,
  1.0, // top left
  -1.0,
  -1.0, // bottom left
  1.0,
  1.0, // top right
  1.0,
  -1.0 // bottom right
]);

//Create vertex buffer
var vertexDataBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexDataBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertexData, gl.STATIC_DRAW);

// Layout of our data in the vertex buffer
var positionHandle = getAttribLocation(program, "position");

gl.enableVertexAttribArray(positionHandle);
gl.vertexAttribPointer(
  positionHandle,
  2, // position is a vec2 (2 values per component)
  gl.FLOAT, // each component is a float
  false, // don't normalize values
  2 * 4, // two 4 byte float components per vertex (32 bit float is 4 bytes)
  0 // how many bytes inside the buffer to start from
);

//Set uniform handle
var timeHandle = getUniformLocation(program, "time");
var widthHandle = getUniformLocation(program, "width");
var heightHandle = getUniformLocation(program, "height");

gl.uniform1f(widthHandle, window.innerWidth);
gl.uniform1f(heightHandle, window.innerHeight);

function draw() {
  //Send uniforms to program
  gl.uniform1f(timeHandle, performance.now());
  //Draw a triangle strip connecting vertices 0-4
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  requestAnimationFrame(draw);
}

draw();
html {
  overflow: hidden;
}
canvas {
  display: block;
}

其他一些随机提示。

  • 这些 ifdef 无关紧要

    #ifdef GL_ES
    precision mediump float;
    #endif
    

    只是

    precision mediump float;
    

    没问题。

  • 我猜这很明显,但为什么要分开传递 widthheight

    怎么样

    uniform vec2 u_resolution;
    
  • 没有理由打电话给performance.now。时间传递给您的requestAnimationFrame 回调

    function draw(time) {
      //Send uniforms to program
      gl.uniform1f(timeHandle, time);
    
      ...
      requestAnimationFrame(draw);
    }
    
    requestAnimationFrame(draw);
    
  • 代码检查编译错误但不检查链接错误

    你应该检查链接错误

    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      throw "Program link failed with: " + gl.getProgramInfoLog(program);
    }
    
    

    如果您的变量不匹配,并且即使在错误的着色器上,规范不需要编译也不会失败,则会出现链接错误。相反,它只要求链接失败。

  • window.innerWidth

    见:this

  • 如果制服不存在,gl.getUniformLocation 返回null

    代码正在检查 -1,这对于属性是正确的,但对于制服不正确。

  • 抛出不存在的属性和制服

    当然,知道它们不存在会很有帮助,但通过注释掉或编辑来调试着色器是很常见的。例如,假设屏幕上没有出现任何内容。如果是我,我要做的第一件事就是将片段着色器更改为此

    const fragmentSource = `
    #version 300 es
    precision mediump float;
    
    uniform vec2 u_resolution;
    uniform float time;
    out vec4 color;
    
    void main() {
        vec2 st = gl_FragCoord.xy / u_resolution;
        color = vec4(st.x, st.y, 0.5, 1.0);
        color = vec4(1, 0, 0, 1);  // <----------------------
    }`;
    

    只需输出一个纯色来检查问题是在片段着色器还是顶点着色器中。在我这样做的那一刻,大多数 WebGL 实现将优化 u_resolution 并且在查找位置时抛出的代码有效地使程序无法调试。

    事实上,由于之前的错误检查为 -1 而不是 null,因此代码仅在当前运行。修复了该错误后,代码崩溃了,因为 time 已优化。

var canvas = document.body.appendChild(document.createElement("canvas"));
var gl = canvas.getContext("webgl2");

//************** Shader sources **************
var vertexSource = `
#version 300 es
in vec2 position;
void main() {
  gl_Position = vec4(position, 0.0, 1.0);
}
`;

var fragmentSource = `
#version 300 es
precision mediump float;

uniform vec2 u_resolution;
uniform float time;
out vec4 color;

void main() {
  vec2 st = gl_FragCoord.xy / u_resolution;
  color = vec4(st.x, st.y, 0.5, 1.0);
}`;


function resize() {
  if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
    canvas.width = canvas.clientWidth;
    canvas.height = canvas.clientHeight;
    gl.viewport(0, 0, canvas.width, canvas.height);
    gl.uniform2f(resHandle, canvas.width, canvas.height);
  }
}

//Compile shader and combine with source
function compileShader(shaderSource, shaderType) {
  var shader = gl.createShader(shaderType);
  gl.shaderSource(shader, shaderSource);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    throw "Shader compile failed with: " + gl.getShaderInfoLog(shader);
  }
  return shader;
}

//From https://codepen.io/jlfwong/pen/GqmroZ
//Utility to complain loudly if we fail to find the attribute/uniform
function getAttribLocation(program, name) {
  var attributeLocation = gl.getAttribLocation(program, name);
  if (attributeLocation === -1) {
    console.warn("Cannot find attribute", name);
  }
  return attributeLocation;
}

function getUniformLocation(program, name) {
  var uniformLocation = gl.getUniformLocation(program, name);
  if (uniformLocation === null) {
    console.warn("Cannot find uniform", name);
  }
  return uniformLocation;
}

//************** Create shaders **************

//Create vertex and fragment shaders
var vertexShader = compileShader(vertexSource.trim(), gl.VERTEX_SHADER);
var fragmentShader = compileShader(fragmentSource.trim(), gl.FRAGMENT_SHADER);

//Create shader programs
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  throw "Program link failed with: " + gl.getProgramInfoLog(program);
}

gl.useProgram(program);

//Set up rectangle covering entire canvas
var vertexData = new Float32Array([
  -1.0,
  1.0, // top left
  -1.0,
  -1.0, // bottom left
  1.0,
  1.0, // top right
  1.0,
  -1.0 // bottom right
]);

//Create vertex buffer
var vertexDataBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexDataBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertexData, gl.STATIC_DRAW);

// Layout of our data in the vertex buffer
var positionHandle = getAttribLocation(program, "position");

gl.enableVertexAttribArray(positionHandle);
gl.vertexAttribPointer(
  positionHandle,
  2, // position is a vec2 (2 values per component)
  gl.FLOAT, // each component is a float
  false, // don't normalize values
  2 * 4, // two 4 byte float components per vertex (32 bit float is 4 bytes)
  0 // how many bytes inside the buffer to start from
);

//Set uniform handle
var timeHandle = getUniformLocation(program, "time");
var resHandle = getUniformLocation(program, "u_resolution");

function draw(time) {
  resize();
  //Send uniforms to program
  gl.uniform1f(timeHandle, time);
  //Draw a triangle strip connecting vertices 0-4
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
html,body {
  height: 100%;
  margin: 0;
}
canvas {
  width: 100%;
  height: 100%;
  display: block;
}

【讨论】:

  • 谢谢!还有一个问题:这个错误呢:Cannot find uniform time?
  • 我在回答中回答了这个问题。来自答案:“事实上,由于先前的错误检查是 -1 而不是 null,因此代码仅在当前运行。修复了该错误后,代码崩溃了,因为 time 已优化。”。我们更改了代码以打印警告,但 time 不存在,因为它没有被使用。
猜你喜欢
  • 1970-01-01
  • 2018-07-03
  • 1970-01-01
  • 2012-12-06
  • 2011-12-28
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多