09-处理不同平台的矩阵布局

本篇将看看如何使用Slang处理不同目标平台的矩阵布局。

处理矩阵布局

背景

GLSL(OpenGL/Vulkan)和HLSL之间矩阵存储布局的转换让多数开发者困扰。当编写跨平台代码时,重要的目标就是生成相同的矩阵并传入相同的代码中。为了解决这个问题,Slang提供了一些必要的工具为GLSL和HLSL使用。

TLDR

  • Slang的矩阵默认布局是行主序。但在目前版本中,通过slangc运行的代码默认是列主序,未来可能会改变。

  • 行主序是唯一跨平台的布局。

  • 对于C++ API,使用setMatrixLayoutMode/spSetMatrixLayoutMode/createSession来设置默认矩阵布局;

    slang::IGlobalSession* globalSession;
    ...
    slang::SessionDesc slangSessionDesc = {};
    slangSessionDesc.defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_COLUMN_MAJOR;
    ...
    slang::ISession* session;
    globalSession->createSession(slangSessionDesc, &session);
  • 对于slangc,使用-matrix-layout-row-major-matrix-layout-column-major设置默认矩阵布局。也能通过C++ API的spProcessCommandLineArguments/processCommandLineArguments实现。

  • 根据CPU端应用程序的数学库,矩阵的大小和目标平台,要看情况在CPU端/GPU端进行矩阵的转置。

官方推荐使用 行主序 row-major 布局矩阵。在反射那一篇文章中,说到

Note that the concepts of “row” and “column” as employed by Slang are the opposite of how Vulkan, SPIR-V, GLSL, and OpenGL use those terms. When Slang reflects a matrix as using row-major layout, the corresponding matrix in generated SPIR-V will have a ColMajor decoration.

那应该不用担心吗,待我实践后再补充补充。

参考资料

  • shader-slang/slang: Making it easier to work with shaders (github.com)
  • Handling Matrix Layout Differences on Different Platforms | slang