模型视图投影矩阵是应该在Actionscript 3中构建还是在顶点着色器中的GPU上构建?

时间:2012-04-08 21:17:33

标签: actionscript-3 gpu shader stage3d

我见过的所有Stage3D示例都在每个渲染事件的AS3中构建模型视图投影矩阵。例如:

modelMatrix.identity();
// Create model matrix here
modelMatrix.translate/rotate/scale
...
modelViewProjectionMatrix.identity();
modelViewProjectionMatrix.append( modelMatrix );
modelViewProjectionMatrix.append( viewMatrix );
modelViewProjectionMatrix.append( projectionMatrix );
// Model view projection matrix to vertex constant register 0
context3D.setProgramConstantsFromMatrix( Context3DProgramType.VERTEX, 0, modelViewProjectionMatrix, true );
...

顶点着色器中的一行将顶点转换为屏幕空间:

m44 op, va0, vc0

有这样做的理由吗? 这些计算不是GPU的用途吗?

为什么不在更改时更新视图和投影矩阵,并将每个矩阵上传到单独的寄存器:

// Projection matrix to vertex constant register 0
// This could be done once on initialization or when the projection matrix changes
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, projectionMatrix, true);
// View matrix to vertex constant register 4
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 4, viewMatrix, true);

然后在每个帧和每个对象上:

modelMatrix.identity();
// Create model matrix here
modelMatrix.translate/rotate/scale
...
// Model matrix to vertex constant register 8
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 8, modelMatrix, true);
...

然后着色器看起来像这样:

// Perform model view projection transformation and store the results in temporary register 0 (vt0)
// - Multiply vertex position by model matrix (vc8)
m44 vt0 va0 vc8
// - Multiply vertex position by view matrix (vc4)
m44 vt0 vt0 vc4
// - Multiply vertex position by projection matrix (vc0) and write the result to the output register
m44 op vt0 vc0

更新

我现在在这里找到了另一个问题,可能已经回答了这个问题:
DirectX world view matrix multiplications - GPU or CPU the place

2 个答案:

答案 0 :(得分:1)

这是一个棘手的优化问题。你应该问的第一件事是:这真的是一个瓶颈吗?如果是,你必须考虑这个:

  • 在AS3中进行矩阵乘法比它应该慢。
  • 顶点程序中的额外矩阵变换几乎是免费的。
  • 设置一个矩阵比将多个矩阵设置为常量要快!
  • 你还需要其他地方的连接矩阵吗?可能会选?

没有简单的答案。为了速度,我会让GPU完成工作。但在许多情况下,您可能需要妥协:发送模型 - >世界和世界 - >剪辑矩阵,如经典OpenGL。对于molehill,特别是在顶点程序中对GPU进行更多的工作。但在担心这个问题之前,一定要确保这个问题确实是一个瓶颈。

tl / dr:如果可以,请在顶点程序中执行!

答案 1 :(得分:1)

不要忘记顶点着色器每个顶点运行一次,你最终会在每帧上进行数百次的乘法运算,

虽然AS3版本每帧只进行一次乘法。

与每个性能问题一样:

优化经常运行的东西,忽略那些只是偶尔运行的东西。