首页 > 解决方案 > A-Frame A-Text 蒙版

问题描述

我找不到任何关于使用 a-text 基元或其他可能性与 a-frame 或threejs 隐藏图片的答案。位图文本应该是底层图像的掩码。有人告诉我,它可以通过着色器https://aframe.io/docs/0.8.0/primitives/a-text.html#attributes_shader解决,并建议我阅读着色器书https://thebookofshaders.com 155页预知!我不确定这是否是正确的提示!?

在这里,您可以将图示的任务位置显示为图形视图:

https://photos.app.goo.gl/MLZjcucfpuqmtinH7

代码笔: http ://codepen.w3x.de

标签: shaderaframe

解决方案


复制并粘贴 A-Frame 文本着色器代码(删除 module.exports)并注册文本着色器。这是当前的 MSDF 着色器:

AFRAME.registerShader('yourtextshader', {
      schema: {
        alphaTest: {type: 'number', is: 'uniform', default: 0.5},
        color: {type: 'color', is: 'uniform', default: 'white'},
        map: {type: 'map', is: 'uniform'},
        negate: {type: 'boolean', is: 'uniform', default: true},
        opacity: {type: 'number', is: 'uniform', default: 1.0}
      },

      raw: true,

      vertexShader: [
        'attribute vec2 uv;',
        'attribute vec3 position;',
        'uniform mat4 projectionMatrix;',
        'uniform mat4 modelViewMatrix;',
        'varying vec2 vUV;',
        'void main(void) {',
        '  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
        '  vUV = uv;',
        '}'
      ].join('\n'),

      fragmentShader: [
        '#ifdef GL_OES_standard_derivatives',
        '#extension GL_OES_standard_derivatives: enable',
        '#endif',

        'precision highp float;',
        'uniform bool negate;',
        'uniform float alphaTest;',
        'uniform float opacity;',
        'uniform sampler2D map;',
        'uniform vec3 color;',
        'varying vec2 vUV;',

        'float median(float r, float g, float b) {',
        '  return max(min(r, g), min(max(r, g), b));',
        '}',

        // FIXME: Experimentally determined constants.
        '#define BIG_ENOUGH 0.001',
        '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',

        'void main() {',
        '  vec3 sample = texture2D(map, vUV).rgb;',
        '  if (negate) { sample = 1.0 - sample; }',

        '  float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
        '  float alpha = clamp(sigDist / fwidth(sigDist) + 0.5, 0.0, 1.0);',
        '  float dscale = 0.353505;',
        '  vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
        '  float isBigEnough = max(abs(duv.x), abs(duv.y));',

        '  // Do modified alpha test.',
        '  if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
        '  gl_FragColor = vec4(color.xyz, alpha * opacity);',
        '}'
      ].join('\n')
    });

片段着色器用于计算文本的颜色。你会得到vUV哪个是那个片段的 UV 贴图,告诉你在纹理中的哪里采样。

你需要做什么来修改这个着色器。还没有时间做一个完整的例子,但是......:

  1. 接受纹理的另一个参数,添加到模式中。
  2. 将该纹理传递到着色器 ( <a-entity text="shader: yourTextShader; yourTexture: #texture)。
  3. 在片段着色器中为该纹理添加制服uniform sampler2D yourTexture)。
  4. 修改片段着色器以使用纹理颜色而不是颜色gl_FragColor = vec4(texture2D(yourTexture, vUv), alpha * opacity)

推荐阅读