【问题标题】:WebGL: Strange behavior when render spritebatch into render textureWebGL:将 spritebatch 渲染到渲染纹理时的奇怪行为
【发布时间】:2015-08-03 19:27:45
【问题描述】:

技术:WebGL / GL

  1. 当我立即将 10k 个精灵(使用 spritebatch)渲染到后台缓冲区时,一切正常。

10k

  1. 当我将它渲染到渲染纹理中时,我遇到了一些奇怪的 alpha 混合问题(我猜..)。在纹理具有透明像素的地方,alpha 计算错误(IMO 应该是累积的)。

10k

1k

200,黑色背景

混合配置:

gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

这就是我创建渲染缓冲区的方式:

this._texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, this._texture);
this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.width, this.height, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null);

this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);


this.renderBuffer = this.gl.createFramebuffer();

this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.renderBuffer);
this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_2D, this._texture, 0);

【问题讨论】:

    标签: javascript webgl


    【解决方案1】:

    我已将混合模式更改为:

    gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
    gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
    

    这是结果:

    说明:

    当您立即渲染到后台缓冲区时,alpha 通道始终设置为 1.0(使用透明画布的情况除外) - 因此,如何计算 alpha 并不重要。

    当您首先渲染到渲染缓冲区(纹理),然后这个准备好的纹理用于渲染到后台缓冲区时 - 您需要为 alpha 和 rgb 使用不同的混合模式。

    SRC_ALPHA 和 ONE_MINUS_SRC_ALPHA 用于 RGB 混合(相乘),具体取决于 SRC 和 DESC alpha。

    如果 alpha 通道也被倍增,它将覆盖纹理具有透明像素的地方的不透明像素。我们需要将每个像素的 alpha 相加,而不是相乘。

    因此需要将 alpha func 设置为:ONE 和 ONE_MINUS_SRC_ALPHA,因此 ALPHA 将被累积,而不是相乘。

    卢克: 我英语不流利(对不起)。如果有人愿意“翻译”这个解释,我将不胜感激。

    【讨论】:

    • 很高兴您解决了问题!如果您不介意分享,您能否解释一下为什么需要分离颜色混合和 Alpha 混合?
    • @WacławJasper 我已经添加了解释,但我不确定你是否可以阅读它:)
    • 谢谢。很有帮助。这是完全可以理解的。当我需要为我的 sprite 渲染器实现准确的 alpha 混合时,可能会为我节省数小时的头痛。
    猜你喜欢
    • 2011-11-24
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多