gpt4 book ai didi

opengl - 优化最小/最大深度 GLSL 着色器

转载 作者:行者123 更新时间:2023-12-01 03:48:38 27 4
gpt4 key购买 nike

我正在实现平铺延迟着色,为此我需要计算平铺的最小/最大深度值。我为每个图块渲染 1 个像素,并在嵌套的 for 循环中收集深度值,如下所示:

float minDepth = 1.0;
float maxDepth = 0.0;

ivec2 clampMax = ivec2(screenSize) - 1;

// Iterate over each pixel in this tile
for (int x = 0; x < 32; x++) {
for (int y = 0; y < 32; y++) {
ivec2 newCoord = screenCoord + ivec2(x,y);
newCoord = min(newCoord, clampMax);

// Fetch the depth for that coordinate
float currentDepth = texelFetch(depth, newCoord, 0).r;

minDepth = min(minDepth, currentDepth);
maxDepth = max(maxDepth, currentDepth);
}
}

到目前为止,这工作正常,但查看生成的程序集,纹理查找得到如下内容:
// R2.xy contains 'newCoord'
MOV.S R2.z, {0, 0, 0, 0}.x;
TXF.F R1.x, R2.xyzz, handle(D0.x), 2D;

这基本上等于:
vec3 coordinate;
coordinate.xy = newCoord;
coordinate.z = 0;
result = texelFetch(depth, coordinate);

所以它为纹理查找生成了一个额外的不必要的指令,在这样一个循环中总结了很多。我的猜测是,NVIDIA 在内部将 texelFetch 实现为
texelFetch(sampler2D sampler, ivec3 coord) 

回到问题: 你会如何优化这个循环?

我在 Windows 上使用带有最新驱动程序的 GTX 670。

最佳答案

不要担心这些额外的步骤。它很可能在比单个全局内存访问 (texelFetch) 快 200 多倍的寄存器中完成。

但这里有一种优化问题而不是循环的方法:

一般来说,最高效的 GPU 程序是那些每个线程做尽可能少的工作,并且所有线程工作的总和与顺序算法所需的数量相同。

Opengls 的方法现在是计算 GPU 上自己线程中的每个像素。这在大多数情况下完全没问题,但在您的问题中,每个线程的工作量非常大(32*32*texelFetch)。

那么如何优化这个问题呢?

-> 减少每个线程的工作量

如何?

-> 平行归约 ( http://www.drdobbs.com/architecture-and-design/parallel-pattern-7-reduce/222000718 )

非正式说明:

  • 你有你的 32x32 区域。
  • 不是计算整个区域的最小值/最大值,而是分多个步骤进行。

  • -> 计算 2x2 块的最小值/最大值(每个区域 16x16 块)

    -> 所以现在你的图像小了 4 倍

    -> 做 5 次

    -> 您现在拥有完整区域的最小值/最大值

    关于opengl - 优化最小/最大深度 GLSL 着色器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24763812/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com