Shader 代码段引用

为了方便代码段复用,ShaderLab 中可以如下使用 include 宏进行代码段引用,后续编译过程中会被自动扩展替换。

#include "{includeKey}"

为了能使代码段能够通过 include 宏进行引用,我们有 2 种方式进行代码段声明:

1. 编辑器中创建 着色器 / 着色器片段

创建的代码段 includeKey 为该文件在工程中的文件路径,比如下图中,如果想在 Shader 资产 UnlitShader 中引用 ShaderChunk 代码段,分别可以通过绝对路径和相对路径引用:

// 相对路径
#include "./ShaderChunk.glsl"
 
// 编辑器解决路径
#include "/ShaderChunk.glsl"  // 项目资产根目录

2. 脚本中显示注册代码段

import { ShaderFactory } from '@galacean/engine';
 
const commonSource = `// shader chunk`;
ShaderFactory.registerInclude('includeKey', commonSource);

ShaderLab 中引用

#include "includeKey"

当前版本中,引擎提供了 PBR ShaderLab 内置代码段,开发者可以通过这些内置代码段对 PBR Shader 进行自定义扩展。需要注意的是,需要对引擎内置 ShaderLab 代码段进行注册后才可使用。

Typescript
import { registerIncludes } from "@galacean/engine-shader-shaderlab";
 
// 对内置 ShaderLab 代码段注册。
registerIncludes();
ShaderLab
...
#include "Common.glsl"
#include "BRDF.glsl"
...

官方内置 PBR ShaderLab 代码段源码 参考

这篇文档对您有帮助吗?