如何以及何时在顶点和片段着色器中选择 highp、lowp 和 mediump?

How and when to choose highp, lowp and mediump in the Vertex and Fragment shader?

他们的最佳做法是什么?有什么性能差异吗?

What's the best practice for them?

在大多数情况下,这些仅在移动设备上很重要。规范说一个实现总是可以使用更高的精度,所以在桌面上,顶点着色器和片段着色器 运行 总是在 highp 中。 (我知道没有桌面 GPU 不是这样)

来自 spec 第 4.5.2 节

4.5.2 Precision Qualifiers

...

Precision qualifiers declare a minimum range and precision that the underlying implementation must use when storing these variables. Implementations may use greater range and precision than requested, but not less.

对于手机和平板电脑,有几个答案。没有最好的。由你决定

  1. 使用你能做到的最低精度,但仍然可以完成你需要它做的事情。

  2. 使用 highp 并忽略性能问题和它不起作用的旧手机

  3. 使用 mediump 并忽略错误(见下文)

  4. 检查用户的设备是否支持 highp,如果不支持则使用功能较少的不同着色器。

WebGL 默认顶点着色器使用 highp,片段着色器没有默认值,您必须指定一个。此外,片段着色器中的 highp 是一项可选功能,一些移动 GPU 不支持它。我不知道 2019 年的百分比是多少。据我所知,2019 年出货的大多数甚至可能是所有手机都支持 highp,但旧手机(2011、2012、2013)不支持。]

来自规范:

The vertex language requires any uses of lowp, mediump and highp to compile and link without error. The fragment language requires any uses of lowp and mediump to compile without error. Support for highp is optional.

你通常需要 highp 的地方的例子。 Phong 阴影点光源通常需要 highp。因此,例如,您可能在不支持 highp 的系统上仅使用定向灯,或者您可能在移动设备上仅使用定向灯以提高性能。

Is there any performance difference?

是的,但正如上面所说,实现可以自由使用更高的精度。因此,如果您在桌面 GPU 上使用 mediump,您将看不到任何性能差异,因为它实际上一直在使用 highp。在移动设备上,您会看到性能差异,至少在 2019 年是这样。您可能还会看到着色器真正需要 highp 的地方。

这是一个设置为使用 mediump 的 phong 着色器。在桌面上,因为 mediump 实际上是 highp 它可以工作

在 mediump 实际上是 mediump 的移动设备上它坏了

大多数 2D 游戏都可以使用 mediump,至少在片段着色器中是这样。