首页 / luma.gl / API 文档
Shader
先看结论
单个渲染阶段编译后的着色器。v9 把「一对源码」拆成两个 Shader,
再由 RenderPipeline 链接成可绘制对象。
device.createShader({ stage: 'vertex', source: glsl }) → Shader
创建参数
| 参数 | 说明 |
|---|---|
source | 必填,着色器源码字符串 |
stage | vertex、fragment 或 compute;GLSL 必填,WGSL 忽略 |
language | glsl、wgsl 或 auto,默认自动识别 |
entryPoint | WGSL 入口函数名,默认 main,仅 WebGPU |
sourceMap | 源码映射,仅 WebGPU |
debugShaders | never、errors、warnings、always,覆盖设备级设置 |
成员
| 成员 | 说明 |
|---|---|
stage | 编译时声明的阶段 |
source | 原始源码 |
compilationStatus | pending、success 或 error |
asyncCompilationStatus | 编译状态的 Promise,异步后端用它等待结果 |
handle | 底层句柄,WebGL 下是 WebGLShader |
id / userData | 调试标识与应用自定义数据 |
destroyed | 是否已释放 |
方法
| 方法 | 返回 | 说明 |
|---|---|---|
getCompilationInfo() | Promise<CompilerMessage[]> | 异步读取编译日志 |
getCompilationInfoSync() | CompilerMessage[] | null | 同步读取,仅 WebGL 可用 |
getTranslatedSource() | string | null | 后端翻译后的源码,用于排查驱动改写 |
debugShader() | Promise<void> | 把错误输出到浏览器控制台 |
destroy() | void | 释放底层着色器对象 |
编译一对着色器
const vs = device.createShader({
stage: 'vertex',
source: [
'#version 300 es',
'in vec3 positions;',
'in vec3 colors;',
'out vec3 vColor;',
'void main() {',
' vColor = colors;',
' gl_Position = vec4(positions, 1.0);',
'}'
].join('\n')
});
const fs = device.createShader({
stage: 'fragment',
source: [
'#version 300 es',
'precision highp float;',
'in vec3 vColor;',
'out vec4 fragColor;',
'void main() {',
' fragColor = vec4(vColor, 1.0);',
'}'
].join('\n')
});
const pipeline = device.createRenderPipeline({
vs: vs,
fs: fs,
topology: 'triangle-list',
bufferLayout: [
{ name: 'positions', stepMode: 'vertex', format: 'float32x3' },
{ name: 'colors', stepMode: 'vertex', format: 'float32x3' }
]
});
GLSL 的 #version 300 es 必须是源码第一行,前面不能有空行或注释。
WebGL2 后端只接受 300 es 版本,写 100 es 会直接编译失败。
读取编译日志
const vs = device.createShader({ stage: 'vertex', source: vsSource });
if (vs.compilationStatus === 'error') {
const log = vs.getCompilationInfoSync();
console.error(log);
vs.debugShader();
}
WebGPU 后端没有同步日志,用 await vs.getCompilationInfo()。
编译失败时管线链接也会失败,先定位到具体阶段,比看管线的错误信息更有用。
与 v8 的差别
| v8 | v9 |
|---|---|
new Program(gl, { vs, fs }) | 两个 device.createShader + device.createRenderPipeline |
| 源码与链接在一起 | 源码按阶段编译,链接交给管线 |
Program 可反复 draw | 绘制经由 RenderPass,管线只描述状态 |
v8 的 Program 在 9.4 中已移除,luma.Program 为 undefined。
旧代码必须改写成上面的两段式结构。
UMD 版本需要四个包。
core 提供 Shader,webgl 提供适配器,
shadertools 提供模块组装,engine 提供 Model。
创建设备时把 luma.webgl2Adapter 显式放进 adapters,
否则会因找不到适配器而失败。
经纬志(2026)。《Shader》。https://www.jingweizhi.com/lumagl/api/shader.html(访问日期 2026-11-03)。