WebGl 在着色器中旋转纹理

WebGl rotate texture within the shader

我正在使用 webgl 将遮罩图像绑定到常规图像。哑光图像赋予常规图像透明度。

我能够成功上传两张图像作为纹理,但是当我 运行 程序时,我的彩色纹理和遮罩纹理不对齐。正如您在下图中看到的那样,黑色应该全部消失,但它似乎缩放并翻转了。

我觉得很奇怪,因为 "color" 通道和 "alpha" 通道都使用相同的纹理。

我的问题是如何 rotate/resize 着色器中的 alpha 通道?或者我必须制作一个新的纹理坐标平面来将 alpha 通道映射到。

下面是我的代码供参考:

vertexShaderScript = [
  'attribute vec4 vertexPos;',
  'attribute vec4 texturePos;',
  'varying vec2 textureCoord;',

  'void main()',
  '{',
  '  gl_Position = vertexPos;',
  '  textureCoord = texturePos.xy;',
  '}'
].join('\n');

fragmentShaderScript = [
  'precision highp float;',
  'varying highp vec2 textureCoord;',
  'uniform sampler2D ySampler;',
  'uniform sampler2D uSampler;',
  'uniform sampler2D vSampler;',
  'uniform sampler2D aSampler;',
  'uniform mat4 YUV2RGB;',

  'void main(void) {',
  '  highp float y = texture2D(ySampler,  textureCoord).r;',
  '  highp float u = texture2D(uSampler,  textureCoord).r;',
  '  highp float v = texture2D(vSampler,  textureCoord).r;',
  '  highp float a = texture2D(aSampler,  textureCoord).r;',
  '  gl_FragColor = vec4(y, u, v, a);',
  '}'
].join('\n');

如果您只想翻转 alpha 纹理坐标

const vertexShaderScript = `
  attribute vec4 vertexPos;
  attribute vec4 texturePos;
  varying vec2 textureCoord;

  void main()
  {
    gl_Position = vertexPos;
    textureCoord = texturePos.xy;
  }
`;

const fragmentShaderScript = `
  precision highp float;
  varying highp vec2 textureCoord;
  uniform sampler2D ySampler;
  uniform sampler2D uSampler;
  uniform sampler2D vSampler;
  uniform sampler2D aSampler;
  uniform mat4 YUV2RGB;

  void main(void) {
    highp float y = texture2D(ySampler,  textureCoord).r;
    highp float u = texture2D(uSampler,  textureCoord).r;
    highp float v = texture2D(vSampler,  textureCoord).r;
    highp float a = texture2D(aSampler,  vec2(textureCoord.x, 1. - textureCoord.y).r;
    gl_FragColor = vec4(y, u, v, a);
  }
`;

但在一般情况下,由您决定如何提供或生成纹理坐标。你可以随心所欲地操纵它们。这有点像问我如何使值 3 我可以回答 3, 1 + 1 + 1, 2 + 1, 5 - 2, 15 / 5, 300 / 100, 7 * 30 / 70, 4 ** 2 - (3 * 4 + 1)

更改纹理坐标的最通用方法是像位置一样将它们乘以矩阵

 uniform mat3 texMatrix;
 attribute vec2 texCoords;

 ... 

 vec2 newTexCoords = (texMatrix * vec3(texCoords, 1)).xy;

然后使用与用于纹理坐标位置的相同类型的矩阵数学。

This article给出了一些通过纹理矩阵操纵纹理坐标的例子