Shader Code Segment Inclusion

To facilitate code reuse, ShaderLab allows including code segments using the include macro. These segments are automatically expanded during compilation.

#include "{includeKey}"

To make a code segment accessible via the include macro, there are two ways to declare it:

1. Create Shader / Shader Chunk in the Editor

The includeKey for created code segments corresponds to the file path in the project. For example, in the image below, if you want to include the ShaderChunk code segment in the UnlitShader shader asset, you can reference it using either absolute or relative paths:

// Relative path
#include "./ShaderChunk.glsl"
 
// Editor-resolved path
#include "/ShaderChunk.glsl"  // Project asset root directory

2. Register Code Segments in Script

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

Referencing in ShaderLab:

#include "includeKey"

In the current version, the engine provides built-in PBR ShaderLab code segments. Developers can use these to customize PBR shaders. Note that you must register these engine-provided ShaderLab code segments before use.

TypeScript
import { registerIncludes } from "@galacean/engine-shader-shaderlab";
 
// Register built-in ShaderLab code segments
registerIncludes();
ShaderLab
...
#include "Common.glsl"
#include "BRDF.glsl"
...

Official built-in PBR ShaderLab code segment source code: Reference

Was this page helpful?