shader-dev

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Shader Craft

Shader 创作

A unified skill covering 36 GLSL shader techniques (ShaderToy-compatible) for real-time visual effects.
这是一项涵盖36种GLSL着色器技术(兼容ShaderToy)的综合技能,用于实现实时视觉效果。

Invocation

调用方式

/shader-dev <request>
$ARGUMENTS
contains the user's request (e.g. "create a raymarched SDF scene with soft shadows").
/shader-dev <request>
$ARGUMENTS
包含用户的请求(例如“创建一个带有软阴影的光线步进SDF场景”)。

Skill Structure

技能结构

shader-dev/
├── SKILL.md                      # Core skill (this file)
├── techniques/                   # Implementation guides (read per routing table)
│   ├── ray-marching.md           # Sphere tracing with SDF
│   ├── sdf-3d.md                 # 3D signed distance functions
│   ├── lighting-model.md         # PBR, Phong, toon shading
│   ├── procedural-noise.md       # Perlin, Simplex, FBM
│   └── ...                       # 34 more technique files
└── reference/                    # Detailed guides (read as needed)
    ├── ray-marching.md           # Math derivations & advanced patterns
    ├── sdf-3d.md                 # Extended SDF theory
    ├── lighting-model.md         # Lighting math deep-dive
    ├── procedural-noise.md       # Noise function theory
    └── ...                       # 34 more reference files
shader-dev/
├── SKILL.md                      # 核心技能(本文档)
├── techniques/                   # 实现指南(根据路由表阅读)
│   ├── ray-marching.md           # 基于SDF的球体追踪
│   ├── sdf-3d.md                 # 3D有符号距离函数
│   ├── lighting-model.md         # PBR、Phong、卡通着色
│   ├── procedural-noise.md       # Perlin、Simplex、FBM噪声
│   └── ...                       # 另外34个技术文件
└── reference/                    # 详细指南(按需阅读)
    ├── ray-marching.md           # 数学推导与高级模式
    ├── sdf-3d.md                 # 扩展SDF理论
    ├── lighting-model.md         # 光照数学深度解析
    ├── procedural-noise.md       # 噪声函数理论
    └── ...                       # 另外34个参考文件

How to Use

使用方法

  1. Read the Technique Routing Table below to identify which technique(s) match the user's request
  2. Read the relevant file(s) from
    techniques/
    — each file contains core principles, implementation steps, and complete code templates
  3. If you need deeper understanding (math derivations, advanced patterns), follow the reference link at the bottom of each technique file to
    reference/
  4. Apply the WebGL2 Adaptation Rules below when generating standalone HTML pages
  1. 阅读下方的技术路由表,确定与用户请求匹配的技术
  2. techniques/
    目录中读取相关文件——每个文件包含核心原理、实现步骤和完整代码模板
  3. 如果需要更深入的理解(数学推导、高级模式),可查看每个技术文件底部指向
    reference/
    目录的参考链接
  4. 生成独立HTML页面时,遵循下方的WebGL2适配规则

Technique Routing Table

技术路由表

User wants to create...Primary techniqueCombine with
3D objects / scenes from mathray-marching + sdf-3dlighting-model, shadow-techniques
Complex 3D shapes (booleans, blends)csg-boolean-operationssdf-3d, ray-marching
Infinite repeating patterns in 3Ddomain-repetitionsdf-3d, ray-marching
Organic / warped shapesdomain-warpingprocedural-noise
Fluid / smoke / ink effectsfluid-simulationmultipass-buffer
Particle effects (fire, sparks, snow)particle-systemprocedural-noise, color-palette
Physically-based simulationssimulation-physicsmultipass-buffer
Game of Life / reaction-diffusioncellular-automatamultipass-buffer, color-palette
Ocean / water surfacewater-oceanatmospheric-scattering, lighting-model
Terrain / landscapeterrain-renderingatmospheric-scattering, procedural-noise
Clouds / fog / volumetric firevolumetric-renderingprocedural-noise, atmospheric-scattering
Sky / sunset / atmosphereatmospheric-scatteringvolumetric-rendering
Realistic lighting (PBR, Phong)lighting-modelshadow-techniques, ambient-occlusion
Shadows (soft / hard)shadow-techniqueslighting-model
Ambient occlusionambient-occlusionlighting-model, normal-estimation
Path tracing / global illuminationpath-tracing-gianalytic-ray-tracing, multipass-buffer
Precise ray-geometry intersectionsanalytic-ray-tracinglighting-model
Voxel worlds (Minecraft-style)voxel-renderinglighting-model, shadow-techniques
Noise / FBM texturesprocedural-noisedomain-warping
Tiled 2D patternsprocedural-2d-patternpolar-uv-manipulation
Voronoi / cell patternsvoronoi-cellular-noisecolor-palette
Fractals (Mandelbrot, Julia, 3D)fractal-renderingcolor-palette, polar-uv-manipulation
Color grading / palettescolor-palette
Bloom / tone mapping / glitchpost-processingmultipass-buffer
Multi-pass ping-pong buffersmultipass-buffer
Texture / sampling techniquestexture-sampling
Camera / matrix transformsmatrix-transform
Surface normalsnormal-estimation
Polar coords / kaleidoscopepolar-uv-manipulationprocedural-2d-pattern
2D shapes / UI from SDFsdf-2dcolor-palette
Procedural audio / musicsound-synthesis
SDF tricks / optimizationsdf-trickssdf-3d, ray-marching
Anti-aliased renderinganti-aliasingsdf-2d, post-processing
Depth of field / motion blur / lens effectscamera-effectspost-processing, multipass-buffer
Advanced texture mapping / no-tile texturestexture-mapping-advancedterrain-rendering, texture-sampling
WebGL2 shader errors / debuggingwebgl-pitfalls
用户想要创建...核心技术可结合使用的技术
基于数学的3D物体/场景ray-marching + sdf-3dlighting-model、shadow-techniques
复杂3D形状(布尔运算、混合)csg-boolean-operationssdf-3d、ray-marching
3D无限重复图案domain-repetitionsdf-3d、ray-marching
有机/扭曲形状domain-warpingprocedural-noise
流体/烟雾/水墨效果fluid-simulationmultipass-buffer
粒子效果(火焰、火花、雪花)particle-systemprocedural-noise、color-palette
基于物理的模拟simulation-physicsmultipass-buffer
生命游戏/反应扩散cellular-automatamultipass-buffer、color-palette
海洋/水面water-oceanatmospheric-scattering、lighting-model
地形/地貌terrain-renderingatmospheric-scattering、procedural-noise
云/雾/体积火焰volumetric-renderingprocedural-noise、atmospheric-scattering
天空/日落/大气atmospheric-scatteringvolumetric-rendering
写实光照(PBR、Phong)lighting-modelshadow-techniques、ambient-occlusion
阴影(软/硬)shadow-techniqueslighting-model
环境光遮蔽ambient-occlusionlighting-model、normal-estimation
路径追踪/全局光照path-tracing-gianalytic-ray-tracing、multipass-buffer
精确光线-几何相交analytic-ray-tracinglighting-model
体素世界(我的世界风格)voxel-renderinglighting-model、shadow-techniques
噪声/FBM纹理procedural-noisedomain-warping
平铺2D图案procedural-2d-patternpolar-uv-manipulation
Voronoi/细胞图案voronoi-cellular-noisecolor-palette
分形(曼德博集合、朱利亚集合、3D分形)fractal-renderingcolor-palette、polar-uv-manipulation
颜色分级/调色板color-palette
Bloom/色调映射/故障效果post-processingmultipass-buffer
多通道乒乓缓冲multipass-buffer
纹理/采样技术texture-sampling
相机/矩阵变换matrix-transform
表面法线normal-estimation
极坐标/万花筒polar-uv-manipulationprocedural-2d-pattern
基于SDF的2D形状/UIsdf-2dcolor-palette
程序化音频/音乐sound-synthesis
SDF技巧/优化sdf-trickssdf-3d、ray-marching
抗锯齿渲染anti-aliasingsdf-2d、post-processing
景深/运动模糊/镜头效果camera-effectspost-processing、multipass-buffer
高级纹理映射/无缝纹理texture-mapping-advancedterrain-rendering、texture-sampling
WebGL2着色器错误/调试webgl-pitfalls

Technique Index

技术索引

Geometry & SDF

几何与SDF

  • sdf-2d — 2D signed distance functions for shapes, UI, anti-aliased rendering
  • sdf-3d — 3D signed distance functions for real-time implicit surface modeling
  • csg-boolean-operations — Constructive solid geometry: union, subtraction, intersection with smooth blending
  • domain-repetition — Infinite space repetition, folding, and limited tiling
  • domain-warping — Distort domains with noise for organic, flowing shapes
  • sdf-tricks — SDF optimization, bounding volumes, binary search refinement, hollowing, layered edges, debug visualization
  • sdf-2d — 用于形状、UI和抗锯齿渲染的2D有符号距离函数
  • sdf-3d — 用于实时隐式表面建模的3D有符号距离函数
  • csg-boolean-operation — 构造实体几何:并集、差集、交集以及平滑混合
  • domain-repetition — 无限空间重复、折叠和有限平铺
  • domain-warping — 使用噪声扭曲空间以创建有机、流动的形状
  • sdf-tricks — SDF优化、包围盒、二分搜索细化、镂空、分层边缘、调试可视化

Ray Casting & Lighting

光线投射与光照

  • ray-marching — Sphere tracing with SDF for 3D scene rendering
  • analytic-ray-tracing — Closed-form ray-primitive intersections (sphere, plane, box, torus)
  • path-tracing-gi — Monte Carlo path tracing for photorealistic global illumination
  • lighting-model — Phong, Blinn-Phong, PBR (Cook-Torrance), and toon shading
  • shadow-techniques — Hard shadows, soft shadows (penumbra estimation), cascade shadows
  • ambient-occlusion — SDF-based AO, screen-space AO approximation
  • normal-estimation — Finite-difference normals, tetrahedron technique
  • ray-marching — 基于SDF的球体追踪,用于3D场景渲染
  • analytic-ray-tracing — 光线与图元的闭合形式相交计算(球体、平面、盒子、圆环)
  • path-tracing-gi — 蒙特卡洛路径追踪,用于照片级写实全局光照
  • lighting-model — Phong、Blinn-Phong、PBR(Cook-Torrance)和卡通着色
  • shadow-techniques — 硬阴影、软阴影(半影估计)、级联阴影
  • ambient-occlusion — 基于SDF的环境光遮蔽、屏幕空间环境光遮蔽近似
  • normal-estimation — 有限差分法线、四面体法

Simulation & Physics

模拟与物理

  • fluid-simulation — Navier-Stokes fluid solver with advection, diffusion, pressure projection
  • simulation-physics — GPU-based physics: springs, cloth, N-body gravity, collision
  • particle-system — Stateless and stateful particle systems (fire, rain, sparks, galaxies)
  • cellular-automata — Game of Life, reaction-diffusion (Turing patterns), sand simulation
  • fluid-simulation — 包含平流、扩散、压力投影的Navier-Stokes流体求解器
  • simulation-physics — 基于GPU的物理模拟:弹簧、布料、N体引力、碰撞
  • particle-system — 无状态和有状态粒子系统(火焰、雨水、火花、星系)
  • cellular-automata — 生命游戏、反应扩散(图灵图案)、沙子模拟

Natural Phenomena

自然现象

  • water-ocean — Gerstner waves, FFT ocean, caustics, underwater fog
  • terrain-rendering — Heightfield ray marching, FBM terrain, erosion
  • atmospheric-scattering — Rayleigh/Mie scattering, god rays, SSS approximation
  • volumetric-rendering — Volume ray marching for clouds, fog, fire, explosions
  • water-ocean — Gerstner波浪、FFT海洋、焦散、水下雾
  • terrain-rendering — 高度场光线步进、FBM地形、侵蚀效果
  • atmospheric-scattering — Rayleigh/Mie散射、上帝光线、次表面散射近似
  • volumetric-rendering — 体积光线步进,用于云、雾、火焰、爆炸效果

Procedural Generation

程序化生成

  • procedural-noise — Value noise, Perlin, Simplex, Worley, FBM, ridged noise
  • procedural-2d-pattern — Brick, hexagon, truchet, Islamic geometric patterns
  • voronoi-cellular-noise — Voronoi diagrams, Worley noise, cracked earth, crystal
  • fractal-rendering — Mandelbrot, Julia sets, 3D fractals (Mandelbox, Mandelbulb)
  • color-palette — Cosine palettes, HSL/HSV/Oklab, dynamic color mapping
  • procedural-noise — 值噪声、Perlin噪声、Simplex噪声、Worley噪声、FBM、脊状噪声
  • procedural-2d-pattern — 砖块、六边形、Truchet、伊斯兰几何图案
  • voronoi-cellular-noise — Voronoi图、Worley噪声、裂纹地面、晶体效果
  • fractal-rendering — 曼德博集合、朱利亚集合、3D分形(Mandelbox、Mandelbulb)
  • color-palette — 余弦调色板、HSL/HSV/Oklab、动态颜色映射

Post-Processing & Infrastructure

后期处理与基础设施

  • post-processing — Bloom, tone mapping (ACES, Reinhard), vignette, chromatic aberration, glitch
  • multipass-buffer — Ping-pong FBO setup, state persistence across frames
  • texture-sampling — Bilinear, bicubic, mipmap, procedural texture lookup
  • matrix-transform — Camera look-at, projection, rotation, orbit controls
  • polar-uv-manipulation — Polar/log-polar coordinates, kaleidoscope, spiral mapping
  • anti-aliasing — SSAA, SDF analytical AA, temporal anti-aliasing (TAA), FXAA post-process
  • camera-effects — Depth of field (thin lens), motion blur, lens distortion, film grain, vignette
  • texture-mapping-advanced — Biplanar mapping, texture repetition avoidance, ray differential filtering
  • post-processing — Bloom、色调映射(ACES、Reinhard)、暗角、色差、故障效果
  • multipass-buffer — 乒乓FBO设置、跨帧状态持久化
  • texture-sampling — 双线性、双三次、Mipmap、程序化纹理查找
  • matrix-transform — 相机看向、投影、旋转、轨道控制
  • polar-uv-manipulation — 极坐标/对数极坐标、万花筒、螺旋映射
  • anti-aliasing — SSAA、基于SDF的解析抗锯齿、时间抗锯齿(TAA)、FXAA后期处理
  • camera-effects — 景深(薄透镜)、运动模糊、镜头畸变、胶片颗粒、暗角
  • texture-mapping-advanced — 双平面映射、避免纹理重复、光线微分过滤

Audio

音频

  • sound-synthesis — Procedural audio in GLSL: oscillators, envelopes, filters, FM synthesis
  • sound-synthesis — GLSL中的程序化音频:振荡器、包络、滤波器、调频合成

Debugging & Validation

调试与验证

  • webgl-pitfalls — Common WebGL2/GLSL errors:
    fragCoord
    ,
    main()
    wrapper, function order, macro limitations, uniform null
  • webgl-pitfalls — WebGL2/GLSL常见错误:
    fragCoord
    main()
    包装器、函数顺序、宏限制、uniform为空

WebGL2 Adaptation Rules

WebGL2适配规则

All technique files use ShaderToy GLSL style. When generating standalone HTML pages, apply these adaptations:
所有技术文件均使用ShaderToy风格的GLSL。生成独立HTML页面时,需遵循以下适配规则:

Shader Version & Output

着色器版本与输出

  • Use
    canvas.getContext("webgl2")
  • Shader first line:
    #version 300 es
    , fragment shader adds
    precision highp float;
  • Fragment shader must declare:
    out vec4 fragColor;
  • Vertex shader:
    attribute
    in
    ,
    varying
    out
  • Fragment shader:
    varying
    in
    ,
    gl_FragColor
    fragColor
    ,
    texture2D()
    texture()
  • 使用
    canvas.getContext("webgl2")
  • 着色器第一行:
    #version 300 es
    ,片段着色器需添加
    precision highp float;
  • 片段着色器必须声明:
    out vec4 fragColor;
  • 顶点着色器:
    attribute
    替换为
    in
    varying
    替换为
    out
  • 片段着色器:
    varying
    替换为
    in
    gl_FragColor
    替换为
    fragColor
    texture2D()
    替换为
    texture()

Fragment Coordinate

片段坐标

  • Use
    gl_FragCoord.xy
    instead of
    fragCoord
    (WebGL2 does not have
    fragCoord
    built-in)
glsl
// WRONG
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
// CORRECT
vec2 uv = (2.0 * gl_FragCoord.xy - iResolution.xy) / iResolution.y;
  • 使用
    gl_FragCoord.xy
    替代
    fragCoord
    (WebGL2不内置
    fragCoord
glsl
// 错误写法
vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;
// 正确写法
vec2 uv = (2.0 * gl_FragCoord.xy - iResolution.xy) / iResolution.y;

main() Wrapper for ShaderToy Templates

ShaderToy模板的main()包装器

  • ShaderToy uses
    void mainImage(out vec4 fragColor, in vec2 fragCoord)
  • WebGL2 requires standard
    void main()
    entry point — always wrap mainImage:
glsl
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    // shader code...
    fragColor = vec4(col, 1.0);
}

void main() {
    mainImage(fragColor, gl_FragCoord.xy);
}
  • ShaderToy使用
    void mainImage(out vec4 fragColor, in vec2 fragCoord)
  • WebGL2要求标准的
    void main()
    入口点——必须始终包装mainImage:
glsl
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
    // 着色器代码...
    fragColor = vec4(col, 1.0);
}

void main() {
    mainImage(fragColor, gl_FragCoord.xy);
}

Function Declaration Order

函数声明顺序

  • GLSL requires functions to be declared before use — either declare before use or reorder:
glsl
// WRONG — getAtmosphere() calls getSunDirection() before it's defined
vec3 getAtmosphere(vec3 dir) { return getSunDirection(); } // Error!
vec3 getSunDirection() { return normalize(vec3(1.0)); }

// CORRECT — define callee first
vec3 getSunDirection() { return normalize(vec3(1.0)); }
vec3 getAtmosphere(vec3 dir) { return getSunDirection(); } // Works
  • GLSL要求函数在使用前声明——要么提前声明,要么调整顺序:
glsl
// 错误写法 — getAtmosphere()在getSunDirection()定义前调用它
vec3 getAtmosphere(vec3 dir) { return getSunDirection(); } // 错误!
vec3 getSunDirection() { return normalize(vec3(1.0)); }

// 正确写法 — 先定义被调用的函数
vec3 getSunDirection() { return normalize(vec3(1.0)); }
vec3 getAtmosphere(vec3 dir) { return getSunDirection(); } // 可正常运行

Macro Limitations

宏限制

  • #define
    cannot use function calls — use
    const
    instead:
glsl
// WRONG
#define SUN_DIR normalize(vec3(0.8, 0.4, -0.6))

// CORRECT
const vec3 SUN_DIR = vec3(0.756, 0.378, -0.567); // Pre-computed normalized value
  • #define
    不能使用函数调用——改用
    const
glsl
// 错误写法
#define SUN_DIR normalize(vec3(0.8, 0.4, -0.6))

// 正确写法
const vec3 SUN_DIR = vec3(0.756, 0.378, -0.567); // 预计算的归一化值

Script Tag Extraction

脚本标签提取

  • When extracting shader source from
    <script>
    tags, ensure
    #version
    is the first character — use
    .trim()
    :
javascript
const fs = document.getElementById('fs').text.trim();
  • <script>
    标签中提取着色器源码时,确保
    #version
    第一个字符——使用
    .trim()
javascript
const fs = document.getElementById('fs').text.trim();

Common Pitfalls

常见陷阱

  • Unused uniforms: Compiler may optimize away unused uniforms, causing
    gl.getUniformLocation()
    to return
    null
    — always use uniforms in a way the compiler cannot optimize out
  • Loop indices: Use runtime constants in loops, not
    #define
    macros in some ES versions
  • Terrain functions: Functions like
    terrainM(vec2)
    need XZ components — use
    terrainM(pos.xz + offset)
    not
    terrainM(pos + offset)
  • 未使用的uniform:编译器可能会优化掉未使用的uniform,导致
    gl.getUniformLocation()
    返回
    null
    ——务必以编译器无法优化的方式使用uniform
  • 循环索引:在某些ES版本中,循环需使用运行时常量,而非
    #define
  • 地形函数:类似
    terrainM(vec2)
    的函数需要XZ分量——使用
    terrainM(pos.xz + offset)
    而非
    terrainM(pos + offset)

HTML Page Setup

HTML页面设置

When generating a standalone HTML page:
  • Canvas fills the entire viewport, auto-resizes on window resize
  • Page background black, no scrollbars:
    body { margin: 0; overflow: hidden; background: #000; }
  • Implement ShaderToy-compatible uniforms:
    iTime
    ,
    iResolution
    ,
    iMouse
    ,
    iFrame
  • For multi-pass effects (Buffer A/B), use WebGL2 framebuffer + ping-pong (see multipass-buffer technique)
生成独立HTML页面时:
  • Canvas填充整个视口,窗口大小改变时自动调整
  • 页面背景为黑色,无滚动条:
    body { margin: 0; overflow: hidden; background: #000; }
  • 实现兼容ShaderToy的uniform:
    iTime
    iResolution
    iMouse
    iFrame
  • 对于多通道效果(Buffer A/B),使用WebGL2帧缓冲+乒乓缓冲(参考multipass-buffer技术)

Common Pitfalls

常见陷阱

JS Variable Declaration Order (TDZ — causes white screen crash)

JS变量声明顺序(TDZ — 导致白屏崩溃)

let
/
const
variables must be declared at the top of the
<script>
block, before any function that references them:
javascript
// 1. State variables FIRST
let frameCount = 0;
let startTime = Date.now();

// 2. Canvas/GL init, shader compile, FBO creation
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl2');
// ...

// 3. Functions and event bindings LAST
function resize() { /* can now safely reference frameCount */ }
function render() { /* ... */ }
window.addEventListener('resize', resize);
Reason:
let
/
const
have a Temporal Dead Zone — referencing them before declaration throws
ReferenceError
, causing a white screen.
let
/
const
变量必须在
<script>
块的顶部声明,早于任何引用它们的函数:
javascript
// 1. 状态变量优先声明
let frameCount = 0;
let startTime = Date.now();

// 2. Canvas/GL初始化、着色器编译、FBO创建
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl2');
// ...

// 3. 函数和事件绑定最后定义
function resize() { /* 现在可以安全引用frameCount */ }
function render() { /* ... */ }
window.addEventListener('resize', resize);
原因:
let
/
const
存在暂时性死区——在声明前引用会抛出
ReferenceError
,导致页面白屏。

GLSL Compilation Errors (self-check after writing shaders)

GLSL编译错误(编写着色器后自查)

  • Function signature mismatch: Call must exactly match definition in parameter count and types. If defined as
    float fbm(vec3 p)
    , cannot call
    fbm(uv)
    with a
    vec2
  • Reserved words as variable names: Do not use:
    patch
    ,
    cast
    ,
    sample
    ,
    filter
    ,
    input
    ,
    output
    ,
    common
    ,
    partition
    ,
    active
  • Strict type matching:
    vec3 x = 1.0
    is illegal — use
    vec3 x = vec3(1.0)
    ; cannot use
    .z
    to access a
    vec2
  • No ternary on structs: ESSL does not allow ternary operator on struct types — use
    if
    /
    else
    instead
  • 函数签名不匹配:调用必须与定义的参数数量和类型完全一致。如果定义为
    float fbm(vec3 p)
    ,则不能用
    vec2
    类型的
    uv
    调用
    fbm(uv)
  • 使用保留字作为变量名:请勿使用以下词汇:
    patch
    cast
    sample
    filter
    input
    output
    common
    partition
    active
  • 严格类型匹配
    vec3 x = 1.0
    是非法的——需使用
    vec3 x = vec3(1.0)
    ;不能用
    .z
    访问
    vec2
    类型变量
  • 结构体不能使用三元运算符:ESSL不允许对结构体类型使用三元运算符——改用
    if
    /
    else

Performance Budget

性能预算

Deployment environments may use headless software rendering with limited GPU power. Stay within these limits:
  • Ray marching main loop: ≤ 128 steps
  • Volume sampling / lighting inner loops: ≤ 32 steps
  • FBM octaves: ≤ 6 layers
  • Total nested loop iterations per pixel: ≤ 1000 (exceeding this freezes the browser)
部署环境可能使用GPU性能有限的无头软件渲染。请遵守以下限制:
  • 光线步进主循环:≤ 128步
  • 体积采样/光照内循环:≤ 32步
  • FBM八度层数:≤ 6层
  • 每像素总嵌套循环迭代次数:≤ 1000(超过此值会导致浏览器冻结)

Quick Recipes

快速方案

Common effect combinations — complete rendering pipelines assembled from technique modules.
常见效果组合——由技术模块组装而成的完整渲染管线。

Photorealistic SDF Scene

照片级写实SDF场景

  1. Geometry: sdf-3d (extended primitives) + csg-boolean-operations (cubic/quartic smin)
  2. Rendering: ray-marching + normal-estimation (tetrahedron method)
  3. Lighting: lighting-model (outdoor three-light model) + shadow-techniques (improved soft shadow) + ambient-occlusion
  4. Atmosphere: atmospheric-scattering (height-based fog with sun tint)
  5. Post: post-processing (ACES tone mapping) + anti-aliasing (2x SSAA) + camera-effects (vignette)
  1. 几何:sdf-3d(扩展图元) + csg-boolean-operations(三次/四次smin平滑)
  2. 渲染:ray-marching + normal-estimation(四面体法)
  3. 光照:lighting-model(户外三光源模型) + shadow-techniques(改进型软阴影) + ambient-occlusion
  4. 大气:atmospheric-scattering(基于高度的雾效与太阳色调)
  5. 后期:post-processing(ACES色调映射) + anti-aliasing(2x SSAA) + camera-effects(暗角)

Organic / Biological Forms

有机/生物形态

  1. Geometry: sdf-3d (extended primitives + deformation operators: twist, bend) + csg-boolean (gradient-aware smin for material blending)
  2. Detail: procedural-noise (FBM with derivatives) + domain-warping
  3. Surface: lighting-model (subsurface scattering approximation via half-Lambert)
  1. 几何:sdf-3d(扩展图元 + 变形操作:扭曲、弯曲) + csg-boolean(基于梯度的smin材质混合)
  2. 细节:procedural-noise(带导数的FBM) + domain-warping
  3. 表面:lighting-model(基于半兰伯特的次表面散射近似)

Procedural Landscape

程序化地形

  1. Terrain: terrain-rendering + procedural-noise (erosion FBM with derivatives)
  2. Texturing: texture-mapping-advanced (biplanar mapping + no-tile)
  3. Sky: atmospheric-scattering (Rayleigh/Mie + height fog)
  4. Water: water-ocean (Gerstner waves) + lighting-model (Fresnel reflections)
  1. 地形:terrain-rendering + procedural-noise(带导数的侵蚀FBM)
  2. 纹理:texture-mapping-advanced(双平面映射 + 无缝)
  3. 天空:atmospheric-scattering(Rayleigh/Mie散射 + 高度雾)
  4. 水体:water-ocean(Gerstner波浪) + lighting-model(菲涅尔反射)

Stylized 2D Art

风格化2D艺术

  1. Shapes: sdf-2d (extended library) + sdf-tricks (layered edges, hollowing)
  2. Color: color-palette (cosine palettes) + polar-uv-manipulation (kaleidoscope)
  3. Polish: anti-aliasing (SDF analytical AA) + post-processing (bloom, chromatic aberration)
  1. 形状:sdf-2d(扩展库) + sdf-tricks(分层边缘、镂空)
  2. 颜色:color-palette(余弦调色板) + polar-uv-manipulation(万花筒)
  3. 润色:anti-aliasing(基于SDF的解析抗锯齿) + post-processing(Bloom、色差)

Shader Debugging Techniques

着色器调试技巧

Visual debugging methods — temporarily replace your output to diagnose issues.
What to checkCodeWhat to look for
Surface normals
col = nor * 0.5 + 0.5;
Smooth gradients = correct normals; banding = epsilon too large
Ray march step count
col = vec3(float(steps) / float(MAX_STEPS));
Red hotspots = performance bottleneck; uniform = wasted iterations
Depth / distance
col = vec3(t / MAX_DIST);
Verify correct hit distances
UV coordinates
col = vec3(uv, 0.0);
Check coordinate mapping
SDF distance field
col = (d > 0.0 ? vec3(0.9,0.6,0.3) : vec3(0.4,0.7,0.85)) * (0.8 + 0.2*cos(150.0*d));
Visualize SDF bands and zero-crossing
Checker pattern (UV)
col = vec3(mod(floor(uv.x*10.)+floor(uv.y*10.), 2.0));
Verify UV distortion, seams
Lighting only
col = vec3(shadow);
or
col = vec3(ao);
Isolate shadow/AO contributions
Material ID
col = palette(matId / maxMatId);
Verify material assignment
可视化调试方法——临时替换输出以诊断问题。
检查内容代码观察要点
表面法线
col = nor * 0.5 + 0.5;
平滑渐变=法线正确;条带化=epsilon值过大
光线步进步数
col = vec3(float(steps) / float(MAX_STEPS));
红色热点=性能瓶颈;颜色均匀=迭代次数浪费
深度/距离
col = vec3(t / MAX_DIST);
验证正确的命中距离
UV坐标
col = vec3(uv, 0.0);
检查坐标映射
SDF距离场
col = (d > 0.0 ? vec3(0.9,0.6,0.3) : vec3(0.4,0.7,0.85)) * (0.8 + 0.2*cos(150.0*d));
可视化SDF条带和零交叉点
棋盘格图案(UV)
col = vec3(mod(floor(uv.x*10.)+floor(uv.y*10.), 2.0));
验证UV扭曲、接缝
仅光照
col = vec3(shadow);
col = vec3(ao);
隔离阴影/环境光遮蔽的贡献
材质ID
col = palette(matId / maxMatId);
验证材质分配