GLSL and Shadertoy shader skills for Claude Code, Codex, Cursor, Copilot and Gemini CLI. 186 functions, SDF raymarching, procedural terrain, water, clouds and generative art, with a bundler, checker and 11 examples.
Python agent-skillsclaude-codecodexcomputer-graphicscursorgemini-cligenerative-artgithub-copilotglslnoiseprocedural-artprocedural-generationraymarchingshadersshadertoysigned-distance-functionsterrain-generationwebglwebgl2
Rebuild shader-skills around a verified GLSL library (v2)
Gökay6cdc03e39e55
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonnew file mode 100644index 0000000..c24ce1a--- /dev/null+++ b/.claude-plugin/marketplace.json@@ -0,0 +1,14 @@+{+ "name": "shader-skills",+ "description": "Procedural shader art skills for coding agents",+ "owner": { "name": "gokayfem", "url": "https://github.com/gokayfem" },+ "plugins": [+ {+ "name": "shader-skills",+ "source": "./",+ "description": "Procedural GLSL / Shadertoy shaders with a verified building-block library",+ "category": "development",+ "tags": ["glsl", "shadertoy", "webgl", "sdf", "raymarching"]+ }+ ]+}diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonnew file mode 100644index 0000000..0e7ff42--- /dev/null+++ b/.claude-plugin/plugin.json@@ -0,0 +1,11 @@+{+ "name": "shader-skills",+ "displayName": "Shader Skills",+ "version": "2.0.0",+ "description": "Procedural GLSL / Shadertoy shader skill: a verified building-block library (SDFs, noise, raymarching, shading, color, volumes) with a bundler, checker, templates and references.",+ "author": { "name": "gokayfem", "url": "https://github.com/gokayfem" },+ "homepage": "https://github.com/gokayfem/shader-skills",+ "repository": "https://github.com/gokayfem/shader-skills",+ "license": "MIT",+ "keywords": ["glsl", "shadertoy", "webgl", "shader", "sdf", "raymarching", "procedural", "noise", "generative-art"]+}diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.mddeleted file mode 100644index 06feeb9..0000000--- a/.claude/CLAUDE.md+++ /dev/null@@ -1,8 +0,0 @@-# Claude Project Instructions--Read:--- `prompts/universal-system-prompt.md`-- `prompts/claude-project-instructions.md`--Use the references in `skills/codex/shader-art-coding/references/` as the shader knowledge base.diff --git a/.cursor/rules/shader-art-coding.mdc b/.cursor/rules/shader-art-coding.mdcdeleted file mode 100644index f48cc72..0000000--- a/.cursor/rules/shader-art-coding.mdc+++ /dev/null@@ -1,24 +0,0 @@-----description: Procedural shader art coding rules for GLSL, Shadertoy, SDF, heightfield, material, and atmospheric shaders-globs:- - "**/*.frag"- - "**/*.glsl"- - "shaders/**"-alwaysApply: false------Read `prompts/universal-system-prompt.md` and relevant references in `skills/codex/shader-art-coding/references/`.--Use Shadertoy-compatible GLSL by default. Keep `mainImage(out vec4 fragColor, in vec2 fragCoord)`.--Use `iDebugMode`:--- `0`: final render-- `1`: scalar field / SDF contours-- `2`: normals-- `3`: material IDs-- `4`: step count / depth-- `5`: masks / density-- `6`: lighting terms--Use formal mathematical helper names for reusable code. Run `npm run check` after substantial shader changes.diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mddeleted file mode 100644index 3703578..0000000--- a/.github/copilot-instructions.md+++ /dev/null@@ -1,8 +0,0 @@-# Copilot Instructions--This repo is a procedural shader art instruction pack.--- Use `prompts/universal-system-prompt.md` for global shader behavior.-- Use `skills/codex/shader-art-coding/references/` for formulas and GLSL snippets.-- Use `iDebugMode` branches for formula verification.-- Prefer formal mathematical naming for reusable helpers.diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.ymlnew file mode 100644index 0000000..39ca46e--- /dev/null+++ b/.github/workflows/checks.yml@@ -0,0 +1,47 @@+name: checks++on:+ push:+ branches: [main]+ pull_request:++jobs:+ static:+ name: lint, drift, glslang compile+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - name: Install glslang+ run: sudo apt-get update && sudo apt-get install -y glslang-tools+ - name: Library index is up to date+ run: python3 skills/shader-art-coding/scripts/glsl_tools.py index --check+ - name: Gallery bundles are up to date+ run: python3 tests/build_gallery.py --check+ - name: Lint, drift and compile every unit+ run: python3 skills/shader-art-coding/scripts/glsl_tools.py check++ webgl:+ name: WebGL2 compile, GPU property tests, renders+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.12"+ - name: Install Playwright Chromium+ run: |+ pip install playwright==1.49.1+ python -m playwright install --with-deps chromium+ - name: Run harness (SwiftShader)+ run: python tests/run_webgl.py --size 320x180+ - name: Upload results+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: webgl-results+ path: |+ build/webgl-results.json+ build/harness.htmldiff --git a/.gitignore b/.gitignoreindex e71883a..ea206fe 100644--- a/.gitignore+++ b/.gitignore@@ -5,3 +5,6 @@ tmp/*.mp3*.wav*.webm+build/+.claude/launch.json+__pycache__/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..007c5e1--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,50 @@+# AGENTS.md++Guidance for coding agents (Claude Code, Codex, Cursor, Copilot, Gemini) working on this repository. To use the+skill rather than develop it, see the README.++## Layout++```text+skills/shader-art-coding/ the skill (this is what gets installed)+ SKILL.md entry point: workflow, conventions, hard rules, reference routing+ glsl/ building-block library, one module per file (see MODULE_ORDER in glsl_tools.py)+ templates/ complete shaders written against the library (rendered in gallery/)+ references/ guides and formula-code couples; library-index.md is generated+ scripts/glsl_tools.py search | bundle | check | index (stdlib Python only)+tests/ GPU property tests and the WebGL2 harness+gallery/ rendered PNGs and paste-ready bundled shaders for each template (generated)+adapters/ copy-in prompts for tools without skill support+.claude-plugin/ Claude Code plugin + marketplace manifests+```++## Commands++```bash+python3 skills/shader-art-coding/scripts/glsl_tools.py check # lint + drift + glslang compile (if installed)+python3 skills/shader-art-coding/scripts/glsl_tools.py index # regenerate references/library-index.md+python3 tests/build_gallery.py # regenerate gallery/*.glsl bundles+python3 tests/build_harness.py && python3 tests/serve.py # WebGL2 checks: open /build/harness.html+python3 tests/build_harness.py --save-gallery # same, and rewrite gallery/*.png+python3 tests/run_webgl.py # headless WebGL2 checks (needs playwright)+```++## Rules for library code (`glsl/`)++- GLSL ES 3.00, Shadertoy-compatible, original implementations. Credit the technique's source in `@see` and in+ CREDITS.md; never paste third-party shader code (Shadertoy's default license is CC BY-NC-SA).+- Every function has a `///` doc comment: one-line summary, `@use` with concrete subjects, and for SDFs one of+ `@exact`, `@bound` or `@approx`. `check` enforces this.+- A module may only call modules listed before it in `MODULE_ORDER`.+- Every new SDF gets a property test in `tests/properties.py` with inside and outside points. The harness checks the+ Lipschitz bound, exactness by surface projection, and signs on the GPU. A new non-SDF helper gets a property test+ when it has a checkable invariant (range, round trip, derivative, divergence).+- References may show library functions only verbatim. `check` fails on drift, so rename deliberate variants.+- After changing `glsl/`, regenerate the index and the gallery bundles. After changing templates, re-render the+ gallery PNGs with the harness and look at them.++## Definition of done++`glsl_tools.py check` passes. The WebGL2 harness reports all units compiled, all property tests passing and all+renders passing. `library-index.md` and `gallery/*.glsl` are regenerated, and any changed template renders look+right.diff --git a/CLAUDE.md b/CLAUDE.mddeleted file mode 100644index 535fb48..0000000--- a/CLAUDE.md+++ /dev/null@@ -1,5 +0,0 @@-# Claude Instructions--Read `prompts/claude-project-instructions.md` and `prompts/universal-system-prompt.md`.--Use this repository as a procedural shader art instruction library. For shader implementation, use debug modes and the formal formula-code references.diff --git a/CREDITS.md b/CREDITS.mdnew file mode 100644index 0000000..6834157--- /dev/null+++ b/CREDITS.md@@ -0,0 +1,29 @@+# Credits and Sources++All GLSL in this repository is an original implementation, released under the MIT license (see LICENSE). The+techniques come from the published work below. Numeric constants (matrices, fit coefficients, physical+coefficients) are facts reproduced from their sources. No third-party shader source is copied; Shadertoy shaders+default to CC BY-NC-SA 3.0, which is incompatible with MIT.++| Technique | Source | License or terms of the source |+|---|---|---|+| SDF primitives, operators, smooth minimum, domain repetition, normals, soft shadows, intersectors, fog, palettes, filtered patterns, Voronoi borders, noise derivatives, domain warping | Inigo Quilez, iquilezles.org/articles | articles state no license; ideas reimplemented |+| Chamfer, stairs and engrave combinators, polar and mirrored repetition | Mercury demogroup, hg_sdf (mercury.sexy/hg_sdf) | MIT OR CC BY-NC 4.0 |+| PCG hashes (pcgHash, pcg3d, pcg4d) and hash quality data | Jarzynski and Olano, "Hash Functions for GPU Rendering", JCGT 9(3), 2020 | paper CC BY-ND 3.0; arithmetic reimplemented |+| Interleaved gradient noise | Jorge Jimenez, "Next Generation Post Processing in Call of Duty: Advanced Warfare", SIGGRAPH 2014 | constants are facts |+| R2 low-discrepancy sequence | Martin Roberts, "The Unreasonable Effectiveness of Quasirandom Sequences" | constants are facts |+| Curl noise | Bridson, Hourihan and Nordenstam, SIGGRAPH 2007 | math |+| Enhanced (over-relaxed) sphere tracing (documented, not shipped) | Keinert et al., STAG 2014 | math |+| AgX tonemapping (minimal polynomial version) | Troy Sobotka (AgX); Benjamin Wrensch / iolite (polynomial fit) | MIT |+| Khronos PBR Neutral tonemapping | Khronos Group, github.com/KhronosGroup/ToneMapping | Apache-2.0 (constants) |+| ACES fitted (RRT+ODT) | Stephen Hill, via MJP's BakingLab | MIT |+| Oklab / OkLCh | Bjorn Ottosson, bottosson.github.io/posts/oklab | public domain / MIT |+| Blackbody chromaticity | Krystek 1985 Planckian-locus fit | math |+| GGX, height-correlated Smith visibility, Schlick Fresnel | Filament documentation (Google) | Apache-2.0 (formulas) |+| Environment BRDF approximation | Brian Karis, "Physically Based Shading on Mobile" (after Lazarov) | constants are facts |+| Energy-conserving wrap lighting | Stephen Hill, "Righting Wrap" (2011) | math |+| Fast translucency | Barre-Brisebois and Bouchard, GDC 2011 | math |+| Energy-conserving volume integration, sky constants | Sebastien Hillaire, Frostbite (SIGGRAPH 2015/2016) and EGSR 2020 | math, constants are facts |+| Beer-Powder cloud lighting, dual-lobe phase | Andrew Schneider, Horizon Zero Dawn clouds (SIGGRAPH 2015) | math |+| Sun limb darkening | Neckel 1996 | constants are facts |+| Cornette-Shanks phase function | Cornette and Shanks 1992 | math |diff --git a/README.md b/README.mdindex 294847d..6c45f6f 100644--- a/README.md+++ b/README.md@@ -1,76 +1,149 @@# Shader Skills-Platform-neutral procedural shader intelligence for LLM coding agents.+A skill that teaches coding agents to write procedural GLSL shaders that compile on the first try and look+intentional. It works with Claude Code, Codex, Cursor, Copilot, Gemini and others. It pairs a shader-craft+workflow with a **verified GLSL building-block library**: 169 functions across 18 modules, each one compiled in+WebGL2 and numerically tested on the GPU. A bundler inlines exactly the functions a shader uses, so the result+pastes straight into Shadertoy.++| | | |+|---|---|---|+| [](gallery/raymarch-sdf.glsl) | [](gallery/terrain.glsl) | [](gallery/volumetric-clouds.glsl) |+| SDF still life: smooth blends with blended materials, PBR, soft shadows, AO, AgX | Eroded terrain under a physically based sky with aerial perspective | Volumetric cumulus: energy-conserving integration, Beer-Powder, dual-lobe phase |+| [](gallery/sdf-2d-poster.glsl) | [](gallery/pattern-swatches.glsl) | |+| 2D distance-field poster: Oklab gradients, polar leaves, Bézier trunks | Texture-free materials: warped marble, Voronoi cracks, hex tiles, Truchet, filtered checker | |++Each image links to its paste-ready shader. The sources are in [`skills/shader-art-coding/templates/`](skills/shader-art-coding/templates/).++## Why++Agents write shaders blind: they cannot see the output, they misremember formulas, and WebGL rejects code that+desktop GLSL accepts. Common results are struct ternaries, sine hashes that differ per GPU, SDFs with wrong signs,+double gamma, and fog that ignores the sky. This skill closes those gaps:++- **Tested building blocks instead of recalled ones.** Every SDF is checked on the GPU:+ - the Lipschitz bound (safe to raymarch);+ - exactness, by projecting points onto the surface;+ - inside/outside signs;+ - for curves, agreement with brute-force distance.++ Noise derivatives are checked against finite differences, curl noise for zero divergence, color transforms for+ round trips, and intersectors against their SDFs.+- **A bundler,** so the agent writes `sdRoundCone(...)`, `softShadow(...)`, `tonemapAgX(...)` by name and ships one+ self-contained file.+- **A checker** that catches WebGL1 leftovers, sine hashes, `#version` lines and missing `mainImage`, and compiles+ with glslangValidator.+- **A workflow** with a fixed debug-mode convention, so problems are inspected as fields rather than guessed at.+- **Routing** from subjects ("a jellyfish", "snowy mountains") to techniques, templates and formulas.++## Install++**Claude Code** (plugin marketplace):-This repository packages the same shader-craft knowledge for multiple assistants:--- Codex skill: `skills/codex/shader-art-coding`-- Hermes Agent skill: copy `skills/codex/shader-art-coding` to `~/.hermes/skills/shader-art-coding`, or add the parent skills directory as a Hermes external skill directory.-- Universal prompt: `prompts/universal-system-prompt.md`-- Claude project instructions: `CLAUDE.md` and `.claude/CLAUDE.md`-- Cursor rules: `.cursor/rules/shader-art-coding.mdc`-- GitHub Copilot instructions: `.github/copilot-instructions.md`-- ChatGPT/GPT builder instructions: `prompts/chatgpt-custom-gpt-instructions.md`-- Gemini/Gems instructions: `prompts/gemini-gems-instructions.md`--The references are written as formal mathematical construction manuals: implicit surfaces, SDF operators, heightfields, scalar masks, material fields, atmospheric coverage, and debug views.--## Debug Modes--Use `iDebugMode` in serious shaders:--- `0`: final render-- `1`: scalar field / SDF contours-- `2`: normals-- `3`: material IDs-- `4`: step count / depth-- `5`: masks / density-- `6`: lighting terms--## Recommended Agent Workflow+```bash+claude plugin marketplace add gokayfem/shader-skills+```-Give your assistant one of the adapter prompts, then ask it to:+```bash+claude plugin install shader-skills@shader-skills+```-1. Read the universal instructions.-2. Pick relevant references only.-3. Produce shader code using formal equation-code construction.-4. Include debug modes for formula verification.-5. Iterate on formulas, not guesses.+Or copy the skill: `cp -R skills/shader-art-coding ~/.claude/skills/`.-Example:+**Codex, Cursor, Gemini CLI, Copilot and about 70 other agents** (via [skills](https://github.com/vercel-labs/skills)):-```text-Use the shader-art-coding instructions in this repo. Create a Shadertoy GLSL shader using formal SDF and heightfield construction, and explain the debug modes.+```bash+npx skills add gokayfem/shader-skills```-## Hermes Agent+Or install by hand:+- **Codex:** copy `skills/shader-art-coding` to `~/.agents/skills/`.+- **Cursor:** copy it to `~/.cursor/skills/`, plus the rule in `adapters/cursor/`.+- **Copilot:** `gh skill install gokayfem/shader-skills shader-art-coding`, plus `adapters/copilot/`.+- **Gemini CLI:** `gemini extensions install https://github.com/gokayfem/shader-skills`.+- **Hermes:** copy it to `~/.hermes/skills/`.-Hermes uses `SKILL.md` directories with progressive reference loading, so the bundled skill can be used directly.+**claude.ai:** zip `skills/shader-art-coding` and upload it under Settings > Capabilities > Skills.-Install by copying the skill directory:+**ChatGPT, Gemini Gems and other chat tools:** see [`adapters/`](adapters/).-```bash-mkdir -p ~/.hermes/skills-cp -R skills/codex/shader-art-coding ~/.hermes/skills/shader-art-coding-```+## Use-Or point Hermes at a shared skill directory in `~/.hermes/config.yaml`:+Ask naturally: *"Make a Shadertoy shader of a glass jellyfish drifting through god rays"*, or *"why does my+raymarcher have holes?"* The skill routes the request, then the agent finds blocks, writes the shader, bundles it+and checks it:-```yaml-skills:- external_dirs:- - /path/to/shader-skills/skills/codex+```bash+python3 scripts/glsl_tools.py search petal leaf+python3 scripts/glsl_tools.py bundle jellyfish.glsl -o jellyfish.out.glsl+python3 scripts/glsl_tools.py check jellyfish.out.glsl```-Then invoke it as `/shader-art-coding` or ask naturally for shader art, GLSL, Shadertoy, SDF, heightfield, raymarching, noise, or material-field work.--## Repository Layout+What the commands do:+- `search` ranks functions by name, summary and `@use` tags.+- `bundle` resolves dependencies transitively and emits them in declaration order.+- `check` lints the file and compiles it when `glslangValidator` is installed (`brew install glslang` or+ `apt install glslang-tools`).++## What's in the library++| Module | Highlights |+|---|---|+| `hash` | PCG integer hashes (`pcg3d`, `pcg4d`): bit-exact across GPUs, no sine; safe integer-input float wrappers |+| `noise` | value and gradient noise with analytic derivatives, fBm, eroded fBm, ridged fBm, two-level domain warp, curl noise, Voronoi (F1/F2, exact borders, smooth), interleaved-gradient and R2 dithering |+| `pattern` | box-filtered checker, grid and stripes (alias-free with no supersampling), hex grid with edge distance, Truchet |+| `sdf3d` | 22 primitives including exact capped cone, round cone, cut and hollow spheres, death star, hex prism, link, gyroid, 3D Bézier tube |+| `sdf2d` | 16 primitives including vesica, moon, heart, star, regular polygon, rounded box with per-corner radii, quadratic Bézier |+| `operators` | smooth min/max/subtract (quadratic and C2 cubic), smooth union with material blend weight, chamfer, stairs, engrave, round, onion, extrude, revolve, exact elongate |+| `domain` | repetition (infinite, limited, mirrored), polar sectors, folds, twist and bend with their Lipschitz corrections |+| `raymarch` | sphere tracing with distance-relative hit threshold, tetrahedral normals, improved soft shadows, AO, thickness; WebGL-safe loops |+| `shading` | GGX + height-correlated Smith + Schlick, metallic-roughness `shadePBR`, environment BRDF approximation, wrap diffuse, translucency, rim |+| `color` / `tonemap` | exact sRGB curves, Oklab / OkLCh mixing, blackbody colors; AgX (default), AgX punchy, Khronos PBR Neutral, ACES fitted, Reinhard |+| `volume` / `atmosphere` | HG, dual-lobe, Rayleigh and Cornette-Shanks phase, energy-conserving `volumeStep`, Beer-Powder, analytic height fog; physically based single-scattering sky, sun disk with limb darkening |+| `camera` / `intersect` / `post` / `debug` | look-at, thin-lens DOF, ortho; analytic sphere/box/plane hits; AA helpers, R2 supersampling offsets, cos⁴ vignette, grain, TPDF dither; distance, normal, id and heat debug views |++The full catalog with signatures, exactness and uses is+[`references/library-index.md`](skills/shader-art-coding/references/library-index.md).++## Verification++| Check | Where | What it proves |+|---|---|---|+| Lint + drift | `glsl_tools.py check` | docs and tags on every function, module order, no WebGL1 or sine-hash patterns, reference snippets identical to the library |+| glslang compile | CI (`checks.yml`) | every library module, reference snippet and template compiles as GLSL ES 3.00 |+| WebGL2 compile | `tests/` harness | all 146 units compile under ANGLE, which also enforces WebGL-only rules |+| GPU property tests | `tests/properties.py` | 68 tests × 16,384 samples: Lipschitz, exactness, signs, brute-force curve distance, derivatives, divergence, ranges, round trips |+| Renders | harness + gallery | every template renders with no NaNs and no black frames; images saved to `gallery/` |++Run it locally: `python3 tests/build_harness.py && python3 tests/serve.py`, then open+`http://127.0.0.1:8765/build/harness.html`. Headless: `python3 tests/run_webgl.py` (needs Playwright).++## Conventions++- `#define DEBUG_MODE 0`: 0 final, 1 distance field, 2 normals, 3 ids, 4 steps, 5 masks, 6 lighting terms.+- Scene contract `vec2 map(vec3 p)` returns `vec2(distance, materialId)`.+- Color pipeline:+ 1. Light in linear color.+ 2. Apply exposure.+ 3. Tonemap each AA sample.+ 4. Average the samples.+ 5. Encode once with `linearToSrgb`.+ 6. Dither.++## Repository```text-prompts/ Platform-neutral and platform-specific prompts-skills/codex/shader-art-coding/ Installed Codex skill package+skills/shader-art-coding/ the skill: SKILL.md, glsl/ library, templates/, references/, scripts/glsl_tools.py+tests/ WebGL2 harness, GPU property tests, gallery builder, headless runner+gallery/ rendered templates and paste-ready bundles+adapters/ prompts for tools without skill support+.claude-plugin/ Claude Code plugin + marketplace manifests```-## License+Contributing: see [AGENTS.md](AGENTS.md) for the rules every library change must pass.++## Credits and license-MIT+MIT. Every function is an original implementation of a published technique. The sources are listed in+[CREDITS.md](CREDITS.md): Inigo Quilez's articles, hg_sdf, Jarzynski & Olano's GPU hash study, Hillaire's+atmosphere and volume work, AgX, Khronos PBR Neutral, Oklab and others.diff --git a/adapters/chatgpt-custom-gpt.md b/adapters/chatgpt-custom-gpt.mdnew file mode 100644index 0000000..24b768d--- /dev/null+++ b/adapters/chatgpt-custom-gpt.md@@ -0,0 +1,19 @@+# ChatGPT Custom GPT++1. Create a GPT and paste `adapters/universal-system-prompt.md` (the part below the line) into **Instructions**.+2. Under **Knowledge**, upload:+ - `skills/shader-art-coding/references/library-index.md`+ - `skills/shader-art-coding/references/subject-routing.md`+ - `skills/shader-art-coding/references/sdf-library-guide.md`+ - `skills/shader-art-coding/references/rendering-pipeline.md`+ - every file in `skills/shader-art-coding/glsl/` (rename `*.glsl` to `*.txt` if the uploader rejects them)+ - optionally the templates in `skills/shader-art-coding/templates/`+3. Add this line to the instructions:++> The uploaded `glsl` files are a tested function library. Copy functions from them verbatim (with their dependencies,+> in the module order common, hash, noise, pattern, sdf3d, sdf2d, operators, domain, raymarch, intersect, camera,+> shading, color, tonemap, volume, atmosphere, post, debug) instead of rewriting them. Use `library-index.md` to find+> them and `subject-routing.md` to choose techniques.++4. With **Code Interpreter** enabled, also upload `skills/shader-art-coding/scripts/glsl_tools.py` and the `glsl/`+ folder as a zip. The GPT can then run `python3 glsl_tools.py bundle shader.glsl` to inline dependencies itself.diff --git a/adapters/claude-project.md b/adapters/claude-project.mdnew file mode 100644index 0000000..a589c23--- /dev/null+++ b/adapters/claude-project.md@@ -0,0 +1,14 @@+# Claude (claude.ai Projects)++Prefer the skill: zip the `skills/shader-art-coding/` folder and upload it under **Settings > Capabilities > Skills**.+Claude then loads `SKILL.md`, the references and the library on demand, and can run `scripts/glsl_tools.py` in its+code environment to bundle and check shaders.++Without skills, use a Project:++1. Paste `adapters/universal-system-prompt.md` (the part below the line) into the project instructions.+2. Add to project knowledge: `references/library-index.md`, `references/subject-routing.md`,+ `references/sdf-library-guide.md`, `references/rendering-pipeline.md`, and the `glsl/*.glsl` files.+3. Add: "Copy library functions verbatim with their dependencies instead of rewriting them."++For Claude Code, install the plugin or copy the skill folder (see the repository README).diff --git a/adapters/copilot/shaders.instructions.md b/adapters/copilot/shaders.instructions.mdnew file mode 100644index 0000000..0e566f1--- /dev/null+++ b/adapters/copilot/shaders.instructions.md@@ -0,0 +1,13 @@+---+applyTo: "**/*.glsl,**/*.frag,**/*.fs"+---++Copy this file into your repository's `.github/instructions/`. For agent mode, also install the skill with+`gh skill install gokayfem/shader-skills shader-art-coding`.++- Write Shadertoy-compatible GLSL ES 3.00 with `mainImage(out vec4 fragColor, in vec2 fragCoord)`.+- Prefer the `shader-art-coding` library functions (SDFs, noise, raymarching, shading, tonemapping) over hand-written+ copies, and bundle with `scripts/glsl_tools.py bundle`.+- No `#version`, custom uniforms, `?:` on structs, or `fract(sin(...))` hashes.+- Debug with `#define DEBUG_MODE 0` (0 final, 1 distance, 2 normals, 3 ids, 4 steps, 5 masks, 6 lighting terms).+- Light in linear color; tonemap per sample, then encode once with the exact sRGB curve, then dither.diff --git a/adapters/cursor/shader-art-coding.mdc b/adapters/cursor/shader-art-coding.mdcnew file mode 100644index 0000000..a9e76f1--- /dev/null+++ b/adapters/cursor/shader-art-coding.mdc@@ -0,0 +1,16 @@+---+description: Procedural GLSL / Shadertoy shader work (SDF raymarching, noise, terrain, volumes, lighting, color)+globs: **/*.glsl,**/*.frag,**/*.fs,**/shaders/**+alwaysApply: false+---++Copy this file into your project's `.cursor/rules/`. Install the skill too (Cursor reads `~/.cursor/skills`,+`~/.claude/skills` and `.agents/skills`), so the rule can point at it.++- Use the `shader-art-coding` skill: find functions with `scripts/glsl_tools.py search`, call library functions by+ name, then `bundle` and `check` the result.+- Shadertoy-compatible GLSL ES 3.00 with `mainImage(out vec4 fragColor, in vec2 fragCoord)`; no `#version`, no custom+ uniforms, no `?:` on structs, no sine hashes.+- `#define DEBUG_MODE 0` (0 final, 1 distance, 2 normals, 3 ids, 4 steps, 5 masks, 6 lighting terms).+- Linear lighting, then exposure, then `tonemapAgX` per AA sample, then the average, then `linearToSrgb` once, then+ `ditherTPDF`.diff --git a/adapters/gemini-gem.md b/adapters/gemini-gem.mdnew file mode 100644index 0000000..08b2314--- /dev/null+++ b/adapters/gemini-gem.md@@ -0,0 +1,9 @@+# Gemini Gem++1. Create a Gem and paste `adapters/universal-system-prompt.md` (the part below the line) into its instructions.+2. Add as knowledge files: `references/library-index.md`, `references/subject-routing.md`,+ `references/sdf-library-guide.md`, `references/rendering-pipeline.md` and the `glsl/*.glsl` files from+ `skills/shader-art-coding/` (rename to `.txt` if needed).+3. Tell the Gem to copy library functions verbatim with their dependencies instead of rewriting them.++For Gemini CLI, install the skill directly (see the repository README); the CLI reads `SKILL.md` folders.diff --git a/adapters/universal-system-prompt.md b/adapters/universal-system-prompt.mdnew file mode 100644index 0000000..05e62d0--- /dev/null+++ b/adapters/universal-system-prompt.md@@ -0,0 +1,46 @@+# Shader Art Coding: Universal System Prompt++Paste this into any assistant that has no skill support. If the assistant can read files, give it the whole+`skills/shader-art-coding/` folder instead: the GLSL library, bundler and references do most of the work.++---++You are a procedural shader engineer. You write, debug, and art-direct GLSL fragment shaders for Shadertoy and WebGL2+(GLSL ES 3.00): SDF raymarching, 2D distance-field graphics, noise and fBm, terrain, volumes, lighting and color.++## Process++1. State the target image: subject, framing, dominant forms, materials, light, motion.+2. Choose the smallest rendering model: 2D distance fields (graphics, patterns), SDF raymarching (objects),+ heightfield marching (landscapes), volume integration (clouds, smoke, fire).+3. Get a first image quickly (coordinates, background, one primitive, one light), then add debug views, then refine:+ proportions, composition, materials, lighting, atmosphere, color, antialiasing, performance.++## Conventions++- `vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;` (one pixel = `2.0 / iResolution.y`).+- Scene function `vec2 map(vec3 p)` returns `vec2(distance, materialId)`.+- `#define DEBUG_MODE 0`: 0 final, 1 distance field, 2 normals, 3 ids, 4 step count, 5 masks, 6 lighting terms.+- Light in linear color; decode picked sRGB colors. Finish with exposure, a tonemap per AA sample (AgX, or Khronos+ PBR Neutral for palette-faithful 2D), averaging, the exact piecewise sRGB encode once, then a +-1 LSB dither.+- Normals from 4 tetrahedral samples with epsilon proportional to distance; soft shadows with the+ closest-approach estimate; 5-sample AO applied to fill light only, never to the sun.+- Fog and aerial perspective blend toward the sky color.++## Hard rules (WebGL / Shadertoy)++- Output `void mainImage(out vec4 fragColor, in vec2 fragCoord)`. No `#version`, no custom uniforms, no+ `gl_FragColor`, `texture2D` or `iGlobalTime`.+- No `?:` on structs; pack results into vectors.+- Write float literals (`2.0 * PI`, `clamp(x, 0.0, 1.0)`).+- No `fract(sin(dot(p, k)) * 43758.5453)` hashes. Use an integer hash such as PCG on `uvec(ivec(floor(p)))`.+- Guard NaN sources (`atan(0,0)`, `pow`/`sqrt` of negatives, `normalize(vec3(0))`).+- Keep `dFdx`/`fwidth` out of non-uniform branches and loops.+- Raymarch loops are bounded; if displacement, warps or twist raise the field's Lipschitz constant above 1, scale the+ step down.+- Repetition with per-cell variation must check neighboring cells, or the march punches holes.++## Response++Deliver complete, paste-ready code; name the art controls as constants; include debug modes; finish with a short+tuning guide (scale, softness, color, light, motion); and say how the shader was checked.diff --git a/gallery/pattern-swatches.glsl b/gallery/pattern-swatches.glslnew file mode 100644index 0000000..3120b39--- /dev/null+++ b/gallery/pattern-swatches.glsl@@ -0,0 +1,345 @@+// Procedural material swatches: six texture-free patterns on one board.+// Shows: two-level domain warping (marble), exact Voronoi borders (cracked earth), hex tiles with bevels,+// Truchet weaves, smooth Voronoi (organic cells) and a box-filtered checker. Each tile uses explicit pixel-size+// filtering instead of fwidth, so it stays valid inside branches.+// @render time=2.0++#define DEBUG_MODE 0 // 0 final | 3 tile ids++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float TAU = 6.28318530717959;+// Clamp to [0,1].+float saturate(float x) { return clamp(x, 0.0, 1.0); }+vec3 saturate(vec3 x) { return clamp(x, 0.0, 1.0); }+// Squared length.+float dot2(vec2 v) { return dot(v, v); }+float dot2(vec3 v) { return dot(v, v); }++// ---- shader-skills library: hash ----+// PCG-style 1D integer hash.+uint pcgHash(uint v) {+ uint state = v * 747796405u + 2891336453u;+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;+ return (word >> 22u) ^ word;+}+// 3D integer hash, three decorrelated outputs.+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }+// Random float in [0,1) for an integer-valued 2D input.+float hash12(vec2 p) {+ uvec2 q = uvec2(ivec2(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));+}+// Random vec2 in [0,1)^2 for an integer-valued 2D input.+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}+// Random vec3 in [0,1)^3 for an integer-valued 3D input.+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }++// ---- shader-skills library: noise ----+// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+// Derivative of quinticFade: 30 t^2 (t - 1)^2.+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }+// Unit gradient for a 2D lattice point.+vec2 latticeGradient(vec2 cell) {+ float a = TAU * hash12(cell);+ return vec2(cos(a), sin(a));+}+// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.+vec3 gradientNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ vec2 ga = latticeGradient(i);+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));+ float va = dot(ga, f);+ float vb = dot(gb, f - vec2(1.0, 0.0));+ float vc = dot(gc, f - vec2(0.0, 1.0));+ float vd = dot(gd, f - vec2(1.0, 1.0));+ float k = va - vb - vc + vd;+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)+ + du * (vec2(vb - va, vc - va) + u.yx * k);+ return vec3(value, deriv);+}+// 2D gradient noise.+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }+// Dot product of a hashed 3D gradient with the offset to its lattice corner.+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;+ return dot(g, f - corner);+}+// 3D gradient noise.+float gradientNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);+}+const int FBM_MAX_OCTAVES = 12;+// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.+float fbm(vec2 p, int octaves, float lacunarity, float persistence) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,+ -0.80, 0.36, -0.48,+ -0.60, -0.48, 0.64);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}+// Two-level domain warp f(p + s*r), r = fbm(p + s*q), q = fbm(p). Writes the intermediate warp vectors so they can drive color. Cost is 5 fBm calls.+float warpedFbm(vec2 p, float strength, int octaves, out vec2 q, out vec2 r) {+ q = vec2(fbm(p, octaves), fbm(p + vec2(3.1, 7.4), octaves));+ r = vec2(fbm(p + strength * q + vec2(9.7, 2.6), octaves),+ fbm(p + strength * q + vec2(6.3, 1.9), octaves));+ return fbm(p + strength * r, octaves);+}+// Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector. Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance, so lines have constant width.+vec3 voronoiBorder(vec2 p, float jitter) {+ vec2 ip = floor(p), fp = fract(p);+ vec2 mg = vec2(0.0), mr = vec2(0.0);+ float md = 8.0;+ for (int j = -1; j <= 1; j++)+ for (int i = -1; i <= 1; i++) {+ vec2 g = vec2(float(i), float(j));+ vec2 r = g + jitter * hash22(ip + g) - fp;+ float d = dot(r, r);+ if (d < md) { md = d; mr = r; mg = g; }+ }+ md = 8.0;+ for (int j = -2; j <= 2; j++)+ for (int i = -2; i <= 2; i++) {+ vec2 g = mg + vec2(float(i), float(j));+ vec2 r = g + jitter * hash22(ip + g) - fp;+ if (dot2(mr - r) > 1e-5) {+ md = min(md, dot(0.5 * (mr + r), normalize(r - mr)));+ }+ }+ return vec3(md, mr);+}+// Smooth Voronoi: a soft-min of distances to feature points. Cells become blobs with no creases. k controls smoothness (large = sharper; around 8-32). Searches 5x5 cells so low k has no seams.+float smoothVoronoi(vec2 p, float k) {+ vec2 ip = floor(p), fp = fract(p);+ float acc = 0.0;+ for (int j = -2; j <= 2; j++)+ for (int i = -2; i <= 2; i++) {+ vec2 g = vec2(float(i), float(j));+ vec2 r = g + hash22(ip + g) - fp;+ acc += exp2(-k * length(r));+ }+ return -log2(acc) / k;+}++// ---- shader-skills library: pattern ----+// Triangle wave, the integral of a square wave. Building block for box-filtered patterns.+vec2 triangleWave(vec2 x) { return 1.0 - 2.0 * abs(fract(x * 0.5) - 0.5); }+// Box-filtered checkerboard with unit squares: 0 or 1 up close, fading to 0.5 where squares are smaller than a pixel. Compute the footprint before any branching: w = fwidth(p) (or max(abs(dFdx(p)), abs(dFdy(p)))).+float filteredChecker(vec2 p, vec2 w) {+ w = max(w, 1e-4);+ vec2 i = (triangleWave(p + 0.5 * w) - triangleWave(p - 0.5 * w)) / w;+ return 0.5 - 0.5 * i.x * i.y;+}+// Hexagonal tiling with unit spacing between neighboring centers. Neighbors sit left/right, so hexes are pointy-top. Returns vec4(local offset from the hex center, integer-valued hex id).+vec4 hexGrid(vec2 p) {+ const vec2 s = vec2(1.0, 1.7320508);+ vec2 a = mod(p, s) - 0.5 * s;+ vec2 b = mod(p - 0.5 * s, s) - 0.5 * s;+ vec2 local = (dot(a, a) < dot(b, b)) ? a : b;+ vec2 center = p - local;+ vec2 id = floor(vec2(center.x * 2.0, center.y * 1.1547005) + 0.5);+ return vec4(local, id);+}+// Distance from a hexGrid local coordinate to its hexagon's edge (0.5 at the center, 0 on the edge).+float hexEdgeDistance(vec2 local) {+ vec2 a = abs(local);+ return 0.5 - max(a.x, dot(a, vec2(0.5, 0.8660254)));+}+// Truchet tiling of quarter-circle arcs, randomly flipped per cell. Returns signed distance to arcs of half-width w.+float truchetArcs(vec2 p, float w) {+ vec2 id = floor(p);+ vec2 f = fract(p) - 0.5;+ if (hash12(id) < 0.5) f.x = -f.x;+ vec2 q = f - 0.5 * sign(f.x + f.y + 1e-6);+ return abs(length(q) - 0.5) - w;+}++// ---- shader-skills library: color ----+// Exact sRGB decode (EOTF): encoded [0,1] -> linear.+vec3 srgbToLinear(vec3 c) {+ c = max(c, 0.0);+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));+}+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}+// Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT).+vec3 linearSrgbToOklab(vec3 c) {+ vec3 lms = c * mat3(0.4122214708, 0.5363325363, 0.0514459929,+ 0.2119034982, 0.6806995451, 0.1073969566,+ 0.0883024619, 0.2817188376, 0.6299787005);+ lms = sign(lms) * pow(abs(lms), vec3(1.0 / 3.0));+ return lms * mat3(0.2104542553, 0.7936177850, -0.0040720468,+ 1.9779984951, -2.4285922050, 0.4505937099,+ 0.0259040371, 0.7827717662, -0.8086757660);+}+// Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping.+vec3 oklabToLinearSrgb(vec3 lab) {+ vec3 lms = lab * mat3(1.0, 0.3963377774, 0.2158037573,+ 1.0, -0.1055613458, -0.0638541728,+ 1.0, -0.0894841775, -1.2914855480);+ lms = lms * lms * lms;+ return lms * mat3(4.0767416621, -3.3077115913, 0.2309699292,+ -1.2684380046, 2.6097574011, -0.3413193965,+ -0.0041960863, -0.7034186147, 1.7076147010);+}+// Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV.+vec3 mixOklab(vec3 a, vec3 b, float t) {+ return oklabToLinearSrgb(mix(linearSrgbToOklab(a), linearSrgbToOklab(b), t));+}+// OkLCh (lightness, chroma, hue in radians) -> linear sRGB. Hue sweeps keep lightness constant. L about 0.4-0.9, C about 0.05-0.2 stays mostly in gamut.+vec3 oklchToLinearSrgb(vec3 lch) {+ return oklabToLinearSrgb(vec3(lch.x, lch.y * cos(lch.z), lch.y * sin(lch.z)));+}++// ---- shader-skills library: post ----+// Antialiased fill of a 2D SDF: 1 inside, 0 outside, box-filtered across one pixel. Uses screen derivatives, so call it outside non-uniform branches and loops. For a fixed pixel size use fillAA(d, px).+float fillAA(float d) {+ float w = length(vec2(dFdx(d), dFdy(d)));+ return clamp(0.5 - d / max(w, 1e-6), 0.0, 1.0);+}+// Antialiased fill with an explicit pixel size px (e.g. 2.0 / iResolution.y for the standard uv). Safe in loops and branches.+float fillAA(float d, float px) { return clamp(0.5 - d / px, 0.0, 1.0); }+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}++// ---- shader-skills library: debug ----+// Distinct color per integer id.+vec3 debugIdColor(float id) {+ return 0.55 + 0.45 * cos(TAU * (0.618034 * id + vec3(0.0, 0.33, 0.67)));+}++// ---- shader ----+vec3 marble(vec2 p) {+ vec2 q, r;+ float f = warpedFbm(p * 1.5, 3.0, 5, q, r);+ vec3 col = mixOklab(srgbToLinear(vec3(0.92, 0.90, 0.86)), srgbToLinear(vec3(0.35, 0.38, 0.45)), saturate(length(q) * 0.9));+ col = mix(col, srgbToLinear(vec3(0.62, 0.42, 0.30)), saturate(r.y * r.y * 2.0));+ return col * (0.85 + 0.25 * f);+}++vec3 crackedEarth(vec2 p, float px) {+ vec3 v = voronoiBorder(p * 4.0, 0.9);+ vec2 cell = floor(p * 4.0 + v.yz);+ float tint = hash12(cell);+ vec3 col = mix(srgbToLinear(vec3(0.62, 0.44, 0.30)), srgbToLinear(vec3(0.75, 0.58, 0.40)), tint);+ col *= 0.75 + 0.25 * smoothstep(0.0, 0.25, v.x); // plates darken toward their curled edges+ float plate = fillAA(0.03 - v.x, px * 4.0); // cracks: border distance < 0.03 cell units+ return mix(srgbToLinear(vec3(0.12, 0.08, 0.06)), col, plate);+}++vec3 hexTiles(vec2 p, float px) {+ vec4 h = hexGrid(p * 5.0);+ float edge = hexEdgeDistance(h.xy);+ vec3 base = oklchToLinearSrgb(vec3(0.7, 0.09, 3.6 + 0.8 * hash12(h.zw)));+ float bevel = smoothstep(0.0, 0.12, edge);+ return mix(vec3(0.02), base * (0.7 + 0.3 * bevel), smoothstep(0.03 - px * 5.0, 0.03 + px * 5.0, edge));+}++vec3 truchet(vec2 p, float px) {+ float d = truchetArcs(p * 5.0, 0.12) / 5.0;+ float stripe = truchetArcs(p * 5.0, 0.03) / 5.0;+ vec3 col = srgbToLinear(vec3(0.08, 0.10, 0.16));+ col = mix(col, srgbToLinear(vec3(0.95, 0.75, 0.30)), fillAA(d, px));+ return mix(col, srgbToLinear(vec3(0.55, 0.20, 0.10)), fillAA(stripe, px));+}++vec3 organicCells(vec2 p) {+ float s = smoothVoronoi(p * 5.0, 12.0);+ vec3 col = mixOklab(srgbToLinear(vec3(0.95, 0.55, 0.55)), srgbToLinear(vec3(0.35, 0.05, 0.15)), saturate(s * 1.6));+ return col * (0.6 + 0.4 * smoothstep(0.1, 0.5, s));+}++vec3 checker(vec2 p, float px) {+ // perspective floor: the filtered checker stays grey instead of moire in the distance+ float z = 1.0 / max(0.55 - p.y, 0.02);+ vec2 floorUV = vec2(p.x * z, z) * 1.5;+ float c = filteredChecker(floorUV, vec2(px * z * z * 1.5 + px * z * 1.5));+ return mix(vec3(0.05), vec3(0.8), c) * smoothstep(0.55, 0.3, p.y);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec2 uv = fragCoord / iResolution.y;+ float px = 1.0 / iResolution.y;+ float aspect = iResolution.x / iResolution.y;+ vec2 grid = vec2(3.0, 2.0);+ vec2 tileSize = vec2(aspect, 1.0) / grid;+ vec2 id = floor(uv / tileSize);+ vec2 local = (uv - id * tileSize) / tileSize.y; // 0..(tile aspect) x 0..1+ vec2 p = local - 0.5 * vec2(tileSize.x / tileSize.y, 1.0);+ float k = id.x + 3.0 * (1.0 - id.y);+ float lpx = px / tileSize.y;++ vec3 col;+ if (k < 0.5) col = marble(p + 0.05 * iTime);+ else if (k < 1.5) col = crackedEarth(p, lpx);+ else if (k < 2.5) col = hexTiles(p, lpx);+ else if (k < 3.5) col = truchet(p, lpx);+ else if (k < 4.5) col = organicCells(p + vec2(0.0, 0.03 * iTime));+ else col = checker(p, lpx);++ // tile frame+ vec2 e = min(local, vec2(tileSize.x / tileSize.y, 1.0) - local);+ col *= smoothstep(0.0, 0.02, min(e.x, e.y));++#if DEBUG_MODE == 3+ col = debugIdColor(k);+#endif+ fragColor = vec4(linearToSrgb(col) + ditherTPDF(fragCoord, iFrame), 1.0);+}diff --git a/gallery/pattern-swatches.png b/gallery/pattern-swatches.pngnew file mode 100644index 0000000..84555c3Binary files /dev/null and b/gallery/pattern-swatches.png differdiff --git a/gallery/raymarch-sdf.glsl b/gallery/raymarch-sdf.glslnew file mode 100644index 0000000..66f6614--- /dev/null+++ b/gallery/raymarch-sdf.glsl@@ -0,0 +1,437 @@+// Studio still life: a smooth-blended sculpture on a plinth, with a gold ring.+// Shows: SDF modeling (smooth union whose blend weight also blends color), PBR key light with soft shadows,+// sky fill + bounce with AO, sky reflections, ray-footprint filtering, fog, AgX, supersampling, DEBUG_MODE.+// Paste-ready version: python3 scripts/glsl_tools.py bundle templates/raymarch-sdf.glsl -o scene.glsl+// @render time=1.2++#define DEBUG_MODE 0 // 0 final | 1 distance slice | 2 normals | 3 material ids | 4 steps | 5 shadow/AO/blend | 6 light terms+#define AA 1 // samples per pixel (4-8 for stills)++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float PI = 3.14159265358979;+const float TAU = 6.28318530717959;+// 2D rotation matrix. `rot2(a) * v` rotates v counter-clockwise by a radians.+mat2 rot2(float a) {+ float c = cos(a), s = sin(a);+ return mat2(c, s, -s, c);+}++// ---- shader-skills library: hash ----+// 3D integer hash, three decorrelated outputs.+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }+// Random vec2 in [0,1)^2 for an integer-valued 2D input.+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}++// ---- shader-skills library: pattern ----+// Triangle wave, the integral of a square wave. Building block for box-filtered patterns.+vec2 triangleWave(vec2 x) { return 1.0 - 2.0 * abs(fract(x * 0.5) - 0.5); }+// Box-filtered checkerboard with unit squares: 0 or 1 up close, fading to 0.5 where squares are smaller than a pixel. Compute the footprint before any branching: w = fwidth(p) (or max(abs(dFdx(p)), abs(dFdy(p)))).+float filteredChecker(vec2 p, vec2 w) {+ w = max(w, 1e-4);+ vec2 i = (triangleWave(p + 0.5 * w) - triangleWave(p - 0.5 * w)) / w;+ return 0.5 - 0.5 * i.x * i.y;+}++// ---- shader-skills library: sdf3d ----+// Sphere of radius r.+float sdSphere(vec3 p, float r) { return length(p) - r; }+// Box with rounded edges. The outer size stays b; r is the edge radius (r <= min(b)).+float sdRoundBox(vec3 p, vec3 b, float r) {+ vec3 q = abs(p) - b + r;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}+// Torus in the XZ plane. t.x = major radius, t.y = tube radius.+float sdTorus(vec3 p, vec2 t) {+ vec2 q = vec2(length(p.xz) - t.x, p.y);+ return length(q) - t.y;+}++// ---- shader-skills library: operators ----+// Smooth union (polynomial, C1). Blends where |a - b| < k, with a max bulge of k/4.+float smin(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return mix(b, a, h) - k * h * (1.0 - h);+}+// Smooth intersection, the mirror of smin.+float smax(float a, float b, float k) { return -smin(-a, -b, k); }+// Smooth subtraction: a with b carved out, with filleted edges.+float smoothSubtract(float a, float b, float k) { return smax(a, -b, k); }+// Smooth union that also returns the blend weight. Returns vec2(distance, weight), where weight is 1 when the result is fully a and 0 when fully b. Use the weight to mix material colors across the blend.+vec2 sminBlend(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return vec2(mix(b, a, h) - k * h * (1.0 - h), h);+}++// ---- shader-skills library: raymarch ----+#define ZERO (min(iFrame, 0))+vec2 map(vec3 p);+const int RAYMARCH_MAX_STEPS = 256;+// Sphere-trace from ro along unit rd between tmin and tmax. Returns vec3(t, materialId, stepCount). t is -1 on a miss. The hit threshold grows with t (about one pixel's footprint), so distant surfaces don't burn steps. stepScale is 1 for exact or bound fields. Use < 1 (e.g. 0.6) when map() has Lipschitz > 1 (displacement, warps, twist).+vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale) {+ float t = tmin;+ for (int i = ZERO; i < RAYMARCH_MAX_STEPS; i++) {+ vec2 h = map(ro + rd * t);+ if (abs(h.x) < max(0.0002 * t, 1e-5)) return vec3(t, h.y, float(i));+ t += h.x * stepScale;+ if (t > tmax) break;+ }+ return vec3(-1.0, -1.0, float(RAYMARCH_MAX_STEPS));+}+// Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered). eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling.+vec3 calcNormal(vec3 p, float eps) {+ vec3 n = vec3(0.0);+ for (int i = ZERO; i < 4; i++) {+ vec3 e = 0.5773 * (2.0 * vec3((((i + 3) >> 1) & 1), ((i >> 1) & 1), (i & 1)) - 1.0);+ n += e * map(p + e * eps).x;+ }+ return normalize(n);+}+// Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard). Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders. Returns 0 (full shadow) .. 1 (lit).+float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k) {+ float res = 1.0;+ float t = tmin;+ float ph = 1e10;+ for (int i = ZERO; i < 64; i++) {+ float h = map(ro + rd * t).x;+ if (h < 0.0001) return 0.0;+ float y = h * h / (2.0 * ph);+ float d = sqrt(max(h * h - y * y, 0.0));+ res = min(res, k * d / max(t - y, 1e-4));+ ph = h;+ t += clamp(h, 0.005, 0.5);+ if (res < 0.001 || t > tmax) break;+ }+ res = clamp(res, 0.0, 1.0);+ return res * res * (3.0 - 2.0 * res);+}+// Ambient occlusion from 5 distance samples along the normal. Compares the expected distance with the actual one. scale is the sampling reach in scene units (about 0.12 for a unit-sized object). Returns 0 (occluded) .. 1 (open).+float calcAO(vec3 p, vec3 n, float scale) {+ float occ = 0.0;+ float weight = 1.0;+ for (int i = ZERO; i < 5; i++) {+ float h = 0.01 + scale * float(i) / 4.0;+ float d = map(p + h * n).x;+ occ += (h - d) * weight;+ weight *= 0.95;+ }+ return clamp(1.0 - 3.0 * occ / max(scale / 0.12, 1e-3), 0.0, 1.0);+}++// ---- shader-skills library: camera ----+// Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward).+mat3 cameraMatrix(vec3 ro, vec3 ta, float roll) {+ vec3 w = normalize(ta - ro);+ vec3 up = vec3(sin(roll), cos(roll), 0.0);+ vec3 u = normalize(cross(w, up));+ vec3 v = cross(u, w);+ return mat3(u, v, w);+}+// Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal).+vec3 cameraRay(mat3 cam, vec2 uv, float focal) {+ return normalize(cam * vec3(uv, focal));+}++// ---- shader-skills library: shading ----+// Schlick Fresnel. u is VoH for lights and NoV for environment reflections and rims. f0 = 0.04 for dielectrics (plastic, skin, stone, water ~0.02); for metals f0 = base color.+vec3 fresnelSchlick(float u, vec3 f0) {+ float m = clamp(1.0 - u, 0.0, 1.0);+ float m2 = m * m;+ return f0 + (1.0 - f0) * (m2 * m2 * m);+}+// GGX / Trowbridge-Reitz normal distribution. alpha = roughness^2.+float distributionGGX(float NoH, float alpha) {+ float a2 = alpha * alpha;+ float d = NoH * NoH * (a2 - 1.0) + 1.0;+ return a2 / (PI * d * d);+}+// Height-correlated Smith visibility. Already contains the 1 / (4 NoL NoV) term.+float visibilitySmithGGX(float NoV, float NoL, float alpha) {+ float a2 = alpha * alpha;+ float gv = NoL * sqrt(NoV * NoV * (1.0 - a2) + a2);+ float gl = NoV * sqrt(NoL * NoL * (1.0 - a2) + a2);+ return 0.5 / max(gv + gl, 1e-6);+}+// Microfacet specular for one light: pi * D * V * F * NoL (artist units). roughness is perceptual, in [0,1].+vec3 specularGGX(vec3 n, vec3 v, vec3 l, float roughness, vec3 f0) {+ vec3 h = normalize(v + l);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ float NoV = max(dot(n, v), 1e-4);+ float NoH = clamp(dot(n, h), 0.0, 1.0);+ float VoH = clamp(dot(v, h), 0.0, 1.0);+ float alpha = max(roughness, 0.045);+ alpha *= alpha;+ return PI * distributionGGX(NoH, alpha) * visibilitySmithGGX(NoV, NoL, alpha) * fresnelSchlick(VoH, f0) * NoL;+}+// Complete metallic-roughness shading for one light (diffuse + specular, NoL included, artist units). Multiply by light color and shadow. Keep albedo around 0.05-0.7 (linear); brighten lights, not albedo.+vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic) {+ vec3 f0 = mix(vec3(0.04), albedo, metallic);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ vec3 F = fresnelSchlick(max(dot(n, v), 0.0), f0);+ vec3 diffuse = albedo * (1.0 - metallic) * (1.0 - F) * NoL;+ return diffuse + specularGGX(n, v, l, roughness, f0);+}+// Split-sum environment specular without a lookup texture (Karis 2014, after Lazarov). Multiply by the sky or environment color in the reflection direction.+vec3 envBRDFApprox(vec3 f0, float NoV, float roughness) {+ vec4 r = roughness * vec4(-1.0, -0.0275, -0.572, 0.022) + vec4(1.0, 0.0425, 1.04, -0.04);+ float a = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;+ vec2 ab = vec2(-1.04, 1.04) * a + r.zw;+ return f0 * ab.x + ab.y;+}+// Hemisphere light: sky color from above blended to ground color from below.+vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor) {+ return mix(groundColor, skyColor, 0.5 + 0.5 * n.y);+}++// ---- shader-skills library: color ----+// Exact sRGB decode (EOTF): encoded [0,1] -> linear.+vec3 srgbToLinear(vec3 c) {+ c = max(c, 0.0);+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));+}+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}+// Relative luminance of linear Rec.709 / sRGB color.+float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }+// Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT).+vec3 linearSrgbToOklab(vec3 c) {+ vec3 lms = c * mat3(0.4122214708, 0.5363325363, 0.0514459929,+ 0.2119034982, 0.6806995451, 0.1073969566,+ 0.0883024619, 0.2817188376, 0.6299787005);+ lms = sign(lms) * pow(abs(lms), vec3(1.0 / 3.0));+ return lms * mat3(0.2104542553, 0.7936177850, -0.0040720468,+ 1.9779984951, -2.4285922050, 0.4505937099,+ 0.0259040371, 0.7827717662, -0.8086757660);+}+// Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping.+vec3 oklabToLinearSrgb(vec3 lab) {+ vec3 lms = lab * mat3(1.0, 0.3963377774, 0.2158037573,+ 1.0, -0.1055613458, -0.0638541728,+ 1.0, -0.0894841775, -1.2914855480);+ lms = lms * lms * lms;+ return lms * mat3(4.0767416621, -3.3077115913, 0.2309699292,+ -1.2684380046, 2.6097574011, -0.3413193965,+ -0.0041960863, -0.7034186147, 1.7076147010);+}+// Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV.+vec3 mixOklab(vec3 a, vec3 b, float t) {+ return oklabToLinearSrgb(mix(linearSrgbToOklab(a), linearSrgbToOklab(b), t));+}++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(vec3 c) {+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,+ 0.0784335999999992, 0.878468636469772, 0.0784336,+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);+ const float minEv = -12.47393, maxEv = 4.026069;+ c = inset * max(c, 0.0);+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);+ vec3 x2 = c * c, x4 = x2 * x2;+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;+ c = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- shader-skills library: volume ----+// Distance fog amount (0 = clear, 1 = fully fogged) for distance t.+float distanceFog(float t, float density) { return 1.0 - exp(-t * density); }++// ---- shader-skills library: atmosphere ----+// Cheap analytic sky: horizon-to-zenith gradient, darker ground below the horizon, sun glow lobes. Returns linear radiance (roughly 0-2; the glow can exceed 1 near the sun).+vec3 simpleSky(vec3 rd, vec3 sunDir) {+ float y = max(rd.y, 0.0);+ vec3 zenith = vec3(0.12, 0.28, 0.62);+ vec3 horizon = vec3(0.62, 0.74, 0.88);+ vec3 col = mix(horizon, zenith, pow(y, 0.5));+ col = mix(col, vec3(0.28, 0.26, 0.24), smoothstep(0.0, -0.08, rd.y));+ float mu = max(dot(rd, sunDir), 0.0);+ col += vec3(1.0, 0.75, 0.45) * (0.25 * pow(mu, 8.0) + 0.6 * pow(mu, 64.0) + 2.0 * pow(mu, 512.0));+ return col;+}++// ---- shader-skills library: post ----+// Subpixel offset in [-0.5, 0.5)^2 for sample i of a supersampling loop (R2 low-discrepancy sequence). Better coverage than a regular grid for any sample count.+vec2 aaOffset(int i) {+ return fract(0.5 + float(i) * vec2(0.7548776662, 0.5698402910)) - 0.5;+}+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}++// ---- shader-skills library: debug ----+// Distance field as contour bands: warm outside, cool inside, white zero line. Bands are 0.1 units apart.+vec3 debugDistance(float d) {+ vec3 col = (d > 0.0) ? vec3(0.9, 0.6, 0.3) : vec3(0.4, 0.7, 0.85);+ col *= 1.0 - exp(-4.0 * abs(d));+ col *= 0.8 + 0.2 * cos(TAU * d / 0.1);+ return mix(col, vec3(1.0), 1.0 - smoothstep(0.0, 0.01, abs(d)));+}+// Normal as RGB.+vec3 debugNormal(vec3 n) { return 0.5 + 0.5 * n; }+// Distinct color per integer id.+vec3 debugIdColor(float id) {+ return 0.55 + 0.45 * cos(TAU * (0.618034 * id + vec3(0.0, 0.33, 0.67)));+}+// Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white.+vec3 debugHeat(float t) {+ t = clamp(t, 0.0, 1.0);+ return clamp(vec3(1.5 * t, 1.6 * t * t * t - 0.1, 0.9 * sin(PI * t) + 0.2 * t * t), 0.0, 1.0);+}++// ---- shader ----+// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.7, 0.6, -0.4));+const vec3 SUN_COLOR = vec3(3.2, 2.8, 2.3);+const vec3 SKY_FILL = vec3(0.35, 0.45, 0.6);+const vec3 GROUND_FILL = vec3(0.18, 0.15, 0.12);+const float BLEND = 0.25; // smooth-union width: larger = softer, fleshier join+const float EXPOSURE = 1.0;+const float FOCAL = 2.2; // larger = more telephoto++// Material ids: integer part = material, fractional part = blend weight between the two glazes.+const float MAT_FLOOR = 1.0;+const float MAT_PLINTH = 2.0;+const float MAT_GLAZE = 3.0;+const float MAT_GOLD = 4.0;++vec2 map(vec3 p) {+ vec2 res = vec2(p.y, MAT_FLOOR);++ float plinth = sdRoundBox(p - vec3(0.0, 0.3, 0.0), vec3(0.9, 0.3, 0.9), 0.04);+ if (plinth < res.x) res = vec2(plinth, MAT_PLINTH);++ // Sculpture: a rounded block and a ball melted together. sminBlend's weight drives the glaze color.+ vec3 q = p - vec3(0.0, 1.0, 0.0);+ q.xz = rot2(0.6) * q.xz;+ float block = sdRoundBox(q, vec3(0.32, 0.38, 0.32), 0.08);+ float ball = sdSphere(q - vec3(0.16, 0.44, 0.05), 0.3);+ vec2 blob = sminBlend(block, ball, BLEND);+ blob.x = smoothSubtract(blob.x, sdTorus(q - vec3(0.0, -0.08, 0.0), vec2(0.4, 0.05)), 0.04);+ if (blob.x < res.x) res = vec2(blob.x, MAT_GLAZE + 0.99 * blob.y);++ // Gold ring standing on the plinth.+ vec3 r = p - vec3(-0.45, 0.8, -0.5);+ r.yz = rot2(1.25) * r.yz;+ float ring = sdTorus(r, vec2(0.17, 0.035));+ if (ring < res.x) res = vec2(ring, MAT_GOLD);+ return res;+}++// footprint = world-space size of one pixel at the hit, used to filter the floor pattern without derivatives.+void material(float id, vec3 p, float footprint, out vec3 albedo, out float rough, out float metal) {+ float m = floor(id);+ rough = 0.5;+ metal = 0.0;+ if (m == MAT_FLOOR) {+ float checker = filteredChecker(p.xz * 2.0, vec2(footprint * 2.0));+ albedo = mix(vec3(0.30, 0.28, 0.26), vec3(0.42, 0.40, 0.37), checker);+ rough = 0.7;+ } else if (m == MAT_PLINTH) {+ albedo = vec3(0.55, 0.53, 0.5);+ rough = 0.85;+ } else if (m == MAT_GLAZE) {+ float w = fract(id) / 0.99;+ albedo = mixOklab(srgbToLinear(vec3(0.95, 0.45, 0.25)), srgbToLinear(vec3(0.15, 0.55, 0.6)), w);+ rough = 0.25;+ } else {+ albedo = vec3(1.0, 0.78, 0.34);+ rough = 0.2;+ metal = 1.0;+ }+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ float an = 0.35 * iTime;+ vec3 ro = vec3(3.4 * sin(an), 1.9, -3.4 * cos(an));+ vec3 ta = vec3(0.0, 0.85, 0.0);+ mat3 cam = cameraMatrix(ro, ta, 0.0);+ vec3 rd = cameraRay(cam, uv, FOCAL);++#if DEBUG_MODE == 1+ return debugDistance(map(vec3(uv.x * 1.6, uv.y * 1.6 + 0.9, 0.0)).x); // slice at z = 0+#endif++ vec3 sky = simpleSky(rd, SUN_DIR);+ vec3 hit = raymarch(ro, rd, 0.1, 30.0, 1.0);+#if DEBUG_MODE == 4+ return debugHeat(hit.z / float(RAYMARCH_MAX_STEPS));+#endif+ if (hit.x < 0.0) return sky;++ float t = hit.x;+ vec3 p = ro + rd * t;+ vec3 n = calcNormal(p, 0.0005 * t);+ vec3 v = -rd;+ vec3 albedo;+ float rough, metal;+ material(hit.y, p, t * 2.0 / (iResolution.y * FOCAL), albedo, rough, metal);++ float sha = softShadow(p + n * 0.002, SUN_DIR, 0.01, 8.0, 12.0);+ float ao = calcAO(p, n, 0.15);+ vec3 refl = reflect(rd, n);+ vec3 f0 = mix(vec3(0.04), albedo, metal);++ vec3 key = shadePBR(n, v, SUN_DIR, albedo, rough, metal) * SUN_COLOR * sha;+ vec3 fill = albedo * (1.0 - metal) * hemisphereLight(n, SKY_FILL, GROUND_FILL) * ao;+ vec3 spec = envBRDFApprox(f0, max(dot(n, v), 0.0), rough) * simpleSky(refl, SUN_DIR)+ * ao * smoothstep(-0.1, 0.3, refl.y);+ vec3 bounceDir = normalize(vec3(-SUN_DIR.x, 0.0, -SUN_DIR.z));+ vec3 bounce = albedo * (1.0 - metal) * vec3(0.25, 0.18, 0.12) * clamp(dot(n, bounceDir), 0.0, 1.0) * ao;++#if DEBUG_MODE == 2+ return debugNormal(n);+#elif DEBUG_MODE == 3+ return debugIdColor(floor(hit.y));+#elif DEBUG_MODE == 5+ return vec3(sha, ao, fract(hit.y) / 0.99);+#elif DEBUG_MODE == 6+ return vec3(luminance(key), luminance(fill + bounce), luminance(spec));+#endif++ vec3 col = key + fill + spec + bounce;+ return mix(col, sky, distanceFog(t, 0.02));+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 acc = vec3(0.0);+ for (int i = 0; i < AA; i++) {+ vec3 c = render(fragCoord + (AA > 1 ? aaOffset(i) : vec2(0.0)));+#if DEBUG_MODE == 0+ c = tonemapAgX(c * EXPOSURE); // tonemap per sample so bright edges antialias+#endif+ acc += c;+ }+ vec3 col = acc / float(AA);+#if DEBUG_MODE == 0+ col = linearToSrgb(col) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/gallery/raymarch-sdf.png b/gallery/raymarch-sdf.pngnew file mode 100644index 0000000..dc9c4d2Binary files /dev/null and b/gallery/raymarch-sdf.png differdiff --git a/gallery/sdf-2d-poster.glsl b/gallery/sdf-2d-poster.glslnew file mode 100644index 0000000..84fdbc0--- /dev/null+++ b/gallery/sdf-2d-poster.glsl@@ -0,0 +1,399 @@+// Flat-graphic poster: dusk sky, striped sun, layered ridges, foliage and stars, all from 2D distance fields.+// Shows: 2D SDF primitives, antialiasing with a fixed pixel size, Oklab gradients, polar repetition for petals,+// per-cell randomness, layered composition back-to-front, film grain, Neutral tonemap for palette fidelity.+// @render time=3.0++#define DEBUG_MODE 0 // 0 final | 1 distance field of the foliage layer | 5 layer masks++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float TAU = 6.28318530717959;+// Squared length.+float dot2(vec2 v) { return dot(v, v); }+float dot2(vec3 v) { return dot(v, v); }+// 2D rotation matrix. `rot2(a) * v` rotates v counter-clockwise by a radians.+mat2 rot2(float a) {+ float c = cos(a), s = sin(a);+ return mat2(c, s, -s, c);+}++// ---- shader-skills library: hash ----+// PCG-style 1D integer hash.+uint pcgHash(uint v) {+ uint state = v * 747796405u + 2891336453u;+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;+ return (word >> 22u) ^ word;+}+// 3D integer hash, three decorrelated outputs.+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }+// Random float in [0,1) for an integer-valued 2D input.+float hash12(vec2 p) {+ uvec2 q = uvec2(ivec2(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));+}+// Random float in [0,1) for an integer-valued 3D input.+float hash13(vec3 p) {+ uvec3 q = uvec3(ivec3(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y + pcgHash(q.z))));+}+// Random vec2 in [0,1)^2 for an integer-valued 2D input.+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}+// Random vec3 in [0,1)^3 for an integer-valued 3D input.+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }+// Random vec3 in [0,1)^3 for an integer-valued 2D input.+vec3 hash32(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x9E37u)));+}++// ---- shader-skills library: noise ----+// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+// Derivative of quinticFade: 30 t^2 (t - 1)^2.+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }+// Unit gradient for a 2D lattice point.+vec2 latticeGradient(vec2 cell) {+ float a = TAU * hash12(cell);+ return vec2(cos(a), sin(a));+}+// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.+vec3 gradientNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ vec2 ga = latticeGradient(i);+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));+ float va = dot(ga, f);+ float vb = dot(gb, f - vec2(1.0, 0.0));+ float vc = dot(gc, f - vec2(0.0, 1.0));+ float vd = dot(gd, f - vec2(1.0, 1.0));+ float k = va - vb - vc + vd;+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)+ + du * (vec2(vb - va, vc - va) + u.yx * k);+ return vec3(value, deriv);+}+// 2D gradient noise.+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }+// Dot product of a hashed 3D gradient with the offset to its lattice corner.+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;+ return dot(g, f - corner);+}+// 3D gradient noise.+float gradientNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);+}+const int FBM_MAX_OCTAVES = 12;+// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.+float fbm(vec2 p, int octaves, float lacunarity, float persistence) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,+ -0.80, 0.36, -0.48,+ -0.60, -0.48, 0.64);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}++// ---- shader-skills library: pattern ----+// Box-filtered stripes along x with period 1 and duty cycle 0.5. Returns 0..1.+float filteredStripes(float x, float w) {+ w = max(w, 1e-4);+ float a = x + 0.5 * w, b = x - 0.5 * w;+ float ia = floor(a) * 0.5 + max(fract(a) - 0.5, 0.0);+ float ib = floor(b) * 0.5 + max(fract(b) - 0.5, 0.0);+ return (ia - ib) / w;+}++// ---- shader-skills library: sdf3d ----+// Unsigned distance to a 3D quadratic Bezier curve A-B-C; subtract a radius for a tube. Solves the closest-point cubic analytically. Falls back to a segment when the curve is straight.+float sdQuadraticBezier(vec3 pos, vec3 A, vec3 B, vec3 C) {+ vec3 a = B - A;+ vec3 b = A - 2.0 * B + C;+ vec3 c = a * 2.0;+ vec3 d = A - pos;+ float bb = dot(b, b);+ if (bb < 1e-10) {+ vec3 pa = pos - A, ca = C - A;+ return length(pa - ca * clamp(dot(pa, ca) / dot(ca, ca), 0.0, 1.0));+ }+ float kk = 1.0 / bb;+ float kx = kk * dot(a, b);+ float ky = kk * (2.0 * dot(a, a) + dot(d, b)) / 3.0;+ float kz = kk * dot(d, a);+ float pp = ky - kx * kx;+ float q = kx * (2.0 * kx * kx - 3.0 * ky) + kz;+ float h = q * q + 4.0 * pp * pp * pp;+ float res;+ if (h >= 0.0) {+ h = sqrt(h);+ vec2 x = (vec2(h, -h) - q) / 2.0;+ vec2 uv = sign(x) * pow(abs(x), vec2(1.0 / 3.0));+ float t = clamp(uv.x + uv.y - kx, 0.0, 1.0);+ res = dot2(d + (c + b * t) * t);+ } else {+ float z = sqrt(-pp);+ float v = acos(clamp(q / (pp * z * 2.0), -1.0, 1.0)) / 3.0;+ float m = cos(v);+ float n = sin(v) * 1.7320508;+ vec2 t = clamp(vec2(m + m, -n - m) * z - kx, 0.0, 1.0);+ res = min(dot2(d + (c + b * t.x) * t.x), dot2(d + (c + b * t.y) * t.y));+ }+ return sqrt(res);+}++// ---- shader-skills library: sdf2d ----+// Circle of radius r.+float sdCircle(vec2 p, float r) { return length(p) - r; }+// Unsigned distance to segment a-b. Subtract a width to get a stroke.+float sdSegment(vec2 p, vec2 a, vec2 b) {+ vec2 pa = p - a, ba = b - a;+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);+ return length(pa - ba * h);+}+// Vesica (lens): intersection of two circles of radius r whose centers sit at (+-d, 0). Points along Y. Needs d < r.+float sdVesica(vec2 p, float r, float d) {+ p = abs(p);+ float b = sqrt(r * r - d * d);+ return ((p.y - b) * d > p.x * b) ? length(p - vec2(0.0, b))+ : length(p - vec2(-d, 0.0)) - r;+}+// Unsigned distance to a quadratic Bezier curve A-B-C. Solves the closest-point cubic analytically. Falls back to a segment when the curve degenerates to a line. Float error in the cubic solve is about 1e-4.+float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C) {+ vec2 a = B - A;+ vec2 b = A - 2.0 * B + C;+ vec2 c = a * 2.0;+ vec2 d = A - pos;+ float bb = dot(b, b);+ if (bb < 1e-10) return sdSegment(pos, A, C);+ float kk = 1.0 / bb;+ float kx = kk * dot(a, b);+ float ky = kk * (2.0 * dot(a, a) + dot(d, b)) / 3.0;+ float kz = kk * dot(d, a);+ float pp = ky - kx * kx;+ float q = kx * (2.0 * kx * kx - 3.0 * ky) + kz;+ float h = q * q + 4.0 * pp * pp * pp;+ float res;+ if (h >= 0.0) {+ h = sqrt(h);+ vec2 x = (vec2(h, -h) - q) / 2.0;+ vec2 uv = sign(x) * pow(abs(x), vec2(1.0 / 3.0));+ float t = clamp(uv.x + uv.y - kx, 0.0, 1.0);+ res = dot2(d + (c + b * t) * t);+ } else {+ float z = sqrt(-pp);+ float v = acos(clamp(q / (pp * z * 2.0), -1.0, 1.0)) / 3.0;+ float m = cos(v);+ float n = sin(v) * 1.7320508;+ vec2 t = clamp(vec2(m + m, -n - m) * z - kx, 0.0, 1.0);+ res = min(dot2(d + (c + b * t.x) * t.x), dot2(d + (c + b * t.y) * t.y));+ }+ return sqrt(res);+}++// ---- shader-skills library: domain ----+// Polar repetition into n sectors around the origin. Returns the point rotated into the sector centered on +X. Single evaluation: exact for shapes symmetric about their sector's center line. For asymmetric or per-sector-varying shapes, evaluate this sector and its neighbor and take the min (see references/sdf-library-guide.md).+vec2 domPolar(vec2 p, float n) {+ if (dot(p, p) < 1e-20) return p;+ float sector = TAU / n;+ float id = floor(atan(p.y, p.x) / sector + 0.5);+ return rot2(-id * sector) * p;+}++// ---- shader-skills library: color ----+// Exact sRGB decode (EOTF): encoded [0,1] -> linear.+vec3 srgbToLinear(vec3 c) {+ c = max(c, 0.0);+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));+}+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}+// Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT).+vec3 linearSrgbToOklab(vec3 c) {+ vec3 lms = c * mat3(0.4122214708, 0.5363325363, 0.0514459929,+ 0.2119034982, 0.6806995451, 0.1073969566,+ 0.0883024619, 0.2817188376, 0.6299787005);+ lms = sign(lms) * pow(abs(lms), vec3(1.0 / 3.0));+ return lms * mat3(0.2104542553, 0.7936177850, -0.0040720468,+ 1.9779984951, -2.4285922050, 0.4505937099,+ 0.0259040371, 0.7827717662, -0.8086757660);+}+// Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping.+vec3 oklabToLinearSrgb(vec3 lab) {+ vec3 lms = lab * mat3(1.0, 0.3963377774, 0.2158037573,+ 1.0, -0.1055613458, -0.0638541728,+ 1.0, -0.0894841775, -1.2914855480);+ lms = lms * lms * lms;+ return lms * mat3(4.0767416621, -3.3077115913, 0.2309699292,+ -1.2684380046, 2.6097574011, -0.3413193965,+ -0.0041960863, -0.7034186147, 1.7076147010);+}+// Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV.+vec3 mixOklab(vec3 a, vec3 b, float t) {+ return oklabToLinearSrgb(mix(linearSrgbToOklab(a), linearSrgbToOklab(b), t));+}++// ---- shader-skills library: tonemap ----+// Khronos PBR Neutral: leaves [0, ~0.76] almost untouched and compresses only highlights, preserving hue.+vec3 tonemapNeutral(vec3 c) {+ const float startCompression = 0.76;+ const float desaturation = 0.15;+ c = max(c, 0.0);+ float x = min(c.r, min(c.g, c.b));+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;+ c -= offset;+ float peak = max(c.r, max(c.g, c.b));+ if (peak < startCompression) return c;+ const float d = 1.0 - startCompression;+ float newPeak = 1.0 - d * d / (peak + d - startCompression);+ c *= newPeak / peak;+ float g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);+ return mix(c, vec3(newPeak), g);+}++// ---- shader-skills library: post ----+// Antialiased fill of a 2D SDF: 1 inside, 0 outside, box-filtered across one pixel. Uses screen derivatives, so call it outside non-uniform branches and loops. For a fixed pixel size use fillAA(d, px).+float fillAA(float d) {+ float w = length(vec2(dFdx(d), dFdy(d)));+ return clamp(0.5 - d / max(w, 1e-6), 0.0, 1.0);+}+// Antialiased fill with an explicit pixel size px (e.g. 2.0 / iResolution.y for the standard uv). Safe in loops and branches.+float fillAA(float d, float px) { return clamp(0.5 - d / px, 0.0, 1.0); }+// Signal-dependent film grain: noise grows with sqrt(intensity), as photon noise does. n should be zero-mean noise (e.g. hash13(vec3(fragCoord, iFrame)) * 2 - 1). Apply in linear HDR before tonemapping.+vec3 filmGrain(vec3 col, float amount, float n) {+ return col + amount * sqrt(max(col, 0.0)) * n;+}+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}++// ---- shader-skills library: debug ----+// Distance field as contour bands: warm outside, cool inside, white zero line. Bands are 0.1 units apart.+vec3 debugDistance(float d) {+ vec3 col = (d > 0.0) ? vec3(0.9, 0.6, 0.3) : vec3(0.4, 0.7, 0.85);+ col *= 1.0 - exp(-4.0 * abs(d));+ col *= 0.8 + 0.2 * cos(TAU * d / 0.1);+ return mix(col, vec3(1.0), 1.0 - smoothstep(0.0, 0.01, abs(d)));+}++// ---- shader ----+// ---- palette (sRGB picks, decoded to linear before use) ----+const vec3 SKY_TOP = vec3(0.13, 0.10, 0.30);+const vec3 SKY_HORIZON = vec3(0.98, 0.52, 0.36);+const vec3 SUN = vec3(1.0, 0.86, 0.55);+const vec3 RIDGE_FAR = vec3(0.55, 0.30, 0.42);+const vec3 RIDGE_NEAR = vec3(0.20, 0.12, 0.26);+const vec3 FOLIAGE = vec3(0.07, 0.05, 0.12);++// Ridge silhouette: y below the line is "inside". Returns an approximate signed distance (good enough for AA).+float ridge(vec2 uv, float base, float amp, float freq, float seed) {+ float h = base + amp * fbm(vec2(uv.x * freq + seed, seed), 5);+ return (uv.y - h) / sqrt(1.0 + 4.0 * amp * amp * freq * freq); // divide by an approximate slope bound+}++// A palm-like plant: a curved trunk plus a fan of vesica leaves around its crown.+float plant(vec2 p) {+ float trunk = sdQuadraticBezier(p, vec2(0.0, -1.0), vec2(0.12, -0.45), vec2(0.02, 0.0)) - 0.025;+ vec2 q = p - vec2(0.02, 0.0);+ q = domPolar(q, 9.0); // 9 leaves, each pointing along +X in its sector+ q.y += 0.06 * q.x * q.x; // droop+ float leaf = sdVesica((q - vec2(0.24, 0.0)).yx, 0.32, 0.27);+ return min(trunk, leaf);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ float px = 2.0 / iResolution.y;++ // sky: perceptual gradient+ vec3 col = mixOklab(srgbToLinear(SKY_HORIZON), srgbToLinear(SKY_TOP), smoothstep(-0.3, 1.0, uv.y));++ // stars: one random star per grid cell, fading toward the horizon+ vec2 cell = floor(uv * 18.0);+ vec3 rnd = hash32(cell);+ float star = sdCircle(uv * 18.0 - cell - 0.2 - 0.6 * rnd.xy, 0.02 + 0.05 * rnd.z * rnd.z) / 18.0;+ float twinkle = 0.6 + 0.4 * sin(iTime * (1.0 + 3.0 * rnd.z) + 6.0 * rnd.x);+ col += vec3(1.0, 0.95, 0.9) * fillAA(star, px) * smoothstep(0.1, 0.8, uv.y) * twinkle;++ // sun with retro gaps that thicken toward its bottom edge+ vec2 sp = uv - vec2(0.42, 0.18);+ float sun = sdCircle(sp, 0.36);+ float gaps = filteredStripes(sp.y * 14.0 + 0.5, px * 14.0);+ float gapMask = mix(1.0, gaps, smoothstep(0.0, -0.3, sp.y)) ;+ col = mix(col, srgbToLinear(SUN) * 1.6, fillAA(sun, px) * gapMask);+ col += srgbToLinear(SUN) * 0.25 * exp(-6.0 * max(sun, 0.0)); // glow++ // ridges, back to front+ col = mix(col, srgbToLinear(RIDGE_FAR), fillAA(ridge(uv, -0.1, 0.18, 1.2, 3.0), px));+ col = mix(col, mixOklab(srgbToLinear(RIDGE_FAR), srgbToLinear(RIDGE_NEAR), 0.6),+ fillAA(ridge(uv, -0.32, 0.14, 1.8, 11.0), px));+ col = mix(col, srgbToLinear(RIDGE_NEAR), fillAA(ridge(uv, -0.55, 0.10, 2.6, 23.0), px));++ // foreground plants+ float plants = min(plant((uv - vec2(-0.95, 0.15)) / 0.9) * 0.9, plant((uv - vec2(1.25, -0.05)) * vec2(-1.0, 1.0) / 0.7) * 0.7);+ col = mix(col, srgbToLinear(FOLIAGE), fillAA(plants, px));++#if DEBUG_MODE == 1+ fragColor = vec4(debugDistance(plants), 1.0);+ return;+#elif DEBUG_MODE == 5+ fragColor = vec4(fillAA(sun, px), fillAA(ridge(uv, -0.1, 0.18, 1.2, 3.0), px), fillAA(plants, px), 1.0);+ return;+#endif++ // finish: grain in linear, palette-faithful tonemap, encode, dither+ col = filmGrain(col, 0.04, hash13(vec3(fragCoord, iFrame)) * 2.0 - 1.0);+ col = linearToSrgb(tonemapNeutral(col)) + ditherTPDF(fragCoord, iFrame);+ fragColor = vec4(col, 1.0);+}diff --git a/gallery/sdf-2d-poster.png b/gallery/sdf-2d-poster.pngnew file mode 100644index 0000000..c90650aBinary files /dev/null and b/gallery/sdf-2d-poster.png differdiff --git a/gallery/terrain.glsl b/gallery/terrain.glslnew file mode 100644index 0000000..2e55b9d--- /dev/null+++ b/gallery/terrain.glsl@@ -0,0 +1,430 @@+// Eroded mountains at golden hour under a physically based sky.+// Shows: derivative-damped fBm terrain, heightfield marching as a scaled bound, slope/altitude material masks,+// soft terrain shadows, single-scattering atmosphere (Rayleigh/Mie/ozone), aerial perspective, sun disk, AgX.+// Units are kilometers so the atmosphere constants apply directly.+// @render time=0.0++#define DEBUG_MODE 0 // 0 final | 1 height map | 2 normals | 3 material masks | 4 steps | 5 shadow | 6 light terms++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float PI = 3.14159265358979;+const float TAU = 6.28318530717959;++// ---- shader-skills library: hash ----+// PCG-style 1D integer hash.+uint pcgHash(uint v) {+ uint state = v * 747796405u + 2891336453u;+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;+ return (word >> 22u) ^ word;+}+// 3D integer hash, three decorrelated outputs.+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }+// Random float in [0,1) for an integer-valued 2D input.+float hash12(vec2 p) {+ uvec2 q = uvec2(ivec2(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));+}+// Random vec2 in [0,1)^2 for an integer-valued 2D input.+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}+// Random vec3 in [0,1)^3 for an integer-valued 3D input.+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }++// ---- shader-skills library: noise ----+// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+// Derivative of quinticFade: 30 t^2 (t - 1)^2.+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }+// Unit gradient for a 2D lattice point.+vec2 latticeGradient(vec2 cell) {+ float a = TAU * hash12(cell);+ return vec2(cos(a), sin(a));+}+// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.+vec3 gradientNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ vec2 ga = latticeGradient(i);+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));+ float va = dot(ga, f);+ float vb = dot(gb, f - vec2(1.0, 0.0));+ float vc = dot(gc, f - vec2(0.0, 1.0));+ float vd = dot(gd, f - vec2(1.0, 1.0));+ float k = va - vb - vc + vd;+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)+ + du * (vec2(vb - va, vc - va) + u.yx * k);+ return vec3(value, deriv);+}+// 2D gradient noise.+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }+// Dot product of a hashed 3D gradient with the offset to its lattice corner.+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;+ return dot(g, f - corner);+}+// 3D gradient noise.+float gradientNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);+}+const int FBM_MAX_OCTAVES = 12;+// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.+float fbm(vec2 p, int octaves, float lacunarity, float persistence) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,+ -0.80, 0.36, -0.48,+ -0.60, -0.48, 0.64);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}+// Terrain fBm where each octave is damped by the accumulated slope, so detail settles in valleys and steep slopes stay smooth. This gives an eroded look without simulation.+float erodedFbm(vec2 p, int octaves) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float h = 0.0, amp = 0.5;+ vec2 slope = vec2(0.0);+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ vec3 n = gradientNoiseD(p);+ slope += n.yz;+ h += amp * n.x / (1.0 + dot(slope, slope));+ amp *= 0.5;+ p = 2.0 * (octaveRotation * p);+ }+ return 2.0 * h;+}++// ---- shader-skills library: raymarch ----+#define ZERO (min(iFrame, 0))+vec2 map(vec3 p);+const int RAYMARCH_MAX_STEPS = 256;+// Sphere-trace from ro along unit rd between tmin and tmax. Returns vec3(t, materialId, stepCount). t is -1 on a miss. The hit threshold grows with t (about one pixel's footprint), so distant surfaces don't burn steps. stepScale is 1 for exact or bound fields. Use < 1 (e.g. 0.6) when map() has Lipschitz > 1 (displacement, warps, twist).+vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale) {+ float t = tmin;+ for (int i = ZERO; i < RAYMARCH_MAX_STEPS; i++) {+ vec2 h = map(ro + rd * t);+ if (abs(h.x) < max(0.0002 * t, 1e-5)) return vec3(t, h.y, float(i));+ t += h.x * stepScale;+ if (t > tmax) break;+ }+ return vec3(-1.0, -1.0, float(RAYMARCH_MAX_STEPS));+}+// Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered). eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling.+vec3 calcNormal(vec3 p, float eps) {+ vec3 n = vec3(0.0);+ for (int i = ZERO; i < 4; i++) {+ vec3 e = 0.5773 * (2.0 * vec3((((i + 3) >> 1) & 1), ((i >> 1) & 1), (i & 1)) - 1.0);+ n += e * map(p + e * eps).x;+ }+ return normalize(n);+}+// Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard). Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders. Returns 0 (full shadow) .. 1 (lit).+float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k) {+ float res = 1.0;+ float t = tmin;+ float ph = 1e10;+ for (int i = ZERO; i < 64; i++) {+ float h = map(ro + rd * t).x;+ if (h < 0.0001) return 0.0;+ float y = h * h / (2.0 * ph);+ float d = sqrt(max(h * h - y * y, 0.0));+ res = min(res, k * d / max(t - y, 1e-4));+ ph = h;+ t += clamp(h, 0.005, 0.5);+ if (res < 0.001 || t > tmax) break;+ }+ res = clamp(res, 0.0, 1.0);+ return res * res * (3.0 - 2.0 * res);+}++// ---- shader-skills library: intersect ----+// Ray vs sphere centered at c with radius r. Returns vec2(tNear, tFar), or vec2(-1) on a miss. Uses the precision-friendly form that measures from the closest point on the ray.+vec2 iSphere(vec3 ro, vec3 rd, vec3 c, float r) {+ vec3 oc = ro - c;+ float b = dot(oc, rd);+ vec3 qc = oc - b * rd;+ float h = r * r - dot(qc, qc);+ if (h < 0.0) return vec2(-1.0);+ h = sqrt(h);+ return vec2(-b - h, -b + h);+}++// ---- shader-skills library: camera ----+// Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward).+mat3 cameraMatrix(vec3 ro, vec3 ta, float roll) {+ vec3 w = normalize(ta - ro);+ vec3 up = vec3(sin(roll), cos(roll), 0.0);+ vec3 u = normalize(cross(w, up));+ vec3 v = cross(u, w);+ return mat3(u, v, w);+}+// Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal).+vec3 cameraRay(mat3 cam, vec2 uv, float focal) {+ return normalize(cam * vec3(uv, focal));+}++// ---- shader-skills library: color ----+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}+// Relative luminance of linear Rec.709 / sRGB color.+float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(vec3 c) {+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,+ 0.0784335999999992, 0.878468636469772, 0.0784336,+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);+ const float minEv = -12.47393, maxEv = 4.026069;+ c = inset * max(c, 0.0);+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);+ vec3 x2 = c * c, x4 = x2 * x2;+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;+ c = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- shader-skills library: volume ----+// Rayleigh phase function.+float phaseRayleigh(float mu) { return 3.0 / (16.0 * PI) * (1.0 + mu * mu); }+// Cornette-Shanks phase (a better-normalized Mie approximation). g = 0.8 for atmospheric haze.+float phaseCornetteShanks(float mu, float g) {+ float g2 = g * g;+ return 3.0 / (8.0 * PI) * (1.0 - g2) * (1.0 + mu * mu)+ / ((2.0 + g2) * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-6), 1.5));+}+// One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media), inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length. Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds.+void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds) {+ vec3 stepT = exp(-sigmaT * ds);+ vec3 integral = (inScatter - inScatter * stepT) / max(sigmaT, vec3(1e-7));+ radiance += transmittance * integral;+ transmittance *= stepT;+}++// ---- shader-skills library: atmosphere ----+// Sun disk with antialiased edge and limb darkening (Neckel 1996). angularRadius in radians (the real sun is 0.00476; art often uses 3-10x). pixelAngle is the angular size of a pixel (about 2 / (iResolution.y * focal)). Returns a 0..1 shape tinted by limb darkening; multiply by a bright sun color (10-50).+vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle) {+ float ang = acos(clamp(dot(rd, sunDir), -1.0, 1.0));+ float edge = 1.0 - smoothstep(angularRadius - pixelAngle, angularRadius + pixelAngle, ang);+ float r = clamp(ang / angularRadius, 0.0, 1.0);+ float muLimb = sqrt(max(1.0 - r * r, 0.0));+ vec3 limb = pow(vec3(muLimb), vec3(0.397, 0.503, 0.652));+ return edge * limb;+}+const float ATMOSPHERE_GROUND_KM = 6360.0;+const float ATMOSPHERE_TOP_KM = 6460.0;+// Densities (rayleigh, mie, ozone) at altitude h km above the ground.+vec3 atmosphereDensity(float h) {+ return vec3(exp(-h / 8.0), exp(-h / 1.2), max(0.0, 1.0 - abs(h - 25.0) / 15.0));+}+// Extinction per km for the given densities.+vec3 atmosphereExtinction(vec3 density) {+ const vec3 rayleigh = vec3(5.802, 13.558, 33.1) * 1e-3;+ const float mie = (3.996 + 4.40) * 1e-3;+ const vec3 ozone = vec3(0.650, 1.881, 0.085) * 1e-3;+ return rayleigh * density.x + mie * density.y + ozone * density.z;+}+// Physically based sky radiance along rd for a viewer viewHeightKm above the ground, with single scattering (16 view steps x 8 light steps). sunIntensity about 20. Sunsets come out somewhat dark because multiple scattering is ignored; add a small ambient term if needed.+vec3 atmosphereSky(vec3 rd, vec3 sunDir, float viewHeightKm, float sunIntensity) {+ const vec3 rayleighScatter = vec3(5.802, 13.558, 33.1) * 1e-3;+ const float mieScatter = 3.996e-3;+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + max(viewHeightKm, 0.001), 0.0);+ vec2 top = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_TOP_KM);+ if (top.y <= 0.0) return vec3(0.0);+ vec2 ground = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_GROUND_KM);+ float tStart = max(top.x, 0.0);+ float tEnd = (ground.x > 0.0) ? ground.x : top.y;+ float mu = dot(rd, sunDir);+ float pR = phaseRayleigh(mu);+ float pM = phaseCornetteShanks(mu, 0.8);+ const int VIEW_STEPS = 16;+ const int LIGHT_STEPS = 8;+ float dt = (tEnd - tStart) / float(VIEW_STEPS);+ vec3 radiance = vec3(0.0), transmittance = vec3(1.0);+ for (int i = 0; i < VIEW_STEPS; i++) {+ vec3 p = ro + rd * (tStart + (float(i) + 0.5) * dt);+ vec3 dens = atmosphereDensity(length(p) - ATMOSPHERE_GROUND_KM);+ vec3 sunT = vec3(0.0);+ if (iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_GROUND_KM).x < 0.0) {+ float tl = iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_TOP_KM).y;+ float dl = tl / float(LIGHT_STEPS);+ vec3 depth = vec3(0.0);+ for (int j = 0; j < LIGHT_STEPS; j++) {+ vec3 q = p + sunDir * ((float(j) + 0.5) * dl);+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * dl;+ }+ sunT = exp(-depth);+ }+ vec3 scatter = sunT * (rayleighScatter * dens.x * pR + mieScatter * dens.y * pM) * sunIntensity;+ volumeStep(radiance, transmittance, atmosphereExtinction(dens), scatter, dt);+ }+ return radiance;+}++// ---- shader-skills library: post ----+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}++// ---- shader-skills library: debug ----+// Normal as RGB.+vec3 debugNormal(vec3 n) { return 0.5 + 0.5 * n; }+// Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white.+vec3 debugHeat(float t) {+ t = clamp(t, 0.0, 1.0);+ return clamp(vec3(1.5 * t, 1.6 * t * t * t - 0.1, 0.9 * sin(PI * t) + 0.2 * t * t), 0.0, 1.0);+}++// ---- shader ----+// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.85, 0.2, -0.45));+const float SUN_INTENSITY = 20.0;+const float TERRAIN_SCALE = 0.32; // horizontal frequency: smaller = broader mountains+const float TERRAIN_HEIGHT = 2.0; // vertical scale in km+const float SNOW_LINE = 1.05; // km+const float EXPOSURE = 1.4;+const float FOCAL = 1.8;++float terrainHeight(vec2 xz) { return TERRAIN_HEIGHT * erodedFbm(xz * TERRAIN_SCALE, 9); }++vec2 map(vec3 p) {+ // p.y - h(xz) is not a distance on slopes. Scaling by 0.45 keeps the march safe for slopes up to about 63 degrees.+ return vec2(0.45 * (p.y - terrainHeight(p.xz)), 1.0);+}++// Transmittance from a point at heightKm toward dir, through the atmosphere (colors the sunlight).+vec3 sunTransmittance(float heightKm, vec3 dir) {+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + heightKm, 0.0);+ if (iSphere(ro, dir, vec3(0.0), ATMOSPHERE_GROUND_KM).x > 0.0) return vec3(0.0);+ float tl = iSphere(ro, dir, vec3(0.0), ATMOSPHERE_TOP_KM).y;+ vec3 depth = vec3(0.0);+ for (int i = 0; i < 12; i++) {+ vec3 q = ro + dir * ((float(i) + 0.5) * tl / 12.0);+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * tl / 12.0;+ }+ return exp(-depth);+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;++#if DEBUG_MODE == 1+ return vec3(terrainHeight(uv * 8.0) / TERRAIN_HEIGHT * 0.5 + 0.3);+#endif++ vec3 ro = vec3(-3.0 + 0.2 * iTime, 0.0, 4.0 - 0.6 * iTime);+ ro.y = terrainHeight(ro.xz) + 0.9;+ vec3 ta = ro + vec3(0.25, -0.16, -1.0);+ mat3 cam = cameraMatrix(ro, ta, 0.0);+ vec3 rd = cameraRay(cam, uv, FOCAL);++ vec3 sky = atmosphereSky(rd, SUN_DIR, ro.y, SUN_INTENSITY);+ vec3 sunColor = SUN_INTENSITY * 0.12 * sunTransmittance(ro.y, SUN_DIR);+ vec3 hit = raymarch(ro, rd, 0.01, 40.0, 1.0);+#if DEBUG_MODE == 4+ return debugHeat(hit.z / float(RAYMARCH_MAX_STEPS));+#endif+ if (hit.x < 0.0) {+ return sky + sunColor * 40.0 * sunDisk(rd, SUN_DIR, 0.012, 2.0 / (iResolution.y * FOCAL));+ }++ float t = hit.x;+ vec3 p = ro + rd * t;+ vec3 n = calcNormal(p, 0.001 * t);++ // material masks: rock on steep slopes, grass on flats, snow on high upward-facing ground+ float flatness = smoothstep(0.72, 0.88, n.y);+ float snow = smoothstep(SNOW_LINE - 0.15, SNOW_LINE + 0.1, p.y + 0.25 * fbm(p.xz * 6.0, 3))+ * smoothstep(0.55, 0.8, n.y);+ float grain = 0.5 + 0.5 * fbm(p.xz * 40.0, 4);+ vec3 rock = mix(vec3(0.10, 0.085, 0.07), vec3(0.20, 0.17, 0.14), grain);+ vec3 grass = mix(vec3(0.06, 0.08, 0.03), vec3(0.11, 0.12, 0.05), grain);+ vec3 albedo = mix(rock, grass, flatness * (1.0 - smoothstep(0.6, 1.0, p.y)));+ albedo = mix(albedo, vec3(0.85, 0.88, 0.92), snow);++ float sha = softShadow(p + n * 0.01, SUN_DIR, 0.02, 20.0, 16.0);+ float NoL = clamp(dot(n, SUN_DIR), 0.0, 1.0);+ vec3 skyAmbient = atmosphereSky(vec3(0.0, 1.0, 0.0), SUN_DIR, p.y, SUN_INTENSITY);+ vec3 key = albedo * sunColor * NoL * sha;+ vec3 fill = albedo * skyAmbient * (0.5 + 0.5 * n.y) * 2.0;+ vec3 bounce = albedo * sunColor * 0.08 * clamp(dot(n, normalize(vec3(-SUN_DIR.x, 0.0, -SUN_DIR.z))), 0.0, 1.0);++#if DEBUG_MODE == 2+ return debugNormal(n);+#elif DEBUG_MODE == 3+ return vec3(1.0 - flatness, flatness, snow);+#elif DEBUG_MODE == 5+ return vec3(sha);+#elif DEBUG_MODE == 6+ return vec3(luminance(key), luminance(fill), luminance(bounce)) * 2.0;+#endif++ vec3 col = key + fill + bounce;+ // aerial perspective: attenuate by the air between camera and hit and fill with sky color. Use the sky at the+ // horizon-clamped direction: below the planet's horizon the sky integral jumps, which would print a seam.+ vec3 fogColor = atmosphereSky(normalize(vec3(rd.x, max(rd.y, 0.02), rd.z)), SUN_DIR, ro.y, SUN_INTENSITY);+ vec3 airT = exp(-t * atmosphereExtinction(atmosphereDensity(0.5 * (ro.y + p.y))) * 4.0);+ return col * airT + fogColor * (1.0 - airT);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 col = render(fragCoord);+#if DEBUG_MODE == 0+ col = linearToSrgb(tonemapAgX(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/gallery/terrain.png b/gallery/terrain.pngnew file mode 100644index 0000000..6fc1078Binary files /dev/null and b/gallery/terrain.png differdiff --git a/gallery/volumetric-clouds.glsl b/gallery/volumetric-clouds.glslnew file mode 100644index 0000000..8eb9148--- /dev/null+++ b/gallery/volumetric-clouds.glsl@@ -0,0 +1,317 @@+// Cumulus cloud layer lit by a low sun, raymarched as a participating medium.+// Shows: coverage-remapped 3D fBm density with a height profile, energy-conserving integration (volumeStep),+// dual-lobe phase for silver linings, Beer-Powder self-shadowing from a short light march, cheap density for+// lighting, jittered start (no banding), sky and sun, AgX.+// @render time=4.0++#define DEBUG_MODE 0 // 0 final | 4 march cost | 5 density / transmittance | 6 light vs ambient++// Library code below is bundled from shader-skills (MIT): https://github.com/gokayfem/shader-skills+// ---- shader-skills library: common ----+const float PI = 3.14159265358979;+const float TAU = 6.28318530717959;+// Clamp to [0,1].+float saturate(float x) { return clamp(x, 0.0, 1.0); }+vec3 saturate(vec3 x) { return clamp(x, 0.0, 1.0); }++// ---- shader-skills library: hash ----+// PCG-style 1D integer hash.+uint pcgHash(uint v) {+ uint state = v * 747796405u + 2891336453u;+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;+ return (word >> 22u) ^ word;+}+// 3D integer hash, three decorrelated outputs.+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}+// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }+// Random float in [0,1) for an integer-valued 2D input.+float hash12(vec2 p) {+ uvec2 q = uvec2(ivec2(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));+}+// Random vec2 in [0,1)^2 for an integer-valued 2D input.+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}+// Random vec3 in [0,1)^3 for an integer-valued 3D input.+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }++// ---- shader-skills library: noise ----+// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+// Derivative of quinticFade: 30 t^2 (t - 1)^2.+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }+// Unit gradient for a 2D lattice point.+vec2 latticeGradient(vec2 cell) {+ float a = TAU * hash12(cell);+ return vec2(cos(a), sin(a));+}+// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.+vec3 gradientNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ vec2 ga = latticeGradient(i);+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));+ float va = dot(ga, f);+ float vb = dot(gb, f - vec2(1.0, 0.0));+ float vc = dot(gc, f - vec2(0.0, 1.0));+ float vd = dot(gd, f - vec2(1.0, 1.0));+ float k = va - vb - vc + vd;+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)+ + du * (vec2(vb - va, vc - va) + u.yx * k);+ return vec3(value, deriv);+}+// 2D gradient noise.+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }+// Dot product of a hashed 3D gradient with the offset to its lattice corner.+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;+ return dot(g, f - corner);+}+// 3D gradient noise.+float gradientNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);+}+const int FBM_MAX_OCTAVES = 12;+// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.+float fbm(vec2 p, int octaves, float lacunarity, float persistence) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}+// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }+// fBm over 3D gradient noise.+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,+ -0.80, 0.36, -0.48,+ -0.60, -0.48, 0.64);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}+// Interleaved gradient noise: cheap per-pixel noise whose 3x3 neighborhoods are nearly stratified. Not a hash. pixel must be integer pixel coordinates (floor(fragCoord)). The frame overload animates it for accumulation and TAA.+float interleavedGradientNoise(vec2 pixel) {+ return fract(52.9829189 * fract(dot(pixel, vec2(0.06711056, 0.00583715))));+}+float interleavedGradientNoise(vec2 pixel, int frame) {+ return interleavedGradientNoise(pixel + 5.588238 * float(frame % 64));+}++// ---- shader-skills library: camera ----+// Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward).+mat3 cameraMatrix(vec3 ro, vec3 ta, float roll) {+ vec3 w = normalize(ta - ro);+ vec3 up = vec3(sin(roll), cos(roll), 0.0);+ vec3 u = normalize(cross(w, up));+ vec3 v = cross(u, w);+ return mat3(u, v, w);+}+// Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal).+vec3 cameraRay(mat3 cam, vec2 uv, float focal) {+ return normalize(cam * vec3(uv, focal));+}++// ---- shader-skills library: color ----+// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}+// Relative luminance of linear Rec.709 / sRGB color.+float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }++// ---- shader-skills library: tonemap ----+// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+vec3 tonemapAgX(vec3 c) {+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,+ 0.0784335999999992, 0.878468636469772, 0.0784336,+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);+ const float minEv = -12.47393, maxEv = 4.026069;+ c = inset * max(c, 0.0);+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);+ vec3 x2 = c * c, x4 = x2 * x2;+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;+ c = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++// ---- shader-skills library: volume ----+// Henyey-Greenstein phase function. g in (-1, 1): > 0 forward (silver linings), < 0 backward.+float phaseHG(float mu, float g) {+ float g2 = g * g;+ return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-6), 1.5));+}+// Two-lobe Henyey-Greenstein: a forward lobe gF and a backward lobe gB, mixed by w (weight of the forward lobe). Keeps the silver lining while clouds lit from behind the camera still show detail.+float phaseDualHG(float mu, float gF, float gB, float w) {+ return mix(phaseHG(mu, gB), phaseHG(mu, gF), w);+}+// Beer-Powder lighting term for clouds: 2 e^-d (1 - e^-2d), where d is optical depth toward the sun. Darkens cloud edges that face the light like powdered sugar. Not energy-conserving; use it on the direct term only.+float beerPowder(float d) { return 2.0 * exp(-d) * (1.0 - exp(-2.0 * d)); }+// One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media), inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length. Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds.+void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds) {+ vec3 stepT = exp(-sigmaT * ds);+ vec3 integral = (inScatter - inScatter * stepT) / max(sigmaT, vec3(1e-7));+ radiance += transmittance * integral;+ transmittance *= stepT;+}++// ---- shader-skills library: atmosphere ----+// Cheap analytic sky: horizon-to-zenith gradient, darker ground below the horizon, sun glow lobes. Returns linear radiance (roughly 0-2; the glow can exceed 1 near the sun).+vec3 simpleSky(vec3 rd, vec3 sunDir) {+ float y = max(rd.y, 0.0);+ vec3 zenith = vec3(0.12, 0.28, 0.62);+ vec3 horizon = vec3(0.62, 0.74, 0.88);+ vec3 col = mix(horizon, zenith, pow(y, 0.5));+ col = mix(col, vec3(0.28, 0.26, 0.24), smoothstep(0.0, -0.08, rd.y));+ float mu = max(dot(rd, sunDir), 0.0);+ col += vec3(1.0, 0.75, 0.45) * (0.25 * pow(mu, 8.0) + 0.6 * pow(mu, 64.0) + 2.0 * pow(mu, 512.0));+ return col;+}+// Sun disk with antialiased edge and limb darkening (Neckel 1996). angularRadius in radians (the real sun is 0.00476; art often uses 3-10x). pixelAngle is the angular size of a pixel (about 2 / (iResolution.y * focal)). Returns a 0..1 shape tinted by limb darkening; multiply by a bright sun color (10-50).+vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle) {+ float ang = acos(clamp(dot(rd, sunDir), -1.0, 1.0));+ float edge = 1.0 - smoothstep(angularRadius - pixelAngle, angularRadius + pixelAngle, ang);+ float r = clamp(ang / angularRadius, 0.0, 1.0);+ float muLimb = sqrt(max(1.0 - r * r, 0.0));+ vec3 limb = pow(vec3(muLimb), vec3(0.397, 0.503, 0.652));+ return edge * limb;+}++// ---- shader-skills library: post ----+// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}++// ---- shader-skills library: debug ----+// Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white.+vec3 debugHeat(float t) {+ t = clamp(t, 0.0, 1.0);+ return clamp(vec3(1.5 * t, 1.6 * t * t * t - 0.1, 0.9 * sin(PI * t) + 0.2 * t * t), 0.0, 1.0);+}++// ---- shader ----+// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.6, 0.25, -0.75));+const vec3 SUN_COLOR = vec3(6.0, 5.2, 4.2);+const float CLOUD_BOTTOM = 1.5;+const float CLOUD_TOP = 3.2;+const float COVERAGE = 0.42; // 0 = clear, 1 = overcast+const float DENSITY = 9.0; // extinction scale: higher = darker, more opaque cores+const float WIND = 0.06;+const float EXPOSURE = 1.0;++// Density in [0, DENSITY]. Use fewer octaves for the light-march samples.+float cloudDensity(vec3 p, int octaves) {+ float h = (p.y - CLOUD_BOTTOM) / (CLOUD_TOP - CLOUD_BOTTOM);+ if (h < 0.0 || h > 1.0) return 0.0;+ float profile = smoothstep(0.0, 0.12, h) * smoothstep(1.0, 0.45, h); // flat-ish bottoms, rounded tops+ vec3 q = p * 0.55 + vec3(iTime * WIND, 0.0, 0.0);+ float n = 0.5 + 0.5 * fbm(q, octaves, 2.02, 0.5);+ float d = saturate((n * profile - (1.0 - COVERAGE)) / COVERAGE);+ return d * DENSITY;+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ vec3 ro = vec3(0.0, 0.3, 0.0);+ mat3 cam = cameraMatrix(ro, ro + vec3(0.35, 0.32, -1.0), 0.0);+ vec3 rd = cameraRay(cam, uv, 1.6);++ vec3 sky = simpleSky(rd, SUN_DIR) * 1.2;+ vec3 col = sky + SUN_COLOR * sunDisk(rd, SUN_DIR, 0.03, 2.0 / (iResolution.y * 1.6));+ if (rd.y <= 0.01) return col;++ // clip the march to the cloud slab+ float t0 = (CLOUD_BOTTOM - ro.y) / rd.y;+ float t1 = min((CLOUD_TOP - ro.y) / rd.y, 30.0);+ const int STEPS = 48;+ float dt = (t1 - t0) / float(STEPS);+ float t = t0 + dt * interleavedGradientNoise(floor(fragCoord), iFrame); // jitter hides slicing++ float mu = dot(rd, SUN_DIR);+ float phase = 4.0 * PI * phaseDualHG(mu, 0.75, -0.25, 0.75); // artist units: isotropic scattering = 1+ vec3 radiance = vec3(0.0), transmittance = vec3(1.0);+ float lightAcc = 0.0, ambientAcc = 0.0;+ int steps = 0;+ for (int i = 0; i < STEPS; i++) {+ vec3 p = ro + rd * t;+ float sigma = cloudDensity(p, 5);+ if (sigma > 0.001) {+ // short light march toward the sun with the cheap (3-octave) density+ float depth = 0.0;+ for (int j = 0; j < 5; j++) depth += cloudDensity(p + SUN_DIR * (0.1 + 0.25 * float(j)), 3) * 0.25;+ float h = (p.y - CLOUD_BOTTOM) / (CLOUD_TOP - CLOUD_BOTTOM);+ vec3 sunLight = SUN_COLOR * phase * mix(exp(-depth), beerPowder(depth), 0.5 - 0.5 * mu);+ vec3 ambient = vec3(0.22, 0.28, 0.38) * (0.3 + 0.7 * h);+ volumeStep(radiance, transmittance, vec3(sigma), sigma * (sunLight + ambient), dt);+ lightAcc += luminance(sunLight) * transmittance.x;+ ambientAcc += luminance(ambient) * transmittance.x;+ }+ steps++;+ if (transmittance.x < 0.01) break;+ t += dt;+ }++#if DEBUG_MODE == 4+ return debugHeat(float(steps) / float(STEPS));+#elif DEBUG_MODE == 5+ return vec3(1.0 - transmittance.x, cloudDensity(ro + rd * (t0 + 0.5 * (t1 - t0)), 5) / DENSITY, 0.0);+#elif DEBUG_MODE == 6+ return vec3(lightAcc, ambientAcc, 0.0) * 0.1;+#endif++ // distant clouds fade into the sky+ float fade = exp(-0.04 * max(t0, 0.0));+ return mix(col, col * transmittance + radiance, fade);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 col = render(fragCoord);+#if DEBUG_MODE == 0+ col = linearToSrgb(tonemapAgX(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/gallery/volumetric-clouds.png b/gallery/volumetric-clouds.pngnew file mode 100644index 0000000..0e07e93Binary files /dev/null and b/gallery/volumetric-clouds.png differdiff --git a/gemini-extension.json b/gemini-extension.jsonnew file mode 100644index 0000000..f102f3e--- /dev/null+++ b/gemini-extension.json@@ -0,0 +1,5 @@+{+ "name": "shader-skills",+ "version": "2.0.0",+ "description": "Procedural GLSL / Shadertoy shader skill with a verified building-block library, bundler and checker."+}diff --git a/prompts/chatgpt-custom-gpt-instructions.md b/prompts/chatgpt-custom-gpt-instructions.mddeleted file mode 100644index b431b6b..0000000--- a/prompts/chatgpt-custom-gpt-instructions.md+++ /dev/null@@ -1,25 +0,0 @@-# ChatGPT / Custom GPT Instructions: Shader Skills--You are a procedural shader engineering assistant. Use the files in this repository as your knowledge base.--Primary instruction file:--```text-prompts/universal-system-prompt.md-```--Reference directory:--```text-skills/codex/shader-art-coding/references/-```--When answering:--- Decompose the visual target into formal mathematical fields.-- Produce Shadertoy-compatible GLSL by default.-- Include debug modes and tuning constants.-- Explain equation-code relationships.-- Include validation and debugging guidance appropriate to the user's target runtime.--Use formal reusable terminology. Avoid naming reusable formulas after scene objects unless the user’s requested subject requires it.diff --git a/prompts/claude-project-instructions.md b/prompts/claude-project-instructions.mddeleted file mode 100644index b4b8559..0000000--- a/prompts/claude-project-instructions.md+++ /dev/null@@ -1,16 +0,0 @@-# Claude Project Instructions: Shader Skills--Use this repository as a procedural shader art knowledge base.--First read:--1. `prompts/universal-system-prompt.md`-2. The relevant files in `skills/codex/shader-art-coding/references/`--When asked to create or improve a shader:--- Use formal mathematical decomposition: domains, scalar fields, implicit surfaces, masks, IDs, material fields, lighting, and post-processing.-- Use `iDebugMode` for debug views.-- Explain what each debug mode verifies.--Avoid copying third-party shader code. Use original implementations based on the reference formulas.diff --git a/prompts/copilot-instructions.md b/prompts/copilot-instructions.mddeleted file mode 100644index 448f014..0000000--- a/prompts/copilot-instructions.md+++ /dev/null@@ -1,13 +0,0 @@-# GitHub Copilot Instructions: Shader Skills--This repository contains platform-neutral shader art instructions.--For shader code:--- Prefer Shadertoy-compatible GLSL.-- Use formal helper names for domains, implicit fields, masks, IDs, material fields, and lighting terms.-- Add debug branches using `iDebugMode`.-- Keep raymarch loops bounded.-- Avoid copying external shader source.--Use `skills/codex/shader-art-coding/references/` for equation-code patterns.diff --git a/prompts/cursor-rules.md b/prompts/cursor-rules.mddeleted file mode 100644index 613475a..0000000--- a/prompts/cursor-rules.md+++ /dev/null@@ -1,10 +0,0 @@-# Cursor Rules: Shader Skills--Apply these rules to shader work in this repository.--- Read `prompts/universal-system-prompt.md` before writing shader code.-- Read only relevant references from `skills/codex/shader-art-coding/references/`.-- Preserve Shadertoy-style `mainImage`.-- Use `iDebugMode` for inspectable intermediate fields.-- Use formal mathematical names for reusable helpers.-- Do not introduce texture dependencies unless requested.diff --git a/prompts/gemini-gems-instructions.md b/prompts/gemini-gems-instructions.mddeleted file mode 100644index ba3caf1..0000000--- a/prompts/gemini-gems-instructions.md+++ /dev/null@@ -1,16 +0,0 @@-# Gemini / Gems Instructions: Shader Skills--Act as a procedural shader art coding expert using this repository as your instruction pack.--Load:--- `prompts/universal-system-prompt.md`-- Task-relevant references from `skills/codex/shader-art-coding/references/`--Default behavior:--- Produce Shadertoy-compatible GLSL.-- Use formal mathematical naming for reusable formulas.-- Include `iDebugMode` branches for scalar fields, normals, IDs, depth/steps, masks, and lighting.-- Prefer original formula-code couples from the references.-- Include validation and debugging guidance appropriate to the user's target runtime.diff --git a/prompts/universal-system-prompt.md b/prompts/universal-system-prompt.mddeleted file mode 100644index 1d8d019..0000000--- a/prompts/universal-system-prompt.md+++ /dev/null@@ -1,68 +0,0 @@-# Universal Shader Art Coding Instructions--You are a procedural shader art coding agent. Use this instruction pack when writing, improving, debugging, explaining, porting, or art-directing GLSL, Shadertoy, WebGL, SDF raymarching, heightfield, procedural texture, material, or mathematical drawing shaders.--## Core Behavior--Treat shader work as visual engineering:--1. Define the intended image as formal fields: coordinate domains, implicit surfaces, scalar masks, material IDs, density fields, lighting terms, and post-process transforms.-2. Choose the simplest rendering model that can express the image:- - 2D analytic fields for flat graphic forms and masks.- - SDF raymarching for implicit geometry and modular/organic 3D structures.- - Heightfield marching for scalar terrain-like surfaces.- - Coverage/density fields for atmosphere, volumes, or clumped detail.- - Fullscreen post-processing for feedback, transitions, and color transforms.-3. Build the shader in inspectable stages: coordinates, primitive field, material ID, lighting, atmosphere, detail, color grade.-4. Add debug modes before adding complexity.-5. Prefer original compact formulas and readable helper functions.-6. Explain formulas by the visual control they expose: scale, thickness, softness, frequency, density, curvature, phase, or material separation.--## Required Output Quality--When producing a complete Shadertoy shader:--- Include `void mainImage(out vec4 fragColor, in vec2 fragCoord)`.-- Normalize coordinates with aspect preservation:--```glsl-vec2 uv = (2.0*fragCoord - iResolution.xy) / iResolution.y;-```--- Keep loops bounded by compile-time constants.-- Include debug support via `iDebugMode` or an equivalent constant.-- Avoid texture dependencies unless the user provides texture inputs.-- Include a short tuning guide for important constants.--## Debug Mode Convention--- `0`: final render-- `1`: scalar field / SDF contours-- `2`: normals-- `3`: material IDs-- `4`: step count / depth-- `5`: masks / density fields-- `6`: lighting terms--## Reference Selection--Use the references in `skills/codex/shader-art-coding/references/` as platform-neutral knowledge:--- `shader-workflow.md`: end-to-end workflow.-- `math-patterns.md`: coordinate and shaping formulas.-- `rendering-patterns.md`: raymarching, normals, lighting, fog, tonemapping.-- `composition-and-debugging.md`: visual hierarchy and formula verification.-- `formula-cookbook.md`: visually verified formula stacks.-- `formula-code-couples-sdf.md`: implicit geometry equation-code pairs.-- `formula-code-couples-terrain.md`: heightfield/density/atmosphere equation-code pairs.-- `formula-code-couples-materials.md`: material/color/polish equation-code pairs.-- `glsl-snippets.md`: reusable Shadertoy-compatible snippets.--Read only the relevant references for the user’s task.--## Style Rules--- Use formal mathematical names in reusable references and explanations.-- Avoid scene-specific names for reusable operators. Prefer names like `radialRowCellSpace`, `bilobedCarrier`, `coverageMask`, `interstitialShell`, `sparseSpotField`, `upwardAccumulation`, and `anisotropicStrandField`.-- Scene labels are allowed only when directly answering a user’s requested subject.-- Do not copy source code from external videos or shaders. Distill techniques into original formulas and implementations.diff --git a/skills/codex/shader-art-coding/SKILL.md b/skills/codex/shader-art-coding/SKILL.mddeleted file mode 100644index e1c6945..0000000--- a/skills/codex/shader-art-coding/SKILL.md+++ /dev/null@@ -1,61 +0,0 @@-----name: shader-art-coding-description: Expert procedural shader art and GLSL/Shadertoy coding guidance. Use when an agent needs to write, improve, debug, explain, port, critique, or art-direct fragment shaders, raymarching shaders, signed-distance-field scenes, procedural heightfields, mathematical organic/object drawing, noise/fbm/domain-warp effects, lighting/material shaders, or compact real-time visual code.-license: MIT-metadata:- hermes:- tags: [shader, glsl, shadertoy, procedural-art, raymarching, sdf]- category: development------# Shader Art Coding--## Operating Mode--Treat shader work as visual engineering. Start from the intended image, choose the smallest mathematical representation that can produce it, then grow the shader through inspectable stages.--For every substantial shader task:--1. State the visual target, camera/framing, dominant forms, material families, and motion.-2. Choose the rendering approach:- - 2D analytic drawing for icons, posters, stylized flat scenes, UI effects, and compact masks.- - Heightfield marching for scalar heightfields, sky radiance fields, fluids, density layers, and atmosphere.- - SDF raymarching for sculpted 3D forms, modular structures, organic carriers, tunnels, and abstract scenes.- - Fullscreen post/effect shader for transitions, glitches, feedback, color, and image processing.-3. Build the first visible image quickly: coordinates, background, one primitive, one light or color ramp.-4. Add debug views before adding complexity: distance field, IDs, normals, layer masks, step count, depth, material index, and noise octave contribution.-5. Refine in this order: proportions, composition, material separation, lighting, atmosphere, color grading, antialiasing, performance.-6. Prefer original compact helpers over copied shader code. Explain non-obvious formulas with the visual control they create.--## Reference Routing--Read only what the current task needs:--- `references/shader-workflow.md`: end-to-end process, task decomposition, build order, and review checklist.-- `references/math-patterns.md`: coordinates, shaping functions, SDFs, repetition, noise, fbm, domain warping, and palettes.-- `references/rendering-patterns.md`: raymarching, normals, AO, soft shadows, materials, fog, tonemapping, and antialiasing.-- `references/composition-and-debugging.md`: visual hierarchy, debug modes, readable iterations, and shader critique.-- `references/formula-cookbook.md`: visually checked formula stacks for radial modular repetition, heightfield synthesis, implicit organic composition, volumetric density, atmospheric fields, and material breakup.-- `references/formula-code-couples-sdf.md`: equation-to-GLSL pairs for implicit primitives, booleans, smoothing, local transforms, contour debugging, radial-cell lattices, bilateral feature fields, anisotropic strand fields, and shell intersections.-- `references/formula-code-couples-terrain.md`: equation-to-GLSL pairs for polynomial height patches, octave synthesis, finite-difference normals, horizon visibility, density fields, atmospheric coverage, accumulation masks, and distance LOD.-- `references/formula-code-couples-materials.md`: equation-to-GLSL pairs for palettes, scalar material masks, lighting terms, sparse stochastic spots, ID-based albedo variation, composition overlays, antialiasing, tonemapping, and temporal polish.-- `references/glsl-snippets.md`: original Shadertoy-compatible helper snippets and a compact complete template.--## Output Expectations--When writing shader code:--- Produce Shadertoy-compatible GLSL unless the user asks for another target.-- Include `mainImage(out vec4 fragColor, in vec2 fragCoord)` for complete Shadertoy shaders.-- Use stable coordinate normalization: center coordinates and preserve aspect ratio.-- Keep loops bounded by compile-time constants.-- Include 1-3 debug switches or clearly described places to inspect intermediate fields.-- Avoid texture dependencies unless the user provides textures or explicitly wants them.-- Finish with a short visual tuning guide: which constants control scale, softness, color, lighting, and motion.--When improving an existing shader:--- Identify the current rendering model and the likely bottlenecks.-- Preserve the user's intent and public interface.-- Improve one layer at a time: correctness, readability, visual quality, then speed.-- Call out risky changes such as altered coordinate scale, changed material IDs, or loop count increases.diff --git a/skills/codex/shader-art-coding/agents/openai.yaml b/skills/codex/shader-art-coding/agents/openai.yamldeleted file mode 100644index 03efb07..0000000--- a/skills/codex/shader-art-coding/agents/openai.yaml+++ /dev/null@@ -1,4 +0,0 @@-interface:- display_name: "Shader Art Coding"- short_description: "Procedural shader math and GLSL craft"- default_prompt: "Use $shader-art-coding to design and implement a polished Shadertoy GLSL shader."diff --git a/skills/codex/shader-art-coding/references/glsl-snippets.md b/skills/codex/shader-art-coding/references/glsl-snippets.mddeleted file mode 100644index 1df377f..0000000--- a/skills/codex/shader-art-coding/references/glsl-snippets.md+++ /dev/null@@ -1,261 +0,0 @@-# GLSL Snippets--These snippets are original Shadertoy-compatible building blocks. Adapt them to the user's scene.--## Hash and Noise--```glsl-float hash12(vec2 p) {- vec3 p3 = fract(vec3(p.xyx) * 0.1031);- p3 += dot(p3, p3.yzx + 33.33);- return fract((p3.x + p3.y) * p3.z);-}--float noise(vec2 p) {- vec2 i = floor(p);- vec2 f = fract(p);- vec2 u = f*f*(3.0 - 2.0*f);- float a = hash12(i + vec2(0.0, 0.0));- float b = hash12(i + vec2(1.0, 0.0));- float c = hash12(i + vec2(0.0, 1.0));- float d = hash12(i + vec2(1.0, 1.0));- return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);-}--float fbm(vec2 p) {- float f = 0.0;- float a = 0.5;- mat2 m = mat2(1.6, 1.2, -1.2, 1.6);- for (int i = 0; i < 5; i++) {- f += a * noise(p);- p = m * p + 11.7;- a *= 0.5;- }- return f;-}-```--## 2D Masks--```glsl-float sdCircle(vec2 p, float r) {- return length(p) - r;-}--float sdRoundBox(vec2 p, vec2 b, float r) {- vec2 q = abs(p) - b + r;- return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;-}--float fillMask(float d) {- return smoothstep(fwidth(d), -fwidth(d), d);-}--float strokeMask(float d, float width) {- float w = fwidth(d);- return smoothstep(width + w, width - w, abs(d));-}-```--## Camera--```glsl-mat3 lookAt(vec3 ro, vec3 ta, float roll) {- vec3 ww = normalize(ta - ro);- vec3 uu = normalize(cross(ww, vec3(sin(roll), cos(roll), 0.0)));- vec3 vv = cross(uu, ww);- return mat3(uu, vv, ww);-}--vec3 cameraRay(vec2 uv, vec3 ro, vec3 ta, float lens) {- mat3 cam = lookAt(ro, ta, 0.0);- return normalize(cam * vec3(uv, lens));-}-```--## SDF Utility Extras--```glsl-float smin(float a, float b, float k) {- float h = clamp(0.5 + 0.5*(b - a)/k, 0.0, 1.0);- return mix(b, a, h) - k*h*(1.0 - h);-}--float sdEllipsoid(vec3 p, vec3 r) {- float k0 = length(p / r);- float k1 = length(p / (r*r));- return k0 * (k0 - 1.0) / k1;-}--float sdTorus(vec3 p, vec2 t) {- vec2 q = vec2(length(p.xz) - t.x, p.y);- return length(q) - t.y;-}--float opSmoothSub(float a, float b, float k) {- float h = clamp(0.5 - 0.5*(b + a)/k, 0.0, 1.0);- return mix(a, -b, h) + k*h*(1.0 - h);-}-```--## Debug Displays--```glsl-vec3 contourDebug(float d) {- float bands = 0.5 + 0.5*cos(80.0*d);- float surface = smoothstep(0.02, 0.0, abs(d));- return mix(vec3(bands), vec3(1.0, 0.35, 0.1), surface);-}--vec3 idColor(float id) {- return vec3(fract(id*0.37), fract(id*0.61), fract(id*0.83));-}-```--## Heightfield Helpers--```glsl-float smoothCellHeight(vec2 p) {- vec2 i = floor(p);- vec2 f = fract(p);- vec2 u = f*f*f*(f*(f*6.0 - 15.0) + 10.0);- float a = hash12(i + vec2(0.0, 0.0));- float b = hash12(i + vec2(1.0, 0.0));- float c = hash12(i + vec2(0.0, 1.0));- float d = hash12(i + vec2(1.0, 1.0));- return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);-}--vec3 heightNormal(vec2 p) {- float e = 0.02;- float h = terrainHeight(p);- return normalize(vec3(- h - terrainHeight(p + vec2(e, 0.0)),- e,- h - terrainHeight(p + vec2(0.0, e))- ));-}-```--`heightNormal` expects the shader to define `terrainHeight(vec2)`.--## Complete Minimal Raymarch Shader--```glsl-#define DEBUG_MODE 0--struct Hit {- float d;- float mat;-};--mat3 lookAt(vec3 ro, vec3 ta, float roll) {- vec3 ww = normalize(ta - ro);- vec3 uu = normalize(cross(ww, vec3(sin(roll), cos(roll), 0.0)));- vec3 vv = cross(uu, ww);- return mat3(uu, vv, ww);-}--vec3 cameraRay(vec2 uv, vec3 ro, vec3 ta, float lens) {- mat3 cam = lookAt(ro, ta, 0.0);- return normalize(cam * vec3(uv, lens));-}--float hash12(vec2 p) {- vec3 p3 = fract(vec3(p.xyx) * 0.1031);- p3 += dot(p3, p3.yzx + 33.33);- return fract((p3.x + p3.y) * p3.z);-}--float sdSphere(vec3 p, float r) {- return length(p) - r;-}--float sdBox(vec3 p, vec3 b) {- vec3 q = abs(p) - b;- return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);-}--float opSmoothUnion(float a, float b, float k) {- float h = clamp(0.5 + 0.5*(b - a)/k, 0.0, 1.0);- return mix(b, a, h) - k*h*(1.0 - h);-}--Hit mapScene(vec3 p) {- Hit h = Hit(p.y + 0.75, 1.0);-- vec3 q = p - vec3(0.0, 0.0, 3.0);- float body = sdSphere(q, 0.85);- float cut = sdBox(q - vec3(0.0, -0.25, 0.0), vec3(1.2, 0.2, 1.2));- body = max(body, -cut);-- if (body < h.d) h = Hit(body, 2.0);- return h;-}--Hit raymarch(vec3 ro, vec3 rd) {- float t = 0.0;- float mat = 0.0;- for (int i = 0; i < 96; i++) {- vec3 p = ro + rd*t;- Hit h = mapScene(p);- if (h.d < 0.001*t + 0.0005) return Hit(t, h.mat);- if (t > 60.0) break;- t += h.d;- mat = h.mat;- }- return Hit(-1.0, mat);-}--vec3 calcNormal(vec3 p) {- vec2 e = vec2(0.001, -0.001);- return normalize(- e.xyy*mapScene(p + e.xyy).d +- e.yyx*mapScene(p + e.yyx).d +- e.yxy*mapScene(p + e.yxy).d +- e.xxx*mapScene(p + e.xxx).d- );-}--vec3 materialColor(float mat, vec3 p) {- if (mat < 1.5) return vec3(0.34, 0.30, 0.25);- float grain = hash12(floor(p.xz*12.0));- return mix(vec3(0.75, 0.42, 0.28), vec3(0.95, 0.72, 0.48), grain);-}--vec3 tonemap(vec3 x) {- x = max(x, 0.0);- return x / (1.0 + x);-}--void mainImage(out vec4 fragColor, in vec2 fragCoord) {- vec2 uv = (2.0*fragCoord - iResolution.xy) / iResolution.y;-- float time = iTime;- vec3 ro = vec3(2.6*sin(0.2*time), 1.1, -1.2 + 2.6*cos(0.2*time));- vec3 ta = vec3(0.0, -0.05, 3.0);- vec3 rd = cameraRay(uv, ro, ta, 1.8);-- vec3 sky = mix(vec3(0.62, 0.76, 0.95), vec3(0.08, 0.11, 0.16), smoothstep(-0.2, 0.8, uv.y));- vec3 col = sky;-- Hit hit = raymarch(ro, rd);- if (hit.d > 0.0) {- vec3 p = ro + rd*hit.d;- vec3 n = calcNormal(p);- vec3 ldir = normalize(vec3(0.5, 0.8, -0.3));- float ndl = max(dot(n, ldir), 0.0);- float fres = pow(1.0 + dot(n, rd), 5.0);- vec3 albedo = materialColor(hit.mat, p);- col = albedo * (0.18 + 1.25*ndl) + 0.16*fres;- float fog = 1.0 - exp(-0.025*hit.d*hit.d);- col = mix(col, sky, clamp(fog, 0.0, 1.0));-- if (DEBUG_MODE == 1) col = 0.5 + 0.5*n;- if (DEBUG_MODE == 2) col = vec3(fract(hit.mat*0.37), fract(hit.mat*0.61), fract(hit.mat*0.83));- }-- col = pow(tonemap(col), vec3(1.0/2.2));- fragColor = vec4(col, 1.0);-}-```diff --git a/skills/codex/shader-art-coding/references/math-patterns.md b/skills/codex/shader-art-coding/references/math-patterns.mddeleted file mode 100644index ae49040..0000000--- a/skills/codex/shader-art-coding/references/math-patterns.md+++ /dev/null@@ -1,160 +0,0 @@-# Math Patterns--## Coordinates--Use centered coordinates for Shadertoy:--```glsl-vec2 uv = (2.0*fragCoord - iResolution.xy) / iResolution.y;-```--Create local spaces by translating, rotating, scaling, mirroring, or repeating before evaluating a shape. Prefer local-space transforms over complicated global formulas.--Common transforms:--- Mirror symmetry: `p.x = abs(p.x);`-- Polar angle: `float a = atan(p.y, p.x);`-- Radius: `float r = length(p);`-- Cell ID: `vec2 id = floor(p);`-- Local cell coordinate: `vec2 q = fract(p) - 0.5;`-- Rotate a local part instead of rotating the whole scene when posing features.--```glsl-mat2 rot(float a) {- float s = sin(a), c = cos(a);- return mat2(c, -s, s, c);-}-```--## Shaping Functions--Use shaping functions as art controls:--- `smoothstep(a, b, x)` creates soft masks and antialias-like transitions.-- `pow(x, k)` remaps contrast; `k > 1` tightens highlights, `k < 1` opens shadows.-- `exp(-k*x)` creates haze, glow falloff, and atmospheric depth.-- `sin` and `cos` are best as periodic controls, not random detail.-- `mix(a, b, t)` should usually receive a named mask.--Name masks after their visual role:--```glsl-float rimMask = smoothstep(0.15, 0.0, abs(d));-float accumulationLine = smoothstep(0.35, 0.75, height + 0.2*noise);-```--## SDF Basics--An SDF returns negative inside, zero on the surface, positive outside. Keep primitive helpers small and composable.--Useful primitives:--```glsl-float sdSphere(vec3 p, float r) {- return length(p) - r;-}--float sdBox(vec3 p, vec3 b) {- vec3 q = abs(p) - b;- return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);-}--float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {- vec3 pa = p - a, ba = b - a;- float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);- return length(pa - ba*h) - r;-}-```--Composition:--```glsl-float opUnion(float a, float b) { return min(a, b); }-float opSub(float a, float b) { return max(a, -b); }-float opIntersect(float a, float b) { return max(a, b); }--float opSmoothUnion(float a, float b, float k) {- float h = clamp(0.5 + 0.5*(b - a)/k, 0.0, 1.0);- return mix(b, a, h) - k*h*(1.0 - h);-}-```--Use smooth union for organic blending and hard boolean operations for manufactured or carved forms.--Smooth subtraction is useful for eyeaperture bands, sockets, grooves, dents, and soft cuts:--```glsl-float opSmoothSub(float a, float b, float k) {- float h = clamp(0.5 - 0.5*(b + a)/k, 0.0, 1.0);- return mix(a, -b, h) + k*h*(1.0 - h);-}-```--## Repetition and IDs--Separate repetition from variation:--```glsl-vec2 cell = floor(p.xz);-vec2 local = fract(p.xz) - 0.5;-float rnd = hash12(cell);-```--For circular repetition, use angle sectors and radius independently. Keep the sector ID for material variation.--## Noise, FBM, and Domain Warping--Use noise in tiers:--- Low frequency: silhouette, heightfield height, coverage masses.-- Mid frequency: material breakup, vegetation clumps, stone surface.-- High frequency: grain, pores, scratches, sparkle.--FBM pattern:--```glsl-float fbm(vec2 p) {- float a = 0.5;- float f = 0.0;- mat2 m = mat2(1.6, 1.2, -1.2, 1.6);- for (int i = 0; i < 5; i++) {- f += a * noise(p);- p = m * p;- a *= 0.5;- }- return f;-}-```--Domain warping means using one field to move the coordinates of another:--```glsl-vec2 warp = vec2(fbm(p + 3.1), fbm(p - 2.7));-float pattern = fbm(p + 0.35*warp);-```--Keep warp amplitude small until the base structure works.--## Formula Debugging--Every scalar field can become an image. Before using a scalar to drive color, geometry, or animation, show it:--```glsl-fragColor = vec4(vec3(fieldValue), 1.0);-fragColor = vec4(vec3(smoothstep(a, b, fieldValue)), 1.0);-fragColor = vec4(0.5 + 0.5*normal, 1.0);-```--If a field is too noisy in grayscale, it will be too noisy after coloring. If a mask has bad edges, material polish will not save it.--## Palettes--Use palettes as controlled ramps, not random RGB constants:--```glsl-vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) {- return a + b*cos(6.28318*(c*t + d));-}-```--For natural scenes, combine physically motivated value ramps with gentle hue shifts: warmer light, cooler shadow, lower saturation in distance.diff --git a/skills/codex/shader-art-coding/references/rendering-patterns.md b/skills/codex/shader-art-coding/references/rendering-patterns.mddeleted file mode 100644index 16351d9..0000000--- a/skills/codex/shader-art-coding/references/rendering-patterns.md+++ /dev/null@@ -1,168 +0,0 @@-# Rendering Patterns--## Raymarching Structure--Use a clear SDF scene function and a bounded marcher:--```glsl-struct Hit {- float d;- float mat;-};--Hit mapScene(vec3 p) {- Hit h = Hit(1e5, 0.0);- float ground = p.y + 1.0;- h = Hit(ground, 1.0);-- float body = sdSphere(p - vec3(0.0, 0.0, 3.0), 1.0);- if (body < h.d) h = Hit(body, 2.0);- return h;-}--Hit raymarch(vec3 ro, vec3 rd) {- float t = 0.0;- float mat = 0.0;- for (int i = 0; i < 96; i++) {- vec3 p = ro + rd*t;- Hit h = mapScene(p);- if (h.d < 0.001*t) return Hit(t, h.mat);- if (t > 80.0) break;- t += h.d;- mat = h.mat;- }- return Hit(-1.0, mat);-}-```--Scale epsilon with distance to reduce shimmer in far geometry.--## Normals--Use tetrahedral sampling for compact normals:--```glsl-vec3 calcNormal(vec3 p) {- vec2 e = vec2(0.001, -0.001);- return normalize(- e.xyy*mapScene(p + e.xyy).d +- e.yyx*mapScene(p + e.yyx).d +- e.yxy*mapScene(p + e.yxy).d +- e.xxx*mapScene(p + e.xxx).d- );-}-```--If the surface has procedural displacement, sample the same displaced field for normals.--## Lighting--Start with one directional light, then add fill and ambient:--```glsl-vec3 shade(vec3 p, vec3 n, vec3 rd, float mat) {- vec3 ldir = normalize(vec3(0.6, 0.8, 0.4));- float ndl = max(dot(n, ldir), 0.0);- float fres = pow(1.0 + dot(n, rd), 5.0);- vec3 albedo = materialColor(mat, p);- vec3 col = albedo * (0.18 + 1.25*ndl);- col += 0.15*fres;- return col;-}-```--Keep material identity visible under diffuse light before adding specular polish.--## Ambient Occlusion and Soft Shadow--Use small, bounded approximations:--```glsl-float calcAO(vec3 p, vec3 n) {- float occ = 0.0;- float sca = 1.0;- for (int i = 0; i < 5; i++) {- float h = 0.02 + 0.12*float(i)/4.0;- float d = mapScene(p + n*h).d;- occ += (h - d) * sca;- sca *= 0.75;- }- return clamp(1.0 - 2.0*occ, 0.0, 1.0);-}--float softShadow(vec3 ro, vec3 rd, float mint, float maxt, float k) {- float res = 1.0;- float t = mint;- for (int i = 0; i < 48; i++) {- float h = mapScene(ro + rd*t).d;- if (h < 0.001) return 0.0;- res = min(res, k*h/t);- t += clamp(h, 0.02, 0.5);- if (t > maxt) break;- }- return clamp(res, 0.0, 1.0);-}-```--Use these as art controls, not as a substitute for good shape design.--## Heightfields and Atmosphere--For landscapes, separate:--- Terrain height function.-- Surface normal from height differences.-- Material masks from altitude, slope, moisture/noise, and distance.-- Sky color and sun direction.-- Fog based on distance and height.--Atmosphere should reinforce depth:--```glsl-vec3 applyFog(vec3 col, vec3 fogCol, float dist) {- float f = 1.0 - exp(-0.025*dist);- return mix(col, fogCol, clamp(f, 0.0, 1.0));-}-```--## Antialiasing--For analytic 2D masks, use derivatives when available:--```glsl-float aaStep(float edge, float x) {- float w = fwidth(x);- return smoothstep(edge - w, edge + w, x);-}-```--For SDF edges, avoid fixed-width smoothing in screen space unless the scale is fixed. Derivative-aware or distance-scaled thresholds usually look better.--## Color Management--If lighting can exceed 1.0, tonemap and gamma-correct:--```glsl-vec3 tonemap(vec3 x) {- x = max(x, 0.0);- return x / (1.0 + x);-}--vec3 toSRGB(vec3 x) {- return pow(max(x, 0.0), vec3(1.0/2.2));-}-```--## Practical Renderer Scaffolding--For complex formula-heavy shaders, keep these renderer pieces stable while changing the scene:--- Camera ray generation.-- `mapScene` returning distance and material ID.-- Normal calculation using the same map as rendering.-- Ambient occlusion and soft shadow functions.-- Background/sky.-- Tonemap/gamma.-- Optional cheap dithering after color grading.--This lets formula experiments focus on one field at a time. Do not rewrite the renderer while testing a new SDF, terrain patch, or material mask unless the renderer is the problem.diff --git a/skills/codex/shader-art-coding/scripts/validate_skill_examples.py b/skills/codex/shader-art-coding/scripts/validate_skill_examples.pydeleted file mode 100644index 76c0b70..0000000--- a/skills/codex/shader-art-coding/scripts/validate_skill_examples.py+++ /dev/null@@ -1,68 +0,0 @@-#!/usr/bin/env python3-"""Validate GLSL snippets bundled with the shader-art-coding skill."""--from __future__ import annotations--import re-import sys-from pathlib import Path---FENCE_RE = re.compile(r"```glsl\n(.*?)\n```", re.DOTALL)---def balanced(source: str, open_ch: str, close_ch: str) -> bool:- depth = 0- for ch in source:- if ch == open_ch:- depth += 1- elif ch == close_ch:- depth -= 1- if depth < 0:- return False- return depth == 0---def main() -> int:- skill_dir = Path(__file__).resolve().parents[1]- refs = skill_dir / "references"- failures: list[str] = []- snippet_count = 0- complete_count = 0-- for path in sorted(refs.glob("*.md")):- text = path.read_text(encoding="utf-8")- for index, snippet in enumerate(FENCE_RE.findall(text), start=1):- snippet_count += 1- label = f"{path.name} snippet {index}"- if ("TO" + "DO") in snippet:- failures.append(f"{label}: contains placeholder text")- for a, b, name in [("{", "}", "braces"), ("(", ")", "parentheses"), ("[", "]", "brackets")]:- if not balanced(snippet, a, b):- failures.append(f"{label}: unbalanced {name}")- if "void mainImage" in snippet:- complete_count += 1- for required in ["fragColor", "fragCoord", "iResolution"]:- if required not in snippet:- failures.append(f"{label}: mainImage missing {required}")- for loop in re.findall(r"for\\s*\\((.*?)\\)", snippet):- if "int" not in loop or "<" not in loop:- failures.append(f"{label}: loop may not be statically bounded: {loop}")-- if snippet_count == 0:- failures.append("no GLSL snippets found")- if complete_count == 0:- failures.append("no complete mainImage snippet found")-- if failures:- print("Validation failed:")- for failure in failures:- print(f"- {failure}")- return 1-- print(f"Validated {snippet_count} GLSL snippets; {complete_count} complete shader snippet(s).")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/skills/shader-art-coding/SKILL.md b/skills/shader-art-coding/SKILL.mdnew file mode 100644index 0000000..a94eb5a--- /dev/null+++ b/skills/shader-art-coding/SKILL.md@@ -0,0 +1,103 @@+---+name: shader-art-coding+description: >-+ Writes, debugs, and art-directs procedural GLSL fragment shaders (Shadertoy mainImage, WebGL2 / GLSL ES 3.00):+ SDF raymarching, 2D distance-field graphics, noise / fBm / domain warping, heightfield terrain, clouds and other+ volumes, PBR lighting, color and tonemapping. Ships a verified GLSL building-block library with a bundler and+ checker. Use when the user asks for a shader, Shadertoy, GLSL/.frag/.glsl code, a raymarcher, an SDF scene, a+ procedural texture or generative visual, or wants a shader fixed, optimized, ported or explained. Not for+ HLSL/Unity ShaderLab or non-graphics GPU compute.+license: MIT+metadata:+ hermes:+ tags:+ - shader+ - glsl+ - shadertoy+ - procedural-art+ - raymarching+ - sdf+ category: development+---++# Shader Art Coding++Treat shader work as visual engineering: start from the intended image, choose the smallest mathematical model that+can produce it, build it in inspectable stages, and verify each stage with a debug view.++## Workflow++1. **Target.** State the image: subject, camera and framing, dominant forms, materials, light, motion.+2. **Route.** Pick the rendering model and starting template from `references/subject-routing.md`:+ 2D distance fields (posters, icons, patterns), SDF raymarching (objects, characters), heightfield marching+ (landscapes), volume integration (clouds, smoke, fire).+3. **Assemble from the library.** Find building blocks with `python3 scripts/glsl_tools.py search <words>` or+ `references/library-index.md`, and call them by name. Do not paste or re-derive library code; it is tested.+4. **First image fast.** Coordinates, background, one primitive, one light. Then add the debug views.+5. **Refine in order:** proportions, composition, material separation, lighting, atmosphere, color, antialiasing,+ performance.+6. **Bundle and check.** `python3 scripts/glsl_tools.py bundle shader.glsl -o out.glsl` inlines exactly the+ functions used. `python3 scripts/glsl_tools.py check out.glsl` lints it and compiles it with glslangValidator+ when installed. Fix every error, then deliver `out.glsl`.++Run the scripts from this skill's directory. They need only Python 3.++## Conventions++- **Coordinates:** `vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;`, so one pixel is+ `2.0 / iResolution.y`.+- **Scene contract:** `vec2 map(vec3 p)` returns `vec2(distance, materialId)`. `raymarch`, `calcNormal`,+ `softShadow`, `calcAO` and `sdfThickness` all use it.+- **Debug:** `#define DEBUG_MODE 0` with 0 final, 1 distance field, 2 normals, 3 ids, 4 steps, 5 masks,+ 6 lighting terms.+- **Color pipeline:** light in linear and decode picked colors with `srgbToLinear`. Then exposure, then the+ tonemap (`tonemapAgX` by default, per AA sample), then the average, then `linearToSrgb` once, then+ `ditherTPDF`.+- **Distances:** respect the `@exact` / `@bound` / `@approx` tags. If a deformation pushes Lipschitz above 1,+ divide the distance or lower the `stepScale` of `raymarch`.++## Hard rules (these break Shadertoy/WebGL)++- No `#version` line, no custom uniforms, no `gl_FragColor` / `texture2D` / `iGlobalTime`.+- No `?:` on structs. Use `vec2(distance, id)` or `if`.+- Write float literals: `2.0 * PI`, `clamp(x, 0.0, 1.0)`.+- No `fract(sin(...) * 43758.5453)` hashes. Use `hash12` / `hash22` / `hash33` (integer PCG).+- Guard NaN sources: `atan(0, 0)`, `pow` of negatives, `sqrt` of negatives, `normalize(vec3(0))`.+- Keep `dFdx` / `fwidth` out of non-uniform branches and loops, or use an explicit pixel size.++## Reference routing++Read only what the task needs:++| File | Read when |+|---|---|+| `references/subject-routing.md` | starting from a subject ("a jellyfish", "mountains"); maps formal names to subjects |+| `references/library-index.md` | choosing functions: every library function with signature, exactness and uses |+| `references/sdf-library-guide.md` | modeling: exactness tiers, blends, neighbor-checked repetition, deformation limits, WebGL pitfalls |+| `references/rendering-pipeline.md` | lighting rigs, shadows/AO, sky and fog, volumes, tonemapping, AA, performance |+| `references/shader-workflow.md` | planning a complex shader end to end; review checklist |+| `references/composition-and-debugging.md` | the image reads poorly, or something is visually wrong |+| `references/formula-cookbook.md` | multi-step recipes: modular cell lattices, terrain synthesis, organic composition |+| `references/formula-code-couples-sdf.md` | equation-to-code for organic and modular SDF features |+| `references/formula-code-couples-terrain.md` | heightfields, density fields, accumulation, atmosphere |+| `references/formula-code-couples-materials.md` | masks, palettes, lighting terms, polish, motion |++Templates in `templates/` are complete, render-verified starting points (gallery in the repository README):+`raymarch-sdf.glsl`, `terrain.glsl`, `volumetric-clouds.glsl`, `sdf-2d-poster.glsl`, `pattern-swatches.glsl`.++## Output expectations++When writing a shader:++- Deliver the bundled, paste-ready Shadertoy code with `mainImage(out vec4 fragColor, in vec2 fragCoord)`.+- Avoid textures unless the user provides them.+- Include `DEBUG_MODE` switches and name the art controls as constants at the top.+- End with a short tuning guide: which constants control scale, softness, color, light and motion.+- Say whether the shader was compile-checked, and how.++When improving an existing shader:++- Identify its rendering model and bottlenecks.+- Preserve its intent and interface.+- Fix correctness first, then readability, visual quality and speed.+- Call out risky changes (coordinate scale, material ids, loop counts).diff --git a/skills/shader-art-coding/agents/openai.yaml b/skills/shader-art-coding/agents/openai.yamlnew file mode 100644index 0000000..0a136ed--- /dev/null+++ b/skills/shader-art-coding/agents/openai.yaml@@ -0,0 +1,5 @@+interface:+ display_name: "Shader Art Coding"+ short_description: "Procedural GLSL/Shadertoy shaders with a verified building-block library"+ brand_color: "#E8673C"+ default_prompt: "Use $shader-art-coding to design and implement a polished Shadertoy GLSL shader, bundled and compile-checked."diff --git a/skills/shader-art-coding/glsl/atmosphere.glsl b/skills/shader-art-coding/glsl/atmosphere.glslnew file mode 100644index 0000000..a054762--- /dev/null+++ b/skills/shader-art-coding/glsl/atmosphere.glsl@@ -0,0 +1,89 @@+//! atmosphere: skies and sun. simpleSky is a cheap artistic gradient. atmosphereSky is physically based single+//! scattering (Rayleigh + Mie + ozone) with constants from Hillaire, "A Scalable and Production Ready Sky and+//! Atmosphere Rendering Technique" (EGSR 2020). Distances are in kilometers to avoid float cancellation.++/// Cheap analytic sky: horizon-to-zenith gradient, darker ground below the horizon, sun glow lobes.+/// Returns linear radiance (roughly 0-2; the glow can exceed 1 near the sun).+/// @use quick backgrounds, reflections, fog color, stylized daylight+vec3 simpleSky(vec3 rd, vec3 sunDir) {+ float y = max(rd.y, 0.0);+ vec3 zenith = vec3(0.12, 0.28, 0.62);+ vec3 horizon = vec3(0.62, 0.74, 0.88);+ vec3 col = mix(horizon, zenith, pow(y, 0.5));+ col = mix(col, vec3(0.28, 0.26, 0.24), smoothstep(0.0, -0.08, rd.y));+ float mu = max(dot(rd, sunDir), 0.0);+ col += vec3(1.0, 0.75, 0.45) * (0.25 * pow(mu, 8.0) + 0.6 * pow(mu, 64.0) + 2.0 * pow(mu, 512.0));+ return col;+}++/// Sun disk with antialiased edge and limb darkening (Neckel 1996). angularRadius in radians (the real sun is+/// 0.00476; art often uses 3-10x). pixelAngle is the angular size of a pixel (about 2 / (iResolution.y * focal)).+/// Returns a 0..1 shape tinted by limb darkening; multiply by a bright sun color (10-50).+/// @use suns, moons (use a different tint), bright stars in skies+vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle) {+ float ang = acos(clamp(dot(rd, sunDir), -1.0, 1.0));+ float edge = 1.0 - smoothstep(angularRadius - pixelAngle, angularRadius + pixelAngle, ang);+ float r = clamp(ang / angularRadius, 0.0, 1.0);+ float muLimb = sqrt(max(1.0 - r * r, 0.0));+ vec3 limb = pow(vec3(muLimb), vec3(0.397, 0.503, 0.652));+ return edge * limb;+}++const float ATMOSPHERE_GROUND_KM = 6360.0;+const float ATMOSPHERE_TOP_KM = 6460.0;++/// Densities (rayleigh, mie, ozone) at altitude h km above the ground.+/// @use custom atmosphere marches (aerial perspective, planet views)+vec3 atmosphereDensity(float h) {+ return vec3(exp(-h / 8.0), exp(-h / 1.2), max(0.0, 1.0 - abs(h - 25.0) / 15.0));+}++/// Extinction per km for the given densities.+/// @use transmittance through air for sun color and aerial perspective+vec3 atmosphereExtinction(vec3 density) {+ const vec3 rayleigh = vec3(5.802, 13.558, 33.1) * 1e-3;+ const float mie = (3.996 + 4.40) * 1e-3;+ const vec3 ozone = vec3(0.650, 1.881, 0.085) * 1e-3;+ return rayleigh * density.x + mie * density.y + ozone * density.z;+}++/// Physically based sky radiance along rd for a viewer viewHeightKm above the ground, with single scattering+/// (16 view steps x 8 light steps). sunIntensity about 20. Sunsets come out somewhat dark because multiple+/// scattering is ignored; add a small ambient term if needed.+/// @use realistic skies, sunsets, aerial perspective colors, planet-from-space views+/// @see https://sebh.github.io/publications/egsr2020.pdf+vec3 atmosphereSky(vec3 rd, vec3 sunDir, float viewHeightKm, float sunIntensity) {+ const vec3 rayleighScatter = vec3(5.802, 13.558, 33.1) * 1e-3;+ const float mieScatter = 3.996e-3;+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + max(viewHeightKm, 0.001), 0.0);+ vec2 top = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_TOP_KM);+ if (top.y <= 0.0) return vec3(0.0);+ vec2 ground = iSphere(ro, rd, vec3(0.0), ATMOSPHERE_GROUND_KM);+ float tStart = max(top.x, 0.0);+ float tEnd = (ground.x > 0.0) ? ground.x : top.y;+ float mu = dot(rd, sunDir);+ float pR = phaseRayleigh(mu);+ float pM = phaseCornetteShanks(mu, 0.8);+ const int VIEW_STEPS = 16;+ const int LIGHT_STEPS = 8;+ float dt = (tEnd - tStart) / float(VIEW_STEPS);+ vec3 radiance = vec3(0.0), transmittance = vec3(1.0);+ for (int i = 0; i < VIEW_STEPS; i++) {+ vec3 p = ro + rd * (tStart + (float(i) + 0.5) * dt);+ vec3 dens = atmosphereDensity(length(p) - ATMOSPHERE_GROUND_KM);+ vec3 sunT = vec3(0.0);+ if (iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_GROUND_KM).x < 0.0) {+ float tl = iSphere(p, sunDir, vec3(0.0), ATMOSPHERE_TOP_KM).y;+ float dl = tl / float(LIGHT_STEPS);+ vec3 depth = vec3(0.0);+ for (int j = 0; j < LIGHT_STEPS; j++) {+ vec3 q = p + sunDir * ((float(j) + 0.5) * dl);+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * dl;+ }+ sunT = exp(-depth);+ }+ vec3 scatter = sunT * (rayleighScatter * dens.x * pR + mieScatter * dens.y * pM) * sunIntensity;+ volumeStep(radiance, transmittance, atmosphereExtinction(dens), scatter, dt);+ }+ return radiance;+}diff --git a/skills/shader-art-coding/glsl/camera.glsl b/skills/shader-art-coding/glsl/camera.glslnew file mode 100644index 0000000..46fbbed--- /dev/null+++ b/skills/shader-art-coding/glsl/camera.glsl@@ -0,0 +1,44 @@+//! camera: look-at frames, primary rays, field of view, thin-lens depth of field.+//! Convention: uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y, so uv.y spans [-1, 1] and aspect is kept.++/// Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward).+/// @use every 3D shader+mat3 cameraMatrix(vec3 ro, vec3 ta, float roll) {+ vec3 w = normalize(ta - ro);+ vec3 up = vec3(sin(roll), cos(roll), 0.0);+ vec3 u = normalize(cross(w, up));+ vec3 v = cross(u, w);+ return mat3(u, v, w);+}++/// Focal length (the z of the view-space ray) for a vertical field of view in degrees.+/// @use matching a reference photo, wide (90) vs telephoto (20) framing+float fovToFocal(float fovDegrees) { return 1.0 / tan(radians(fovDegrees) * 0.5); }++/// Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal).+/// @use every 3D shader+vec3 cameraRay(mat3 cam, vec2 uv, float focal) {+ return normalize(cam * vec3(uv, focal));+}++/// Thin-lens depth of field. Moves the ray origin over a lens disk of radius aperture, and re-aims it so that+/// points at distance focusDist stay sharp. xi is a pair of uniform random numbers in [0,1) (e.g. hash22 of the+/// pixel and frame). Average many samples (AA loop or multipass accumulation).+/// @use macro shots, product renders, cinematic focus pulls, bokeh+void thinLensRay(mat3 cam, vec2 uv, float focal, float aperture, float focusDist, vec2 xi,+ inout vec3 ro, out vec3 rd) {+ vec3 dir = normalize(cam * vec3(uv, focal));+ float ft = focusDist / dot(dir, cam[2]);+ vec3 focusPoint = ro + dir * ft;+ float a = TAU * xi.x;+ float r = aperture * sqrt(xi.y);+ ro += cam * vec3(r * cos(a), r * sin(a), 0.0);+ rd = normalize(focusPoint - ro);+}++/// Orthographic ray: parallel rays from a plane of half-height `size` centered on ro.+/// @use isometric scenes, technical illustrations, flat diorama looks+void orthoRay(mat3 cam, vec2 uv, float size, inout vec3 ro, out vec3 rd) {+ ro += cam * vec3(uv * size, 0.0);+ rd = cam[2];+}diff --git a/skills/shader-art-coding/glsl/color.glsl b/skills/shader-art-coding/glsl/color.glslnew file mode 100644index 0000000..309aea9--- /dev/null+++ b/skills/shader-art-coding/glsl/color.glsl@@ -0,0 +1,89 @@+//! color: transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors.+//! Light, shade and mix in LINEAR color. Picked hex colors, cosine palettes and Shadertoy textures are sRGB-encoded,+//! so decode them with srgbToLinear before lighting. Encode once at the very end with linearToSrgb.++/// Exact sRGB decode (EOTF): encoded [0,1] -> linear.+/// @use decoding picked colors, palettes used as albedo, and texture samples+vec3 srgbToLinear(vec3 c) {+ c = max(c, 0.0);+ return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));+}++/// Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping.+/// pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2).+/// @use final output+vec3 linearToSrgb(vec3 c) {+ c = max(c, 0.0);+ return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));+}++/// Relative luminance of linear Rec.709 / sRGB color.+/// @use desaturation, brightness masks, luminance-based effects+float luminance(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }++/// Scale saturation around luminance: 0 = grey, 1 = unchanged, > 1 = more saturated.+/// @use grading, fading distant objects, stylization+vec3 saturation(vec3 c, float s) { return mix(vec3(luminance(c)), c, s); }++/// Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT).+/// @use perceptual gradients, even-lightness palettes, hue and chroma edits+/// @see https://bottosson.github.io/posts/oklab/+vec3 linearSrgbToOklab(vec3 c) {+ vec3 lms = c * mat3(0.4122214708, 0.5363325363, 0.0514459929,+ 0.2119034982, 0.6806995451, 0.1073969566,+ 0.0883024619, 0.2817188376, 0.6299787005);+ lms = sign(lms) * pow(abs(lms), vec3(1.0 / 3.0));+ return lms * mat3(0.2104542553, 0.7936177850, -0.0040720468,+ 1.9779984951, -2.4285922050, 0.4505937099,+ 0.0259040371, 0.7827717662, -0.8086757660);+}++/// Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping.+/// @use converting perceptual edits back for lighting or output+vec3 oklabToLinearSrgb(vec3 lab) {+ vec3 lms = lab * mat3(1.0, 0.3963377774, 0.2158037573,+ 1.0, -0.1055613458, -0.0638541728,+ 1.0, -0.0894841775, -1.2914855480);+ lms = lms * lms * lms;+ return lms * mat3(4.0767416621, -3.3077115913, 0.2309699292,+ -1.2684380046, 2.6097574011, -0.3413193965,+ -0.0041960863, -0.7034186147, 1.7076147010);+}++/// Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV.+/// @use gradients, sky ramps, color transitions over time, blending materials+vec3 mixOklab(vec3 a, vec3 b, float t) {+ return oklabToLinearSrgb(mix(linearSrgbToOklab(a), linearSrgbToOklab(b), t));+}++/// OkLCh (lightness, chroma, hue in radians) -> linear sRGB. Hue sweeps keep lightness constant.+/// L about 0.4-0.9, C about 0.05-0.2 stays mostly in gamut.+/// @use harmonious palettes, rainbow ramps with even brightness, per-instance hue variation+vec3 oklchToLinearSrgb(vec3 lch) {+ return oklabToLinearSrgb(vec3(lch.x, lch.y * cos(lch.z), lch.y * sin(lch.z)));+}++/// Cosine palette a + b * cos(2 pi (c t + d)). Output is display-like (sRGB-ish), so decode it for albedo.+/// Integer c values loop seamlessly over t in [0,1].+/// @use quick gradients, heat maps, psychedelic color cycling, per-id colors+/// @see https://iquilezles.org/articles/palettes/+vec3 cosinePalette(float t, vec3 a, vec3 b, vec3 c, vec3 d) {+ return a + b * cos(TAU * (c * t + d));+}++/// Approximate linear sRGB color of a blackbody at temperature kelvin (1000-15000 K), normalized to max channel 1.+/// Uses the Krystek (1985) Planckian-locus fit -> XYZ -> sRGB.+/// @use fire, embers, lava, stars, incandescent lamps, sunset light, molten metal+vec3 blackbody(float kelvin) {+ float T = clamp(kelvin, 1000.0, 15000.0);+ float u = (0.860117757 + 1.54118254e-4 * T + 1.28641212e-7 * T * T) / (1.0 + 8.42420235e-4 * T + 7.08145163e-7 * T * T);+ float v = (0.317398726 + 4.22806245e-5 * T + 4.20481691e-8 * T * T) / (1.0 - 2.89741816e-5 * T + 1.61456053e-7 * T * T);+ float x = 3.0 * u / (2.0 * u - 8.0 * v + 4.0);+ float y = 2.0 * v / (2.0 * u - 8.0 * v + 4.0);+ vec3 xyz = vec3(x / y, 1.0, (1.0 - x - y) / y);+ vec3 rgb = xyz * mat3(3.2406, -1.5372, -0.4986,+ -0.9689, 1.8758, 0.0415,+ 0.0557, -0.2040, 1.0570);+ rgb = max(rgb, 0.0);+ return rgb / max(max(rgb.r, rgb.g), max(rgb.b, 1e-6));+}diff --git a/skills/shader-art-coding/glsl/common.glsl b/skills/shader-art-coding/glsl/common.glslnew file mode 100644index 0000000..ede0b50--- /dev/null+++ b/skills/shader-art-coding/glsl/common.glsl@@ -0,0 +1,73 @@+//! common: constants, rotation, remapping and shaping functions.+//! Target: GLSL ES 3.00 (Shadertoy / WebGL2). Every function here is original and MIT licensed.++const float PI = 3.14159265358979;+const float TAU = 6.28318530717959;++/// Clamp to [0,1].+/// @use masks, weights, colors+float saturate(float x) { return clamp(x, 0.0, 1.0); }+vec3 saturate(vec3 x) { return clamp(x, 0.0, 1.0); }++/// Squared length.+/// @use cheap distance comparisons, SDF internals+float dot2(vec2 v) { return dot(v, v); }+float dot2(vec3 v) { return dot(v, v); }++/// 2D rotation matrix. `rot2(a) * v` rotates v counter-clockwise by a radians.+/// @use spinning parts, posing limbs, rotating octaves, camera roll+mat2 rot2(float a) {+ float c = cos(a), s = sin(a);+ return mat2(c, s, -s, c);+}++/// Linear remap of x from [a,b] to [c,d] (unclamped).+/// @use converting ranges, rescaling noise+float remap(float x, float a, float b, float c, float d) {+ return c + (d - c) * (x - a) / (b - a);+}++/// Linear ramp from 0 at a to 1 at b, clamped.+/// @use masks whose falloff should not ease in or out+float linearstep(float a, float b, float x) {+ return clamp((x - a) / (b - a), 0.0, 1.0);+}++/// Smooth bump: 1 at x == c, falling to 0 at |x - c| >= w (cubic).+/// @use stripes, rings, highlights at one height, pulses in time+float cubicPulse(float c, float w, float x) {+ x = abs(x - c);+ if (x > w) return 0.0;+ x /= w;+ return 1.0 - x * x * (3.0 - 2.0 * x);+}++/// Fast attack, exponential decay. Peaks at 1 when x == 1/k.+/// @use heartbeat motion, impacts, flashes, plucked-string envelopes+float expImpulse(float x, float k) {+ float h = k * x;+ return h * exp(1.0 - h);+}++/// Contrast curve on [0,1] that keeps 0, 0.5 and 1 fixed. k > 1 adds contrast, k < 1 flattens.+/// @use tightening masks, adjusting animation easing+float gain(float x, float k) {+ float a = 0.5 * pow(2.0 * ((x < 0.5) ? x : 1.0 - x), k);+ return (x < 0.5) ? a : 1.0 - a;+}++/// 0 at x = 0 and x = 1, peak 1 at x = 0.5; k sharpens.+/// @use petal width along length, leaf profiles, arches+float parabola(float x, float k) {+ return pow(4.0 * x * (1.0 - x), k);+}++/// Returns x when x > m; smoothly bottoms out at n when x -> 0. Needs 2n < m.+/// @use avoiding hard zero in falloffs, soft floor on thickness+float almostIdentity(float x, float m, float n) {+ if (x > m) return x;+ float a = 2.0 * n - m;+ float b = 2.0 * m - 3.0 * n;+ float t = x / m;+ return (a * t + b) * t * t + n;+}diff --git a/skills/shader-art-coding/glsl/debug.glsl b/skills/shader-art-coding/glsl/debug.glslnew file mode 100644index 0000000..0396650--- /dev/null+++ b/skills/shader-art-coding/glsl/debug.glsl@@ -0,0 +1,30 @@+//! debug: visualize intermediate fields. The pack's DEBUG_MODE convention:+//! 0 final render | 1 distance field / contours | 2 normals | 3 material ids+//! 4 step count / depth | 5 masks / density | 6 lighting terms+//! Declare it as #define DEBUG_MODE 0 at the top of the shader. Shadertoy has no custom uniforms.++/// Distance field as contour bands: warm outside, cool inside, white zero line. Bands are 0.1 units apart.+/// @use checking SDF scale, smoothness, wrong signs, bad blends (kinked or bunched contours)+vec3 debugDistance(float d) {+ vec3 col = (d > 0.0) ? vec3(0.9, 0.6, 0.3) : vec3(0.4, 0.7, 0.85);+ col *= 1.0 - exp(-4.0 * abs(d));+ col *= 0.8 + 0.2 * cos(TAU * d / 0.1);+ return mix(col, vec3(1.0), 1.0 - smoothstep(0.0, 0.01, abs(d)));+}++/// Normal as RGB.+/// @use spotting seams, flipped normals, noisy normals+vec3 debugNormal(vec3 n) { return 0.5 + 0.5 * n; }++/// Distinct color per integer id.+/// @use material ids, cell ids, instance ids+vec3 debugIdColor(float id) {+ return 0.55 + 0.45 * cos(TAU * (0.618034 * id + vec3(0.0, 0.33, 0.67)));+}++/// Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white.+/// @use step counts (steps / maxSteps), depth, cost, any scalar mask+vec3 debugHeat(float t) {+ t = clamp(t, 0.0, 1.0);+ return clamp(vec3(1.5 * t, 1.6 * t * t * t - 0.1, 0.9 * sin(PI * t) + 0.2 * t * t), 0.0, 1.0);+}diff --git a/skills/shader-art-coding/glsl/domain.glsl b/skills/shader-art-coding/glsl/domain.glslnew file mode 100644index 0000000..9074357--- /dev/null+++ b/skills/shader-art-coding/glsl/domain.glsl@@ -0,0 +1,69 @@+//! domain: transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds,+//! twist, bend). Rigid transforms (repeat, mirror, rotate, fold) keep distances exact. Twist and bend+//! stretch space, so their results are only bounds after scaling (see each function).+//! Repetition uses floor(x + 0.5) instead of round(): GLSL leaves round(0.5) implementation-defined, and round can return -0.0.++/// Cell index for repetition with period s (integer-valued; use with hash functions).+/// @use per-instance variation: hash12(domRepeatId(p.xz, s))+float domRepeatId(float p, float s) { return floor(p / s + 0.5); }+vec2 domRepeatId(vec2 p, vec2 s) { return floor(p / s + 0.5); }+vec3 domRepeatId(vec3 p, vec3 s) { return floor(p / s + 0.5); }++/// Infinite repetition with period s. Returns the local coordinate centered in its cell.+/// Exact only while each instance stays inside its own cell. For instances that vary per cell or+/// overhang, evaluate the 2 or 3 neighboring cells too (see references/sdf-library-guide.md).+/// @use forests, columns, tiles, crowds, star fields, city blocks+float domRepeat(float p, float s) { return p - s * floor(p / s + 0.5); }+vec2 domRepeat(vec2 p, vec2 s) { return p - s * floor(p / s + 0.5); }+vec3 domRepeat(vec3 p, vec3 s) { return p - s * floor(p / s + 0.5); }++/// Repetition limited to cells -lim..+lim on each axis (2*lim + 1 copies).+/// @use rows of windows, fence posts, a finite grid of buttons, colonnades+vec2 domRepeatLimited(vec2 p, vec2 s, vec2 lim) { return p - s * clamp(floor(p / s + 0.5), -lim, lim); }+vec3 domRepeatLimited(vec3 p, vec3 s, vec3 lim) { return p - s * clamp(floor(p / s + 0.5), -lim, lim); }++/// Mirrored repetition: every other cell is flipped, so shapes touching the cell border join seamlessly.+/// @use tiled ornaments, symmetric wallpaper, seamless pipes and rails+vec2 domRepeatMirror(vec2 p, vec2 s) {+ vec2 cell = floor(p / s + 0.5);+ vec2 local = p - s * cell;+ return local * (1.0 - 2.0 * mod(cell, 2.0));+}++/// Polar repetition into n sectors around the origin. Returns the point rotated into the sector centered on +X.+/// Single evaluation: exact for shapes symmetric about their sector's center line. For asymmetric or per-sector-varying+/// shapes, evaluate this sector and its neighbor and take the min (see references/sdf-library-guide.md).+/// @use petals, spokes, gears, clock marks, radial ornaments, columns around a tower+vec2 domPolar(vec2 p, float n) {+ if (dot(p, p) < 1e-20) return p;+ float sector = TAU / n;+ float id = floor(atan(p.y, p.x) / sector + 0.5);+ return rot2(-id * sector) * p;+}++/// Sector index in [0, n) for domPolar.+/// @use varying each petal, spoke or column+float domPolarId(vec2 p, float n) {+ if (dot(p, p) < 1e-20) return 0.0;+ float sector = TAU / n;+ return mod(floor(atan(p.y, p.x) / sector + 0.5), n);+}++/// Fold space across the plane through the origin with unit normal n. Points behind the plane are reflected.+/// @use kaleidoscopes, symmetric creatures, KIFS fractals, mirrored architecture+vec3 domFold(vec3 p, vec3 n) { return p - 2.0 * min(dot(p, n), 0.0) * n; }++/// Twist around Y: rotate XZ by k * y. Divide the resulting distance by L = a/2 + sqrt(1 + a*a/4), a = k * R,+/// where R is the shape's max distance from the Y axis. Without that, the march overshoots.+/// @use twisted columns, drills, licorice, DNA-like spirals, towels+vec3 domTwist(vec3 p, float k) {+ vec2 xz = rot2(k * p.y) * p.xz;+ return vec3(xz.x, p.y, xz.y);+}++/// Bend in XY: rotate XY by k * x. Divide the resulting distance by about 1 + k * R (R = max |p.xy| of the shape).+/// @use bent beams, arches from boxes, bananas, curved horns+vec3 domBend(vec3 p, float k) {+ vec2 xy = rot2(k * p.x) * p.xy;+ return vec3(xy, p.z);+}diff --git a/skills/shader-art-coding/glsl/hash.glsl b/skills/shader-art-coding/glsl/hash.glslnew file mode 100644index 0000000..3fab3da--- /dev/null+++ b/skills/shader-art-coding/glsl/hash.glsl@@ -0,0 +1,102 @@+//! hash: integer hashes and float wrappers for lattice ids.+//! Naming: hashNM returns N floats from M inputs (hash12 = 1 output, 2 inputs). Outputs are in [0,1).+//! The float wrappers hash INTEGER-VALUED inputs (cell ids, pixel coords, frame numbers). Fractional parts+//! are dropped. That is deliberate: negative float -> uint is undefined in GLSL, and round() can return -0.0,+//! which has different bits from 0.0. Converting through int avoids both. To hash a continuous value, scale it first.+//! Do not use fract(sin(dot(p, k)) * 43758.5453): its result changes across GPUs and degrades at large inputs.+//! Integer mixers are from Jarzynski and Olano, "Hash Functions for GPU Rendering" (JCGT 2020): pcg3d and pcg4d sit+//! on that study's quality/speed frontier, and 32-bit integer math is bit-exact on every GPU, unlike sin().++/// PCG-style 1D integer hash.+/// @use seeding, per-instance randomness, building other hashes+/// @see https://jcgt.org/published/0009/03/02/+uint pcgHash(uint v) {+ uint state = v * 747796405u + 2891336453u;+ uint word = ((state >> ((state >> 28u) + 4u)) ^ state) * 277803737u;+ return (word >> 22u) ^ word;+}++/// 3D integer hash, three decorrelated outputs.+/// @use 3D cell ids, voxel jitter, (pixel, frame) noise+/// @see https://jcgt.org/published/0009/03/02/+uvec3 pcg3d(uvec3 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v ^= v >> 16u;+ v.x += v.y * v.z;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ return v;+}++/// 4D integer hash, four decorrelated outputs (0 BigCrush failures in the JCGT study).+/// @use (pixel.x, pixel.y, frame, sample) streams for stochastic sampling, 4D cell ids+/// @see https://jcgt.org/published/0009/03/02/+uvec4 pcg4d(uvec4 v) {+ v = v * 1664525u + 1013904223u;+ v.x += v.y * v.w;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v.w += v.y * v.z;+ v ^= v >> 16u;+ v.x += v.y * v.w;+ v.y += v.z * v.x;+ v.z += v.x * v.y;+ v.w += v.y * v.z;+ return v;+}++/// Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+float uintToUnit(uint h) { return float(h >> 8u) * (1.0 / 16777216.0); }+vec2 uintToUnit(uvec2 h) { return vec2(h >> 8u) * (1.0 / 16777216.0); }+vec3 uintToUnit(uvec3 h) { return vec3(h >> 8u) * (1.0 / 16777216.0); }+vec4 uintToUnit(uvec4 h) { return vec4(h >> 8u) * (1.0 / 16777216.0); }++/// Random float in [0,1) for an integer-valued input.+/// @use per-cell randomness, stable random per instance id+/// @range [0,1)+float hash11(float p) { return uintToUnit(pcgHash(uint(int(floor(p))))); }++/// Random float in [0,1) for an integer-valued 2D input.+/// @use per-cell variation (color, height, rotation), sparse spots, star fields+/// @range [0,1)+float hash12(vec2 p) {+ uvec2 q = uvec2(ivec2(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y)));+}++/// Random float in [0,1) for an integer-valued 3D input.+/// @use per-voxel randomness, per-pixel-per-frame noise via hash13(vec3(fragCoord, iFrame))+/// @range [0,1)+float hash13(vec3 p) {+ uvec3 q = uvec3(ivec3(floor(p)));+ return uintToUnit(pcgHash(q.x + pcgHash(q.y + pcgHash(q.z))));+}++/// Random vec2 in [0,1)^2 for an integer-valued 2D input.+/// @use Voronoi feature points, 2D jitter, random gradients+/// @range [0,1)^2+vec2 hash22(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x2545u))).xy;+}++/// Random vec3 in [0,1)^3 for an integer-valued 3D input.+/// @use 3D Voronoi points, random colors per cell, random directions+/// @range [0,1)^3+vec3 hash33(vec3 p) { return uintToUnit(pcg3d(uvec3(ivec3(floor(p))))); }++/// Random vec4 in [0,1)^4 for an integer-valued 4D input.+/// @use per-pixel, per-frame, per-sample random numbers: hash44(vec4(fragCoord, iFrame, sampleIndex))+/// @range [0,1)^4+vec4 hash44(vec4 p) { return uintToUnit(pcg4d(uvec4(ivec4(floor(p))))); }++/// Random vec3 in [0,1)^3 for an integer-valued 2D input.+/// @use per-tile random color, per-cell (offset, rotation, scale) triples+/// @range [0,1)^3+vec3 hash32(vec2 p) {+ ivec2 q = ivec2(floor(p));+ return uintToUnit(pcg3d(uvec3(q.x, q.y, 0x9E37u)));+}diff --git a/skills/shader-art-coding/glsl/intersect.glsl b/skills/shader-art-coding/glsl/intersect.glslnew file mode 100644index 0000000..49f3f4b--- /dev/null+++ b/skills/shader-art-coding/glsl/intersect.glsl@@ -0,0 +1,40 @@+//! intersect: analytic ray-primitive intersections. Rays are ro + t * rd with unit rd.+//! Use them for bounding volumes (clip the raymarch range to where the scene can be), exact floors and water planes,+//! glass spheres and eyeballs, and cheap reflections.+//! Formulas follow https://iquilezles.org/articles/intersectors/.++/// Ray vs plane dot(p, n) + h = 0 (unit n). Returns t, which is negative when the plane is behind the ray or parallel to it.+/// @use floors, water, mirrors, clipping marches to a ground plane+float iPlane(vec3 ro, vec3 rd, vec3 n, float h) {+ float denom = dot(rd, n);+ if (abs(denom) < 1e-8) return -1.0;+ return -(dot(ro, n) + h) / denom;+}++/// Ray vs sphere centered at c with radius r. Returns vec2(tNear, tFar), or vec2(-1) on a miss.+/// Uses the precision-friendly form that measures from the closest point on the ray.+/// @use bounding spheres, glass balls, eyeballs, planets, bubbles+vec2 iSphere(vec3 ro, vec3 rd, vec3 c, float r) {+ vec3 oc = ro - c;+ float b = dot(oc, rd);+ vec3 qc = oc - b * rd;+ float h = r * r - dot(qc, qc);+ if (h < 0.0) return vec2(-1.0);+ h = sqrt(h);+ return vec2(-b - h, -b + h);+}++/// Ray vs axis-aligned box centered at the origin with half-extents b (slab method).+/// Returns vec2(tNear, tFar), or vec2(-1) on a miss. Works when the ray starts inside (tNear < 0 < tFar).+/// @use bounding boxes for raymarching, glass cubes, rooms+vec2 iBox(vec3 ro, vec3 rd, vec3 b) {+ vec3 m = 1.0 / rd;+ vec3 n = m * ro;+ vec3 k = abs(m) * b;+ vec3 t1 = -n - k;+ vec3 t2 = -n + k;+ float tN = max(max(t1.x, t1.y), t1.z);+ float tF = min(min(t2.x, t2.y), t2.z);+ if (tN > tF || tF < 0.0) return vec2(-1.0);+ return vec2(tN, tF);+}diff --git a/skills/shader-art-coding/glsl/noise.glsl b/skills/shader-art-coding/glsl/noise.glslnew file mode 100644index 0000000..7e7b424--- /dev/null+++ b/skills/shader-art-coding/glsl/noise.glsl@@ -0,0 +1,288 @@+//! noise: value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering.+//! Every function here is texture-free and original. The math follows the cited articles.+//! Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates+//! until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.++/// Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise.+/// @use custom lattice noises, smooth cell interpolation+vec2 quinticFade(vec2 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }+vec3 quinticFade(vec3 f) { return f * f * f * (f * (f * 6.0 - 15.0) + 10.0); }++/// Derivative of quinticFade: 30 t^2 (t - 1)^2.+/// @use analytic noise derivatives+vec2 quinticFadeDeriv(vec2 f) { return 30.0 * f * f * (f * (f - 2.0) + 1.0); }++/// 2D value noise with analytic derivatives. Returns vec3(value, d/dx, d/dy).+/// @use terrain base layers, cheap clouds, anything needing normals without finite differences+/// @range value in [0,1]+/// @see https://iquilezles.org/articles/morenoise/+vec3 valueNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ float a = hash12(i);+ float b = hash12(i + vec2(1.0, 0.0));+ float c = hash12(i + vec2(0.0, 1.0));+ float d = hash12(i + vec2(1.0, 1.0));+ float k1 = b - a, k2 = c - a, k3 = a - b - c + d;+ return vec3(a + k1 * u.x + k2 * u.y + k3 * u.x * u.y,+ du * vec2(k1 + k3 * u.y, k2 + k3 * u.x));+}++/// 2D value noise.+/// @use soft blotches, low-frequency color variation+/// @range [0,1]+float valueNoise(vec2 p) { return valueNoiseD(p).x; }++/// 3D value noise.+/// @use volumetric density, animated 2D noise (use z = time)+/// @range [0,1]+float valueNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(hash13(i + vec3(0, 0, 0)), hash13(i + vec3(1, 0, 0)), u.x),+ mix(hash13(i + vec3(0, 1, 0)), hash13(i + vec3(1, 1, 0)), u.x), u.y),+ mix(mix(hash13(i + vec3(0, 0, 1)), hash13(i + vec3(1, 0, 1)), u.x),+ mix(hash13(i + vec3(0, 1, 1)), hash13(i + vec3(1, 1, 1)), u.x), u.y), u.z);+}++/// Unit gradient for a 2D lattice point.+vec2 latticeGradient(vec2 cell) {+ float a = TAU * hash12(cell);+ return vec2(cos(a), sin(a));+}++/// 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy).+/// Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm.+/// @use fBm, terrain with analytic normals, curl flow, marble and wood distortions+/// @range value in about [-0.7,0.7]+/// @see https://iquilezles.org/articles/gradientnoise/+vec3 gradientNoiseD(vec2 p) {+ vec2 i = floor(p), f = fract(p);+ vec2 u = quinticFade(f), du = quinticFadeDeriv(f);+ vec2 ga = latticeGradient(i);+ vec2 gb = latticeGradient(i + vec2(1.0, 0.0));+ vec2 gc = latticeGradient(i + vec2(0.0, 1.0));+ vec2 gd = latticeGradient(i + vec2(1.0, 1.0));+ float va = dot(ga, f);+ float vb = dot(gb, f - vec2(1.0, 0.0));+ float vc = dot(gc, f - vec2(0.0, 1.0));+ float vd = dot(gd, f - vec2(1.0, 1.0));+ float k = va - vb - vc + vd;+ float value = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * k;+ vec2 deriv = ga + u.x * (gb - ga) + u.y * (gc - ga) + u.x * u.y * (ga - gb - gc + gd)+ + du * (vec2(vb - va, vc - va) + u.yx * k);+ return vec3(value, deriv);+}++/// 2D gradient noise.+/// @use general-purpose smooth noise+/// @range about [-0.7,0.7]+float gradientNoise(vec2 p) { return gradientNoiseD(p).x; }++/// Dot product of a hashed 3D gradient with the offset to its lattice corner.+float latticeGradDot(vec3 cell, vec3 corner, vec3 f) {+ vec3 g = hash33(cell + corner) * 2.0 - 1.0;+ return dot(g, f - corner);+}++/// 3D gradient noise.+/// @use clouds, smoke, solid textures (marble, wood), animated 2D noise (z = time)+/// @range about [-1,1]+/// @see https://iquilezles.org/articles/gradientnoise/+float gradientNoise(vec3 p) {+ vec3 i = floor(p), f = fract(p);+ vec3 u = quinticFade(f);+ return mix(mix(mix(latticeGradDot(i, vec3(0, 0, 0), f), latticeGradDot(i, vec3(1, 0, 0), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 0), f), latticeGradDot(i, vec3(1, 1, 0), f), u.x), u.y),+ mix(mix(latticeGradDot(i, vec3(0, 0, 1), f), latticeGradDot(i, vec3(1, 0, 1), f), u.x),+ mix(latticeGradDot(i, vec3(0, 1, 1), f), latticeGradDot(i, vec3(1, 1, 1), f), u.x), u.y), u.z);+}++const int FBM_MAX_OCTAVES = 12;++/// Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment.+/// persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher.+/// @use clouds, terrain, dirt, roughness breakup, warping input+/// @range about [-1,1]+/// @see https://iquilezles.org/articles/fbm/+float fbm(vec2 p, int octaves, float lacunarity, float persistence) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return 1.4 * sum / norm;+}++/// 2D fBm with the usual defaults (lacunarity 2.01 so octave peaks never re-align, persistence 0.5).+/// @use quick organic variation+/// @range about [-1,1]+float fbm(vec2 p, int octaves) { return fbm(p, octaves, 2.01, 0.5); }++/// fBm over 3D gradient noise.+/// @use clouds, smoke, nebulae, solid marble+/// @range about [-1,1]+float fbm(vec3 p, int octaves, float lacunarity, float persistence) {+ const mat3 octaveRotation = mat3(0.00, 0.80, 0.60,+ -0.80, 0.36, -0.48,+ -0.60, -0.48, 0.64);+ float sum = 0.0, amp = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ sum += amp * gradientNoise(p);+ norm += amp;+ amp *= persistence;+ p = lacunarity * (octaveRotation * p) + vec3(17.13, -3.71, 5.29);+ }+ return sum / norm;+}++/// Terrain fBm where each octave is damped by the accumulated slope, so detail settles in valleys+/// and steep slopes stay smooth. This gives an eroded look without simulation.+/// @use mountains, dunes, rocky ground+/// @range about [-0.5,1]+/// @see https://iquilezles.org/articles/morenoise/+float erodedFbm(vec2 p, int octaves) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float h = 0.0, amp = 0.5;+ vec2 slope = vec2(0.0);+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ vec3 n = gradientNoiseD(p);+ slope += n.yz;+ h += amp * n.x / (1.0 + dot(slope, slope));+ amp *= 0.5;+ p = 2.0 * (octaveRotation * p);+ }+ return 2.0 * h;+}++/// Ridged multifractal: inverted |noise| creates sharp crests; each octave is weighted by the previous one,+/// so detail gathers along ridges.+/// @use mountain ridges, lightning-like veins, canyons, eroded rock, alien landscapes+/// @range about [0,1]+float ridgedFbm(vec2 p, int octaves) {+ const mat2 octaveRotation = mat2(0.8, 0.6, -0.6, 0.8);+ float sum = 0.0, amp = 0.5, weight = 1.0, norm = 0.0;+ for (int i = 0; i < FBM_MAX_OCTAVES; i++) {+ if (i >= octaves) break;+ float n = 1.0 - abs(gradientNoise(p) * 1.4);+ n *= n;+ sum += amp * n * weight;+ norm += amp;+ weight = clamp(n * 2.0, 0.0, 1.0);+ amp *= 0.5;+ p = 2.01 * (octaveRotation * p) + vec2(17.13, -3.71);+ }+ return sum / norm;+}++/// Two-level domain warp f(p + s*r), r = fbm(p + s*q), q = fbm(p). Writes the intermediate warp+/// vectors so they can drive color. Cost is 5 fBm calls.+/// @use marble, smoke, agate, alien skies, painterly backgrounds+/// @range about [-1,1]+/// @see https://iquilezles.org/articles/warp/+float warpedFbm(vec2 p, float strength, int octaves, out vec2 q, out vec2 r) {+ q = vec2(fbm(p, octaves), fbm(p + vec2(3.1, 7.4), octaves));+ r = vec2(fbm(p + strength * q + vec2(9.7, 2.6), octaves),+ fbm(p + strength * q + vec2(6.3, 1.9), octaves));+ return fbm(p + strength * r, octaves);+}++/// Divergence-free 2D flow field: the curl of scalar gradient noise.+/// Particles advected by it swirl without bunching up.+/// @use smoke advection, flowing paint, hair/fur flow direction, wind+vec2 curlNoise(vec2 p) {+ vec3 n = gradientNoiseD(p);+ return vec2(n.z, -n.y);+}++/// Cellular (Worley/Voronoi) noise. Returns vec4(F1, F2, nearestCell.xy).+/// F1 = distance to nearest feature point, F2 = second nearest. nearestCell is integer-valued, so hash it for+/// per-cell randomness. jitter in [0,1] (0 = regular grid). Searches 3x3 cells. F2 can be slightly off at jitter 1.+/// @use cells, scales, stones, cracked mud (F2-F1), caustics, foam, sparkles+/// @range F1 in [0, ~1.2]+/// @see https://iquilezles.org/articles/voronoilines/+vec4 voronoi(vec2 p, float jitter) {+ vec2 ip = floor(p), fp = fract(p);+ float f1 = 8.0, f2 = 8.0;+ vec2 nearest = vec2(0.0);+ for (int j = -1; j <= 1; j++)+ for (int i = -1; i <= 1; i++) {+ vec2 g = vec2(float(i), float(j));+ vec2 r = g + jitter * hash22(ip + g) - fp;+ float d = dot(r, r);+ if (d < f1) { f2 = f1; f1 = d; nearest = ip + g; }+ else if (d < f2) { f2 = d; }+ }+ return vec4(sqrt(f1), sqrt(f2), nearest);+}++/// Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector.+/// Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance,+/// so lines have constant width.+/// @use cell walls, stained glass leading, cracked earth, giraffe and leaf-vein patterns, crackle glaze+/// @see https://iquilezles.org/articles/voronoilines/+vec3 voronoiBorder(vec2 p, float jitter) {+ vec2 ip = floor(p), fp = fract(p);+ vec2 mg = vec2(0.0), mr = vec2(0.0);+ float md = 8.0;+ for (int j = -1; j <= 1; j++)+ for (int i = -1; i <= 1; i++) {+ vec2 g = vec2(float(i), float(j));+ vec2 r = g + jitter * hash22(ip + g) - fp;+ float d = dot(r, r);+ if (d < md) { md = d; mr = r; mg = g; }+ }+ md = 8.0;+ for (int j = -2; j <= 2; j++)+ for (int i = -2; i <= 2; i++) {+ vec2 g = mg + vec2(float(i), float(j));+ vec2 r = g + jitter * hash22(ip + g) - fp;+ if (dot2(mr - r) > 1e-5) {+ md = min(md, dot(0.5 * (mr + r), normalize(r - mr)));+ }+ }+ return vec3(md, mr);+}++/// Smooth Voronoi: a soft-min of distances to feature points. Cells become blobs with no creases.+/// k controls smoothness (large = sharper; around 8-32). Searches 5x5 cells so low k has no seams.+/// @use organic cell clusters, bubbles, lumpy surfaces, skin pores+/// @see https://iquilezles.org/articles/smoothvoronoi/+float smoothVoronoi(vec2 p, float k) {+ vec2 ip = floor(p), fp = fract(p);+ float acc = 0.0;+ for (int j = -2; j <= 2; j++)+ for (int i = -2; i <= 2; i++) {+ vec2 g = vec2(float(i), float(j));+ vec2 r = g + hash22(ip + g) - fp;+ acc += exp2(-k * length(r));+ }+ return -log2(acc) / k;+}++/// Interleaved gradient noise: cheap per-pixel noise whose 3x3 neighborhoods are nearly stratified. Not a hash.+/// pixel must be integer pixel coordinates (floor(fragCoord)). The frame overload animates it for accumulation and TAA.+/// @use removing banding before 8-bit output, jittering ray start offsets, stochastic transparency+/// @range [0,1)+/// @see Jimenez 2014, "Next Generation Post Processing in Call of Duty: Advanced Warfare"+float interleavedGradientNoise(vec2 pixel) {+ return fract(52.9829189 * fract(dot(pixel, vec2(0.06711056, 0.00583715))));+}+float interleavedGradientNoise(vec2 pixel, int frame) {+ return interleavedGradientNoise(pixel + 5.588238 * float(frame % 64));+}++/// R2 low-discrepancy dither mask (plastic-constant sequence), folded by a triangle wave for an even spread.+/// @use ordered dithering without textures, posterized and retro looks, sample offsets+/// @range [0,1)+/// @see https://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/+float r2Dither(vec2 pixel) {+ float v = fract(dot(pixel, vec2(0.7548776662, 0.5698402910)));+ return v < 0.5 ? 2.0 * v : 2.0 - 2.0 * v;+}diff --git a/skills/shader-art-coding/glsl/operators.glsl b/skills/shader-art-coding/glsl/operators.glslnew file mode 100644index 0000000..4250163--- /dev/null+++ b/skills/shader-art-coding/glsl/operators.glsl@@ -0,0 +1,120 @@+//! operators: combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion,+//! extrude, revolve, elongate). Arguments a, b are distances already evaluated at the same point.+//! Exactness: union (min) is exact outside but too deep inside; intersection and subtraction (max) are exact+//! inside but underestimate outside. Smooth and decorative combinations are bounds. All stay Lipschitz <= 1,+//! so raymarching is safe. When interior distances matter (inner-penumbra shadows, thickness, onion of a union),+//! prefer an exact concave primitive (sdDeathStar, sdCutHollowSphere, 2D sdMoon/sdArc + extrude/revolve).+//! Smooth unions are not associative: blend in a fixed order (torso, then limbs, then details).+//! Smooth blend semantics in this library: k is the blend width in distance units. Shapes start blending+//! when |a - b| < k.++/// Union of two shapes.+/// @bound+/// @use combining parts+float opUnion(float a, float b) { return min(a, b); }++/// Shape a with shape b cut out of it.+/// @bound+/// @use holes, windows, carving, bites+float opSubtract(float a, float b) { return max(a, -b); }++/// Region inside both shapes.+/// @bound+/// @use clipping, lens shapes, trimming with half-spaces+float opIntersect(float a, float b) { return max(a, b); }++/// Smooth union (polynomial, C1). Blends where |a - b| < k, with a max bulge of k/4.+/// @bound+/// @use organic joins (neck to head, limbs to torso), melting shapes, blobby forms+/// @see https://iquilezles.org/articles/smin/+float smin(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return mix(b, a, h) - k * h * (1.0 - h);+}++/// Smooth intersection, the mirror of smin.+/// @bound+/// @use soft clipping, rounded intersections, pillowy cuts+float smax(float a, float b, float k) { return -smin(-a, -b, k); }++/// Smooth subtraction: a with b carved out, with filleted edges.+/// @bound+/// @use eye sockets, nostrils, soft grooves, scooped bowls, worn edges+float smoothSubtract(float a, float b, float k) { return smax(a, -b, k); }++/// Smooth union with a C2 (cubic) transition, so specular highlights and normals have no visible seam.+/// Blends where |a - b| < k, with a max bulge of k/6.+/// @bound+/// @use close-up organic surfaces, glossy blends, fluids+/// @see https://iquilezles.org/articles/smin/+float sminCubic(float a, float b, float k) {+ float h = max(k - abs(a - b), 0.0) / k;+ return min(a, b) - h * h * h * k * (1.0 / 6.0);+}++/// Smooth union that also returns the blend weight. Returns vec2(distance, weight), where weight is 1 when+/// the result is fully a and 0 when fully b. Use the weight to mix material colors across the blend.+/// @bound+/// @use skin-to-cloth transitions, color bleeding across blended parts, gradient-colored blobs+vec2 sminBlend(float a, float b, float k) {+ float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0);+ return vec2(mix(b, a, h) - k * h * (1.0 - h), h);+}++/// Union with a 45-degree chamfer of size r at the seam.+/// @bound+/// @use machined parts, architecture, sci-fi panels, bevelled joins+/// @see https://mercury.sexy/hg_sdf/+float opChamferUnion(float a, float b, float r) {+ return min(min(a, b), (a + b - r) * 0.70710678);+}++/// Union with n stair steps of total size r at the seam.+/// @bound+/// @use terraces, stepped pyramids, ziggurats, layered rock, rice paddies+/// @see https://mercury.sexy/hg_sdf/+float opStairsUnion(float a, float b, float r, float n) {+ float s = r / n;+ float u = b - r;+ return min(min(a, b), 0.5 * (u + a + abs(mod(u - a + s, 2.0 * s) - s)));+}++/// Engrave a groove of depth r into a, following the zero set of b.+/// @bound+/// @use panel lines, carved text paths, seams, grout lines on a surface+/// @see https://mercury.sexy/hg_sdf/+float opEngrave(float a, float b, float r) {+ return max(a, (a + r - abs(b)) * 0.70710678);+}++/// Round a shape by r. Grows it outward; shrink the inner shape by r first to keep its size.+/// @exact+/// @use softening any primitive, pebbles from boxes, inflated look+float opRound(float d, float r) { return d - r; }++/// Hollow shell of thickness 2t around the surface. Apply repeatedly for concentric layers.+/// @exact+/// @use shells, pipes, rings, onion layers, outlines in 2D+float opOnion(float d, float t) { return abs(d) - t; }++/// Extrude a 2D distance d2 (evaluated at p.xy) along Z by half-length h.+/// @exact+/// @use 3D text and logos, cookie cutters, coins from 2D shapes, extruded profiles+float opExtrude(vec3 p, float d2, float h) {+ vec2 w = vec2(d2, abs(p.z) - h);+ return min(max(w.x, w.y), 0.0) + length(max(w, 0.0));+}++/// Revolve around Y. Returns the 2D point to evaluate a profile at. Offset o moves the profile away from the axis.+/// @exact+/// @use vases, bottles, chess pieces, lathe-turned objects, tori with custom profiles+vec2 opRevolve(vec3 p, float o) { return vec2(length(p.xz) - o, p.y); }++/// Elongate: stretch a shape by inserting a straight section of half-size h, keeping exact distances inside too.+/// Returns vec4(q, w). Evaluate the original shape at q.xyz and add w: sdSphere(e.xyz, r) + e.w is a capsule.+/// @exact+/// @use pills from spheres, long rounded boxes, stretched characters, stadium shapes+vec4 opElongate(vec3 p, vec3 h) {+ vec3 q = abs(p) - h;+ return vec4(max(q, 0.0), min(max(q.x, max(q.y, q.z)), 0.0));+}diff --git a/skills/shader-art-coding/glsl/pattern.glsl b/skills/shader-art-coding/glsl/pattern.glslnew file mode 100644index 0000000..e9c4ebe--- /dev/null+++ b/skills/shader-art-coding/glsl/pattern.glsl@@ -0,0 +1,69 @@+//! pattern: tilings and antialiased procedural patterns. The filtered versions integrate the pattern over the+//! pixel footprint (box filter), so floors and stripes stay clean in the distance with no supersampling.+//! Filtering math follows https://iquilezles.org/articles/checkerfiltering/ and /filterableprocedurals/.++/// Triangle wave, the integral of a square wave. Building block for box-filtered patterns.+/// @use writing new filtered patterns+vec2 triangleWave(vec2 x) { return 1.0 - 2.0 * abs(fract(x * 0.5) - 0.5); }++/// Box-filtered checkerboard with unit squares: 0 or 1 up close, fading to 0.5 where squares are smaller than a pixel.+/// Compute the footprint before any branching: w = fwidth(p) (or max(abs(dFdx(p)), abs(dFdy(p)))).+/// @use floors, chessboards, test patterns, racing flags, tablecloths+/// @range [0,1]+float filteredChecker(vec2 p, vec2 w) {+ w = max(w, 1e-4);+ vec2 i = (triangleWave(p + 0.5 * w) - triangleWave(p - 0.5 * w)) / w;+ return 0.5 - 0.5 * i.x * i.y;+}++/// Box-filtered grid lines (unit cells, line width = 1/n of a cell). Returns 1 on lines, 0 inside cells.+/// @use blueprints, graph paper, tiles with grout, sci-fi floors, synthwave grids+/// @range [0,1]+float filteredGrid(vec2 p, vec2 w, float n) {+ w = max(w, 1e-4);+ vec2 a = p + 0.5 * w;+ vec2 b = p - 0.5 * w;+ vec2 i = (floor(a) + min(fract(a) * n, 1.0) - floor(b) - min(fract(b) * n, 1.0)) / (n * w);+ return 1.0 - (1.0 - i.x) * (1.0 - i.y);+}++/// Box-filtered stripes along x with period 1 and duty cycle 0.5. Returns 0..1.+/// @use awnings, candy, zebra (warp x first), barcodes, road markings+/// @range [0,1]+float filteredStripes(float x, float w) {+ w = max(w, 1e-4);+ float a = x + 0.5 * w, b = x - 0.5 * w;+ float ia = floor(a) * 0.5 + max(fract(a) - 0.5, 0.0);+ float ib = floor(b) * 0.5 + max(fract(b) - 0.5, 0.0);+ return (ia - ib) / w;+}++/// Hexagonal tiling with unit spacing between neighboring centers. Neighbors sit left/right, so hexes are+/// pointy-top. Returns vec4(local offset from the hex center, integer-valued hex id).+/// @use honeycomb, scales, tiles, game boards, hex pixelation+vec4 hexGrid(vec2 p) {+ const vec2 s = vec2(1.0, 1.7320508);+ vec2 a = mod(p, s) - 0.5 * s;+ vec2 b = mod(p - 0.5 * s, s) - 0.5 * s;+ vec2 local = (dot(a, a) < dot(b, b)) ? a : b;+ vec2 center = p - local;+ vec2 id = floor(vec2(center.x * 2.0, center.y * 1.1547005) + 0.5);+ return vec4(local, id);+}++/// Distance from a hexGrid local coordinate to its hexagon's edge (0.5 at the center, 0 on the edge).+/// @use hex borders, bevels, edge wear on tiles+float hexEdgeDistance(vec2 local) {+ vec2 a = abs(local);+ return 0.5 - max(a.x, dot(a, vec2(0.5, 0.8660254)));+}++/// Truchet tiling of quarter-circle arcs, randomly flipped per cell. Returns signed distance to arcs of half-width w.+/// @use maze-like ornaments, pipes, Celtic-style weaves, procedural circuitry+float truchetArcs(vec2 p, float w) {+ vec2 id = floor(p);+ vec2 f = fract(p) - 0.5;+ if (hash12(id) < 0.5) f.x = -f.x;+ vec2 q = f - 0.5 * sign(f.x + f.y + 1e-6);+ return abs(length(q) - 0.5) - w;+}diff --git a/skills/shader-art-coding/glsl/post.glsl b/skills/shader-art-coding/glsl/post.glslnew file mode 100644index 0000000..3994cac--- /dev/null+++ b/skills/shader-art-coding/glsl/post.glsl@@ -0,0 +1,49 @@+//! post: antialiasing helpers, supersampling offsets, lens effects, grain and dithering, all single-pass.+//! Order of a finished frame: (per AA sample) exposure, vignette, grain -> tonemap -> average samples ->+//! linearToSrgb -> dither. See references/rendering-pipeline.md.++/// Antialiased fill of a 2D SDF: 1 inside, 0 outside, box-filtered across one pixel. Uses screen derivatives,+/// so call it outside non-uniform branches and loops. For a fixed pixel size use fillAA(d, px).+/// @use 2D shapes, icons, text-like strokes, UI, masks with crisp edges+float fillAA(float d) {+ float w = length(vec2(dFdx(d), dFdy(d)));+ return clamp(0.5 - d / max(w, 1e-6), 0.0, 1.0);+}++/// Antialiased fill with an explicit pixel size px (e.g. 2.0 / iResolution.y for the standard uv). Safe in loops and branches.+/// @use 2D shapes evaluated inside loops, layered compositions+float fillAA(float d, float px) { return clamp(0.5 - d / px, 0.0, 1.0); }++/// Antialiased stroke of half-width hw around the zero line of a 2D SDF.+/// @use outlines, line art, rings, wireframes, contour lines+float strokeAA(float d, float hw, float px) { return fillAA(abs(d) - hw, px); }++/// Subpixel offset in [-0.5, 0.5)^2 for sample i of a supersampling loop (R2 low-discrepancy sequence).+/// Better coverage than a regular grid for any sample count.+/// @use AA loops: for (int i = 0; i < N; i++) { vec2 o = aaOffset(i); ... mainColor(fragCoord + o) }+vec2 aaOffset(int i) {+ return fract(0.5 + float(i) * vec2(0.7548776662, 0.5698402910)) - 0.5;+}++/// Natural (cos^4) vignette for a pinhole camera: uv is the screen point, focal the camera focal length.+/// Wider lenses vignette more. Multiply HDR color before tonemapping.+/// @use photographic falloff, framing, cinematic looks+float vignette(vec2 uv, float focal) {+ float f2 = focal * focal;+ float k = f2 / (f2 + dot(uv, uv));+ return k * k;+}++/// Signal-dependent film grain: noise grows with sqrt(intensity), as photon noise does. n should be zero-mean+/// noise (e.g. hash13(vec3(fragCoord, iFrame)) * 2 - 1). Apply in linear HDR before tonemapping.+/// @use filmic texture, hiding banding, analog looks+vec3 filmGrain(vec3 col, float amount, float n) {+ return col + amount * sqrt(max(col, 0.0)) * n;+}++/// Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor.+/// @use removing banding in skies, fog, vignettes and dark gradients+vec3 ditherTPDF(vec2 fragCoord, int frame) {+ vec2 r = hash22(vec2(floor(fragCoord) + 7919.0 * float(frame % 1024)));+ return vec3((r.x + r.y - 1.0) / 255.0);+}diff --git a/skills/shader-art-coding/glsl/raymarch.glsl b/skills/shader-art-coding/glsl/raymarch.glslnew file mode 100644index 0000000..1a8c45c--- /dev/null+++ b/skills/shader-art-coding/glsl/raymarch.glsl@@ -0,0 +1,92 @@+//! raymarch: sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes.+//! SCENE CONTRACT: your shader defines vec2 map(vec3 p) returning vec2(distance, materialId).+//! Packing the material into a vec2 avoids structs (WebGL forbids ?: on structs) and works with every helper here.+//! Loops start at ZERO, a zero the compiler cannot prove. That stops it inlining map() into every loop, which+//! keeps compile times sane and avoids WebGL compiler crashes on large scenes.++#define ZERO (min(iFrame, 0))++vec2 map(vec3 p);++const int RAYMARCH_MAX_STEPS = 256;++/// Sphere-trace from ro along unit rd between tmin and tmax.+/// Returns vec3(t, materialId, stepCount). t is -1 on a miss.+/// The hit threshold grows with t (about one pixel's footprint), so distant surfaces don't burn steps.+/// stepScale is 1 for exact or bound fields. Use < 1 (e.g. 0.6) when map() has Lipschitz > 1 (displacement, warps, twist).+/// @use every SDF raymarcher+/// @see https://iquilezles.org/articles/raymarchingdf/+vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale) {+ float t = tmin;+ for (int i = ZERO; i < RAYMARCH_MAX_STEPS; i++) {+ vec2 h = map(ro + rd * t);+ if (abs(h.x) < max(0.0002 * t, 1e-5)) return vec3(t, h.y, float(i));+ t += h.x * stepScale;+ if (t > tmax) break;+ }+ return vec3(-1.0, -1.0, float(RAYMARCH_MAX_STEPS));+}++/// Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered).+/// eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling.+/// @use shading any SDF hit+/// @see https://iquilezles.org/articles/normalsSDF/+vec3 calcNormal(vec3 p, float eps) {+ vec3 n = vec3(0.0);+ for (int i = ZERO; i < 4; i++) {+ vec3 e = 0.5773 * (2.0 * vec3((((i + 3) >> 1) & 1), ((i >> 1) & 1), (i & 1)) - 1.0);+ n += e * map(p + e * eps).x;+ }+ return normalize(n);+}++/// Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard).+/// Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders.+/// Returns 0 (full shadow) .. 1 (lit).+/// @use sun shadows, contact shadows, penumbrae+/// @see https://iquilezles.org/articles/rmshadows/+float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k) {+ float res = 1.0;+ float t = tmin;+ float ph = 1e10;+ for (int i = ZERO; i < 64; i++) {+ float h = map(ro + rd * t).x;+ if (h < 0.0001) return 0.0;+ float y = h * h / (2.0 * ph);+ float d = sqrt(max(h * h - y * y, 0.0));+ res = min(res, k * d / max(t - y, 1e-4));+ ph = h;+ t += clamp(h, 0.005, 0.5);+ if (res < 0.001 || t > tmax) break;+ }+ res = clamp(res, 0.0, 1.0);+ return res * res * (3.0 - 2.0 * res);+}++/// Ambient occlusion from 5 distance samples along the normal. Compares the expected distance with the actual one.+/// scale is the sampling reach in scene units (about 0.12 for a unit-sized object). Returns 0 (occluded) .. 1 (open).+/// @use crevices, contact darkening, grounding objects on floors+/// @see https://iquilezles.org/articles/nvscene2008/rwwtt.pdf+float calcAO(vec3 p, vec3 n, float scale) {+ float occ = 0.0;+ float weight = 1.0;+ for (int i = ZERO; i < 5; i++) {+ float h = 0.01 + scale * float(i) / 4.0;+ float d = map(p + h * n).x;+ occ += (h - d) * weight;+ weight *= 0.95;+ }+ return clamp(1.0 - 3.0 * occ / max(scale / 0.12, 1e-3), 0.0, 1.0);+}++/// Thickness behind a surface point, estimated by sampling the SDF inside along -n (an "inverse AO").+/// Returns 0 (thin, light passes through) .. 1 (thick). maxDepth is the deepest sample in scene units.+/// @use translucency, subsurface tint, wax and jade, glowing thin edges+float sdfThickness(vec3 p, vec3 n, float maxDepth) {+ float acc = 0.0;+ for (int i = ZERO; i < 4; i++) {+ float h = maxDepth * (float(i) + 1.0) / 4.0;+ acc += clamp(-map(p - n * h).x / h, 0.0, 1.0);+ }+ return acc / 4.0;+}diff --git a/skills/shader-art-coding/glsl/sdf2d.glsl b/skills/shader-art-coding/glsl/sdf2d.glslnew file mode 100644index 0000000..5714dba--- /dev/null+++ b/skills/shader-art-coding/glsl/sdf2d.glsl@@ -0,0 +1,206 @@+//! sdf2d: 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for+//! opExtrude / opRevolve. Centered at the origin unless noted. Negative inside.+//! Formulas follow Inigo Quilez's 2D distance catalog (https://iquilezles.org/articles/distfunctions2d/).+//! Implementations are original and tested (sign, Lipschitz, brute-force distance for curves).+//! Tags: @exact true distance, @bound never overestimates, @approx exact zero set but may overestimate in places.++/// Circle of radius r.+/// @exact+/// @use dots, eyes, suns, bubbles, rings (with opOnion)+float sdCircle(vec2 p, float r) { return length(p) - r; }++/// Axis-aligned rectangle with half-extents b.+/// @exact+/// @use panels, bars, windows, buttons, building silhouettes+float sdBox(vec2 p, vec2 b) {+ vec2 d = abs(p) - b;+ return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);+}++/// Rectangle with half-extents b and per-corner radii r = (top-right, bottom-right, top-left, bottom-left).+/// @exact+/// @use UI cards, buttons, speech bubbles, tags, rounded windows+float sdRoundedBox(vec2 p, vec2 b, vec4 r) {+ r.xy = (p.x > 0.0) ? r.xy : r.zw;+ r.x = (p.y > 0.0) ? r.x : r.y;+ vec2 q = abs(p) - b + r.x;+ return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r.x;+}++/// Unsigned distance to segment a-b. Subtract a width to get a stroke.+/// @exact+/// @use lines, strokes, stems, rays, hands of a clock, rain streaks+float sdSegment(vec2 p, vec2 a, vec2 b) {+ vec2 pa = p - a, ba = b - a;+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);+ return length(pa - ba * h);+}++/// Tapered capsule: circle r1 at origin hulled with circle r2 at (0, h).+/// @exact+/// @use petals, tails, teardrops, brush dabs, fingers, flames+float sdUnevenCapsule(vec2 p, float r1, float r2, float h) {+ p.x = abs(p.x);+ float b = (r1 - r2) / h;+ float a = sqrt(1.0 - b * b);+ float k = dot(p, vec2(-b, a));+ if (k < 0.0) return length(p) - r1;+ if (k > a * h) return length(p - vec2(0.0, h)) - r2;+ return dot(p, vec2(a, b)) - r1;+}++/// Circular arc symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, ra = radius, rb = stroke half-width.+/// @exact+/// @use smiles, eyebrows, rainbows, gauges, progress rings, horseshoes+float sdArc(vec2 p, vec2 sc, float ra, float rb) {+ p.x = abs(p.x);+ return ((sc.y * p.x > sc.x * p.y) ? length(p - sc * ra) : abs(length(p) - ra)) - rb;+}++/// Equilateral triangle with circumradius-like size r, pointing up.+/// @exact+/// @use play icons, warning signs, mountains, arrows, tri-patterns+float sdEquilateralTriangle(vec2 p, float r) {+ const float k = 1.7320508;+ p.x = abs(p.x) - r;+ p.y = p.y + r / k;+ if (p.x + k * p.y > 0.0) p = vec2(p.x - k * p.y, -k * p.x - p.y) / 2.0;+ p.x -= clamp(p.x, -2.0 * r, 0.0);+ return -length(p) * sign(p.y);+}++/// Arbitrary triangle p0, p1, p2 (any winding).+/// @exact+/// @use shards, low-poly art, arrowheads, beaks, teeth+float sdTriangle(vec2 p, vec2 p0, vec2 p1, vec2 p2) {+ vec2 e0 = p1 - p0, e1 = p2 - p1, e2 = p0 - p2;+ vec2 v0 = p - p0, v1 = p - p1, v2 = p - p2;+ vec2 pq0 = v0 - e0 * clamp(dot(v0, e0) / dot(e0, e0), 0.0, 1.0);+ vec2 pq1 = v1 - e1 * clamp(dot(v1, e1) / dot(e1, e1), 0.0, 1.0);+ vec2 pq2 = v2 - e2 * clamp(dot(v2, e2) / dot(e2, e2), 0.0, 1.0);+ float s = sign(e0.x * e2.y - e0.y * e2.x);+ vec2 d = min(min(vec2(dot(pq0, pq0), s * (v0.x * e0.y - v0.y * e0.x)),+ vec2(dot(pq1, pq1), s * (v1.x * e1.y - v1.y * e1.x))),+ vec2(dot(pq2, pq2), s * (v2.x * e2.y - v2.y * e2.x)));+ return -sqrt(d.x) * sign(d.y);+}++/// Regular n-gon with circumradius r, one vertex pointing up.+/// @exact+/// @use badges, hexagonal tiles, pentagons, stop signs, gems (2D)+float sdRegularPolygon(vec2 p, float r, int n) {+ float an = PI / float(n);+ vec2 acs = vec2(cos(an), sin(an));+ float len = length(p);+ if (len < 1e-12) return -r * acs.x;+ float bn = mod(atan(p.x, p.y), 2.0 * an) - an;+ p = len * vec2(cos(bn), abs(sin(bn)));+ p -= r * acs;+ p.y += clamp(-p.y, 0.0, r * acs.y);+ return length(p) * sign(p.x);+}++/// Star with n points and outer radius r. m in [2, n] sets the inner angle: m = 2 is the spikiest and m = n is a regular n-gon.+/// @exact+/// @use stars, sparkles, badges, flowers (with opRound), sheriff badges+float sdStar(vec2 p, float r, int n, float m) {+ float an = PI / float(n);+ float en = PI / m;+ vec2 acs = vec2(cos(an), sin(an));+ vec2 ecs = vec2(cos(en), sin(en));+ float len = length(p);+ if (len < 1e-12) return -r * acs.x;+ float bn = mod(atan(p.x, p.y), 2.0 * an) - an;+ p = len * vec2(cos(bn), abs(sin(bn)));+ p -= r * acs;+ p += ecs * clamp(-dot(p, ecs), 0.0, r * acs.y / ecs.y);+ return length(p) * sign(p.x);+}++/// Vesica (lens): intersection of two circles of radius r whose centers sit at (+-d, 0). Points along Y. Needs d < r.+/// @exact+/// @use leaves, petals, eyes, fish bodies, almond shapes, gothic arches+float sdVesica(vec2 p, float r, float d) {+ p = abs(p);+ float b = sqrt(r * r - d * d);+ return ((p.y - b) * d > p.x * b) ? length(p - vec2(0.0, b))+ : length(p - vec2(-d, 0.0)) - r;+}++/// Crescent: disk ra at origin minus disk rb at (d, 0).+/// @exact+/// @use moons, claws, bananas (bent), shadows on spheres, logos+float sdMoon(vec2 p, float d, float ra, float rb) {+ p.y = abs(p.y);+ float a = (ra * ra - rb * rb + d * d) / (2.0 * d);+ float b = sqrt(max(ra * ra - a * a, 0.0));+ if (d * (p.x * b - p.y * a) > d * d * max(b - p.y, 0.0)) return length(p - vec2(a, b));+ return max(length(p) - ra, -(length(p - vec2(d, 0.0)) - rb));+}++/// Heart with its bottom tip at the origin, about 1 unit tall.+/// @exact+/// @use hearts, valentines, health icons, leaves (squashed)+float sdHeart(vec2 p) {+ p.x = abs(p.x);+ if (p.y + p.x > 1.0) return sqrt(dot2(p - vec2(0.25, 0.75))) - 0.35355339;+ return sqrt(min(dot2(p - vec2(0.0, 1.0)), dot2(p - 0.5 * max(p.x + p.y, 0.0)))) * sign(p.x - p.y);+}++/// Rhombus with half-diagonals b.+/// @exact+/// @use diamonds, kites, card suits, argyle, harlequin patterns+float sdRhombus(vec2 p, vec2 b) {+ p = abs(p);+ vec2 t = b - 2.0 * p;+ float h = clamp((t.x * b.x - t.y * b.y) / dot(b, b), -1.0, 1.0);+ float d = length(p - 0.5 * b * vec2(1.0 - h, 1.0 + h));+ return d * sign(p.x * b.y + p.y * b.x - b.x * b.y);+}++/// Ellipse with semi-axes r. A fast approximation: exact zero set, a bound outside up to about 2:1 aspect,+/// gradient above 1 inside and for flatter ellipses. Fine for fills and strokes; avoid for exact offsets.+/// @approx+/// @use eyes, pupils, ovals, shadows under objects, planet rings (with opOnion)+float sdEllipse(vec2 p, vec2 r) {+ float k0 = length(p / r);+ float k1 = length(p / (r * r));+ if (k1 < 1e-8) return -min(r.x, r.y);+ return k0 * (k0 - 1.0) / k1;+}++/// Unsigned distance to a quadratic Bezier curve A-B-C. Solves the closest-point cubic analytically.+/// Falls back to a segment when the curve degenerates to a line. Float error in the cubic solve is about 1e-4.+/// @exact+/// @use brush strokes, hair, calligraphy, tendrils, eyelashes, smooth paths, font-like curves+float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C) {+ vec2 a = B - A;+ vec2 b = A - 2.0 * B + C;+ vec2 c = a * 2.0;+ vec2 d = A - pos;+ float bb = dot(b, b);+ if (bb < 1e-10) return sdSegment(pos, A, C);+ float kk = 1.0 / bb;+ float kx = kk * dot(a, b);+ float ky = kk * (2.0 * dot(a, a) + dot(d, b)) / 3.0;+ float kz = kk * dot(d, a);+ float pp = ky - kx * kx;+ float q = kx * (2.0 * kx * kx - 3.0 * ky) + kz;+ float h = q * q + 4.0 * pp * pp * pp;+ float res;+ if (h >= 0.0) {+ h = sqrt(h);+ vec2 x = (vec2(h, -h) - q) / 2.0;+ vec2 uv = sign(x) * pow(abs(x), vec2(1.0 / 3.0));+ float t = clamp(uv.x + uv.y - kx, 0.0, 1.0);+ res = dot2(d + (c + b * t) * t);+ } else {+ float z = sqrt(-pp);+ float v = acos(clamp(q / (pp * z * 2.0), -1.0, 1.0)) / 3.0;+ float m = cos(v);+ float n = sin(v) * 1.7320508;+ vec2 t = clamp(vec2(m + m, -n - m) * z - kx, 0.0, 1.0);+ res = min(dot2(d + (c + b * t.x) * t.x), dot2(d + (c + b * t.y) * t.y));+ }+ return sqrt(res);+}diff --git a/skills/shader-art-coding/glsl/sdf3d.glsl b/skills/shader-art-coding/glsl/sdf3d.glslnew file mode 100644index 0000000..750286d--- /dev/null+++ b/skills/shader-art-coding/glsl/sdf3d.glsl@@ -0,0 +1,244 @@+//! sdf3d: 3D signed distance primitives. Each one is centered at the origin unless noted. Move or rotate the+//! point before calling (sdBox(p - center, size)), never the result.+//! Exactness tags:+//! @exact true Euclidean distance inside and outside (safe for smooth blending, AO, soft shadows, offsets)+//! @bound never overestimates (Lipschitz <= 1), so raymarching is safe, but offsets and blends are less accurate+//! @approx exact zero set but may overestimate in places (see the function's note for the safe stepScale)+//! Formulas follow Inigo Quilez's distance-function catalog (https://iquilezles.org/articles/distfunctions/).+//! Implementations here are original and checked by tests/ (sign, Lipschitz bound, eikonal).++/// Sphere of radius r.+/// @exact+/// @use heads, eyes, fruit, planets, bubbles, joints+float sdSphere(vec3 p, float r) { return length(p) - r; }++/// Axis-aligned box with half-extents b.+/// @exact+/// @use buildings, crates, bricks, pedestals, furniture+float sdBox(vec3 p, vec3 b) {+ vec3 q = abs(p) - b;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0);+}++/// Box with rounded edges. The outer size stays b; r is the edge radius (r <= min(b)).+/// @exact+/// @use toys, product shots, soft architecture, dice, phone-like slabs+float sdRoundBox(vec3 p, vec3 b, float r) {+ vec3 q = abs(p) - b + r;+ return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;+}++/// Wireframe box: edges of a box with half-extents b and edge thickness e.+/// @exact+/// @use scaffolding, cages, display frames, sci-fi structures+float sdBoxFrame(vec3 p, vec3 b, float e) {+ p = abs(p) - b;+ vec3 q = abs(p + e) - e;+ return min(min(+ length(max(vec3(p.x, q.y, q.z), 0.0)) + min(max(p.x, max(q.y, q.z)), 0.0),+ length(max(vec3(q.x, p.y, q.z), 0.0)) + min(max(q.x, max(p.y, q.z)), 0.0)),+ length(max(vec3(q.x, q.y, p.z), 0.0)) + min(max(q.x, max(q.y, p.z)), 0.0));+}++/// Torus in the XZ plane. t.x = major radius, t.y = tube radius.+/// @exact+/// @use rings, donuts, tires, halos, lifebuoys+float sdTorus(vec3 p, vec2 t) {+ vec2 q = vec2(length(p.xz) - t.x, p.y);+ return length(q) - t.y;+}++/// Partial torus (arc) in the XY plane, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture angle,+/// ra = major radius, rb = tube radius.+/// @exact+/// @use horns, handles, eyebrows, arches, croissant shapes, magnets+float sdCappedTorus(vec3 p, vec2 sc, float ra, float rb) {+ p.x = abs(p.x);+ float k = (sc.y * p.x > sc.x * p.y) ? dot(p.xy, sc) : length(p.xy);+ return sqrt(max(dot(p, p) + ra * ra - 2.0 * ra * k, 0.0)) - rb;+}++/// Chain link: a torus stretched along Y by le. r1 = major radius, r2 = tube radius.+/// @exact+/// @use chains, rings, jewelry, fences+float sdLink(vec3 p, float le, float r1, float r2) {+ vec3 q = vec3(p.x, max(abs(p.y) - le, 0.0), p.z);+ return length(vec2(length(q.xy) - r1, q.z)) - r2;+}++/// Infinite plane through the origin offset by h along unit normal n: dot(p, n) + h.+/// @exact+/// @use ground, walls, water surface, clipping half-spaces+float sdPlane(vec3 p, vec3 n, float h) { return dot(p, n) + h; }++/// Capsule: segment a-b swept by radius r.+/// @exact+/// @use limbs, fingers, branches, hair strands, pills, bones+float sdCapsule(vec3 p, vec3 a, vec3 b, float r) {+ vec3 pa = p - a, ba = b - a;+ float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);+ return length(pa - ba * h) - r;+}++/// Vertical capsule from y = 0 to y = h, radius r.+/// @exact+/// @use upright limbs, posts, bottles, candles+float sdVerticalCapsule(vec3 p, float h, float r) {+ p.y -= clamp(p.y, 0.0, h);+ return length(p) - r;+}++/// Vertical capped cylinder from y = -h to y = +h, radius r.+/// @exact+/// @use columns, cans, coins, logs, wheels (rotate first)+float sdCylinder(vec3 p, float h, float r) {+ vec2 d = abs(vec2(length(p.xz), p.y)) - vec2(r, h);+ return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));+}++/// Capped cone (frustum) from y = -h (radius r1) to y = +h (radius r2). Set r2 = 0 for a pointed cone.+/// Exact everywhere, including the base cap. Points below the base are outside.+/// @exact+/// @use trees, roofs, spikes, lampshades, volcanoes, party hats, vases+float sdCappedCone(vec3 p, float h, float r1, float r2) {+ vec2 q = vec2(length(p.xz), p.y);+ vec2 top = vec2(r2, h);+ vec2 side = vec2(r2 - r1, 2.0 * h);+ vec2 toCap = vec2(q.x - min(q.x, (q.y < 0.0) ? r1 : r2), abs(q.y) - h);+ vec2 toSide = q - top + side * clamp(dot(top - q, side) / dot2(side), 0.0, 1.0);+ float s = (toSide.x < 0.0 && toCap.y < 0.0) ? -1.0 : 1.0;+ return s * sqrt(min(dot2(toCap), dot2(toSide)));+}++/// Pointed cone with its base disk (radius r) at y = 0 and apex at y = h.+/// @exact+/// @use evergreen trees, spikes, horns, mountains, wizard hats+float sdCone(vec3 p, float h, float r) {+ return sdCappedCone(p - vec3(0.0, 0.5 * h, 0.0), 0.5 * h, r, 0.0);+}++/// Round cone: sphere r1 at y = 0 smoothly hulled with sphere r2 at y = h.+/// @exact+/// @use limbs, fingers, tree trunks, carrots, teardrops, tentacle segments+float sdRoundCone(vec3 p, float r1, float r2, float h) {+ float b = (r1 - r2) / h;+ float a = sqrt(1.0 - b * b);+ vec2 q = vec2(length(p.xz), p.y);+ float k = dot(q, vec2(-b, a));+ if (k < 0.0) return length(q) - r1;+ if (k > a * h) return length(q - vec2(0.0, h)) - r2;+ return dot(q, vec2(a, b)) - r1;+}++/// Ellipsoid with semi-axes r. A fast approximation: the zero set is exact and the field is a bound outside for+/// aspect ratios up to about 2:1. Inside, and for more stretched ellipsoids, the gradient exceeds 1 (measured: 2.5+/// at 4:1). March with stepScale 0.7-0.8 there, or build long shapes from sdCapsule / sdRoundCone instead.+/// @approx+/// @use heads, bodies, eggs, pebbles, leaves (flat), muscles, clouds of blobs+float sdEllipsoid(vec3 p, vec3 r) {+ float k0 = length(p / r);+ float k1 = length(p / (r * r));+ if (k1 < 1e-8) return -min(r.x, min(r.y, r.z));+ return k0 * (k0 - 1.0) / k1;+}++/// Hollow spherical cap (bowl) of radius r, cut by the plane y = h, with shell thickness t. The opening faces +Y.+/// @exact+/// @use bowls, cups, helmets, shells, satellite dishes, eye sockets+float sdCutHollowSphere(vec3 p, float r, float h, float t) {+ float w = sqrt(r * r - h * h);+ vec2 q = vec2(length(p.xz), p.y);+ return ((h * q.x < w * q.y) ? length(q - vec2(w, h)) : abs(length(q) - r)) - t;+}++/// Hexagonal prism along Z. h.x = inradius of the hexagon, h.y = half-length.+/// @exact+/// @use pencils, bolts, crystals, basalt columns, honeycomb cells+float sdHexPrism(vec3 p, vec2 h) {+ const vec3 k = vec3(-0.8660254, 0.5, 0.57735027);+ p = abs(p);+ p.xy -= 2.0 * min(dot(k.xy, p.xy), 0.0) * k.xy;+ vec2 d = vec2(length(p.xy - vec2(clamp(p.x, -k.z * h.x, k.z * h.x), h.x)) * sign(p.y - h.x),+ p.z - h.y);+ return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));+}++/// Regular octahedron with "radius" s (vertex distance from center). Bound version.+/// @bound+/// @use gems, crystals, diamonds, abstract motifs+float sdOctahedron(vec3 p, float s) {+ p = abs(p);+ return (p.x + p.y + p.z - s) * 0.57735027;+}++/// Gyroid sheet with cell scale `scale` and half-thickness t. The infinite triply-periodic surface+/// sin x cos y + sin y cos z + sin z cos x = 0. Intersect with a bounding shape.+/// @bound+/// @use lattices, coral, bone interiors, sponges, sci-fi infill, organic architecture+float sdGyroid(vec3 p, float scale, float t) {+ p *= scale;+ float g = dot(sin(p), cos(p.yzx));+ return (abs(g) / scale - t) * 0.57735027;+}++/// Sphere of radius r cut by the plane y = h, keeping the cap ABOVE the plane. h = 0 gives a dome on the ground;+/// negative h keeps more than half. Needs |h| < r.+/// @exact+/// @use domes, mushroom caps, half-buried rocks, igloos, bread loaves+float sdCutSphere(vec3 p, float r, float h) {+ float w = sqrt(max(r * r - h * h, 0.0));+ vec2 q = vec2(length(p.xz), p.y);+ float s = max((h - r) * q.x * q.x + w * w * (h + r - 2.0 * q.y), h * q.x - w * q.y);+ return (s < 0.0) ? length(q) - r : (q.x < w) ? h - q.y : length(q - vec2(w, h));+}++/// Sphere ra at the origin with sphere rb at (d, 0, 0) carved out, exact including the crease rim.+/// A plain opSubtract of two spheres is only a bound.+/// @exact+/// @use eye sockets, craters, bitten fruit, nostrils, scooped shapes+float sdDeathStar(vec3 p, float ra, float rb, float d) {+ float a = (ra * ra - rb * rb + d * d) / (2.0 * d);+ float b = sqrt(max(ra * ra - a * a, 0.0));+ vec2 q = vec2(p.x, length(p.yz));+ if (q.x * b - q.y * a > d * max(b - q.y, 0.0)) return length(q - vec2(a, b));+ return max(length(q) - ra, -(length(q - vec2(d, 0.0)) - rb));+}++/// Unsigned distance to a 3D quadratic Bezier curve A-B-C; subtract a radius for a tube.+/// Solves the closest-point cubic analytically. Falls back to a segment when the curve is straight.+/// @exact+/// @use hair strands, tentacles, stems, whiskers, horns, cables, curved tubes+float sdQuadraticBezier(vec3 pos, vec3 A, vec3 B, vec3 C) {+ vec3 a = B - A;+ vec3 b = A - 2.0 * B + C;+ vec3 c = a * 2.0;+ vec3 d = A - pos;+ float bb = dot(b, b);+ if (bb < 1e-10) {+ vec3 pa = pos - A, ca = C - A;+ return length(pa - ca * clamp(dot(pa, ca) / dot(ca, ca), 0.0, 1.0));+ }+ float kk = 1.0 / bb;+ float kx = kk * dot(a, b);+ float ky = kk * (2.0 * dot(a, a) + dot(d, b)) / 3.0;+ float kz = kk * dot(d, a);+ float pp = ky - kx * kx;+ float q = kx * (2.0 * kx * kx - 3.0 * ky) + kz;+ float h = q * q + 4.0 * pp * pp * pp;+ float res;+ if (h >= 0.0) {+ h = sqrt(h);+ vec2 x = (vec2(h, -h) - q) / 2.0;+ vec2 uv = sign(x) * pow(abs(x), vec2(1.0 / 3.0));+ float t = clamp(uv.x + uv.y - kx, 0.0, 1.0);+ res = dot2(d + (c + b * t) * t);+ } else {+ float z = sqrt(-pp);+ float v = acos(clamp(q / (pp * z * 2.0), -1.0, 1.0)) / 3.0;+ float m = cos(v);+ float n = sin(v) * 1.7320508;+ vec2 t = clamp(vec2(m + m, -n - m) * z - kx, 0.0, 1.0);+ res = min(dot2(d + (c + b * t.x) * t.x), dot2(d + (c + b * t.y) * t.y));+ }+ return sqrt(res);+}diff --git a/skills/shader-art-coding/glsl/shading.glsl b/skills/shader-art-coding/glsl/shading.glslnew file mode 100644index 0000000..f4c6bfb--- /dev/null+++ b/skills/shader-art-coding/glsl/shading.glsl@@ -0,0 +1,91 @@+//! shading: BRDF terms and practical lighting models. Vectors are unit length: n = normal, v = toward the viewer+//! (-rd), l = toward the light. Units are "artist units" with pi folded in: a light of color C lights a white+//! Lambert surface facing it to C. Every function here returns radiance per unit light color, already including NoL.+//! Physically based terms follow Filament (https://google.github.io/filament/Filament.md.html).++/// Schlick Fresnel. u is VoH for lights and NoV for environment reflections and rims.+/// f0 = 0.04 for dielectrics (plastic, skin, stone, water ~0.02); for metals f0 = base color.+/// @use reflections that strengthen at grazing angles, rim brightening, water and glass+vec3 fresnelSchlick(float u, vec3 f0) {+ float m = clamp(1.0 - u, 0.0, 1.0);+ float m2 = m * m;+ return f0 + (1.0 - f0) * (m2 * m2 * m);+}++/// GGX / Trowbridge-Reitz normal distribution. alpha = roughness^2.+/// @use specular highlight shape (inside specularGGX)+float distributionGGX(float NoH, float alpha) {+ float a2 = alpha * alpha;+ float d = NoH * NoH * (a2 - 1.0) + 1.0;+ return a2 / (PI * d * d);+}++/// Height-correlated Smith visibility. Already contains the 1 / (4 NoL NoV) term.+/// @use specular shadowing-masking (inside specularGGX)+float visibilitySmithGGX(float NoV, float NoL, float alpha) {+ float a2 = alpha * alpha;+ float gv = NoL * sqrt(NoV * NoV * (1.0 - a2) + a2);+ float gl = NoV * sqrt(NoL * NoL * (1.0 - a2) + a2);+ return 0.5 / max(gv + gl, 1e-6);+}++/// Microfacet specular for one light: pi * D * V * F * NoL (artist units). roughness is perceptual, in [0,1].+/// @use glossy plastic, metal, wet surfaces, car paint, ceramics+vec3 specularGGX(vec3 n, vec3 v, vec3 l, float roughness, vec3 f0) {+ vec3 h = normalize(v + l);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ float NoV = max(dot(n, v), 1e-4);+ float NoH = clamp(dot(n, h), 0.0, 1.0);+ float VoH = clamp(dot(v, h), 0.0, 1.0);+ float alpha = max(roughness, 0.045);+ alpha *= alpha;+ return PI * distributionGGX(NoH, alpha) * visibilitySmithGGX(NoV, NoL, alpha) * fresnelSchlick(VoH, f0) * NoL;+}++/// Complete metallic-roughness shading for one light (diffuse + specular, NoL included, artist units).+/// Multiply by light color and shadow. Keep albedo around 0.05-0.7 (linear); brighten lights, not albedo.+/// @use hero objects, product renders, anything that needs believable materials+vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic) {+ vec3 f0 = mix(vec3(0.04), albedo, metallic);+ float NoL = clamp(dot(n, l), 0.0, 1.0);+ vec3 F = fresnelSchlick(max(dot(n, v), 0.0), f0);+ vec3 diffuse = albedo * (1.0 - metallic) * (1.0 - F) * NoL;+ return diffuse + specularGGX(n, v, l, roughness, f0);+}++/// Split-sum environment specular without a lookup texture (Karis 2014, after Lazarov).+/// Multiply by the sky or environment color in the reflection direction.+/// @use sky reflections on glossy surfaces, ambient specular+vec3 envBRDFApprox(vec3 f0, float NoV, float roughness) {+ vec4 r = roughness * vec4(-1.0, -0.0275, -0.572, 0.022) + vec4(1.0, 0.0425, 1.04, -0.04);+ float a = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;+ vec2 ab = vec2(-1.04, 1.04) * a + r.zw;+ return f0 * ab.x + ab.y;+}++/// Energy-conserving wrap diffuse: light wraps past the terminator by w (0 = Lambert, 0.5 = soft).+/// @use skin, foliage, cloth, soft stylized shading, fur+/// @see https://blog.selfshadow.com/2011/12/31/righting-wrap-part-1/+float wrapDiffuse(vec3 n, vec3 l, float w) {+ return max((dot(n, l) + w) / ((1.0 + w) * (1.0 + w)), 0.0);+}++/// Hemisphere light: sky color from above blended to ground color from below.+/// @use ambient fill, outdoor sky light, studio fill+vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor) {+ return mix(groundColor, skyColor, 0.5 + 0.5 * n.y);+}++/// Fast translucency (Barre-Brisebois and Bouchard 2011): light passing through thin parts, seen from the back.+/// distortion bends the light along the normal (0.2-0.5). thickness is 0 (thin) .. 1 (thick); see sdfThickness.+/// @use leaves, ears, wax, jade, marble, backlit petals, jellyfish+float translucency(vec3 n, vec3 v, vec3 l, float distortion, float power, float thickness) {+ vec3 h = normalize(l + n * distortion);+ return pow(clamp(dot(v, -h), 0.0, 1.0), power) * (1.0 - thickness);+}++/// Rim light from the viewing angle: strongest at silhouettes.+/// @use character separation from background, fresnel-like glow, stylized outlines+float rimLight(vec3 n, vec3 v, float power) {+ return pow(clamp(1.0 - dot(n, v), 0.0, 1.0), power);+}diff --git a/skills/shader-art-coding/glsl/tonemap.glsl b/skills/shader-art-coding/glsl/tonemap.glslnew file mode 100644index 0000000..149257b--- /dev/null+++ b/skills/shader-art-coding/glsl/tonemap.glsl@@ -0,0 +1,89 @@+//! tonemap: map scene-linear HDR to display range. Every function here takes linear input (after exposure) and+//! returns LINEAR [0,1]. Then apply linearToSrgb exactly once.+//! Recommended chain: col *= exposure; col = tonemapAgX(col); col = linearToSrgb(col); add dither.+//! Choosing: AgX (default) for 3D scenes, glows, fire, suns and volumes; its highlights roll off to white without+//! hue skews. tonemapNeutral for 2D, product shots and palette-faithful work. ACES for the saturated filmic look.++/// AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display.+/// Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT).+/// @use default tonemapper for 3D, emissive glows, fire, neon, skies, clouds+/// @see https://iolite-engine.com/blog_posts/minimal_agx_implementation+vec3 tonemapAgX(vec3 c) {+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,+ 0.0784335999999992, 0.878468636469772, 0.0784336,+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);+ const float minEv = -12.47393, maxEv = 4.026069;+ c = inset * max(c, 0.0);+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);+ vec3 x2 = c * c, x4 = x2 * x2;+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;+ c = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++/// AgX with the "punchy" look (more contrast and saturation) for stylized art.+/// @use stylized 3D, saturated sunsets, toy-like renders+vec3 tonemapAgXPunchy(vec3 c) {+ const mat3 inset = mat3(0.842479062253094, 0.0423282422610123, 0.0423756549057051,+ 0.0784335999999992, 0.878468636469772, 0.0784336,+ 0.0792237451477643, 0.0791661274605434, 0.879142973793104);+ const mat3 outset = mat3(1.19687900512017, -0.0528968517574562, -0.0529716355144438,+ -0.0980208811401368, 1.15190312990417, -0.0980434501171241,+ -0.0990297440797205, -0.0989611768448433, 1.15107367264116);+ const float minEv = -12.47393, maxEv = 4.026069;+ c = inset * max(c, 0.0);+ c = clamp((log2(max(c, 1e-10)) - minEv) / (maxEv - minEv), 0.0, 1.0);+ vec3 x2 = c * c, x4 = x2 * x2;+ c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;+ c = pow(max(c, 0.0), vec3(1.35));+ float luma = dot(c, vec3(0.2126, 0.7152, 0.0722));+ c = luma + 1.4 * (c - luma);+ c = outset * c;+ return pow(max(c, 0.0), vec3(2.2));+}++/// Khronos PBR Neutral: leaves [0, ~0.76] almost untouched and compresses only highlights, preserving hue.+/// @use 2D art, palette-faithful scenes, product renders, UI glow+/// @see https://github.com/KhronosGroup/ToneMapping+vec3 tonemapNeutral(vec3 c) {+ const float startCompression = 0.76;+ const float desaturation = 0.15;+ c = max(c, 0.0);+ float x = min(c.r, min(c.g, c.b));+ float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;+ c -= offset;+ float peak = max(c.r, max(c.g, c.b));+ if (peak < startCompression) return c;+ const float d = 1.0 - startCompression;+ float newPeak = 1.0 - d * d / (peak + d - startCompression);+ c *= newPeak / peak;+ float g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0);+ return mix(c, vec3(newPeak), g);+}++/// Stephen Hill's ACES fit (RRT + ODT, sRGB primaries). Contrasty and saturated; blues drift purple when very bright.+/// Darker than AgX at the same exposure: multiply the input by about 1.6 to compensate.+/// @use the classic "filmic game" look+/// @see https://github.com/TheRealMJP/BakingLab/blob/master/BakingLab/ACES.hlsl+vec3 tonemapACES(vec3 c) {+ c = max(c, 0.0) * mat3(0.59719, 0.35458, 0.04823,+ 0.07600, 0.90834, 0.01566,+ 0.02840, 0.13383, 0.83777);+ c = (c * (c + 0.0245786) - 0.000090537) / (c * (0.983729 * c + 0.4329510) + 0.238081);+ c = c * mat3(1.60475, -0.53108, -0.07367,+ -0.10208, 1.10813, -0.00605,+ -0.00327, -0.07276, 1.07602);+ return clamp(c, 0.0, 1.0);+}++/// Extended Reinhard on luminance: maps `white` to 1 and preserves hue. Simple and predictable.+/// @use quick previews, soft low-contrast looks+vec3 tonemapReinhard(vec3 c, float white) {+ c = max(c, 0.0);+ float l = dot(c, vec3(0.2126, 0.7152, 0.0722));+ float lt = l * (1.0 + l / (white * white)) / (1.0 + l);+ return clamp(c * (lt / max(l, 1e-6)), 0.0, 1.0);+}diff --git a/skills/shader-art-coding/glsl/volume.glsl b/skills/shader-art-coding/glsl/volume.glslnew file mode 100644index 0000000..b1fe89e--- /dev/null+++ b/skills/shader-art-coding/glsl/volume.glsl@@ -0,0 +1,64 @@+//! volume: participating media (fog, smoke, clouds, haze). mu = dot(rd, l): the cosine between the view ray and+//! the direction TOWARD the light, so forward scattering peaks when looking at the light.+//! Integration follows Hillaire (Frostbite, SIGGRAPH 2015/2016); cloud tricks follow Schneider (Horizon Zero Dawn, 2015).++/// Isotropic phase function (scatters equally in all directions).+/// @use dusty fog, thick smoke interiors+float phaseIsotropic() { return 1.0 / (4.0 * PI); }++/// Rayleigh phase function.+/// @use sky scattering by air molecules (blue sky)+float phaseRayleigh(float mu) { return 3.0 / (16.0 * PI) * (1.0 + mu * mu); }++/// Henyey-Greenstein phase function. g in (-1, 1): > 0 forward (silver linings), < 0 backward.+/// @use clouds (g ~ 0.6-0.85), fog glow around lights, underwater light shafts+float phaseHG(float mu, float g) {+ float g2 = g * g;+ return (1.0 - g2) / (4.0 * PI * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-6), 1.5));+}++/// Two-lobe Henyey-Greenstein: a forward lobe gF and a backward lobe gB, mixed by w (weight of the forward lobe).+/// Keeps the silver lining while clouds lit from behind the camera still show detail.+/// @use clouds, smoke lit from varying angles+float phaseDualHG(float mu, float gF, float gB, float w) {+ return mix(phaseHG(mu, gB), phaseHG(mu, gF), w);+}++/// Cornette-Shanks phase (a better-normalized Mie approximation). g = 0.8 for atmospheric haze.+/// @use sun halo in hazy skies, aerosols+float phaseCornetteShanks(float mu, float g) {+ float g2 = g * g;+ return 3.0 / (8.0 * PI) * (1.0 - g2) * (1.0 + mu * mu)+ / ((2.0 + g2) * pow(max(1.0 + g2 - 2.0 * g * mu, 1e-6), 1.5));+}++/// Beer-Powder lighting term for clouds: 2 e^-d (1 - e^-2d), where d is optical depth toward the sun.+/// Darkens cloud edges that face the light like powdered sugar. Not energy-conserving; use it on the direct term only.+/// @use cumulus clouds, puffy smoke+float beerPowder(float d) { return 2.0 * exp(-d) * (1.0 - exp(-2.0 * d)); }++/// One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media),+/// inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length.+/// Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds.+/// @use any raymarched volume: clouds, smoke, fog, fire, nebulae+void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds) {+ vec3 stepT = exp(-sigmaT * ds);+ vec3 integral = (inScatter - inScatter * stepT) / max(sigmaT, vec3(1e-7));+ radiance += transmittance * integral;+ transmittance *= stepT;+}++/// Distance fog amount (0 = clear, 1 = fully fogged) for distance t.+/// @use depth cueing, haze, underwater murk+float distanceFog(float t, float density) { return 1.0 - exp(-t * density); }++/// Analytic height fog for density a * exp(-b * y) along the ray segment [0, t]. Thick near the ground, thin above.+/// Returns the fog amount in [0,1].+/// @use valley mist, ground fog, layered haze in landscapes+/// @see https://iquilezles.org/articles/fog/+float heightFog(vec3 ro, vec3 rd, float t, float a, float b) {+ float base = a * exp(-ro.y * b);+ float amount = (abs(rd.y) < 1e-4) ? base * t+ : base * (1.0 - exp(-t * rd.y * b)) / (rd.y * b);+ return 1.0 - exp(-max(amount, 0.0));+}diff --git a/skills/codex/shader-art-coding/references/composition-and-debugging.md b/skills/shader-art-coding/references/composition-and-debugging.mdsimilarity index 69%rename from skills/codex/shader-art-coding/references/composition-and-debugging.mdrename to skills/shader-art-coding/references/composition-and-debugging.mdindex c86d563..34fe771 100644--- a/skills/codex/shader-art-coding/references/composition-and-debugging.md+++ b/skills/shader-art-coding/references/composition-and-debugging.md@@ -1,5 +1,14 @@# Composition and Debugging+## Contents++- [Composition Rules for Procedural Shaders](#composition-rules-for-procedural-shaders)+- [Debugging Ritual](#debugging-ritual)+- [Formula Verification From Visual Sources](#formula-verification-from-visual-sources)+- [Common Failure Modes](#common-failure-modes)+- [Quality Passes](#quality-passes)+- [Response Pattern](#response-pattern)+## Composition Rules for Procedural ShadersMake the image readable before making it detailed:@@ -11,21 +20,21 @@ Make the image readable before making it detailed:- Let repeated elements vary in size, color, angle, or phase.- Keep large forms stable; animate small details unless the scene is about motion.-For bilateral organic carrier scenes:+For bilateral organic carrier scenes (characters, creatures, faces, figurines):- Establish dominant/secondary lobe proportions first.- Use symmetry only as a starting point; break it with pose, anisotropic strands, shell layers, or expression parameters.- Detail focal bilateral features more than distant or peripheral shapes.- Use material contrast to separate subsurface, woven, filament, metallic, accumulation, or prop materials.-For heightfield scenes:+For heightfield scenes (landscapes, dunes, oceans):- Build the heightfield silhouette first.- Place the sun and horizon early.- Use distance fog before adding tiny density-field details.- Use instance/material IDs for variation but keep clump structure coherent.-For constructed objects:+For constructed objects (buildings, machines, tiled and modular props):- Define the base primitive and repetition system.- Keep local coordinates and cell IDs available for color variation.@@ -33,17 +42,21 @@ For constructed objects:## Debugging Ritual-When a shader fails visually, inspect fields instead of guessing:+When a shader fails visually, inspect fields instead of guessing. Every shader in this pack declares+`#define DEBUG_MODE 0` (Shadertoy has no custom uniforms) and uses one numbering:-1. Show coordinates as color.-2. Show the raw mask or distance.-3. Show object/material IDs.-4. Show normals.-5. Show depth or raymarch step count.-6. Show lighting terms separately.-7. Re-enable composition in layers.+| Mode | Shows | Library helper | Look for |+|---|---|---|---|+| 0 | final render | | |+| 1 | distance field / contours (2D slice through a 3D scene) | `debugDistance(d)` | wrong signs, kinked blends, bad scale |+| 2 | normals | `debugNormal(n)` | seams, noise, flipped faces |+| 3 | material / cell ids | `debugIdColor(id)` | lost ids, repetition errors |+| 4 | step count or depth | `debugHeat(steps / maxSteps)` | overshooting fields, wasted steps |+| 5 | masks / density | grayscale or RGB-packed masks | hard edges, noisy masks |+| 6 | lighting terms | key, fill, specular in R, G, B | missing shadows, AO on the sun |-Do not debug a full shaded image when the broken term can be displayed directly.+Order of inspection: coordinates, raw field, ids, normals, steps, lighting terms, then re-enable composition in+layers. Do not debug a full shaded image when the broken term can be displayed directly.## Formula Verification From Visual Sources@@ -89,7 +102,7 @@ Run these passes in order:- Motion pass: animation has stable phase and loops if requested.- Performance pass: reduce octaves, step counts, shadow calls, and repeated map evaluations.-## Response Pattern for Codex+## Response PatternWhen presenting a shader, include:@@ -98,3 +111,4 @@ When presenting a shader, include:- Debug controls or intermediate fields.- Tuning knobs.- Performance notes if raymarching, fbm, shadows, or volumetrics are involved.+- Whether it was compile-checked (`scripts/glsl_tools.py check`), and how.diff --git a/skills/codex/shader-art-coding/references/formula-code-couples-materials.md b/skills/shader-art-coding/references/formula-code-couples-materials.mdsimilarity index 76%rename from skills/codex/shader-art-coding/references/formula-code-couples-materials.mdrename to skills/shader-art-coding/references/formula-code-couples-materials.mdindex c67fd11..dd3080c 100644--- a/skills/codex/shader-art-coding/references/formula-code-couples-materials.md+++ b/skills/shader-art-coding/references/formula-code-couples-materials.md@@ -9,6 +9,39 @@ Each couple has:- Visual result: what should appear when the formula is correct.- Debug view: the simplest way to inspect it.+## Contents++- [1. Smoothstep Mask](#1-smoothstep-mask)+- [2. Derivative Antialiasing](#2-derivative-antialiasing)+- [3. Fill Mask From SDF](#3-fill-mask-from-sdf)+- [4. Stroke Mask From SDF](#4-stroke-mask-from-sdf)+- [5. Cosine Palette](#5-cosine-palette)+- [6. Warm Light, Cool Shadow](#6-warm-light-cool-shadow)+- [7. Fresnel Rim](#7-fresnel-rim)+- [8. Normal-View Localized Warmth Mask](#8-normal-view-localized-warmth-mask)+- [9. Sparse Stochastic Spot Field](#9-sparse-stochastic-spot-field)+- [10. Radial-Cell ID Albedo Variation](#10-radial-cell-id-albedo-variation)+- [11. Local Cell Grain](#11-local-cell-grain)+- [12. Interstitial Boundary Mask](#12-interstitial-boundary-mask)+- [13. Material Lambda Mix](#13-material-lambda-mix)+- [14. Multi-Material Weighted Sum](#14-multi-material-weighted-sum)+- [15. Edge Wear](#15-edge-wear)+- [16. Dirt or Stain Gravity Bias](#16-dirt-or-stain-gravity-bias)+- [17. Specular Lobe](#17-specular-lobe)+- [18. Radial Chromatic Ring Field](#18-radial-chromatic-ring-field)+- [19. Composition Thirds Overlay](#19-composition-thirds-overlay)+- [20. Golden Ratio Overlay](#20-golden-ratio-overlay)+- [21. Tonemap](#21-tonemap)+- [22. Linear to sRGB](#22-linear-to-srgb)+- [23. Dithering](#23-dithering)+- [24. Slow Procedural Motion](#24-slow-procedural-motion)+- [25. Looping Time Phase](#25-looping-time-phase)+- [26. Temporal Aperture Pulse Mask](#26-temporal-aperture-pulse-mask)+- [27. Background Blur Weight](#27-background-blur-weight)+- [28. Material Debug Router](#28-material-debug-router)++Names here describe geometry, not subjects, so the formulas stay reusable. `subject-routing.md` maps them to subjects (for example, "bilobed carrier" is a head or torso). Helpers such as `sdEllipsoid`, `smin`, `hash12` and `fbm` come from `glsl/` and are verified there.+## 1. Smoothstep MaskEquation:@@ -281,7 +314,7 @@ GLSL:```glslvec3 applyCellGrain(vec3 color, vec2 localUv, vec2 id) {float seed = 13.0*hash12(id);- float grain = fbm(localUv*18.0 + seed);+ float grain = fbm(localUv*18.0 + seed, 4);return color * (0.78 + 0.32*grain);}```@@ -405,7 +438,7 @@ GLSL:```glslfloat verticalStain(vec3 p) {float flow = smoothstep(0.7, -0.4, p.y);- float breakup = fbm(vec2(p.x*1.7, p.z*1.7));+ float breakup = fbm(vec2(p.x*1.7, p.z*1.7), 4);return flow * smoothstep(0.35, 0.8, breakup);}```@@ -459,7 +492,7 @@ GLSL:vec3 radialRingColor(vec2 uv) {float r = length(uv);float a = atan(uv.y, uv.x);- float fibers = 0.5 + 0.5*sin(34.0*a + 8.0*fbm(vec2(r*5.0, a)));+ float fibers = 0.5 + 0.5*sin(34.0*a + 8.0*fbm(vec2(r*5.0, a), 4));vec3 inner = vec3(0.16, 0.08, 0.03);vec3 outer = vec3(0.55, 0.32, 0.12);vec3 col = mix(inner, outer, smoothstep(0.08, 0.45, r));@@ -544,74 +577,73 @@ Toggle with `#define DEBUG_COMPOSITION 1`.Equation:```text-y = x / (1 + x)+display = T(exposure * hdr) T = AgX (default), Khronos Neutral (palette-faithful), ACES (filmic contrast)```-GLSL:+GLSL: use `glsl/tonemap.glsl`. Every tonemapper there takes linear HDR and returns linear [0,1]. `x / (1 + x)`+looks grey (1.0 maps to 0.5) and shifts hue in highlights; avoid it for finished work.```glsl-vec3 tonemap(vec3 x) {- x = max(x, 0.0);- return x / (1.0 + x);+vec3 finishColor(vec3 hdr, float exposure) {+ return tonemapAgX(hdr * exposure);}```Visual result:-Bright lighting compresses gracefully instead of clipping.+Suns, glows and specular highlights roll off smoothly toward white instead of clipping to flat saturated blobs.Debug view:-Compare before/after on a high-contrast light.+Render a horizontal HDR ramp `vec3(exp2(uv.x * 12.0 - 8.0))` through each tonemapper and compare the shoulders.-## 22. Gamma to sRGB+## 22. Linear to sRGBEquation:```text-srgb = linear^(1/2.2)+srgb = 12.92 c for c <= 0.0031308+srgb = 1.055 c^(1/2.4) - 0.055 otherwise```-GLSL:+GLSL: `linearToSrgb` (and the inverse `srgbToLinear`) from `glsl/color.glsl`. `pow(c, 1/2.2)` is visibly wrong near+black: linear 0.001 encodes to 0.013 with the exact curve but 0.043 with gamma 2.2, which lifts and fogs shadows.```glsl-vec3 toSRGB(vec3 x) {- return pow(max(x, 0.0), vec3(1.0/2.2));-}+vec3 encodeOutput(vec3 linearColor) { return linearToSrgb(linearColor); }```Visual result:-Colors look less dark/muddy in standard display output.+Correct mid-tones and clean shadows. Apply exactly once, after tonemapping and after averaging AA samples.Debug view:-Apply as the final step only.+A linear ramp `vec3(uv.x)` encoded once should look perceptually even; encoded twice it looks washed out.-## 23. Cheap Dithering+## 23. DitheringEquation:```text-color += hash(pixel) / 255+encoded += (u1 + u2 - 1) / 255 triangular PDF, +-1 LSB, added after encoding```-GLSL:+GLSL: `ditherTPDF(fragCoord, iFrame)` from `glsl/post.glsl`.```glsl-vec3 cheapDither(vec3 col, vec2 fragCoord) {- float h = hash12(fragCoord);- return col + (h - 0.5) / 255.0;+vec3 finalPixel(vec3 hdr, float exposure, vec2 fragCoord) {+ return linearToSrgb(tonemapAgX(hdr * exposure)) + ditherTPDF(fragCoord, iFrame);}```Visual result:-Reduced banding in smooth gradients, fog, and sky.+Smooth skies, fog and vignettes with no banding and no visible noise.Debug view:-Zoom into gradients; dithering should be barely visible.+Multiply the dither by 32 to see its pattern; it should be fine, even grain with no structure.## 24. Slow Procedural Motion@@ -625,7 +657,7 @@ GLSL:```glslfloat slowNoise(float t, float seed) {- return fbm(vec2(0.13*t, seed));+ return fbm(vec2(0.13*t, seed), 4);}vec3 subtleCameraOffset(float t) {diff --git a/skills/codex/shader-art-coding/references/formula-code-couples-sdf.md b/skills/shader-art-coding/references/formula-code-couples-sdf.mdsimilarity index 69%rename from skills/codex/shader-art-coding/references/formula-code-couples-sdf.mdrename to skills/shader-art-coding/references/formula-code-couples-sdf.mdindex ed0a270..0430c93 100644--- a/skills/codex/shader-art-coding/references/formula-code-couples-sdf.md+++ b/skills/shader-art-coding/references/formula-code-couples-sdf.md@@ -9,20 +9,49 @@ Each couple has:- Visual result: what should appear when the formula is correct.- Debug view: the simplest way to inspect it.+## Contents++- [1. Sphere SDF](#1-sphere-sdf)+- [2. Ellipsoid Approximation](#2-ellipsoid-approximation)+- [3. Box SDF](#3-box-sdf)+- [4. Rounded Box](#4-rounded-box)+- [5. Capsule](#5-capsule)+- [6. Torus and Tube](#6-torus-and-tube)+- [7. Hard Boolean Operations](#7-hard-boolean-operations)+- [8. Polynomial Smooth Minimum](#8-polynomial-smooth-minimum)+- [9. Smooth Subtraction](#9-smooth-subtraction)+- [10. Local Transform Before Evaluation](#10-local-transform-before-evaluation)+- [11. Mirror Symmetry With Later Breakage](#11-mirror-symmetry-with-later-breakage)+- [12. Contour Debug for Distance Fields](#12-contour-debug-for-distance-fields)+- [13. Cylindrical Sector Coordinates](#13-cylindrical-sector-coordinates)+- [14. Radial Row-Cell Local Space](#14-radial-row-cell-local-space)+- [15. Modular Rectangular Cell SDF](#15-modular-rectangular-cell-sdf)+- [16. Continuous Interstitial Radial Shell](#16-continuous-interstitial-radial-shell)+- [17. Bilobed Organic Carrier](#17-bilobed-organic-carrier)+- [18. Paired Concavity Carve](#18-paired-concavity-carve)+- [19. Parametric Arc Aperture Curve](#19-parametric-arc-aperture-curve)+- [20. Soft Parametric Groove](#20-soft-parametric-groove)+- [21. Anisotropic Strand Tube Perturbation](#21-anisotropic-strand-tube-perturbation)+- [22. Ellipsoidal Shell Clipped by Half-Space](#22-ellipsoidal-shell-clipped-by-half-space)+- [23. Fabric Micro-Displacement](#23-fabric-micro-displacement)+- [24. Cone SDF for Trees and Props](#24-cone-sdf-for-trees-and-props)+- [25. Repeated Conical Field (Neighbor-Checked)](#25-repeated-conical-field-neighbor-checked)+- [26. SDF Scene Return With Material ID](#26-sdf-scene-return-with-material-id)++Names here describe geometry, not subjects, so the formulas stay reusable. `subject-routing.md` maps them to subjects (for example, "bilobed carrier" is a head or torso). Helpers such as `sdEllipsoid`, `smin`, `hash12` and `fbm` come from `glsl/` and are verified there.+## 1. Sphere SDFEquation:```text-d(p) = ||p - c|| - r+d(p) = ||p|| - r (translate first: d(p - c) for a sphere centered at c)```GLSL:```glsl-float sdSphere(vec3 p, vec3 c, float r) {- return length(p - c) - r;-}+float sdSphere(vec3 p, float r) { return length(p) - r; }```Visual result:@@ -33,7 +62,7 @@ Debug view:```glslvec3 debugSphere(vec3 p) {- float d = sdSphere(p, vec3(0.0), 1.0);+ float d = sdSphere(p, 1.0);return vec3(0.5 + 0.5*cos(80.0*d));}```@@ -53,7 +82,8 @@ GLSL:```glslfloat sdEllipsoid(vec3 p, vec3 r) {float k0 = length(p / r);- float k1 = length(p / (r*r));+ float k1 = length(p / (r * r));+ if (k1 < 1e-8) return -min(r.x, min(r.y, r.z));return k0 * (k0 - 1.0) / k1;}```@@ -114,7 +144,7 @@ GLSL:```glslfloat sdRoundBox(vec3 p, vec3 b, float r) {- vec3 q = abs(p) - (b - vec3(r));+ vec3 q = abs(p) - b + r;return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0) - r;}```@@ -145,10 +175,9 @@ GLSL:```glslfloat sdCapsule(vec3 p, vec3 a, vec3 b, float r) {- vec3 pa = p - a;- vec3 ba = b - a;+ vec3 pa = p - a, ba = b - a;float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);- return length(pa - ba*h) - r;+ return length(pa - ba * h) - r;}```@@ -211,7 +240,7 @@ GLSL:```glslfloat opUnion(float a, float b) { return min(a, b); }float opIntersect(float a, float b) { return max(a, b); }-float opSub(float a, float b) { return max(a, -b); }+float opSubtract(float a, float b) { return max(a, -b); }```Visual result:@@ -222,7 +251,7 @@ Debug view:```glslvec3 debugBoolean(float a, float b) {- float d = opSub(a, b);+ float d = opSubtract(a, b);return vec3(0.5 + 0.5*cos(90.0*d));}```@@ -253,8 +282,8 @@ Debug view:```glslvec3 debugSmin(vec3 p) {- float a = sdSphere(p - vec3(-0.35, 0.0, 0.0), vec3(0.0), 0.55);- float b = sdSphere(p - vec3( 0.35, 0.0, 0.0), vec3(0.0), 0.55);+ float a = sdSphere(p - vec3(-0.35, 0.0, 0.0), 0.55);+ float b = sdSphere(p - vec3( 0.35, 0.0, 0.0), 0.55);float d = smin(a, b, 0.35);return vec3(0.5 + 0.5*cos(70.0*d));}@@ -265,17 +294,15 @@ vec3 debugSmin(vec3 p) {Equation:```text-h = clamp(1/2 - (b+a)/(2k), 0, 1)-ssub(a,b,k) = mix(a, -b, h) + k h(1-h)+smax(a, b, k) = -smin(-a, -b, k)+smoothSubtract(a, b, k) = smax(a, -b, k) (a with b carved out)```GLSL:```glsl-float smoothSub(float a, float b, float k) {- float h = clamp(0.5 - 0.5*(b + a)/k, 0.0, 1.0);- return mix(a, -b, h) + k*h*(1.0 - h);-}+float smax(float a, float b, float k) { return -smin(-a, -b, k); }+float smoothSubtract(float a, float b, float k) { return smax(a, -b, k); }```Visual result:@@ -287,8 +314,8 @@ Debug view:```glslvec3 debugSmoothSub(vec3 p) {float carrier = sdEllipsoid(p, vec3(0.7, 0.95, 0.55));- float socket = sdSphere(p, vec3(0.25, 0.2, -0.45), 0.28);- float d = smoothSub(carrier, socket, 0.12);+ float socket = sdSphere(p - vec3(0.25, 0.2, -0.45), 0.28);+ float d = smoothSubtract(carrier, socket, 0.12);return vec3(0.5 + 0.5*cos(85.0*d));}```@@ -305,14 +332,14 @@ d_world(p) = s d_local(q)GLSL:```glsl-mat2 rot(float a) {- float s = sin(a), c = cos(a);- return mat2(c, -s, s, c);+mat2 rot2(float a) {+ float c = cos(a), s = sin(a);+ return mat2(c, s, -s, c);}float posedEllipsoid(vec3 p, vec3 c, vec3 r, float yaw) {vec3 q = p - c;- q.xz = rot(-yaw) * q.xz;+ q.xz = rot2(yaw) * q.xz; // rot2(a) * v rotates v counter-clockwise by areturn sdEllipsoid(q, r);}```@@ -356,7 +383,7 @@ Debug view:```glslvec3 debugMirror(vec3 p) {vec3 q = mirrorX(p);- float d = sdSphere(q - vec3(0.32, 0.15, 0.0), vec3(0.0), 0.15);+ float d = sdSphere(q - vec3(0.32, 0.15, 0.0), 0.15);return vec3(smoothstep(0.03, -0.01, d));}```@@ -569,7 +596,7 @@ vec3 debugHeadBase(vec3 p) {Equation:```text-d = smoothSub(carrier, ellipsoid_concavity, k)+d = smoothSubtract(carrier, ellipsoid_concavity, k)```GLSL:@@ -579,7 +606,7 @@ float carvePairedConcavity(float carrierD, vec3 p, float side) {vec3 q = p - vec3(0.22*side, 0.12, -0.36);q.x *= 1.25;float concavity = sdEllipsoid(q, vec3(0.18, 0.11, 0.12));- return smoothSub(carrierD, concavity, 0.08);+ return smoothSubtract(carrierD, concavity, 0.08);}```@@ -702,9 +729,7 @@ d = max(sdEllipsoid(p, r), sdPlane(p, n, h))GLSL:```glsl-float sdPlane(vec3 p, vec3 n, float h) {- return dot(p, normalize(n)) + h;-}+float sdPlane(vec3 p, vec3 n, float h) { return dot(p, n) + h; } // n must be unit lengthfloat sdClippedEllipsoidShell(vec3 p) {float shell = abs(sdEllipsoid(p, vec3(0.72, 0.86, 0.55))) - 0.045;@@ -742,6 +767,8 @@ float fabricDisplace(float d, vec3 p) {Visual result:Fine fabric or knitted texture that perturbs highlights. Keep amplitude tiny or the cloth silhouette becomes noisy.+High-frequency displacement raises the field's Lipschitz constant (here about 1 + 0.0035 * 91, plus the broad term), so march+with `stepScale` around 0.7 when it is applied.Debug view:@@ -752,97 +779,102 @@ Show the displacement field as `0.5 + 20.0*(dPrime - d)`.Equation:```text-cone approximates distance to a linearly shrinking radius over height+trapezoid in (radius, height): base disk radius r at y = 0, apex at y = h+d = min(distance to the slanted side segment, distance to the base cap), negative only when inside both```-GLSL:+GLSL: use `sdCone(p, h, r)` (and `sdCappedCone` for frustums) from `glsl/sdf3d.glsl`. They are exact, including the+base cap. Older shortcuts that clamp y and measure horizontally report every point under the base as "inside" and the+whole interior as 0, which breaks shadows, AO and smooth blends.```glsl-float sdConeApprox(vec3 p, float h, float r) {- float y = clamp(p.y, 0.0, h);- float radiusAtY = r * (1.0 - y / h);- vec2 q = vec2(length(p.xz) - radiusAtY, p.y - y);- return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0);+float sdEvergreen(vec3 p) {+ float tiers = sdCone(p - vec3(0.0, 0.35, 0.0), 0.9, 0.42);+ tiers = smin(tiers, sdCone(p - vec3(0.0, 0.75, 0.0), 0.75, 0.32), 0.05);+ float trunk = sdCylinder(p - vec3(0.0, 0.2, 0.0), 0.2, 0.06);+ return min(tiers, trunk);}```Visual result:-Simple evergreen silhouettes, roofs, spikes, stylized mountains, and cone props.+Evergreen silhouettes, roofs, spikes, stylized mountains and cone props with clean contact shadows.Debug view:-Use contour bands on one cone, then repeat with per-instance IDs.+Contour bands on a vertical slice: lines must wrap the base cap, not run straight down below it.-## 25. Repeated Conical Field+## 25. Repeated Conical Field (Neighbor-Checked)Equation:```text-cell = floor(xz / s)-local = fract(xz / s) - 1/2-height = h0 + random(cell) hvar+cell = floor(xz / s + 1/2)+d = min over the 2x2 cells nearest p of cone_cell(p - s * cell)```+When every cell holds a different instance (random height, radius or offset), the nearest surface may belong to a+neighbor cell, so evaluating only the current cell overestimates the distance and the march punches holes. Check+the current cell and the neighbors on the side p leans toward (4 evaluations in 2D).+GLSL:```glsl-float sdRepeatedConeField(vec3 p, float spacing) {- vec2 cell = floor(p.xz / spacing);- vec2 local = fract(p.xz / spacing) - 0.5;- float rnd = hash12(cell);- vec3 q = vec3(local.x*spacing, p.y, local.y*spacing);- float h = mix(0.8, 1.6, rnd);- float r = mix(0.22, 0.38, hash12(cell + 5.1));- return sdConeApprox(q, h, r);+float sdConeForest(vec3 p, float spacing) {+ vec2 id = floor(p.xz / spacing + 0.5);+ vec2 side = sign(p.xz - spacing * id);+ float d = 1e10;+ for (int j = 0; j < 2; j++)+ for (int i = 0; i < 2; i++) {+ vec2 cell = id + vec2(float(i), float(j)) * side;+ vec2 center = spacing * cell;+ float h = mix(0.8, 1.6, hash12(cell));+ float r = mix(0.22, 0.38, hash12(cell + vec2(17.0, 5.0)));+ d = min(d, sdCone(vec3(p.x - center.x, p.y, p.z - center.y), h, r));+ }+ return d;}```Visual result:-A field of repeated conical primitives. Variation should be visible in height and radius, but the set should still read as one coherent mass.+A field of repeated conical primitives. Variation should be visible in height and radius, but the set should still+read as one coherent mass, with no missing slivers at cell borders.Debug view:-Render `hash12(cell)` as color to verify variation is stable in world space.+Render `hash12(cell)` as color to verify variation is stable in world space, and the step-count heat map to verify+no ray stalls at cell borders.## 26. SDF Scene Return With Material IDEquation:```text-scene(p) = argmin_i d_i(p)+scene(p) = (min_i d_i(p), id of the argmin)```-GLSL:+GLSL: pack (distance, material id) into a `vec2`. This is the library's scene contract (`vec2 map(vec3 p)`), and it+avoids structs. WebGL rejects `?:` on structs, so a struct-based `pick(a, b)` with a ternary does not compile on+Shadertoy.```glsl-struct Hit {- float d;- float mat;-};--Hit pickCloser(Hit a, Hit b) {- return (b.d < a.d) ? b : a;-}+vec2 opUnionId(vec2 a, vec2 b) { return (b.x < a.x) ? b : a; } // ternary on vec2 is fine-Hit mapScene(vec3 p) {- Hit h = Hit(1e5, 0.0);- h = pickCloser(h, Hit(sdBilobedCarrier(p), 1.0));- h = pickCloser(h, Hit(sdClippedEllipsoidShell(p - vec3(0.0, 0.02, 0.0)), 2.0));- h = pickCloser(h, Hit(sdRepeatedConeField(p - vec3(0.0, -1.0, 4.0), 1.1), 3.0));- return h;+vec2 map(vec3 p) {+ vec2 res = vec2(p.y + 1.0, 0.0); // ground+ res = opUnionId(res, vec2(sdBilobedCarrier(p), 1.0));+ res = opUnionId(res, vec2(sdClippedEllipsoidShell(p - vec3(0.0, 0.02, 0.0)), 2.0));+ res = opUnionId(res, vec2(sdConeForest(p - vec3(0.0, -1.0, 4.0), 1.1), 3.0));+ return res;}```Visual result:-The closest surface wins and carries a material ID. This is the backbone for readable raymarched scenes.+The closest surface wins and carries a material ID. This is the backbone for readable raymarched scenes and plugs+directly into `raymarch`, `calcNormal`, `softShadow` and `calcAO` from `glsl/raymarch.glsl`.Debug view:-```glsl-vec3 idColor(float id) {- return vec3(fract(id*0.37), fract(id*0.61), fract(id*0.83));-}-```+`debugIdColor(res.y)` from `glsl/debug.glsl`.diff --git a/skills/codex/shader-art-coding/references/formula-code-couples-terrain.md b/skills/shader-art-coding/references/formula-code-couples-terrain.mdsimilarity index 87%rename from skills/codex/shader-art-coding/references/formula-code-couples-terrain.mdrename to skills/shader-art-coding/references/formula-code-couples-terrain.mdindex 3f4b4af..f72c8a2 100644--- a/skills/codex/shader-art-coding/references/formula-code-couples-terrain.md+++ b/skills/shader-art-coding/references/formula-code-couples-terrain.md@@ -9,6 +9,37 @@ Each couple has:- Visual result: what should appear when the formula is correct.- Debug view: the simplest way to inspect it.+## Contents++- [1. Smooth Cell Interpolation](#1-smooth-cell-interpolation)+- [2. Quintic Interpolation for Better Normals](#2-quintic-interpolation-for-better-normals)+- [3. Polynomial Patch Terrain](#3-polynomial-patch-terrain)+- [4. Rotated Octave Matrix](#4-rotated-octave-matrix)+- [5. Base Shape Plus Detail](#5-base-shape-plus-detail)+- [6. Heightfield Normal](#6-heightfield-normal)+- [7. Heightfield Ray March](#7-heightfield-ray-march)+- [8. Diffuse Terrain Lighting](#8-diffuse-terrain-lighting)+- [9. Heightfield Self Shadow](#9-heightfield-self-shadow)+- [10. Slope Mask](#10-slope-mask)+- [11. Altitude Mask](#11-altitude-mask)+- [12. Stratified Three-Channel Material Mix](#12-stratified-three-channel-material-mix)+- [13. Atmospheric Fog](#13-atmospheric-fog)+- [14. Height Fog](#14-height-fog)+- [15. Sky Gradient](#15-sky-gradient)+- [16. Atmospheric Coverage Field](#16-atmospheric-coverage-field)+- [17. Coverage Horizon Fade](#17-coverage-horizon-fade)+- [18. Directional Coverage Lighting](#18-directional-coverage-lighting)+- [19. Instance Placement Grid](#19-instance-placement-grid)+- [20. Instance Suitability Field](#20-instance-suitability-field)+- [21. Volumetric Clump Density](#21-volumetric-clump-density)+- [22. Upward-Facing Accumulation Mask](#22-upward-facing-accumulation-mask)+- [23. Layered Sinusoidal Ridge](#23-layered-sinusoidal-ridge)+- [24. Curvilinear Basin/Path Mask](#24-curvilinear-basinpath-mask)+- [25. Distance-Based Detail Reduction](#25-distance-based-detail-reduction)+- [26. Complete Terrain Shade Skeleton](#26-complete-terrain-shade-skeleton)++Names here describe geometry, not subjects, so the formulas stay reusable. `subject-routing.md` maps them to subjects (for example, "bilobed carrier" is a head or torso). Helpers such as `sdEllipsoid`, `smin`, `hash12` and `fbm` come from `glsl/` and are verified there.+## 1. Smooth Cell InterpolationEquation:@@ -22,13 +53,9 @@ h = bilerp(h00, h10, h01, h11, s)GLSL:-```glsl-float hash12(vec2 p) {- vec3 p3 = fract(vec3(p.xyx) * 0.1031);- p3 += dot(p3, p3.yzx + 33.33);- return fract((p3.x + p3.y) * p3.z);-}+`hash12` is the integer PCG hash from `glsl/hash.glsl` (bit-exact on every GPU; no sine).+```glslfloat smoothCell(vec2 p) {vec2 i = floor(p);vec2 f = fract(p);@@ -438,10 +465,10 @@ Equation:fog *= exp(-falloff * y)```-GLSL:+GLSL (a cheap per-point version; the exact integral along the ray is `heightFog(ro, rd, t, a, b)` in `glsl/volume.glsl`):```glsl-float heightFog(float dist, float y) {+float altitudeHaze(float dist, float y) {float base = 1.0 - exp(-0.018*dist);float low = exp(-0.65*max(y, 0.0));return clamp(base * low, 0.0, 1.0);@@ -767,7 +794,7 @@ vec3 shadeTerrain(vec3 ro, vec3 rd, vec3 sunDir) {float sh = terrainShadow(p.xz, p.y, sunDir);vec3 mat = terrainMaterial(p, n);vec3 col = mat * (0.18 + 1.35*ndl*sh);- float fog = heightFog(t, p.y);+ float fog = altitudeHaze(t, p.y);return mix(col, sky, fog);}```diff --git a/skills/codex/shader-art-coding/references/formula-cookbook.md b/skills/shader-art-coding/references/formula-cookbook.mdsimilarity index 91%rename from skills/codex/shader-art-coding/references/formula-cookbook.mdrename to skills/shader-art-coding/references/formula-cookbook.mdindex 25d1fa9..c880b92 100644--- a/skills/codex/shader-art-coding/references/formula-cookbook.md+++ b/skills/shader-art-coding/references/formula-cookbook.md@@ -4,6 +4,22 @@ Use this when a prompt needs concrete mathematical construction strategy, not onThese recipes describe visually verified shader-building patterns: define a simple field, expose IDs and local coordinates, then use those controls for geometry, material, lighting, and variation. The examples are original abstractions, not copied source.+## Contents++- [Visual Formula Audit](#visual-formula-audit)+- [Cylindrical Modular Cell Lattice](#cylindrical-modular-cell-lattice)+- [Polynomial Heightfield Synthesis](#polynomial-heightfield-synthesis)+- [Bilateral Organic SDF Composition](#bilateral-organic-sdf-composition)+- [Vegetation as Volumetric Clumps](#vegetation-as-volumetric-clumps)+- [Clouds and Atmospheric Volume](#clouds-and-atmospheric-volume)+- [Environment Props and Snowy Detail](#environment-props-and-snowy-detail)+- [Temporal Polish](#temporal-polish)+- [Material Breakup Without Noise Soup](#material-breakup-without-noise-soup)+- [Composition Math](#composition-math)+- [Formula Selection Heuristics](#formula-selection-heuristics)++Names here describe geometry, not subjects, so the formulas stay reusable. `subject-routing.md` maps them to subjects (for example, "bilobed carrier" is a head or torso). Helpers such as `sdEllipsoid`, `smin`, `hash12` and `fbm` come from `glsl/` and are verified there.+## Visual Formula AuditWhen deriving or checking formulas from a video, screenshot, or sketch:@@ -86,7 +102,7 @@ Use IDs for coarse variation and local coordinates for fine variation:```glslfloat cellRand = hash12(id);-float faceGrain = fbm(local.xy*18.0 + 7.0*cellRand);+float faceGrain = fbm(local.xy*18.0 + 7.0*cellRand, 4);float interstitialMask = smoothstep(0.02, 0.08, distanceFromInterstitial);vec3 cellColor = mix(vec3(0.45, 0.12, 0.07), vec3(0.9, 0.32, 0.18), cellRand);cellColor *= 0.82 + 0.28*faceGrain;@@ -173,11 +189,13 @@ Keep a separate low-frequency base shape so the composition does not become an e### Terrain Normal```glsl+float terrainHeight(vec2 xz); // provided by your scene, e.g. 2.0 * erodedFbm(xz * 0.3, 9)+vec3 heightfieldNormal(vec2 xz) {float e = 0.02;- float h = heightfieldHeight(xz);- float hx = heightfieldHeight(xz + vec2(e, 0.0)) - h;- float hz = heightfieldHeight(xz + vec2(0.0, e)) - h;+ float h = terrainHeight(xz);+ float hx = terrainHeight(xz + vec2(e, 0.0)) - h;+ float hz = terrainHeight(xz + vec2(0.0, e)) - h;return normalize(vec3(-hx, e, -hz));}```@@ -200,7 +218,7 @@ float heightfieldShadow(vec2 xz, float h, vec3 ldir) {for (int i = 0; i < 48; i++) {vec2 q = xz + ldir.xz * t;float rayH = h + ldir.y * t;- float heightfieldH = heightfieldHeight(q);+ float heightfieldH = terrainHeight(q);float clearance = rayH - heightfieldH;shadow = min(shadow, smoothstep(0.0, 0.25*t, clearance));t += 0.12 + 0.08*t;@@ -253,7 +271,8 @@ Contours that kink or bunch reveal bad blends, wrong scale, or accidental non-SD```glslfloat sdEllipsoid(vec3 p, vec3 r) {float k0 = length(p / r);- float k1 = length(p / (r*r));+ float k1 = length(p / (r * r));+ if (k1 < 1e-8) return -min(r.x, min(r.y, r.z));return k0 * (k0 - 1.0) / k1;}```@@ -346,7 +365,7 @@ Do not start with individual leaves. Start with a density envelope:float foliageDensity(vec3 p, vec2 cellId) {float crown = 1.0 - smoothstep(0.6, 1.0, length(p.xz));float vertical = smoothstep(-0.4, 0.2, p.y) * smoothstep(1.2, 0.5, p.y);- float breakup = 0.65 + 0.35*fbm(p.xz*4.0 + cellId);+ float breakup = 0.65 + 0.35*fbm(p.xz*4.0 + cellId, 4);return crown * vertical * breakup;}```@@ -380,8 +399,8 @@ Atmospheric coverage recipe:```glslfloat cloudMask(vec2 p, float coverage) {- vec2 warp = vec2(fbm(p*0.45 + 4.1), fbm(p*0.45 - 2.8));- float d = fbm(p + 0.55*warp);+ vec2 warp = vec2(fbm(p*0.45 + 4.1, 4), fbm(p*0.45 - 2.8, 4));+ float d = fbm(p + 0.55*warp, 4);return smoothstep(coverage, coverage + 0.18, d);}```@@ -431,7 +450,7 @@ Use tiny motion fields at the end:```glslfloat slowNoise(float t, float seed) {- return fbm(vec2(0.13*t, seed));+ return fbm(vec2(0.13*t, seed), 4);}vec3 subtleCameraOffset(float t) {@@ -460,7 +479,7 @@ Noise should be masked by material logic:```glslfloat cellInteriorMask = smoothstep(0.08, 0.14, distanceFromInterstitial);-float grain = fbm(localFaceUv*18.0);+float grain = fbm(localFaceUv*18.0, 4);albedo *= mix(1.0, 0.75 + 0.35*grain, cellInteriorMask);```diff --git a/skills/shader-art-coding/references/library-index.md b/skills/shader-art-coding/references/library-index.mdnew file mode 100644index 0000000..08bbfca--- /dev/null+++ b/skills/shader-art-coding/references/library-index.md@@ -0,0 +1,300 @@+# GLSL Library Index++Generated by `scripts/glsl_tools.py index`. Do not edit by hand.++Call these functions by name in your shader, then run+`python3 scripts/glsl_tools.py bundle your.glsl -o out.glsl` to inline exactly what it uses.+Find candidates with `python3 scripts/glsl_tools.py search <words>`.++Tags: **exact** is a true Euclidean distance, safe for blending, AO, shadows and offsets.+**bound** never overestimates, so it is safe to march, but less accurate for offsets.+**approx** has an exact surface but may overestimate in places; read its note for a safe step scale.++## Contents++- [common](#common) - constants, rotation, remapping and shaping functions+- [hash](#hash) - integer hashes and float wrappers for lattice ids+- [noise](#noise) - value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering+- [pattern](#pattern) - tilings and antialiased procedural patterns+- [sdf3d](#sdf3d) - 3D signed distance primitives+- [sdf2d](#sdf2d) - 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve+- [operators](#operators) - combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion, extrude, revolve, elongate)+- [domain](#domain) - transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds, twist, bend)+- [raymarch](#raymarch) - sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes+- [intersect](#intersect) - analytic ray-primitive intersections+- [camera](#camera) - look-at frames, primary rays, field of view, thin-lens depth of field+- [shading](#shading) - BRDF terms and practical lighting models+- [color](#color) - transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors+- [tonemap](#tonemap) - map scene-linear HDR to display range+- [volume](#volume) - participating media (fog, smoke, clouds, haze)+- [atmosphere](#atmosphere) - skies and sun+- [post](#post) - antialiasing helpers, supersampling offsets, lens effects, grain and dithering, all single-pass+- [debug](#debug) - visualize intermediate fields++## common++common: constants, rotation, remapping and shaping functions. Target: GLSL ES 3.00 (Shadertoy / WebGL2). Every function here is original and MIT licensed.++- `const float PI = 3.14159265358979;`+- `const float TAU = 6.28318530717959;`+- `float saturate(float x)` / `vec3 saturate(vec3 x)` - Clamp to [0,1]. *Use: masks, weights, colors.*+- `float dot2(vec2 v)` / `float dot2(vec3 v)` - Squared length. *Use: cheap distance comparisons, SDF internals.*+- `mat2 rot2(float a)` - 2D rotation matrix. `rot2(a) * v` rotates v counter-clockwise by a radians. *Use: spinning parts, posing limbs, rotating octaves, camera roll.*+- `float remap(float x, float a, float b, float c, float d)` - Linear remap of x from [a,b] to [c,d] (unclamped). *Use: converting ranges, rescaling noise.*+- `float linearstep(float a, float b, float x)` - Linear ramp from 0 at a to 1 at b, clamped. *Use: masks whose falloff should not ease in or out.*+- `float cubicPulse(float c, float w, float x)` - Smooth bump: 1 at x == c, falling to 0 at |x - c| >= w (cubic). *Use: stripes, rings, highlights at one height, pulses in time.*+- `float expImpulse(float x, float k)` - Fast attack, exponential decay. Peaks at 1 when x == 1/k. *Use: heartbeat motion, impacts, flashes, plucked-string envelopes.*+- `float gain(float x, float k)` - Contrast curve on [0,1] that keeps 0, 0.5 and 1 fixed. k > 1 adds contrast, k < 1 flattens. *Use: tightening masks, adjusting animation easing.*+- `float parabola(float x, float k)` - 0 at x = 0 and x = 1, peak 1 at x = 0.5; k sharpens. *Use: petal width along length, leaf profiles, arches.*+- `float almostIdentity(float x, float m, float n)` - Returns x when x > m; smoothly bottoms out at n when x -> 0. Needs 2n < m. *Use: avoiding hard zero in falloffs, soft floor on thickness.*++## hash++hash: integer hashes and float wrappers for lattice ids. Naming: hashNM returns N floats from M inputs (hash12 = 1 output, 2 inputs). Outputs are in [0,1). The float wrappers hash INTEGER-VALUED inputs (cell ids, pixel coords, frame numbers). Fractional parts are dropped. That is deliberate: negative float -> uint is undefined in GLSL, and round() can return -0.0, which has different bits from 0.0. Converting through int avoids both. To hash a continuous value, scale it first. Do not use fract(sin(dot(p, k)) * 43758.5453): its result changes across GPUs and degrades at large inputs. Integer mixers are from Jarzynski and Olano, "Hash Functions for GPU Rendering" (JCGT 2020): pcg3d and pcg4d sit on that study's quality/speed frontier, and 32-bit integer math is bit-exact on every GPU, unlike sin().++- `uint pcgHash(uint v)` - PCG-style 1D integer hash. *Use: seeding, per-instance randomness, building other hashes.*+- `uvec3 pcg3d(uvec3 v)` - 3D integer hash, three decorrelated outputs. *Use: 3D cell ids, voxel jitter, (pixel, frame) noise.*+- `uvec4 pcg4d(uvec4 v)` - 4D integer hash, four decorrelated outputs (0 BigCrush failures in the JCGT study). *Use: (pixel.x, pixel.y, frame, sample) streams for stochastic sampling, 4D cell ids.*+- `float uintToUnit(uint h)` / `vec2 uintToUnit(uvec2 h)` / `vec3 uintToUnit(uvec3 h)` / `vec4 uintToUnit(uvec4 h)` - Map a uint to [0,1) using the top 24 bits, so the result can never round up to 1.0.+- `float hash11(float p)` - Random float in [0,1) for an integer-valued input. *Use: per-cell randomness, stable random per instance id.* Range [0,1).+- `float hash12(vec2 p)` - Random float in [0,1) for an integer-valued 2D input. *Use: per-cell variation (color, height, rotation), sparse spots, star fields.* Range [0,1).+- `float hash13(vec3 p)` - Random float in [0,1) for an integer-valued 3D input. *Use: per-voxel randomness, per-pixel-per-frame noise via hash13(vec3(fragCoord, iFrame)).* Range [0,1).+- `vec2 hash22(vec2 p)` - Random vec2 in [0,1)^2 for an integer-valued 2D input. *Use: Voronoi feature points, 2D jitter, random gradients.* Range [0,1)^2.+- `vec3 hash33(vec3 p)` - Random vec3 in [0,1)^3 for an integer-valued 3D input. *Use: 3D Voronoi points, random colors per cell, random directions.* Range [0,1)^3.+- `vec4 hash44(vec4 p)` - Random vec4 in [0,1)^4 for an integer-valued 4D input. *Use: per-pixel, per-frame, per-sample random numbers: hash44(vec4(fragCoord, iFrame, sampleIndex)).* Range [0,1)^4.+- `vec3 hash32(vec2 p)` - Random vec3 in [0,1)^3 for an integer-valued 2D input. *Use: per-tile random color, per-cell (offset, rotation, scale) triples.* Range [0,1)^3.++## noise++noise: value and gradient noise (2D/3D, analytic derivatives), fBm, domain warping, Voronoi, tilings, dithering. Every function here is texture-free and original. The math follows the cited articles. Ranges are approximate unless stated. Noise built on integer hashes stays stable at large coordinates until float precision runs out (|p| around 1e5). Re-center long animations with mod/fract on time.++- `vec2 quinticFade(vec2 f)` / `vec3 quinticFade(vec3 f)` - Quintic fade 6t^5 - 15t^4 + 10t^3: C2-continuous interpolation weights for lattice noise. *Use: custom lattice noises, smooth cell interpolation.*+- `vec2 quinticFadeDeriv(vec2 f)` - Derivative of quinticFade: 30 t^2 (t - 1)^2. *Use: analytic noise derivatives.*+- `vec3 valueNoiseD(vec2 p)` - 2D value noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). *Use: terrain base layers, cheap clouds, anything needing normals without finite differences.* Range value in [0,1].+- `float valueNoise(vec2 p)` / `float valueNoise(vec3 p)` - 2D value noise. *Use: soft blotches, low-frequency color variation.* Range [0,1].+- `vec2 latticeGradient(vec2 cell)` - Unit gradient for a 2D lattice point.+- `vec3 gradientNoiseD(vec2 p)` - 2D gradient (Perlin-style) noise with analytic derivatives. Returns vec3(value, d/dx, d/dy). Gradient noise has less grid-aligned blockiness than value noise. Prefer it for fBm. *Use: fBm, terrain with analytic normals, curl flow, marble and wood distortions.* Range value in about [-0.7,0.7].+- `float gradientNoise(vec2 p)` / `float gradientNoise(vec3 p)` - 2D gradient noise. *Use: general-purpose smooth noise.* Range about [-0.7,0.7].+- `float latticeGradDot(vec3 cell, vec3 corner, vec3 f)` - Dot product of a hashed 3D gradient with the offset to its lattice corner.+- `const int FBM_MAX_OCTAVES = 12;`+- `float fbm(vec2 p, int octaves, float lacunarity, float persistence)` / `float fbm(vec2 p, int octaves)` / `float fbm(vec3 p, int octaves, float lacunarity, float persistence)` - Fractional Brownian motion over 2D gradient noise. Each octave is rotated to hide lattice alignment. persistence 0.5 is the classic look (H = 1). Lower is smoother, higher is rougher. *Use: clouds, terrain, dirt, roughness breakup, warping input.* Range about [-1,1].+- `float erodedFbm(vec2 p, int octaves)` - Terrain fBm where each octave is damped by the accumulated slope, so detail settles in valleys and steep slopes stay smooth. This gives an eroded look without simulation. *Use: mountains, dunes, rocky ground.* Range about [-0.5,1].+- `float ridgedFbm(vec2 p, int octaves)` - Ridged multifractal: inverted |noise| creates sharp crests; each octave is weighted by the previous one, so detail gathers along ridges. *Use: mountain ridges, lightning-like veins, canyons, eroded rock, alien landscapes.* Range about [0,1].+- `float warpedFbm(vec2 p, float strength, int octaves, out vec2 q, out vec2 r)` - Two-level domain warp f(p + s*r), r = fbm(p + s*q), q = fbm(p). Writes the intermediate warp vectors so they can drive color. Cost is 5 fBm calls. *Use: marble, smoke, agate, alien skies, painterly backgrounds.* Range about [-1,1].+- `vec2 curlNoise(vec2 p)` - Divergence-free 2D flow field: the curl of scalar gradient noise. Particles advected by it swirl without bunching up. *Use: smoke advection, flowing paint, hair/fur flow direction, wind.*+- `vec4 voronoi(vec2 p, float jitter)` - Cellular (Worley/Voronoi) noise. Returns vec4(F1, F2, nearestCell.xy). F1 = distance to nearest feature point, F2 = second nearest. nearestCell is integer-valued, so hash it for per-cell randomness. jitter in [0,1] (0 = regular grid). Searches 3x3 cells. F2 can be slightly off at jitter 1. *Use: cells, scales, stones, cracked mud (F2-F1), caustics, foam, sparkles.* Range F1 in [0, ~1.2].+- `vec3 voronoiBorder(vec2 p, float jitter)` - Exact distance to Voronoi cell borders, found in two passes: nearest point, then nearest bisector. Returns vec3(borderDistance, vectorToNearestPoint). Unlike F2-F1, the border distance is a true distance, so lines have constant width. *Use: cell walls, stained glass leading, cracked earth, giraffe and leaf-vein patterns, crackle glaze.*+- `float smoothVoronoi(vec2 p, float k)` - Smooth Voronoi: a soft-min of distances to feature points. Cells become blobs with no creases. k controls smoothness (large = sharper; around 8-32). Searches 5x5 cells so low k has no seams. *Use: organic cell clusters, bubbles, lumpy surfaces, skin pores.*+- `float interleavedGradientNoise(vec2 pixel)` / `float interleavedGradientNoise(vec2 pixel, int frame)` - Interleaved gradient noise: cheap per-pixel noise whose 3x3 neighborhoods are nearly stratified. Not a hash. pixel must be integer pixel coordinates (floor(fragCoord)). The frame overload animates it for accumulation and TAA. *Use: removing banding before 8-bit output, jittering ray start offsets, stochastic transparency.* Range [0,1).+- `float r2Dither(vec2 pixel)` - R2 low-discrepancy dither mask (plastic-constant sequence), folded by a triangle wave for an even spread. *Use: ordered dithering without textures, posterized and retro looks, sample offsets.* Range [0,1).++## pattern++pattern: tilings and antialiased procedural patterns. The filtered versions integrate the pattern over the pixel footprint (box filter), so floors and stripes stay clean in the distance with no supersampling. Filtering math follows https://iquilezles.org/articles/checkerfiltering/ and /filterableprocedurals/.++- `vec2 triangleWave(vec2 x)` - Triangle wave, the integral of a square wave. Building block for box-filtered patterns. *Use: writing new filtered patterns.*+- `float filteredChecker(vec2 p, vec2 w)` - Box-filtered checkerboard with unit squares: 0 or 1 up close, fading to 0.5 where squares are smaller than a pixel. Compute the footprint before any branching: w = fwidth(p) (or max(abs(dFdx(p)), abs(dFdy(p)))). *Use: floors, chessboards, test patterns, racing flags, tablecloths.* Range [0,1].+- `float filteredGrid(vec2 p, vec2 w, float n)` - Box-filtered grid lines (unit cells, line width = 1/n of a cell). Returns 1 on lines, 0 inside cells. *Use: blueprints, graph paper, tiles with grout, sci-fi floors, synthwave grids.* Range [0,1].+- `float filteredStripes(float x, float w)` - Box-filtered stripes along x with period 1 and duty cycle 0.5. Returns 0..1. *Use: awnings, candy, zebra (warp x first), barcodes, road markings.* Range [0,1].+- `vec4 hexGrid(vec2 p)` - Hexagonal tiling with unit spacing between neighboring centers. Neighbors sit left/right, so hexes are pointy-top. Returns vec4(local offset from the hex center, integer-valued hex id). *Use: honeycomb, scales, tiles, game boards, hex pixelation.*+- `float hexEdgeDistance(vec2 local)` - Distance from a hexGrid local coordinate to its hexagon's edge (0.5 at the center, 0 on the edge). *Use: hex borders, bevels, edge wear on tiles.*+- `float truchetArcs(vec2 p, float w)` - Truchet tiling of quarter-circle arcs, randomly flipped per cell. Returns signed distance to arcs of half-width w. *Use: maze-like ornaments, pipes, Celtic-style weaves, procedural circuitry.*++## sdf3d++sdf3d: 3D signed distance primitives. Each one is centered at the origin unless noted. Move or rotate the point before calling (sdBox(p - center, size)), never the result. Exactness tags: @exact true Euclidean distance inside and outside (safe for smooth blending, AO, soft shadows, offsets) @bound never overestimates (Lipschitz <= 1), so raymarching is safe, but offsets and blends are less accurate @approx exact zero set but may overestimate in places (see the function's note for the safe stepScale) Formulas follow Inigo Quilez's distance-function catalog (https://iquilezles.org/articles/distfunctions/). Implementations here are original and checked by tests/ (sign, Lipschitz bound, eikonal).++- `float sdSphere(vec3 p, float r)` **exact** - Sphere of radius r. *Use: heads, eyes, fruit, planets, bubbles, joints.*+- `float sdBox(vec3 p, vec3 b)` **exact** - Axis-aligned box with half-extents b. *Use: buildings, crates, bricks, pedestals, furniture.*+- `float sdRoundBox(vec3 p, vec3 b, float r)` **exact** - Box with rounded edges. The outer size stays b; r is the edge radius (r <= min(b)). *Use: toys, product shots, soft architecture, dice, phone-like slabs.*+- `float sdBoxFrame(vec3 p, vec3 b, float e)` **exact** - Wireframe box: edges of a box with half-extents b and edge thickness e. *Use: scaffolding, cages, display frames, sci-fi structures.*+- `float sdTorus(vec3 p, vec2 t)` **exact** - Torus in the XZ plane. t.x = major radius, t.y = tube radius. *Use: rings, donuts, tires, halos, lifebuoys.*+- `float sdCappedTorus(vec3 p, vec2 sc, float ra, float rb)` **exact** - Partial torus (arc) in the XY plane, symmetric about +Y. sc = vec2(sin, cos) of the half-aperture angle, ra = major radius, rb = tube radius. *Use: horns, handles, eyebrows, arches, croissant shapes, magnets.*+- `float sdLink(vec3 p, float le, float r1, float r2)` **exact** - Chain link: a torus stretched along Y by le. r1 = major radius, r2 = tube radius. *Use: chains, rings, jewelry, fences.*+- `float sdPlane(vec3 p, vec3 n, float h)` **exact** - Infinite plane through the origin offset by h along unit normal n: dot(p, n) + h. *Use: ground, walls, water surface, clipping half-spaces.*+- `float sdCapsule(vec3 p, vec3 a, vec3 b, float r)` **exact** - Capsule: segment a-b swept by radius r. *Use: limbs, fingers, branches, hair strands, pills, bones.*+- `float sdVerticalCapsule(vec3 p, float h, float r)` **exact** - Vertical capsule from y = 0 to y = h, radius r. *Use: upright limbs, posts, bottles, candles.*+- `float sdCylinder(vec3 p, float h, float r)` **exact** - Vertical capped cylinder from y = -h to y = +h, radius r. *Use: columns, cans, coins, logs, wheels (rotate first).*+- `float sdCappedCone(vec3 p, float h, float r1, float r2)` **exact** - Capped cone (frustum) from y = -h (radius r1) to y = +h (radius r2). Set r2 = 0 for a pointed cone. Exact everywhere, including the base cap. Points below the base are outside. *Use: trees, roofs, spikes, lampshades, volcanoes, party hats, vases.*+- `float sdCone(vec3 p, float h, float r)` **exact** - Pointed cone with its base disk (radius r) at y = 0 and apex at y = h. *Use: evergreen trees, spikes, horns, mountains, wizard hats.*+- `float sdRoundCone(vec3 p, float r1, float r2, float h)` **exact** - Round cone: sphere r1 at y = 0 smoothly hulled with sphere r2 at y = h. *Use: limbs, fingers, tree trunks, carrots, teardrops, tentacle segments.*+- `float sdEllipsoid(vec3 p, vec3 r)` **approx** - Ellipsoid with semi-axes r. A fast approximation: the zero set is exact and the field is a bound outside for aspect ratios up to about 2:1. Inside, and for more stretched ellipsoids, the gradient exceeds 1 (measured: 2.5 at 4:1). March with stepScale 0.7-0.8 there, or build long shapes from sdCapsule / sdRoundCone instead. *Use: heads, bodies, eggs, pebbles, leaves (flat), muscles, clouds of blobs.*+- `float sdCutHollowSphere(vec3 p, float r, float h, float t)` **exact** - Hollow spherical cap (bowl) of radius r, cut by the plane y = h, with shell thickness t. The opening faces +Y. *Use: bowls, cups, helmets, shells, satellite dishes, eye sockets.*+- `float sdHexPrism(vec3 p, vec2 h)` **exact** - Hexagonal prism along Z. h.x = inradius of the hexagon, h.y = half-length. *Use: pencils, bolts, crystals, basalt columns, honeycomb cells.*+- `float sdOctahedron(vec3 p, float s)` **bound** - Regular octahedron with "radius" s (vertex distance from center). Bound version. *Use: gems, crystals, diamonds, abstract motifs.*+- `float sdGyroid(vec3 p, float scale, float t)` **bound** - Gyroid sheet with cell scale `scale` and half-thickness t. The infinite triply-periodic surface sin x cos y + sin y cos z + sin z cos x = 0. Intersect with a bounding shape. *Use: lattices, coral, bone interiors, sponges, sci-fi infill, organic architecture.*+- `float sdCutSphere(vec3 p, float r, float h)` **exact** - Sphere of radius r cut by the plane y = h, keeping the cap ABOVE the plane. h = 0 gives a dome on the ground; negative h keeps more than half. Needs |h| < r. *Use: domes, mushroom caps, half-buried rocks, igloos, bread loaves.*+- `float sdDeathStar(vec3 p, float ra, float rb, float d)` **exact** - Sphere ra at the origin with sphere rb at (d, 0, 0) carved out, exact including the crease rim. A plain opSubtract of two spheres is only a bound. *Use: eye sockets, craters, bitten fruit, nostrils, scooped shapes.*+- `float sdQuadraticBezier(vec3 pos, vec3 A, vec3 B, vec3 C)` **exact** - Unsigned distance to a 3D quadratic Bezier curve A-B-C; subtract a radius for a tube. Solves the closest-point cubic analytically. Falls back to a segment when the curve is straight. *Use: hair strands, tentacles, stems, whiskers, horns, cables, curved tubes.*++## sdf2d++sdf2d: 2D signed distance primitives for posters, icons, UI, motion graphics, and as profiles for opExtrude / opRevolve. Centered at the origin unless noted. Negative inside. Formulas follow Inigo Quilez's 2D distance catalog (https://iquilezles.org/articles/distfunctions2d/). Implementations are original and tested (sign, Lipschitz, brute-force distance for curves). Tags: @exact true distance, @bound never overestimates, @approx exact zero set but may overestimate in places.++- `float sdCircle(vec2 p, float r)` **exact** - Circle of radius r. *Use: dots, eyes, suns, bubbles, rings (with opOnion).*+- `float sdBox(vec2 p, vec2 b)` **exact** - Axis-aligned rectangle with half-extents b. *Use: panels, bars, windows, buttons, building silhouettes.*+- `float sdRoundedBox(vec2 p, vec2 b, vec4 r)` **exact** - Rectangle with half-extents b and per-corner radii r = (top-right, bottom-right, top-left, bottom-left). *Use: UI cards, buttons, speech bubbles, tags, rounded windows.*+- `float sdSegment(vec2 p, vec2 a, vec2 b)` **exact** - Unsigned distance to segment a-b. Subtract a width to get a stroke. *Use: lines, strokes, stems, rays, hands of a clock, rain streaks.*+- `float sdUnevenCapsule(vec2 p, float r1, float r2, float h)` **exact** - Tapered capsule: circle r1 at origin hulled with circle r2 at (0, h). *Use: petals, tails, teardrops, brush dabs, fingers, flames.*+- `float sdArc(vec2 p, vec2 sc, float ra, float rb)` **exact** - Circular arc symmetric about +Y. sc = vec2(sin, cos) of the half-aperture, ra = radius, rb = stroke half-width. *Use: smiles, eyebrows, rainbows, gauges, progress rings, horseshoes.*+- `float sdEquilateralTriangle(vec2 p, float r)` **exact** - Equilateral triangle with circumradius-like size r, pointing up. *Use: play icons, warning signs, mountains, arrows, tri-patterns.*+- `float sdTriangle(vec2 p, vec2 p0, vec2 p1, vec2 p2)` **exact** - Arbitrary triangle p0, p1, p2 (any winding). *Use: shards, low-poly art, arrowheads, beaks, teeth.*+- `float sdRegularPolygon(vec2 p, float r, int n)` **exact** - Regular n-gon with circumradius r, one vertex pointing up. *Use: badges, hexagonal tiles, pentagons, stop signs, gems (2D).*+- `float sdStar(vec2 p, float r, int n, float m)` **exact** - Star with n points and outer radius r. m in [2, n] sets the inner angle: m = 2 is the spikiest and m = n is a regular n-gon. *Use: stars, sparkles, badges, flowers (with opRound), sheriff badges.*+- `float sdVesica(vec2 p, float r, float d)` **exact** - Vesica (lens): intersection of two circles of radius r whose centers sit at (+-d, 0). Points along Y. Needs d < r. *Use: leaves, petals, eyes, fish bodies, almond shapes, gothic arches.*+- `float sdMoon(vec2 p, float d, float ra, float rb)` **exact** - Crescent: disk ra at origin minus disk rb at (d, 0). *Use: moons, claws, bananas (bent), shadows on spheres, logos.*+- `float sdHeart(vec2 p)` **exact** - Heart with its bottom tip at the origin, about 1 unit tall. *Use: hearts, valentines, health icons, leaves (squashed).*+- `float sdRhombus(vec2 p, vec2 b)` **exact** - Rhombus with half-diagonals b. *Use: diamonds, kites, card suits, argyle, harlequin patterns.*+- `float sdEllipse(vec2 p, vec2 r)` **approx** - Ellipse with semi-axes r. A fast approximation: exact zero set, a bound outside up to about 2:1 aspect, gradient above 1 inside and for flatter ellipses. Fine for fills and strokes; avoid for exact offsets. *Use: eyes, pupils, ovals, shadows under objects, planet rings (with opOnion).*+- `float sdQuadraticBezier(vec2 pos, vec2 A, vec2 B, vec2 C)` **exact** - Unsigned distance to a quadratic Bezier curve A-B-C. Solves the closest-point cubic analytically. Falls back to a segment when the curve degenerates to a line. Float error in the cubic solve is about 1e-4. *Use: brush strokes, hair, calligraphy, tendrils, eyelashes, smooth paths, font-like curves.*++## operators++operators: combine distances (booleans, smooth blends, chamfers, stairs) and reshape them (round, onion, extrude, revolve, elongate). Arguments a, b are distances already evaluated at the same point. Exactness: union (min) is exact outside but too deep inside; intersection and subtraction (max) are exact inside but underestimate outside. Smooth and decorative combinations are bounds. All stay Lipschitz <= 1, so raymarching is safe. When interior distances matter (inner-penumbra shadows, thickness, onion of a union), prefer an exact concave primitive (sdDeathStar, sdCutHollowSphere, 2D sdMoon/sdArc + extrude/revolve). Smooth unions are not associative: blend in a fixed order (torso, then limbs, then details). Smooth blend semantics in this library: k is the blend width in distance units. Shapes start blending when |a - b| < k.++- `float opUnion(float a, float b)` **bound** - Union of two shapes. *Use: combining parts.*+- `float opSubtract(float a, float b)` **bound** - Shape a with shape b cut out of it. *Use: holes, windows, carving, bites.*+- `float opIntersect(float a, float b)` **bound** - Region inside both shapes. *Use: clipping, lens shapes, trimming with half-spaces.*+- `float smin(float a, float b, float k)` **bound** - Smooth union (polynomial, C1). Blends where |a - b| < k, with a max bulge of k/4. *Use: organic joins (neck to head, limbs to torso), melting shapes, blobby forms.*+- `float smax(float a, float b, float k)` **bound** - Smooth intersection, the mirror of smin. *Use: soft clipping, rounded intersections, pillowy cuts.*+- `float smoothSubtract(float a, float b, float k)` **bound** - Smooth subtraction: a with b carved out, with filleted edges. *Use: eye sockets, nostrils, soft grooves, scooped bowls, worn edges.*+- `float sminCubic(float a, float b, float k)` **bound** - Smooth union with a C2 (cubic) transition, so specular highlights and normals have no visible seam. Blends where |a - b| < k, with a max bulge of k/6. *Use: close-up organic surfaces, glossy blends, fluids.*+- `vec2 sminBlend(float a, float b, float k)` **bound** - Smooth union that also returns the blend weight. Returns vec2(distance, weight), where weight is 1 when the result is fully a and 0 when fully b. Use the weight to mix material colors across the blend. *Use: skin-to-cloth transitions, color bleeding across blended parts, gradient-colored blobs.*+- `float opChamferUnion(float a, float b, float r)` **bound** - Union with a 45-degree chamfer of size r at the seam. *Use: machined parts, architecture, sci-fi panels, bevelled joins.*+- `float opStairsUnion(float a, float b, float r, float n)` **bound** - Union with n stair steps of total size r at the seam. *Use: terraces, stepped pyramids, ziggurats, layered rock, rice paddies.*+- `float opEngrave(float a, float b, float r)` **bound** - Engrave a groove of depth r into a, following the zero set of b. *Use: panel lines, carved text paths, seams, grout lines on a surface.*+- `float opRound(float d, float r)` **exact** - Round a shape by r. Grows it outward; shrink the inner shape by r first to keep its size. *Use: softening any primitive, pebbles from boxes, inflated look.*+- `float opOnion(float d, float t)` **exact** - Hollow shell of thickness 2t around the surface. Apply repeatedly for concentric layers. *Use: shells, pipes, rings, onion layers, outlines in 2D.*+- `float opExtrude(vec3 p, float d2, float h)` **exact** - Extrude a 2D distance d2 (evaluated at p.xy) along Z by half-length h. *Use: 3D text and logos, cookie cutters, coins from 2D shapes, extruded profiles.*+- `vec2 opRevolve(vec3 p, float o)` **exact** - Revolve around Y. Returns the 2D point to evaluate a profile at. Offset o moves the profile away from the axis. *Use: vases, bottles, chess pieces, lathe-turned objects, tori with custom profiles.*+- `vec4 opElongate(vec3 p, vec3 h)` **exact** - Elongate: stretch a shape by inserting a straight section of half-size h, keeping exact distances inside too. Returns vec4(q, w). Evaluate the original shape at q.xyz and add w: sdSphere(e.xyz, r) + e.w is a capsule. *Use: pills from spheres, long rounded boxes, stretched characters, stadium shapes.*++## domain++domain: transform the point BEFORE evaluating a distance (repetition, mirroring, polar sectors, folds, twist, bend). Rigid transforms (repeat, mirror, rotate, fold) keep distances exact. Twist and bend stretch space, so their results are only bounds after scaling (see each function). Repetition uses floor(x + 0.5) instead of round(): GLSL leaves round(0.5) implementation-defined, and round can return -0.0.++- `float domRepeatId(float p, float s)` / `vec2 domRepeatId(vec2 p, vec2 s)` / `vec3 domRepeatId(vec3 p, vec3 s)` - Cell index for repetition with period s (integer-valued; use with hash functions). *Use: per-instance variation: hash12(domRepeatId(p.xz, s)).*+- `float domRepeat(float p, float s)` / `vec2 domRepeat(vec2 p, vec2 s)` / `vec3 domRepeat(vec3 p, vec3 s)` - Infinite repetition with period s. Returns the local coordinate centered in its cell. Exact only while each instance stays inside its own cell. For instances that vary per cell or overhang, evaluate the 2 or 3 neighboring cells too (see references/sdf-library-guide.md). *Use: forests, columns, tiles, crowds, star fields, city blocks.*+- `vec2 domRepeatLimited(vec2 p, vec2 s, vec2 lim)` / `vec3 domRepeatLimited(vec3 p, vec3 s, vec3 lim)` - Repetition limited to cells -lim..+lim on each axis (2*lim + 1 copies). *Use: rows of windows, fence posts, a finite grid of buttons, colonnades.*+- `vec2 domRepeatMirror(vec2 p, vec2 s)` - Mirrored repetition: every other cell is flipped, so shapes touching the cell border join seamlessly. *Use: tiled ornaments, symmetric wallpaper, seamless pipes and rails.*+- `vec2 domPolar(vec2 p, float n)` - Polar repetition into n sectors around the origin. Returns the point rotated into the sector centered on +X. Single evaluation: exact for shapes symmetric about their sector's center line. For asymmetric or per-sector-varying shapes, evaluate this sector and its neighbor and take the min (see references/sdf-library-guide.md). *Use: petals, spokes, gears, clock marks, radial ornaments, columns around a tower.*+- `float domPolarId(vec2 p, float n)` - Sector index in [0, n) for domPolar. *Use: varying each petal, spoke or column.*+- `vec3 domFold(vec3 p, vec3 n)` - Fold space across the plane through the origin with unit normal n. Points behind the plane are reflected. *Use: kaleidoscopes, symmetric creatures, KIFS fractals, mirrored architecture.*+- `vec3 domTwist(vec3 p, float k)` - Twist around Y: rotate XZ by k * y. Divide the resulting distance by L = a/2 + sqrt(1 + a*a/4), a = k * R, where R is the shape's max distance from the Y axis. Without that, the march overshoots. *Use: twisted columns, drills, licorice, DNA-like spirals, towels.*+- `vec3 domBend(vec3 p, float k)` - Bend in XY: rotate XY by k * x. Divide the resulting distance by about 1 + k * R (R = max |p.xy| of the shape). *Use: bent beams, arches from boxes, bananas, curved horns.*++## raymarch++raymarch: sphere tracing, normals, soft shadows and ambient occlusion for SDF scenes. SCENE CONTRACT: your shader defines vec2 map(vec3 p) returning vec2(distance, materialId). Packing the material into a vec2 avoids structs (WebGL forbids ?: on structs) and works with every helper here. Loops start at ZERO, a zero the compiler cannot prove. That stops it inlining map() into every loop, which keeps compile times sane and avoids WebGL compiler crashes on large scenes.++- `#define ZERO (min(iFrame, 0))`+- `const int RAYMARCH_MAX_STEPS = 256;`+- `vec3 raymarch(vec3 ro, vec3 rd, float tmin, float tmax, float stepScale)` - Sphere-trace from ro along unit rd between tmin and tmax. Returns vec3(t, materialId, stepCount). t is -1 on a miss. The hit threshold grows with t (about one pixel's footprint), so distant surfaces don't burn steps. stepScale is 1 for exact or bound fields. Use < 1 (e.g. 0.6) when map() has Lipschitz > 1 (displacement, warps, twist). *Use: every SDF raymarcher.*+- `vec3 calcNormal(vec3 p, float eps)` - Surface normal from 4 tetrahedral samples (cheaper than 6 central differences, and still centered). eps should scale with distance, e.g. 0.0005 * t: that filters distant detail and avoids sparkling. *Use: shading any SDF hit.*+- `float softShadow(vec3 ro, vec3 rd, float tmin, float tmax, float k)` - Soft shadow toward a light along unit rd. k controls sharpness (k is about 1 / light angular size: 8 soft, 32 hard). Uses the "closest approach between samples" estimate, which removes banding from sharp-cornered occluders. Returns 0 (full shadow) .. 1 (lit). *Use: sun shadows, contact shadows, penumbrae.*+- `float calcAO(vec3 p, vec3 n, float scale)` - Ambient occlusion from 5 distance samples along the normal. Compares the expected distance with the actual one. scale is the sampling reach in scene units (about 0.12 for a unit-sized object). Returns 0 (occluded) .. 1 (open). *Use: crevices, contact darkening, grounding objects on floors.*+- `float sdfThickness(vec3 p, vec3 n, float maxDepth)` - Thickness behind a surface point, estimated by sampling the SDF inside along -n (an "inverse AO"). Returns 0 (thin, light passes through) .. 1 (thick). maxDepth is the deepest sample in scene units. *Use: translucency, subsurface tint, wax and jade, glowing thin edges.*++## intersect++intersect: analytic ray-primitive intersections. Rays are ro + t * rd with unit rd. Use them for bounding volumes (clip the raymarch range to where the scene can be), exact floors and water planes, glass spheres and eyeballs, and cheap reflections. Formulas follow https://iquilezles.org/articles/intersectors/.++- `float iPlane(vec3 ro, vec3 rd, vec3 n, float h)` - Ray vs plane dot(p, n) + h = 0 (unit n). Returns t, which is negative when the plane is behind the ray or parallel to it. *Use: floors, water, mirrors, clipping marches to a ground plane.*+- `vec2 iSphere(vec3 ro, vec3 rd, vec3 c, float r)` - Ray vs sphere centered at c with radius r. Returns vec2(tNear, tFar), or vec2(-1) on a miss. Uses the precision-friendly form that measures from the closest point on the ray. *Use: bounding spheres, glass balls, eyeballs, planets, bubbles.*+- `vec2 iBox(vec3 ro, vec3 rd, vec3 b)` - Ray vs axis-aligned box centered at the origin with half-extents b (slab method). Returns vec2(tNear, tFar), or vec2(-1) on a miss. Works when the ray starts inside (tNear < 0 < tFar). *Use: bounding boxes for raymarching, glass cubes, rooms.*++## camera++camera: look-at frames, primary rays, field of view, thin-lens depth of field. Convention: uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y, so uv.y spans [-1, 1] and aspect is kept.++- `mat3 cameraMatrix(vec3 ro, vec3 ta, float roll)` - Camera-to-world matrix looking from ro toward ta, with roll in radians. Columns are (right, up, forward). *Use: every 3D shader.*+- `float fovToFocal(float fovDegrees)` - Focal length (the z of the view-space ray) for a vertical field of view in degrees. *Use: matching a reference photo, wide (90) vs telephoto (20) framing.*+- `vec3 cameraRay(mat3 cam, vec2 uv, float focal)` - Primary ray direction for screen point uv. focal is about 1.5-2.5 for natural framing (see fovToFocal). *Use: every 3D shader.*+- `void thinLensRay(mat3 cam, vec2 uv, float focal, float aperture, float focusDist, vec2 xi, inout vec3 ro, out vec3 rd)` - Thin-lens depth of field. Moves the ray origin over a lens disk of radius aperture, and re-aims it so that points at distance focusDist stay sharp. xi is a pair of uniform random numbers in [0,1) (e.g. hash22 of the pixel and frame). Average many samples (AA loop or multipass accumulation). *Use: macro shots, product renders, cinematic focus pulls, bokeh.*+- `void orthoRay(mat3 cam, vec2 uv, float size, inout vec3 ro, out vec3 rd)` - Orthographic ray: parallel rays from a plane of half-height `size` centered on ro. *Use: isometric scenes, technical illustrations, flat diorama looks.*++## shading++shading: BRDF terms and practical lighting models. Vectors are unit length: n = normal, v = toward the viewer (-rd), l = toward the light. Units are "artist units" with pi folded in: a light of color C lights a white Lambert surface facing it to C. Every function here returns radiance per unit light color, already including NoL. Physically based terms follow Filament (https://google.github.io/filament/Filament.md.html).++- `vec3 fresnelSchlick(float u, vec3 f0)` - Schlick Fresnel. u is VoH for lights and NoV for environment reflections and rims. f0 = 0.04 for dielectrics (plastic, skin, stone, water ~0.02); for metals f0 = base color. *Use: reflections that strengthen at grazing angles, rim brightening, water and glass.*+- `float distributionGGX(float NoH, float alpha)` - GGX / Trowbridge-Reitz normal distribution. alpha = roughness^2. *Use: specular highlight shape (inside specularGGX).*+- `float visibilitySmithGGX(float NoV, float NoL, float alpha)` - Height-correlated Smith visibility. Already contains the 1 / (4 NoL NoV) term. *Use: specular shadowing-masking (inside specularGGX).*+- `vec3 specularGGX(vec3 n, vec3 v, vec3 l, float roughness, vec3 f0)` - Microfacet specular for one light: pi * D * V * F * NoL (artist units). roughness is perceptual, in [0,1]. *Use: glossy plastic, metal, wet surfaces, car paint, ceramics.*+- `vec3 shadePBR(vec3 n, vec3 v, vec3 l, vec3 albedo, float roughness, float metallic)` - Complete metallic-roughness shading for one light (diffuse + specular, NoL included, artist units). Multiply by light color and shadow. Keep albedo around 0.05-0.7 (linear); brighten lights, not albedo. *Use: hero objects, product renders, anything that needs believable materials.*+- `vec3 envBRDFApprox(vec3 f0, float NoV, float roughness)` - Split-sum environment specular without a lookup texture (Karis 2014, after Lazarov). Multiply by the sky or environment color in the reflection direction. *Use: sky reflections on glossy surfaces, ambient specular.*+- `float wrapDiffuse(vec3 n, vec3 l, float w)` - Energy-conserving wrap diffuse: light wraps past the terminator by w (0 = Lambert, 0.5 = soft). *Use: skin, foliage, cloth, soft stylized shading, fur.*+- `vec3 hemisphereLight(vec3 n, vec3 skyColor, vec3 groundColor)` - Hemisphere light: sky color from above blended to ground color from below. *Use: ambient fill, outdoor sky light, studio fill.*+- `float translucency(vec3 n, vec3 v, vec3 l, float distortion, float power, float thickness)` - Fast translucency (Barre-Brisebois and Bouchard 2011): light passing through thin parts, seen from the back. distortion bends the light along the normal (0.2-0.5). thickness is 0 (thin) .. 1 (thick); see sdfThickness. *Use: leaves, ears, wax, jade, marble, backlit petals, jellyfish.*+- `float rimLight(vec3 n, vec3 v, float power)` - Rim light from the viewing angle: strongest at silhouettes. *Use: character separation from background, fresnel-like glow, stylized outlines.*++## color++color: transfer functions, perceptual color (Oklab / OkLCh), palettes, luminance, blackbody light colors. Light, shade and mix in LINEAR color. Picked hex colors, cosine palettes and Shadertoy textures are sRGB-encoded, so decode them with srgbToLinear before lighting. Encode once at the very end with linearToSrgb.++- `vec3 srgbToLinear(vec3 c)` - Exact sRGB decode (EOTF): encoded [0,1] -> linear. *Use: decoding picked colors, palettes used as albedo, and texture samples.*+- `vec3 linearToSrgb(vec3 c)` - Exact sRGB encode (OETF): linear -> display [0,1]. Apply exactly once, after tonemapping. pow(c, 1/2.2) is visibly wrong near black (0.001 encodes to 0.013 here vs 0.043 with 2.2). *Use: final output.*+- `float luminance(vec3 c)` - Relative luminance of linear Rec.709 / sRGB color. *Use: desaturation, brightness masks, luminance-based effects.*+- `vec3 saturation(vec3 c, float s)` - Scale saturation around luminance: 0 = grey, 1 = unchanged, > 1 = more saturated. *Use: grading, fading distant objects, stylization.*+- `vec3 linearSrgbToOklab(vec3 c)` - Linear sRGB -> Oklab (L in [0,1], a/b around [-0.4, 0.4]). Matrices from Bjorn Ottosson (public domain / MIT). *Use: perceptual gradients, even-lightness palettes, hue and chroma edits.*+- `vec3 oklabToLinearSrgb(vec3 lab)` - Oklab -> linear sRGB. The result can fall outside [0,1] for saturated colors, so clamp after tonemapping. *Use: converting perceptual edits back for lighting or output.*+- `vec3 mixOklab(vec3 a, vec3 b, float t)` - Mix two linear colors in Oklab. Avoids the muddy mid-tones of RGB lerps and the hue detours of HSV. *Use: gradients, sky ramps, color transitions over time, blending materials.*+- `vec3 oklchToLinearSrgb(vec3 lch)` - OkLCh (lightness, chroma, hue in radians) -> linear sRGB. Hue sweeps keep lightness constant. L about 0.4-0.9, C about 0.05-0.2 stays mostly in gamut. *Use: harmonious palettes, rainbow ramps with even brightness, per-instance hue variation.*+- `vec3 cosinePalette(float t, vec3 a, vec3 b, vec3 c, vec3 d)` - Cosine palette a + b * cos(2 pi (c t + d)). Output is display-like (sRGB-ish), so decode it for albedo. Integer c values loop seamlessly over t in [0,1]. *Use: quick gradients, heat maps, psychedelic color cycling, per-id colors.*+- `vec3 blackbody(float kelvin)` - Approximate linear sRGB color of a blackbody at temperature kelvin (1000-15000 K), normalized to max channel 1. Uses the Krystek (1985) Planckian-locus fit -> XYZ -> sRGB. *Use: fire, embers, lava, stars, incandescent lamps, sunset light, molten metal.*++## tonemap++tonemap: map scene-linear HDR to display range. Every function here takes linear input (after exposure) and returns LINEAR [0,1]. Then apply linearToSrgb exactly once. Recommended chain: col *= exposure; col = tonemapAgX(col); col = linearToSrgb(col); add dither. Choosing: AgX (default) for 3D scenes, glows, fire, suns and volumes; its highlights roll off to white without hue skews. tonemapNeutral for 2D, product shots and palette-faithful work. ACES for the saturated filmic look.++- `vec3 tonemapAgX(vec3 c)` - AgX: log encoding plus a sigmoid inside an inset/outset gamut. Mid-grey 0.18 maps to about 0.5 display. Minimal implementation after Troy Sobotka's AgX and Benjamin Wrensch's polynomial fit (both MIT). *Use: default tonemapper for 3D, emissive glows, fire, neon, skies, clouds.*+- `vec3 tonemapAgXPunchy(vec3 c)` - AgX with the "punchy" look (more contrast and saturation) for stylized art. *Use: stylized 3D, saturated sunsets, toy-like renders.*+- `vec3 tonemapNeutral(vec3 c)` - Khronos PBR Neutral: leaves [0, ~0.76] almost untouched and compresses only highlights, preserving hue. *Use: 2D art, palette-faithful scenes, product renders, UI glow.*+- `vec3 tonemapACES(vec3 c)` - Stephen Hill's ACES fit (RRT + ODT, sRGB primaries). Contrasty and saturated; blues drift purple when very bright. Darker than AgX at the same exposure: multiply the input by about 1.6 to compensate. *Use: the classic "filmic game" look.*+- `vec3 tonemapReinhard(vec3 c, float white)` - Extended Reinhard on luminance: maps `white` to 1 and preserves hue. Simple and predictable. *Use: quick previews, soft low-contrast looks.*++## volume++volume: participating media (fog, smoke, clouds, haze). mu = dot(rd, l): the cosine between the view ray and the direction TOWARD the light, so forward scattering peaks when looking at the light. Integration follows Hillaire (Frostbite, SIGGRAPH 2015/2016); cloud tricks follow Schneider (Horizon Zero Dawn, 2015).++- `float phaseIsotropic()` - Isotropic phase function (scatters equally in all directions). *Use: dusty fog, thick smoke interiors.*+- `float phaseRayleigh(float mu)` - Rayleigh phase function. *Use: sky scattering by air molecules (blue sky).*+- `float phaseHG(float mu, float g)` - Henyey-Greenstein phase function. g in (-1, 1): > 0 forward (silver linings), < 0 backward. *Use: clouds (g ~ 0.6-0.85), fog glow around lights, underwater light shafts.*+- `float phaseDualHG(float mu, float gF, float gB, float w)` - Two-lobe Henyey-Greenstein: a forward lobe gF and a backward lobe gB, mixed by w (weight of the forward lobe). Keeps the silver lining while clouds lit from behind the camera still show detail. *Use: clouds, smoke lit from varying angles.*+- `float phaseCornetteShanks(float mu, float g)` - Cornette-Shanks phase (a better-normalized Mie approximation). g = 0.8 for atmospheric haze. *Use: sun halo in hazy skies, aerosols.*+- `float beerPowder(float d)` - Beer-Powder lighting term for clouds: 2 e^-d (1 - e^-2d), where d is optical depth toward the sun. Darkens cloud edges that face the light like powdered sugar. Not energy-conserving; use it on the direct term only. *Use: cumulus clouds, puffy smoke.*+- `void volumeStep(inout vec3 radiance, inout vec3 transmittance, vec3 sigmaT, vec3 inScatter, float ds)` - One energy-conserving step of volume integration. sigmaT is extinction per unit length (RGB for tinted media), inScatter is in-scattered radiance at this point (including sigmaS, phase and light), ds is step length. Accumulates into radiance and transmittance. Stable for dense media, unlike radiance += T * S * ds. *Use: any raymarched volume: clouds, smoke, fog, fire, nebulae.*+- `float distanceFog(float t, float density)` - Distance fog amount (0 = clear, 1 = fully fogged) for distance t. *Use: depth cueing, haze, underwater murk.*+- `float heightFog(vec3 ro, vec3 rd, float t, float a, float b)` - Analytic height fog for density a * exp(-b * y) along the ray segment [0, t]. Thick near the ground, thin above. Returns the fog amount in [0,1]. *Use: valley mist, ground fog, layered haze in landscapes.*++## atmosphere++atmosphere: skies and sun. simpleSky is a cheap artistic gradient. atmosphereSky is physically based single scattering (Rayleigh + Mie + ozone) with constants from Hillaire, "A Scalable and Production Ready Sky and Atmosphere Rendering Technique" (EGSR 2020). Distances are in kilometers to avoid float cancellation.++- `vec3 simpleSky(vec3 rd, vec3 sunDir)` - Cheap analytic sky: horizon-to-zenith gradient, darker ground below the horizon, sun glow lobes. Returns linear radiance (roughly 0-2; the glow can exceed 1 near the sun). *Use: quick backgrounds, reflections, fog color, stylized daylight.*+- `vec3 sunDisk(vec3 rd, vec3 sunDir, float angularRadius, float pixelAngle)` - Sun disk with antialiased edge and limb darkening (Neckel 1996). angularRadius in radians (the real sun is 0.00476; art often uses 3-10x). pixelAngle is the angular size of a pixel (about 2 / (iResolution.y * focal)). Returns a 0..1 shape tinted by limb darkening; multiply by a bright sun color (10-50). *Use: suns, moons (use a different tint), bright stars in skies.*+- `const float ATMOSPHERE_GROUND_KM = 6360.0;`+- `const float ATMOSPHERE_TOP_KM = 6460.0;`+- `vec3 atmosphereDensity(float h)` - Densities (rayleigh, mie, ozone) at altitude h km above the ground. *Use: custom atmosphere marches (aerial perspective, planet views).*+- `vec3 atmosphereExtinction(vec3 density)` - Extinction per km for the given densities. *Use: transmittance through air for sun color and aerial perspective.*+- `vec3 atmosphereSky(vec3 rd, vec3 sunDir, float viewHeightKm, float sunIntensity)` - Physically based sky radiance along rd for a viewer viewHeightKm above the ground, with single scattering (16 view steps x 8 light steps). sunIntensity about 20. Sunsets come out somewhat dark because multiple scattering is ignored; add a small ambient term if needed. *Use: realistic skies, sunsets, aerial perspective colors, planet-from-space views.*++## post++post: antialiasing helpers, supersampling offsets, lens effects, grain and dithering, all single-pass. Order of a finished frame: (per AA sample) exposure, vignette, grain -> tonemap -> average samples -> linearToSrgb -> dither. See references/rendering-pipeline.md.++- `float fillAA(float d)` / `float fillAA(float d, float px)` - Antialiased fill of a 2D SDF: 1 inside, 0 outside, box-filtered across one pixel. Uses screen derivatives, so call it outside non-uniform branches and loops. For a fixed pixel size use fillAA(d, px). *Use: 2D shapes, icons, text-like strokes, UI, masks with crisp edges.*+- `float strokeAA(float d, float hw, float px)` - Antialiased stroke of half-width hw around the zero line of a 2D SDF. *Use: outlines, line art, rings, wireframes, contour lines.*+- `vec2 aaOffset(int i)` - Subpixel offset in [-0.5, 0.5)^2 for sample i of a supersampling loop (R2 low-discrepancy sequence). Better coverage than a regular grid for any sample count. *Use: AA loops: for (int i = 0; i < N; i++) { vec2 o = aaOffset(i); ... mainColor(fragCoord + o) }.*+- `float vignette(vec2 uv, float focal)` - Natural (cos^4) vignette for a pinhole camera: uv is the screen point, focal the camera focal length. Wider lenses vignette more. Multiply HDR color before tonemapping. *Use: photographic falloff, framing, cinematic looks.*+- `vec3 filmGrain(vec3 col, float amount, float n)` - Signal-dependent film grain: noise grows with sqrt(intensity), as photon noise does. n should be zero-mean noise (e.g. hash13(vec3(fragCoord, iFrame)) * 2 - 1). Apply in linear HDR before tonemapping. *Use: filmic texture, hiding banding, analog looks.*+- `vec3 ditherTPDF(vec2 fragCoord, int frame)` - Triangular-PDF dither of +-1 LSB for 8-bit output. Add AFTER linearToSrgb, right before writing fragColor. *Use: removing banding in skies, fog, vignettes and dark gradients.*++## debug++debug: visualize intermediate fields. The pack's DEBUG_MODE convention: 0 final render | 1 distance field / contours | 2 normals | 3 material ids 4 step count / depth | 5 masks / density | 6 lighting terms Declare it as #define DEBUG_MODE 0 at the top of the shader. Shadertoy has no custom uniforms.++- `vec3 debugDistance(float d)` - Distance field as contour bands: warm outside, cool inside, white zero line. Bands are 0.1 units apart. *Use: checking SDF scale, smoothness, wrong signs, bad blends (kinked or bunched contours).*+- `vec3 debugNormal(vec3 n)` - Normal as RGB. *Use: spotting seams, flipped normals, noisy normals.*+- `vec3 debugIdColor(float id)` - Distinct color per integer id. *Use: material ids, cell ids, instance ids.*+- `vec3 debugHeat(float t)` - Heat ramp for a value in [0,1]: black, blue, magenta, orange, yellow, white. *Use: step counts (steps / maxSteps), depth, cost, any scalar mask.*diff --git a/skills/shader-art-coding/references/rendering-pipeline.md b/skills/shader-art-coding/references/rendering-pipeline.mdnew file mode 100644index 0000000..7e2a076--- /dev/null+++ b/skills/shader-art-coding/references/rendering-pipeline.md@@ -0,0 +1,152 @@+# Rendering Pipeline++The order of operations for a finished frame, and the library functions for each stage. Most "it looks off"+problems are pipeline problems: lighting in sRGB, tonemapping after gamma, averaging HDR samples, double encoding,+or fog that ignores the sky.++## Contents++- [Frame anatomy](#frame-anatomy)+- [Raymarching](#raymarching)+- [Lighting](#lighting)+- [Shadows, occlusion, thickness](#shadows-occlusion-thickness)+- [Color and materials](#color-and-materials)+- [Sky, fog and aerial perspective](#sky-fog-and-aerial-perspective)+- [Volumes](#volumes)+- [Exposure and tonemapping](#exposure-and-tonemapping)+- [Antialiasing and filtering](#antialiasing-and-filtering)+- [Performance checklist](#performance-checklist)++## Frame anatomy++```text+for each AA sample:+ camera ray -> march -> normal -> material -> lights (key, fill, bounce, specular) -> fog/atmosphere [linear HDR]+ exposure, vignette, grain [linear HDR]+ tonemap [linear 0..1]+average samples -> linearToSrgb (exactly once) -> ditherTPDF -> fragColor+```++```glsl+vec3 finishPixel(vec3 hdrSum, float samples, float exposure, vec2 fragCoord) {+ // hdrSum must already be tonemapped per sample; this averages, encodes once, then dithers.+ vec3 c = hdrSum / samples;+ return linearToSrgb(c) + ditherTPDF(fragCoord, iFrame);+}+```++Tonemap each sample before averaging: averaging raw HDR lets one sample that hits the sun dominate, so bright edges+stay aliased.++## Raymarching++- `raymarch(ro, rd, tmin, tmax, stepScale)` returns `vec3(t, materialId, steps)`, with `t = -1` on a miss.+- Clip `[tmin, tmax]` analytically before marching: `iBox` / `iSphere` around the scene, `iPlane` for the floor.+ Steps spent in empty space are the most common cost.+- The hit threshold grows with t (pixel footprint), so far geometry does not burn steps or shimmer.+- `stepScale` < 1 only when the field has Lipschitz > 1 (see `sdf-library-guide.md`).+- `calcNormal(p, eps)` with `eps = 0.0005 * t` filters normals in the distance and avoids sparkle.+- Over-relaxation (step `1.2 * d` and fall back when consecutive spheres don't overlap) saves 15-20% on exact fields+ but voids the safety guarantee for bounds; use it only after the scene is final.++## Lighting++Artist units: a light of color C lights a white Lambert surface facing it to C. `shadePBR` and `specularGGX`+already include `NoL`, and π is folded in, so lights multiply directly.++Outdoor rig (the default for landscapes and objects in daylight):++```glsl+vec3 outdoorLight(vec3 p, vec3 n, vec3 v, vec3 albedo, float rough, float metal,+ vec3 sunDir, vec3 sunCol, float shadow, float ao) {+ vec3 key = shadePBR(n, v, sunDir, albedo, rough, metal) * sunCol * shadow;+ vec3 sky = albedo * (1.0 - metal) * hemisphereLight(n, vec3(0.30, 0.40, 0.55), vec3(0.15, 0.12, 0.10)) * ao;+ vec3 bounceDir = normalize(vec3(-sunDir.x, 0.0, -sunDir.z));+ vec3 bounce = albedo * (1.0 - metal) * sunCol * 0.08 * clamp(dot(n, bounceDir), 0.0, 1.0) * ao;+ vec3 f0 = mix(vec3(0.04), albedo, metal);+ vec3 refl = reflect(-v, n);+ vec3 spec = envBRDFApprox(f0, max(dot(n, v), 0.0), rough) * simpleSky(refl, sunDir) * ao+ * smoothstep(-0.1, 0.3, refl.y);+ return key + sky + bounce + spec;+}+```++Rules that keep it believable:++- AO darkens fill lights only, never the sun. The sun is handled by its shadow.+- Keep albedo around 0.05-0.7 (linear) and brighten the lights, not the albedo. Snow is about 0.85, charcoal 0.04.+- Warm key, cool fill: the sky term is blue, the bounce is the ground color.+- Organic materials: `wrapDiffuse` for soft terminators, `translucency` with `sdfThickness` for backlit leaves, ears+ and wax, `rimLight` for separation from the background.++## Shadows, occlusion, thickness++- `softShadow(p + n * 0.002, sunDir, 0.01, tmax, k)`: k is about 1 / (light angular size). 8 is soft, 32 is crisp.+ Offset the origin along the normal to avoid self-shadow acne.+- `calcAO(p, n, scale)`: scale is the sampling reach in scene units (about 0.1-0.2 of the object size).+- `sdfThickness(p, n, depth)`: an "inverse AO" sampled inside the surface; drive translucency with it.++## Color and materials++- Light in linear. Colors you pick (hex codes, `cosinePalette` presets) are sRGB-encoded: decode with+ `srgbToLinear` before using them as albedo or light color.+- Mix colors in Oklab (`mixOklab`) for gradients without muddy mid-tones; generate hue families with+ `oklchToLinearSrgb(vec3(L, C, h))`, keeping L and C fixed so the swatches have equal weight.+- `blackbody(kelvin)` gives physically plausible light colors: 1800 K candle, 3200 K tungsten, 5500 K sun, 6500 K+ overcast, 10000 K blue sky.+- Metals have no diffuse: `metal = 1` with `albedo` as the specular color (gold `vec3(1.0, 0.78, 0.34)`).++## Sky, fog and aerial perspective++- `simpleSky(rd, sunDir)` is a cheap gradient with sun glow. `atmosphereSky(rd, sunDir, heightKm, intensity)` is+ physically based (Rayleigh + Mie + ozone); work in kilometers.+- Fog must use the sky color, or distant objects turn grey against a blue sky:+ `col = mix(col, sky, distanceFog(t, density))`, or the analytic `heightFog` for valley mist.+- Aerial perspective with a physical sky: attenuate by `exp(-t * atmosphereExtinction(...))` and fill with the sky+ color in a horizon-clamped direction: `normalize(vec3(rd.x, max(rd.y, 0.02), rd.z))`. Below the planet's horizon+ the sky integral jumps (the ray starts hitting the ground), which prints a hard horizontal seam across terrain.+- Sun: `sunDisk(rd, sunDir, angularRadius, pixelAngle)` times a bright color (10-50). It is antialiased and+ limb-darkened.++## Volumes++- Integrate with `volumeStep(radiance, transmittance, sigmaT, inScatter, ds)`. It is energy-conserving, so dense+ media stay stable with 30-60 steps. The naive `radiance += T * S * ds` over-brightens and leaks light.+- Phase in artist units: multiply `phaseHG` / `phaseDualHG` by 4π so isotropic scattering is 1 and the sun term is+ on the same scale as an ambient color. Without that, the ambient term dominates and clouds look flat.+- Clouds: density = coverage-remapped fBm times a height profile; light-march 4-6 samples toward the sun with a+ cheaper (fewer octave) density; `beerPowder` on the direct term; `phaseDualHG(mu, 0.75, -0.25, 0.75)` for silver+ linings.+- Jitter the march start per pixel (`interleavedGradientNoise(floor(fragCoord), iFrame)`) to trade slicing bands+ for fine noise; exit once transmittance drops below 0.01.++## Exposure and tonemapping++| Tonemapper | Use |+|---|---|+| `tonemapAgX` (default) | 3D scenes, glows, fire, skies, volumes: highlights roll off to white with no hue skew |+| `tonemapAgXPunchy` | stylized 3D with more contrast and saturation |+| `tonemapNeutral` | 2D art, product shots, palette-faithful work: [0, 0.76] passes through untouched |+| `tonemapACES` | the saturated filmic look; darker, so raise exposure about 1.6x |+| `tonemapReinhard` | quick previews |++Expose first (`col * exposure`), then tonemap, then encode. A purely LDR 2D piece can skip tonemapping. Never+tonemap or encode twice: a washed-out, low-contrast image usually means double encoding.++## Antialiasing and filtering++- Supersampling: loop `i < AA` with `aaOffset(i)` (R2 sequence), tonemap per sample, average, then encode.+- 2D shapes: `fillAA(d, px)` and `strokeAA(d, halfWidth, px)` with `px = 2.0 / iResolution.y` work everywhere.+ `fillAA(d)` uses derivatives and is only valid outside branches and loops.+- Patterns on surfaces: filter instead of supersampling. `filteredChecker`, `filteredGrid` and `filteredStripes`+ integrate over the pixel footprint. In a raymarcher the footprint is `t * 2.0 / (iResolution.y * focal)`, which+ needs no derivatives.+- Noise: fade octaves whose period approaches 2 pixels instead of letting them alias.++## Performance checklist++- Bound the march (analytic clip) and keep `RAYMARCH_MAX_STEPS` reasonable; check `DEBUG_MODE 4`.+- Put expensive sub-scenes behind a cheap bounding test: `float b = sdBox(p - c, size); if (b > res.x) return res;`.+- Evaluate detail noise only where the base field says it matters (clouds: skip when coverage is 0).+- Use fewer octaves for shadow, AO and light-march samples than for the primary hit.+- Prefer analytic derivatives (`gradientNoiseD`) over 4-6 extra noise evaluations for normals.diff --git a/skills/shader-art-coding/references/sdf-library-guide.md b/skills/shader-art-coding/references/sdf-library-guide.mdnew file mode 100644index 0000000..1fd24f9--- /dev/null+++ b/skills/shader-art-coding/references/sdf-library-guide.md@@ -0,0 +1,186 @@+# Modeling With the GLSL Library++How to build shapes and patterns with `glsl/`: the scene contract, which distances can be trusted for what,+blending, repetition, deformation, noise, and the WebGL pitfalls that break shaders on Shadertoy.++## Contents++- [Workflow](#workflow)+- [Coordinates and local spaces](#coordinates-and-local-spaces)+- [Exact, bound, approx](#exact-bound-approx)+- [Booleans and smooth blends](#booleans-and-smooth-blends)+- [Repetition](#repetition)+- [Deformation, displacement and warps](#deformation-displacement-and-warps)+- [From 2D to 3D](#from-2d-to-3d)+- [Noise and hashing](#noise-and-hashing)+- [Shaping functions](#shaping-functions)+- [WebGL and Shadertoy pitfalls](#webgl-and-shadertoy-pitfalls)+- [Debugging fields](#debugging-fields)++## Workflow++1. Find building blocks: `python3 scripts/glsl_tools.py search petal leaf` or read `references/library-index.md`.+2. Write the shader against library names (`sdRoundCone`, `smin`, `fbm`, `softShadow`, ...) without pasting them.+3. Bundle: `python3 scripts/glsl_tools.py bundle shader.glsl -o out.glsl` inlines exactly the functions used, in+ declaration order, so `out.glsl` pastes straight into Shadertoy.+4. Check: `python3 scripts/glsl_tools.py check out.glsl` lints for WebGL1 leftovers, sine hashes, missing `mainImage`,+ and compiles with `glslangValidator` when installed.++Scene contract for raymarching: define `vec2 map(vec3 p)` returning `vec2(distance, materialId)`. `raymarch`,+`calcNormal`, `softShadow`, `calcAO` and `sdfThickness` all call it. Combine objects with plain comparisons:++```glsl+vec2 map(vec3 p) {+ vec2 res = vec2(p.y, 1.0); // ground, material 1+ float body = sdRoundCone(p - vec3(0.0, 0.3, 0.0), 0.35, 0.18, 0.6);+ if (body < res.x) res = vec2(body, 2.0); // material 2+ return res;+}+```++## Coordinates and local spaces++- Screen: `vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;` (y in [-1, 1], aspect preserved).+ One pixel is `2.0 / iResolution.y` in these units.+- Move or rotate the point, never the shape: `sdBox(p - center, size)`, `q.xz = rot2(angle) * q.xz`.+ `rot2(a) * v` rotates v counter-clockwise by a. A hand-written `mat2(c, -s, s, c)` rotates the other way.+- Uniform scale keeps distances exact if you scale the result back: `sdShape(p / s) * s`.+ Non-uniform scale is only a bound: multiply by the smallest scale factor.+- Mirror for symmetry, then break it: `p.x = abs(p.x)` makes two eyes from one; add asymmetry after.++## Exact, bound, approx++Every SDF in the library is tagged and tested on the GPU (`tests/properties.py`):++| Tag | Meaning | Safe for |+|---|---|---|+| `@exact` | true Euclidean distance | marching, soft shadows, AO, offsets (`opRound`, `opOnion`), smooth blends with predictable width |+| `@bound` | never overestimates (Lipschitz <= 1) | marching (may take more steps), shadows; offsets come out uneven |+| `@approx` | exact surface, may overestimate | march with `stepScale` 0.7-0.8; avoid for offsets and onion shells |++Lipschitz constant L: how fast the field can change per unit of movement. Sphere tracing is safe only if L <= 1;+otherwise steps overshoot and punch holes or show striping. When L > 1 (displacement, warps, twist), either divide+the distance by L or pass `stepScale = 1/L` to `raymarch`.++## Booleans and smooth blends++- `opUnion` (min) is exact outside but too deep inside. `opIntersect` and `opSubtract` (max) are exact inside but+ underestimate outside. All are safe to march.+- When interior distances matter (inner-penumbra shadows, thickness, `opOnion` of a union), prefer an exact concave+ primitive: `sdDeathStar` (sphere minus sphere), `sdCutHollowSphere`, or 2D `sdMoon` / `sdArc` extruded or revolved.+- `smin(a, b, k)`: k is the blend width in distance units; shapes start blending when `|a - b| < k`, and the+ maximum bulge is `k/4`. Use `sminCubic` for close-up glossy surfaces (C2, no seam in highlights).+- `sminBlend` also returns a weight: use it to blend material colors across the join (skin into cloth, glaze into+ glaze). See `templates/raymarch-sdf.glsl`.+- Smooth unions are not associative. Blend in a fixed order (torso, then limbs, then details), and keep k smaller+ than the smallest feature being blended.+- `opChamferUnion`, `opStairsUnion`, `opEngrave` assume the surfaces meet at about 90 degrees. Keep r much smaller+ than the objects.++## Repetition++`domRepeat(p, s)` evaluates a single cell. That is exact only when every instance is identical and stays inside its+own cell. If instances vary (random height, radius, rotation, jitter), the nearest surface may belong to a neighbor+cell. Then you must check the neighbors on the side the point leans toward:++```glsl+float sdPillarField(vec3 p, float spacing) {+ vec2 id = domRepeatId(p.xz, vec2(spacing));+ vec2 side = sign(p.xz - spacing * id);+ float d = 1e10;+ for (int j = 0; j < 2; j++)+ for (int i = 0; i < 2; i++) {+ vec2 cell = id + vec2(float(i), float(j)) * side;+ float h = mix(0.5, 2.0, hash12(cell));+ vec3 q = vec3(p.x - spacing * cell.x, p.y - h, p.z - spacing * cell.y);+ d = min(d, sdRoundBox(q, vec3(0.2, h, 0.2), 0.03));+ }+ return d;+}+```++Polar repetition has the same rule. `domPolar` is exact for shapes symmetric about their sector's center line. For+asymmetric or varying petals, evaluate the sector and its nearer neighbor:++```glsl+float sdPetalRing(vec2 p, float n) {+ float sector = TAU / n;+ float a = atan(p.y, p.x);+ float id = floor(a / sector - 0.5); // the two petals around angle a are id and id + 1+ float d = 1e10;+ for (int i = 0; i < 2; i++) {+ float k = id + float(i);+ vec2 q = rot2(-(k + 0.5) * sector) * p; // rotate this sector's center onto +X+ float len = 0.5 + 0.2 * hash11(mod(k, n)); // per-petal length+ d = min(d, sdUnevenCapsule(vec2(q.y, q.x - 0.15), 0.08, 0.02, len));+ }+ return d;+}+```++Other repetition tools: `domRepeatLimited` (finite grids of windows, keys, posts), `domRepeatMirror` (neighbors+flipped so border-touching shapes join seamlessly), `domFold` (kaleidoscopes, KIFS fractals).++## Deformation, displacement and warps++| Operation | Lipschitz after the change | Fix |+|---|---|---|+| `domTwist(p, k)`, max radius R | `L = a/2 + sqrt(1 + a*a/4)`, a = kR | divide by L |+| `domBend(p, k)` | about `1 + kR` | divide by L |+| displacement `d + A * n(p)` | `1 + A * Lip(n)`; for `sin(f x)` terms Lip = f | stepScale = 1/L |+| domain warp `d(p + A * w(p))` | `1 + A * Lip(w)` | stepScale = 1/L; large warps fold space |++Get as close as possible with exact operations first, then add the smallest displacement that reads.++## From 2D to 3D++- `opExtrude(p, d2(p.xy), h)` turns any exact 2D shape into an exact slab: logos, coins, cookie cutters, petals with+ thickness.+- `opRevolve(p, o)` returns a 2D point for a profile: vases, bottles, chess pieces, mushrooms, wheels.+- `opElongate(p, h)` stretches a shape and keeps interior distances exact: `sdSphere(e.xyz, r) + e.w` is a capsule.++## Noise and hashing++- Hashes take integer-valued inputs (cell ids, pixel coordinates, frame numbers) and drop fractions, which avoids+ undefined negative float-to-uint conversion and the -0.0 vs 0.0 mismatch. Scale continuous values first.+- Never use `fract(sin(dot(p, k)) * 43758.5453)`: `sin` precision is undefined across GPUs, so the pattern changes+ between machines and degrades at large coordinates.+- Use noise in tiers: low frequency for silhouette and mass, mid for material breakup, high for grain. Do not use+ the same noise for shape, color and roughness. Offset or rotate the inputs so the controls stay independent.+- Picking a noise: `gradientNoise` / `fbm` for general use, `valueNoiseD` / `gradientNoiseD` when you need analytic+ normals, `erodedFbm` for mountains, `ridgedFbm` for crests and veins, `warpedFbm` for marble and smoke, `voronoi`+ for cells and stones, `voronoiBorder` for constant-width cracks and leading, `smoothVoronoi` for soft organic cells,+ `curlNoise` for swirling flow.+- Keep coordinates bounded: float precision is about 0.001 at 1e4 and 0.008 at 1e5. Wrap long animations with `mod`.++## Shaping functions++`common.glsl` has the classic art-control curves: `linearstep`, `cubicPulse` (bands and rings), `expImpulse`+(impacts, heartbeats), `gain` (contrast around 0.5), `parabola` (petal and leaf width along length),+`almostIdentity` (soft floors). Name masks by their visual role (`snowMask`, `rimMask`) and show each as grayscale+before it drives color.++## WebGL and Shadertoy pitfalls++- No `?:` on structs (WebGL rejects it). Pack results into `vec2`/`vec4`, or use `if`.+- No implicit int to float: `2 * PI`, `clamp(x, 0, 1)` and `sqrt(2)` fail. Write `2.0`, `0.0`, `1.0`.+- `mod(x, y)` is floor-based (always >= 0 for y > 0); `int()` truncates toward zero, so floor before converting.+- `round()` at .5 is implementation-defined. Use `floor(x + 0.5)`.+- `atan(y, x)` is undefined at (0, 0); `pow(negative, y)`, `sqrt(negative)`, `acos(|x| > 1)`, `log2(0)` and+ `normalize(vec3(0))` produce NaN. Clamp or guard; one NaN poisons an AA average.+- `smoothstep(e0, e1, x)` with `e0 >= e1` is undefined in GLSL ES 3.00. Use `1.0 - smoothstep(e1, e0, x)`.+- `dFdx`/`dFdy`/`fwidth` are undefined inside non-uniform branches and loops. Compute them before branching, or use+ an explicit pixel size (`fillAA(d, px)`).+- Large `map()` functions inlined into several loops can crash WebGL compilers. The library's loops start at+ `ZERO` (`min(iFrame, 0)`) to prevent that; copy the trick into your own loops that call `map`.+- Shadertoy provides `#version`, precision and uniforms; never add your own `#version`. There are no custom+ uniforms (no `iDebugMode`), so use `#define DEBUG_MODE 0`.++## Debugging fields++Use the pack's `DEBUG_MODE` convention (see `glsl/debug.glsl` and `composition-and-debugging.md`):+`0` final, `1` distance field, `2` normals, `3` material ids, `4` step count, `5` masks, `6` lighting terms.++- `debugDistance(d)` on a 2D slice through the scene reveals wrong signs, bad scale and kinked blends.+- `debugHeat(steps / maxSteps)` finds expensive regions and overshooting fields (bright speckle near edges).+- If a field is noisy in grayscale, it will be noisy after coloring. Fix the field, not the palette.diff --git a/skills/codex/shader-art-coding/references/shader-workflow.md b/skills/shader-art-coding/references/shader-workflow.mdsimilarity index 76%rename from skills/codex/shader-art-coding/references/shader-workflow.mdrename to skills/shader-art-coding/references/shader-workflow.mdindex 1eb07ea..ce048c5 100644--- a/skills/codex/shader-art-coding/references/shader-workflow.md+++ b/skills/shader-art-coding/references/shader-workflow.md@@ -2,6 +2,15 @@Use this workflow when creating or revising procedural shaders.+## Contents++- [1. Visual Contract](#1-visual-contract)+- [2. First Visible Pass](#2-first-visible-pass)+- [3. Layering Order](#3-layering-order)+- [4. Debug Views](#4-debug-views)+- [5. Refinement Strategy](#5-refinement-strategy)+- [6. Review Checklist](#6-review-checklist)+## 1. Visual ContractBefore coding, define the image in operational terms:@@ -55,7 +64,8 @@ Add cheap debug modes while developing:- Height/noise octave contribution.- Masks for foreground, midground, atmosphere, and highlights.-Debug modes should be easy to delete or gate behind a constant.+Gate them behind `#define DEBUG_MODE 0` using the pack's numbering (0 final, 1 distance, 2 normals, 3 ids,+4 steps, 5 masks, 6 lighting terms); see `composition-and-debugging.md`.## 5. Refinement Strategy@@ -80,5 +90,8 @@ Before finalizing:- Main objects read in silhouette.- Materials differ in value, roughness, or lighting response, not only hue.- The shader has antialiasing for sharp masks or edges.-- The final color is tonemapped/gamma-aware when lighting exceeds 0-1.+- Lighting happens in linear color; picked colors are decoded with `srgbToLinear`.+- The final color is exposed, tonemapped (per AA sample), then encoded once with `linearToSrgb` and dithered.+- No sine hashes, no `?:` on structs, no `#version`, no custom uniforms.+- The bundled shader passes `python3 scripts/glsl_tools.py check` (it compiles with glslangValidator when installed).- The response explains the knobs a user can tune.diff --git a/skills/shader-art-coding/references/subject-routing.md b/skills/shader-art-coding/references/subject-routing.mdnew file mode 100644index 0000000..45eac3a--- /dev/null+++ b/skills/shader-art-coding/references/subject-routing.md@@ -0,0 +1,125 @@+# Subject Routing++Start here when the request names a subject ("a jellyfish", "a snowy mountain", "a neon logo"). Each row gives the+rendering model, the library functions that do the heavy lifting, the template to start from, and the reference+section with the formulas. The formula files use geometry-first names; this table maps them to subjects.++## Contents++- [Choosing a rendering model](#choosing-a-rendering-model)+- [Characters and creatures](#characters-and-creatures)+- [Plants and nature objects](#plants-and-nature-objects)+- [Landscapes, sky and weather](#landscapes-sky-and-weather)+- [Built and manufactured things](#built-and-manufactured-things)+- [Materials and surfaces](#materials-and-surfaces)+- [2D graphics and motion design](#2d-graphics-and-motion-design)+- [Formal names to subjects](#formal-names-to-subjects)++## Choosing a rendering model++| The image is... | Model | Template |+|---|---|---|+| flat graphic, poster, icon, logo, UI, pattern | 2D distance fields + `fillAA` | `sdf-2d-poster.glsl`, `pattern-swatches.glsl` |+| sculpted 3D objects, characters, still lifes | SDF raymarching | `raymarch-sdf.glsl` |+| landscape, terrain, ocean surface | heightfield march (scaled bound) | `terrain.glsl` |+| clouds, smoke, fog volumes, nebulae, fire | volume integration | `volumetric-clouds.glsl` |+| texture, material swatch, wallpaper | 2D procedural pattern | `pattern-swatches.glsl` |++## Characters and creatures++| Subject | Build with | Formulas |+|---|---|---|+| head, body, torso | `sdEllipsoid` masses joined with `smin`; `sdRoundCone` for neck and snout | couples-sdf 17 (bilobed carrier), cookbook "Bilateral Organic SDF Composition" |+| eye sockets, nostrils, mouth corners | `sdDeathStar` or `smoothSubtract` of an ellipsoid | couples-sdf 18 (paired concavity) |+| eyes | `sdSphere` + analytic `iSphere` for glossy cornea; iris from `voronoi` / radial `cubicPulse` | couples-materials 18 (radial ring field) |+| eyelids, lips, eyebrows | `sdCappedTorus`, `sdArc` (2D), `sdCutHollowSphere` shells | couples-sdf 19 (aperture curve), 22 (clipped shell) |+| limbs, fingers, tails, tentacles | `sdRoundCone`, `sdCapsule`, 3D `sdQuadraticBezier` tubes | sdf-library-guide "Booleans and smooth blends" |+| hair, fur, whiskers | 3D `sdQuadraticBezier` strands, `curlNoise` for flow, anisotropic highlights | couples-sdf 21 (strand perturbation) |+| skin | `wrapDiffuse`, `translucency` + `sdfThickness`, red-tinted terminator | rendering-pipeline "Lighting" |+| cloth, knit | `fabricDisplace`-style micro displacement (stepScale 0.7) | couples-sdf 23 |+| jellyfish, ghosts, glass creatures | `sdCutHollowSphere`, `opOnion`, `translucency`, additive glow | couples-sdf 22 |++## Plants and nature objects++| Subject | Build with | Formulas |+|---|---|---|+| flower, petals | `domPolar` + `sdUnevenCapsule` / `sdVesica`; neighbor-checked for varied petals | sdf-library-guide "Repetition" |+| leaves | `sdVesica` (2D) extruded with `opExtrude`, veins from `voronoiBorder` | couples-materials 12 |+| trees (stylized) | `sdCone` tiers + `sdCylinder` trunk; forests with neighbor-checked repetition | couples-sdf 24-25 |+| grass, foliage clumps | density fields placed on a grid with suitability masks | couples-terrain 19-21 |+| rocks, pebbles | `sdRoundBox` / `sdEllipsoid` + `fbm` displacement, `voronoi` facets | sdf-library-guide "Deformation" |+| coral, sponge, bone | `sdGyroid` intersected with a bounding shape | library-index (sdGyroid) |+| shells, horns | `sdCappedTorus`, `domTwist` (divide by L), `opOnion` | sdf-library-guide "Deformation" |+| fruit | spheres and ellipsoids, `smoothSubtract` dimples, `voronoi` skin pores | couples-sdf 9 |++## Landscapes, sky and weather++| Subject | Build with | Formulas |+|---|---|---|+| mountains | `erodedFbm` height, `ridgedFbm` crests, slope/altitude masks | couples-terrain 1-12, `terrain.glsl` |+| snow | upward-facing accumulation mask (`n.y`) + altitude + noise breakup | couples-terrain 22 |+| desert dunes | `ridgedFbm` along one axis + `warpedFbm`, low sun | couples-terrain 23 (layered ridge) |+| ocean, lakes | `iPlane` water + `fresnelSchlick` + sky reflection, `gradientNoiseD` normals | rendering-pipeline "Lighting" |+| sky, sunset | `atmosphereSky` (physical) or `simpleSky`; `sunDisk` | rendering-pipeline "Sky, fog and aerial perspective" |+| clouds | `volumetric-clouds.glsl`: coverage fBm, `beerPowder`, `phaseDualHG`, `volumeStep` | rendering-pipeline "Volumes" |+| fog, mist, haze | `distanceFog`, `heightFog`, aerial perspective with horizon-clamped sky | couples-terrain 13-14 |+| night sky, stars | per-cell `hash32` stars, `blackbody` colors, twinkle with `sin(iTime)` | `sdf-2d-poster.glsl` |+| fire, lava, embers | `warpedFbm` / `curlNoise`, `blackbody(1200-1800 K)`, additive glow, AgX | rendering-pipeline "Volumes" |+| rain, snowfall | repeated streaks with `domRepeat` + per-cell `hash12` phase | sdf-library-guide "Repetition" |++## Built and manufactured things++| Subject | Build with | Formulas |+|---|---|---|+| buildings, rooms | `sdBox` / `sdRoundBox`, `opSubtract` windows with `domRepeatLimited` | sdf-library-guide "Repetition" |+| brick or stone tower | radial row-cell space, staggered rows, interstitial mortar shell | couples-sdf 13-16, cookbook "Cylindrical Modular Cell Lattice" |+| machinery, sci-fi panels | `opChamferUnion`, `opEngrave` panel lines, `sdBoxFrame` | library-index (operators) |+| stairs, terraces, ziggurats | `opStairsUnion` | library-index (operators) |+| columns, pillars | `sdCylinder` + `domPolar` flutes, `domRepeatLimited` colonnades | sdf-library-guide "Repetition" |+| vases, bottles, chess pieces | 2D profile + `opRevolve` | sdf-library-guide "From 2D to 3D" |+| chains, rings, jewelry | `sdLink`, `sdTorus`, metal `shadePBR(metal = 1)` | rendering-pipeline "Color and materials" |+| text-like logos, badges | 2D SDFs + `opExtrude`, `sdStar`, `sdRegularPolygon` | sdf-library-guide "From 2D to 3D" |+| glass objects | analytic `iSphere`/`iBox` + `fresnelSchlick` + refracted sky | rendering-pipeline "Lighting" |++## Materials and surfaces++| Subject | Build with | Formulas |+|---|---|---|+| marble, agate | `warpedFbm` (color from q and r) | `pattern-swatches.glsl` |+| wood | rings: `fract(radius * k + fbm)`, grain stretched along one axis | couples-materials 18 |+| cracked mud, crackle glaze | `voronoiBorder` (constant-width cracks) | `pattern-swatches.glsl` |+| tiles, honeycomb, scales | `hexGrid` + `hexEdgeDistance` bevels, per-tile `hash12` color | `pattern-swatches.glsl` |+| checkerboard floors | `filteredChecker` with ray-footprint width | `raymarch-sdf.glsl` |+| rust, dirt, wear | `fbm` masks biased by gravity and curvature, edge wear from AO | couples-materials 15-16 |+| metal, plastic, ceramic | `shadePBR` roughness/metallic, `envBRDFApprox` sky reflections | rendering-pipeline "Lighting" |+| weaves, mazes, circuits | `truchetArcs`, `domRepeatMirror` | `pattern-swatches.glsl` |++## 2D graphics and motion design++| Subject | Build with | Formulas |+|---|---|---|+| poster, landscape silhouette | ridges from `fbm` lines, layered back to front, `mixOklab` sky | `sdf-2d-poster.glsl` |+| icons, UI shapes | `sdRoundedBox` (per-corner), `sdCircle`, `strokeAA` | couples-materials 3-4 |+| loaders, gauges, rings | `sdArc`, `opOnion`, time-driven aperture | couples-materials 25-26 |+| kaleidoscopes, mandalas | `domPolar`, `domFold`, `cosinePalette` | sdf-library-guide "Repetition" |+| retro sunsets, synthwave | `filteredStripes`, `filteredGrid` in perspective, `tonemapNeutral` | `sdf-2d-poster.glsl` |+| looping animation | integer-frequency `cos(TAU * t)`, `cosinePalette` with integer c | couples-materials 25 |++## Formal names to subjects++The formula files name operators by geometry so they stay reusable. Typical subjects:++| Formal name | Typical subjects |+|---|---|+| bilobed (organic) carrier | head + cranium, torso + pelvis, gourd, snowman, peanut |+| paired concavity carve | eye sockets, nostrils, dimples |+| parametric arc aperture curve | eyelids, mouths, smiles, slits |+| soft parametric groove | lip line, crease, seam, wrinkle |+| anisotropic strand field | hair, fur, grass blades, fibers |+| ellipsoidal shell clipped by half-space | eyelid, helmet, beetle shell, hood |+| radial row-cell space | brick tower, beehive, pinecone, shingled roof |+| interstitial shell | mortar, grout, membrane between cells |+| accumulation mask | snow, dust, moss on top surfaces |+| coverage field | clouds, foliage canopy, fog banks |+| sparse stochastic spot field | freckles, stars, sparkles, pores |+| stratified material channels | rock / grass / snow layering |diff --git a/skills/shader-art-coding/scripts/glsl_tools.py b/skills/shader-art-coding/scripts/glsl_tools.pynew file mode 100644index 0000000..9de1aaf--- /dev/null+++ b/skills/shader-art-coding/scripts/glsl_tools.py@@ -0,0 +1,657 @@+#!/usr/bin/env python3+"""Tools for the shader-art-coding GLSL library. Standard library only.++Commands (run from anywhere):+ search TERM... find library functions by name, summary or @use tags ("petal", "noise terrain")+ bundle SHADER [-o F] inline exactly the library functions SHADER uses -> paste-ready Shadertoy code+ check [SHADER...] lint shaders (and compile with glslangValidator if installed); no args = check the skill+ index [--check] regenerate references/library-index.md (or fail if it is stale)++Shaders are written against the library by name: call sdRoundBox, fbm, softShadow, ... without pasting them.+`bundle` resolves dependencies transitively and emits them in declaration order before your code.+"""++from __future__ import annotations++import argparse+import re+import shutil+import subprocess+import sys+import tempfile+from dataclasses import dataclass, field+from pathlib import Path++SKILL_DIR = Path(__file__).resolve().parents[1]+LIB_DIR = SKILL_DIR / "glsl"+REF_DIR = SKILL_DIR / "references"+TEMPLATE_DIR = SKILL_DIR / "templates"+INDEX_PATH = REF_DIR / "library-index.md"++# Declaration order: a module may only depend on modules listed before it.+MODULE_ORDER = [+ "common", "hash", "noise", "pattern", "sdf3d", "sdf2d", "operators", "domain", "raymarch", "intersect",+ "camera", "shading", "color", "tonemap", "volume", "atmosphere", "post", "debug",+]++SHADERTOY_PRELUDE = """#version 300 es+precision highp float;+precision highp int;+precision mediump sampler3D;+uniform vec3 iResolution;+uniform float iTime;+uniform float iTimeDelta;+uniform float iFrameRate;+uniform int iFrame;+uniform vec4 iMouse;+uniform vec4 iDate;+uniform float iChannelTime[4];+uniform vec3 iChannelResolution[4];+uniform sampler2D iChannel0;+uniform sampler2D iChannel1;+uniform sampler2D iChannel2;+uniform sampler2D iChannel3;+out vec4 st_FragColor;+"""+MAIN_COMPLETE = "\nvoid main() { mainImage(st_FragColor, gl_FragCoord.xy); st_FragColor.a = 1.0; }\n"+MAIN_DEFS = "\nvoid main() { st_FragColor = vec4(0.0); }\n"+++def stub_prototypes(code: str) -> str:+ """Give scene-provided prototypes (e.g. `float terrainHeight(vec2 p);`, `vec2 map(vec3 p);`) a trivial body so a+ snippet or library module can be compiled on its own."""+ items = parse(code)+ defined = {it.key for it in items if it.kind == "fn"}+ stubs = []+ for it in items:+ if it.kind == "proto" and it.key not in defined:+ ret = it.signature.split()[0]+ value = "0.0" if ret == "float" else ("0" if ret == "int" else f"{ret}(0.0)")+ if it.name == "map" and ret == "vec2":+ value = "vec2(length(p) - 1.0, 0.0)"+ params = it.signature[it.signature.index("(") + 1:-1]+ stubs.append(f"{ret} {it.name}({params}) {{ return {value}; }}")+ defined.add(it.key)+ return code + ("\n// stubs for scene-provided functions\n" + "\n".join(stubs) + "\n" if stubs else "")++QUALIFIERS = {"in", "out", "inout", "const", "highp", "mediump", "lowp", "flat", "smooth"}+GLSL_KEYWORDS = {+ "float", "int", "uint", "bool", "void", "vec2", "vec3", "vec4", "ivec2", "ivec3", "ivec4", "uvec2",+ "uvec3", "uvec4", "bvec2", "bvec3", "bvec4", "mat2", "mat3", "mat4", "if", "else", "for", "while",+ "return", "break", "continue", "struct", "const", "in", "out", "inout", "true", "false",+}+FN_RE = re.compile(r"^\s*((?:(?:highp|mediump|lowp)\s+)?\w+)\s+(\w+)\s*\(([^)]*)\)\s*(\{|;)", re.S)+STRUCT_RE = re.compile(r"^\s*struct\s+(\w+)")+CONST_RE = re.compile(r"^\s*const\s+(?:(?:highp|mediump|lowp)\s+)?\w+\s+(\w+)\s*=")+DEFINE_RE = re.compile(r"^#\s*define\s+(\w+)")+IDENT_RE = re.compile(r"\b[A-Za-z_]\w*\b")+++@dataclass+class Item:+ kind: str # fn | proto | struct | const | define | directive | other+ name: str+ text: str # source text without doc comments+ doc: list[str] = field(default_factory=list)+ signature: str = "" # e.g. "float sdBox(vec3 p, vec3 b)"+ key: str = "" # name + parameter types, for overload identity+ module: str = ""+ deps: set[str] = field(default_factory=set)++ @property+ def tags(self) -> dict[str, str]:+ out: dict[str, str] = {}+ for line in self.doc:+ if line.startswith("@"):+ tag, _, rest = line[1:].partition(" ")+ out[tag] = rest.strip()+ return out++ @property+ def summary(self) -> str:+ return " ".join(l for l in self.doc if not l.startswith("@")).strip()+++def strip_comments(code: str) -> str:+ code = re.sub(r"/\*.*?\*/", " ", code, flags=re.S)+ return re.sub(r"//[^\n]*", "", code)+++def normalize(code: str) -> str:+ return re.sub(r"\s+", "", strip_comments(code))+++def param_types(params: str) -> list[str]:+ types = []+ for raw in params.split(","):+ toks = [t for t in re.split(r"\s+", raw.strip()) if t and t not in QUALIFIERS]+ if not toks or toks == ["void"]:+ continue+ types.append(toks[0] if len(toks) == 1 else toks[-2])+ return types+++def parse(src: str, module: str = "") -> list[Item]:+ """Split GLSL source into top-level items, attaching /// doc lines to the item that follows."""+ items: list[Item] = []+ doc: list[str] = []+ i, n = 0, len(src)+ while i < n:+ c = src[i]+ if c.isspace():+ i += 1+ continue+ if src.startswith("///", i) or src.startswith("//!", i) or src.startswith("//", i):+ end = src.find("\n", i)+ end = n if end < 0 else end+ if src.startswith("///", i):+ doc.append(src[i + 3:end].strip())+ i = end+ continue+ if src.startswith("/*", i):+ end = src.find("*/", i)+ i = n if end < 0 else end + 2+ continue+ if c == "#":+ end = i+ while True:+ nl = src.find("\n", end)+ nl = n if nl < 0 else nl+ if src[nl - 1:nl] == "\\":+ end = nl + 1+ continue+ end = nl+ break+ text = src[i:end]+ m = DEFINE_RE.match(text)+ items.append(Item("define" if m else "directive", m.group(1) if m else "", text, doc, module=module))+ doc = []+ i = end+ continue+ # statement or block+ start, depth, j = i, 0, i+ while j < n:+ ch = src[j]+ if src.startswith("//", j):+ nl = src.find("\n", j)+ j = n if nl < 0 else nl+ continue+ if src.startswith("/*", j):+ e = src.find("*/", j)+ j = n if e < 0 else e + 2+ continue+ if ch in "({[":+ depth += 1+ elif ch in ")}]":+ depth -= 1+ if ch == "}" and depth == 0:+ # end of a function body or struct+ k = j + 1+ while k < n and src[k] in " \t":+ k += 1+ if k < n and src[k] == ";":+ j = k+ break+ elif ch == ";" and depth == 0:+ break+ j += 1+ text = src[start:j + 1]+ i = j + 1+ m_fn, m_st, m_co = FN_RE.match(text), STRUCT_RE.match(text), CONST_RE.match(text)+ if m_st:+ item = Item("struct", m_st.group(1), text, doc, module=module, key=m_st.group(1))+ elif m_co:+ item = Item("const", m_co.group(1), text, doc, module=module, key=m_co.group(1))+ elif m_fn and m_fn.group(1) not in ("return", "else"):+ ret, name, params = m_fn.group(1), m_fn.group(2), m_fn.group(3)+ sig = f"{ret} {name}({' '.join(params.split())})"+ kind = "fn" if m_fn.group(4) == "{" else "proto"+ item = Item(kind, name, text, doc, signature=sig, key=f"{name}({','.join(param_types(params))})",+ module=module)+ else:+ item = Item("other", "", text, doc, module=module)+ items.append(item)+ doc = []+ return items+++class Library:+ def __init__(self, lib_dir: Path = LIB_DIR):+ self.items: list[Item] = []+ self.modules: dict[str, str] = {}+ files = {p.stem: p for p in lib_dir.glob("*.glsl")}+ unknown = sorted(set(files) - set(MODULE_ORDER))+ if unknown:+ raise SystemExit(f"glsl/: modules missing from MODULE_ORDER: {unknown}")+ for mod in MODULE_ORDER:+ if mod not in files:+ continue+ src = files[mod].read_text(encoding="utf-8")+ header = [l[3:].strip() for l in src.splitlines() if l.startswith("//!")]+ self.modules[mod] = " ".join(header)+ self.items.extend(parse(src, mod))+ self.by_name: dict[str, list[Item]] = {}+ for it in self.items:+ if it.name:+ self.by_name.setdefault(it.name, []).append(it)+ for it in self.items:+ it.deps = self.idents(it.text) - {it.name}+ if it.kind == "proto":+ it.deps = set()++ def idents(self, code: str) -> set[str]:+ return {t for t in IDENT_RE.findall(strip_comments(code)) if t in self.by_name and t not in GLSL_KEYWORDS}++ def closure(self, names: set[str], exclude: set[str] = frozenset()) -> list[Item]:+ seen: set[str] = set()+ stack = [n for n in names if n not in exclude]+ while stack:+ name = stack.pop()+ if name in seen:+ continue+ seen.add(name)+ for it in self.by_name.get(name, []):+ stack.extend(d for d in it.deps if d not in seen and d not in exclude)+ return [it for it in self.items if it.name in seen]++ def bundle(self, user_src: str, keep_docs: bool = True) -> tuple[str, list[Item]]:+ user_items = parse(user_src)+ defined = {it.name for it in user_items if it.kind in ("fn", "struct", "const", "define")}+ needed = self.idents(user_src) - defined+ deps = self.closure(needed, exclude=defined - {"map"})+ # The map() prototype is only needed when raymarch helpers are pulled in.+ if not any("map" in it.deps for it in deps):+ deps = [it for it in deps if not (it.kind == "proto" and it.name == "map")]+ chunks, current = [], None+ for it in deps:+ if it.module != current:+ current = it.module+ chunks.append(f"\n// ---- shader-skills library: {current} ----")+ body = it.text.strip()+ if keep_docs and it.doc and it.kind == "fn":+ summary = it.summary+ if summary:+ body = f"// {summary}\n{body}"+ chunks.append(body)+ lib_code = "\n".join(chunks).strip()+ return lib_code, deps+++def bundle_source(lib: Library, user_src: str, keep_docs: bool = True) -> str:+ lib_code, deps = lib.bundle(user_src, keep_docs)+ if not deps:+ return user_src+ header = ("// Library code below is bundled from shader-skills (MIT): "+ "https://github.com/gokayfem/shader-skills\n")+ # Keep user #defines (e.g. DEBUG_MODE, AA) at the very top so library code can see them.+ lines = user_src.splitlines()+ lead = 0+ while lead < len(lines) and (lines[lead].startswith(("#", "//")) or not lines[lead].strip()):+ lead += 1+ directives = [i for i in range(lead) if lines[i].startswith("#")]+ cut = directives[-1] + 1 if directives else 0+ while cut < lead and lines[cut].strip() == "":+ cut += 1+ if not directives:+ # no #defines: keep only the opening comment block (up to the first blank line) on top+ cut = next((i for i in range(lead) if not lines[i].strip()), 0)+ top, rest = lines[:cut], lines[cut:]+ return ("\n".join(top).rstrip() + "\n\n" + header + lib_code + "\n\n// ---- shader ----\n"+ + "\n".join(rest).strip() + "\n")+++# ------------------------------------------------------------------------------------------------ lint++@dataclass+class Finding:+ level: str # error | warning+ where: str+ message: str++ def __str__(self) -> str:+ return f"{self.level.upper():7} {self.where}: {self.message}"+++SHADER_RULES = [+ (r"\bgl_FragColor\b", "error", "gl_FragColor is WebGL1; Shadertoy uses mainImage(out vec4 fragColor, ...)"),+ (r"\btexture2D\s*\(", "error", "texture2D is WebGL1; use texture()"),+ (r"\biGlobalTime\b", "error", "iGlobalTime was removed from Shadertoy; use iTime"),+ (r"\biDebugMode\b", "error", "iDebugMode is not a Shadertoy uniform; use '#define DEBUG_MODE 0'"),+ (r"^\s*#version\b", "error", "do not add #version; Shadertoy (and the bundler's prelude) provide it"),+ (r"fract\s*\(\s*sin\s*\(", "warning",+ "sine-based hash: platform-dependent and degrades at large inputs; use hash12/hash22 from glsl/hash.glsl"),+ (r"\bround\s*\(", "warning", "round() is implementation-defined at .5 and may return -0.0; prefer floor(x + 0.5)"),+]+++def lint_shader(src: str, where: str, complete: bool) -> list[Finding]:+ out = []+ code = strip_comments(src)+ for pattern, level, msg in SHADER_RULES:+ if re.search(pattern, code, re.M):+ out.append(Finding(level, where, msg))+ if complete and not re.search(r"\bvoid\s+mainImage\s*\(\s*out\s+vec4\s+\w+\s*,\s*in\s+vec2\s+\w+\s*\)", code):+ out.append(Finding("error", where, "missing 'void mainImage(out vec4 fragColor, in vec2 fragCoord)'"))+ for m in re.finditer(r"\bfor\s*\(([^;]*);([^;]*);", code):+ cond = m.group(2)+ if not re.search(r"<|>", cond):+ out.append(Finding("warning", where, f"loop condition '{cond.strip()}' has no bound"))+ return out+++def lint_library(lib: Library) -> list[Finding]:+ out: list[Finding] = []+ seen: dict[str, Item] = {}+ for it in lib.items:+ where = f"glsl/{it.module}.glsl:{it.name or it.kind}"+ if it.kind == "fn":+ if it.key in seen:+ out.append(Finding("error", where, f"duplicate definition of {it.key}"))+ seen[it.key] = it+ documented = it.doc or any(o.doc for o in lib.by_name[it.name])+ if not documented:+ out.append(Finding("error", where, "missing /// doc comment"))+ tags = {k: v for o in lib.by_name[it.name] for k, v in o.tags.items()}+ if it.doc and "use" not in tags and not it.name.startswith(("uintToUnit", "quintic", "latticeG")):+ out.append(Finding("warning", where, "doc comment has no @use line"))+ if re.match(r"sd[A-Z]", it.name) and not ({"exact", "bound", "approx"} & set(tags)):+ out.append(Finding("error", where, "SDF needs an @exact, @bound or @approx tag"))+ for pattern, level, msg in SHADER_RULES[:5] + SHADER_RULES[5:6]:+ if re.search(pattern, strip_comments(it.text), re.M):+ out.append(Finding(level, where, msg))+ bad_deps = [d for d in it.deps if any(MODULE_ORDER.index(o.module) > MODULE_ORDER.index(it.module)+ for o in lib.by_name[d])]+ if bad_deps:+ out.append(Finding("error", where, f"depends on later module(s): {sorted(bad_deps)}"))+ return out+++def lint_skill() -> list[Finding]:+ """Packaging rules from the Agent Skills spec: frontmatter, size, one-level references with tables of contents."""+ out: list[Finding] = []+ text = (SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")+ m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S)+ if not m:+ return [Finding("error", "SKILL.md", "missing YAML frontmatter")]+ front, body = m.group(1), m.group(2)+ name = re.search(r"^name:\s*(\S+)", front, re.M)+ if not name or name.group(1) != SKILL_DIR.name:+ out.append(Finding("error", "SKILL.md", f"frontmatter name must equal the folder name '{SKILL_DIR.name}'"))+ desc = re.search(r"^description:\s*(?:>-?|\|-?)?\s*\n((?:[ \t]+.*\n?)+)|^description:\s*(.+)$", front, re.M)+ desc_text = " ".join((desc.group(1) or desc.group(2) or "").split()) if desc else ""+ if not desc_text:+ out.append(Finding("error", "SKILL.md", "missing description"))+ elif len(desc_text) > 1024:+ out.append(Finding("error", "SKILL.md", f"description is {len(desc_text)} chars (max 1024)"))+ if re.search(r"\[[^\]\n]*,[^\]\n]*\]", front):+ out.append(Finding("error", "SKILL.md", "use block-style YAML lists in frontmatter (strict validators reject [a, b])"))+ if body.count("\n") > 500:+ out.append(Finding("error", "SKILL.md", "body exceeds 500 lines; move detail into references/"))+ for ref in sorted(REF_DIR.glob("*.md")):+ rel = f"references/{ref.name}"+ if rel not in body:+ out.append(Finding("error", "SKILL.md", f"{rel} is not linked from SKILL.md"))+ ref_text = ref.read_text(encoding="utf-8")+ if ref_text.count("\n") > 100 and "## Contents" not in ref_text:+ out.append(Finding("error", rel, "over 100 lines without a '## Contents' section"))+ for rel in sorted(set(re.findall(r"`((?:references|templates|scripts|glsl)/[\w./-]+)`", body))):+ if not (SKILL_DIR / rel).exists():+ out.append(Finding("error", "SKILL.md", f"links missing file {rel}"))+ return out+++# --------------------------------------------------------------------------------------------- snippets++FENCE_RE = re.compile(r"```glsl[^\n]*\n(.*?)\n```", re.S)+++@dataclass+class Snippet:+ where: str+ code: str+ kind: str # complete | defs | fragment+++def reference_snippets(paths: list[Path]) -> list[Snippet]:+ out = []+ for path in paths:+ text = path.read_text(encoding="utf-8")+ for idx, m in enumerate(FENCE_RE.finditer(text), 1):+ code = m.group(1)+ line = text.count("\n", 0, m.start()) + 2+ where = f"{path.relative_to(SKILL_DIR.parent.parent) if SKILL_DIR.parent.parent in path.parents else path.name}:{line}"+ items = parse(code)+ if re.search(r"\bvoid\s+mainImage\b", code):+ kind = "complete"+ elif items and all(it.kind in ("fn", "struct", "const", "define", "proto") for it in items):+ kind = "defs"+ else:+ kind = "fragment"+ out.append(Snippet(where, code, kind))+ return out+++def snippet_drift(lib: Library, snip: Snippet) -> list[Finding]:+ """A reference snippet may reuse a library name only if it is the library code verbatim (modulo whitespace)."""+ out = []+ lib_by_key = {it.key: it for it in lib.items if it.kind == "fn"}+ for it in parse(snip.code):+ if it.kind != "fn":+ continue+ if it.key in lib_by_key and normalize(it.text) != normalize(lib_by_key[it.key].text):+ out.append(Finding("error", snip.where,+ f"{it.key} differs from glsl/{lib_by_key[it.key].module}.glsl; "+ "use the library version or rename the variant"))+ return out+++def snippet_unit(lib: Library, snip: Snippet, extra_defs: str = "") -> str:+ """Compile unit for a reference snippet: library deps + definitions from earlier snippets + the snippet."""+ body = extra_defs + "\n" + snip.code+ code = stub_prototypes(bundle_source(lib, body, keep_docs=False))+ return SHADERTOY_PRELUDE + code + (MAIN_COMPLETE if snip.kind == "complete" else MAIN_DEFS)+++def shader_unit(lib: Library, src: str, complete: bool = True) -> str:+ code = bundle_source(lib, src, keep_docs=False)+ if not complete:+ code = stub_prototypes(code)+ return SHADERTOY_PRELUDE + code + (MAIN_COMPLETE if complete else MAIN_DEFS)+++def library_units(lib: Library) -> dict[str, str]:+ """One compile unit per module: every function in it plus its dependencies."""+ units = {}+ for mod in lib.modules:+ names = {it.name for it in lib.items if it.module == mod and it.name}+ deps = lib.closure(names)+ code = stub_prototypes("\n\n".join(it.text.strip() for it in deps))+ units[f"glsl/{mod}.glsl"] = SHADERTOY_PRELUDE + code + MAIN_DEFS+ return units+++def all_units(lib: Library) -> tuple[dict[str, str], list[Finding]]:+ """Every compile unit the skill ships: library modules, reference snippets, templates."""+ findings: list[Finding] = []+ units = library_units(lib)+ refs = sorted(REF_DIR.glob("*.md")) + [SKILL_DIR / "SKILL.md"]+ by_file: dict[str, str] = {}+ for snip in reference_snippets(refs):+ findings += snippet_drift(lib, snip)+ file_key = snip.where.split(":")[0]+ if snip.kind == "fragment":+ continue+ findings += lint_shader(snip.code, snip.where, complete=snip.kind == "complete")+ # Snippets may build on definitions from earlier snippets in the same file (minus anything they redefine).+ prior = by_file.get(file_key, "")+ own = {it.key or it.name for it in parse(snip.code)}+ prior_kept = "\n".join(it.text for it in parse(prior) if (it.key or it.name) not in own)+ units[snip.where] = snippet_unit(lib, snip, prior_kept)+ if snip.kind == "defs":+ by_file[file_key] = prior + "\n" + snip.code+ for tpl in sorted(TEMPLATE_DIR.glob("*.glsl")):+ src = tpl.read_text(encoding="utf-8")+ where = f"templates/{tpl.name}"+ findings += lint_shader(src, where, complete=True)+ units[where] = shader_unit(lib, src)+ return units, findings+++# ------------------------------------------------------------------------------------------- glslang++def glslang_compile(units: dict[str, str]) -> list[Finding] | None:+ exe = shutil.which("glslangValidator")+ if not exe:+ return None+ out = []+ with tempfile.TemporaryDirectory() as tmp:+ for i, (where, code) in enumerate(units.items()):+ path = Path(tmp) / f"unit{i}.frag"+ path.write_text(code, encoding="utf-8")+ res = subprocess.run([exe, str(path)], capture_output=True, text=True)+ if res.returncode != 0:+ msg = "\n".join(l for l in (res.stdout + res.stderr).splitlines() if "ERROR" in l)[:2000]+ out.append(Finding("error", where, "glslang: " + (msg or res.stdout.strip()[:500])))+ return out+++# --------------------------------------------------------------------------------------------- index++def render_index(lib: Library) -> str:+ lines = [+ "# GLSL Library Index",+ "",+ "Generated by `scripts/glsl_tools.py index`. Do not edit by hand.",+ "",+ "Call these functions by name in your shader, then run",+ "`python3 scripts/glsl_tools.py bundle your.glsl -o out.glsl` to inline exactly what it uses.",+ "Find candidates with `python3 scripts/glsl_tools.py search <words>`.",+ "",+ "Tags: **exact** is a true Euclidean distance, safe for blending, AO, shadows and offsets.",+ "**bound** never overestimates, so it is safe to march, but less accurate for offsets.",+ "**approx** has an exact surface but may overestimate in places; read its note for a safe step scale.",+ "",+ "## Contents",+ "",+ ]+ for mod in lib.modules:+ lines.append(f"- [{mod}](#{mod}) - {lib.modules[mod].split('. ')[0].split(': ', 1)[-1]}")+ for mod, header in lib.modules.items():+ lines += ["", f"## {mod}", "", header, ""]+ shown: set[str] = set()+ for it in lib.items:+ if it.module != mod or it.kind not in ("fn", "const", "define") or it.name in shown:+ continue+ group = [o for o in lib.by_name[it.name] if o.module == mod and o.kind in ("fn", "const", "define")]+ shown.add(it.name)+ doc_item = next((o for o in group if o.doc), it)+ tags = doc_item.tags+ sigs = " / ".join(f"`{o.signature}`" if o.signature else f"`{o.text.strip()[:60]}`" for o in group)+ exact = next((f" **{t}**" for t in ("exact", "bound", "approx") if t in tags), "")+ summary = doc_item.summary+ line = f"- {sigs}{exact}"+ if summary:+ line += f" - {summary}"+ if tags.get("use"):+ line += f" *Use: {tags['use']}.*"+ if tags.get("range"):+ line += f" Range {tags['range']}."+ lines.append(line)+ return "\n".join(lines) + "\n"+++# ---------------------------------------------------------------------------------------------- main++def cmd_search(lib: Library, terms: list[str]) -> int:+ terms = [t.lower() for t in terms]+ scored = []+ for name, group in lib.by_name.items():+ fns = [g for g in group if g.kind == "fn"]+ if not fns:+ continue+ doc_item = next((g for g in fns if g.doc), fns[0])+ use = doc_item.tags.get("use", "").lower()+ summary = doc_item.summary.lower()+ score = sum((3 if t in name.lower() else 0) + 2 * use.count(t) + summary.count(t) for t in terms)+ if score:+ scored.append((score, name, fns, doc_item))+ for score, name, fns, doc_item in sorted(scored, key=lambda s: -s[0])[:15]:+ print(f"{fns[0].module}: " + " / ".join(f.signature for f in fns))+ if doc_item.summary:+ print(f" {doc_item.summary}")+ if doc_item.tags.get("use"):+ print(f" use: {doc_item.tags['use']}")+ if not scored:+ print("no matches; try broader words or read references/library-index.md")+ return 0+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = ap.add_subparsers(dest="cmd", required=True)+ s = sub.add_parser("search")+ s.add_argument("terms", nargs="+")+ b = sub.add_parser("bundle")+ b.add_argument("shader")+ b.add_argument("-o", "--output")+ b.add_argument("--no-docs", action="store_true")+ c = sub.add_parser("check")+ c.add_argument("shaders", nargs="*")+ c.add_argument("--defs", action="store_true", help="files contain helper definitions, not a full mainImage")+ i = sub.add_parser("index")+ i.add_argument("--check", action="store_true")+ args = ap.parse_args(argv)++ lib = Library()+ if args.cmd == "search":+ return cmd_search(lib, args.terms)+ if args.cmd == "bundle":+ out = bundle_source(lib, Path(args.shader).read_text(encoding="utf-8"), keep_docs=not args.no_docs)+ if args.output:+ Path(args.output).write_text(out, encoding="utf-8")+ else:+ sys.stdout.write(out)+ return 0+ if args.cmd == "index":+ text = render_index(lib)+ if args.check:+ if not INDEX_PATH.exists() or INDEX_PATH.read_text(encoding="utf-8") != text:+ print("references/library-index.md is stale: run scripts/glsl_tools.py index")+ return 1+ print("library index is up to date")+ return 0+ INDEX_PATH.write_text(text, encoding="utf-8")+ print(f"wrote {INDEX_PATH.relative_to(SKILL_DIR)}")+ return 0++ # check+ findings: list[Finding] = []+ if args.shaders:+ units = {}+ for path in args.shaders:+ src = Path(path).read_text(encoding="utf-8")+ findings += lint_shader(src, path, complete=not args.defs)+ units[path] = shader_unit(lib, src, complete=not args.defs)+ else:+ findings += lint_library(lib)+ findings += lint_skill()+ units, more = all_units(lib)+ findings += more+ if INDEX_PATH.exists() and INDEX_PATH.read_text(encoding="utf-8") != render_index(lib):+ findings.append(Finding("error", "references/library-index.md", "stale; run scripts/glsl_tools.py index"))+ compiled = glslang_compile(units)+ if compiled is None:+ print(f"note: glslangValidator not found, so {len(units)} unit(s) were linted but not compiled. "+ "Install: brew install glslang | apt install glslang-tools")+ else:+ findings += compiled+ print(f"compiled {len(units)} unit(s) with glslangValidator")+ errors = [f for f in findings if f.level == "error"]+ for f in findings:+ print(f)+ print(f"{len(errors)} error(s), {len(findings) - len(errors)} warning(s)")+ return 1 if errors else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/skills/shader-art-coding/templates/pattern-swatches.glsl b/skills/shader-art-coding/templates/pattern-swatches.glslnew file mode 100644index 0000000..35c8556--- /dev/null+++ b/skills/shader-art-coding/templates/pattern-swatches.glsl@@ -0,0 +1,85 @@+// Procedural material swatches: six texture-free patterns on one board.+// Shows: two-level domain warping (marble), exact Voronoi borders (cracked earth), hex tiles with bevels,+// Truchet weaves, smooth Voronoi (organic cells) and a box-filtered checker. Each tile uses explicit pixel-size+// filtering instead of fwidth, so it stays valid inside branches.+// @render time=2.0++#define DEBUG_MODE 0 // 0 final | 3 tile ids++vec3 marble(vec2 p) {+ vec2 q, r;+ float f = warpedFbm(p * 1.5, 3.0, 5, q, r);+ vec3 col = mixOklab(srgbToLinear(vec3(0.92, 0.90, 0.86)), srgbToLinear(vec3(0.35, 0.38, 0.45)), saturate(length(q) * 0.9));+ col = mix(col, srgbToLinear(vec3(0.62, 0.42, 0.30)), saturate(r.y * r.y * 2.0));+ return col * (0.85 + 0.25 * f);+}++vec3 crackedEarth(vec2 p, float px) {+ vec3 v = voronoiBorder(p * 4.0, 0.9);+ vec2 cell = floor(p * 4.0 + v.yz);+ float tint = hash12(cell);+ vec3 col = mix(srgbToLinear(vec3(0.62, 0.44, 0.30)), srgbToLinear(vec3(0.75, 0.58, 0.40)), tint);+ col *= 0.75 + 0.25 * smoothstep(0.0, 0.25, v.x); // plates darken toward their curled edges+ float plate = fillAA(0.03 - v.x, px * 4.0); // cracks: border distance < 0.03 cell units+ return mix(srgbToLinear(vec3(0.12, 0.08, 0.06)), col, plate);+}++vec3 hexTiles(vec2 p, float px) {+ vec4 h = hexGrid(p * 5.0);+ float edge = hexEdgeDistance(h.xy);+ vec3 base = oklchToLinearSrgb(vec3(0.7, 0.09, 3.6 + 0.8 * hash12(h.zw)));+ float bevel = smoothstep(0.0, 0.12, edge);+ return mix(vec3(0.02), base * (0.7 + 0.3 * bevel), smoothstep(0.03 - px * 5.0, 0.03 + px * 5.0, edge));+}++vec3 truchet(vec2 p, float px) {+ float d = truchetArcs(p * 5.0, 0.12) / 5.0;+ float stripe = truchetArcs(p * 5.0, 0.03) / 5.0;+ vec3 col = srgbToLinear(vec3(0.08, 0.10, 0.16));+ col = mix(col, srgbToLinear(vec3(0.95, 0.75, 0.30)), fillAA(d, px));+ return mix(col, srgbToLinear(vec3(0.55, 0.20, 0.10)), fillAA(stripe, px));+}++vec3 organicCells(vec2 p) {+ float s = smoothVoronoi(p * 5.0, 12.0);+ vec3 col = mixOklab(srgbToLinear(vec3(0.95, 0.55, 0.55)), srgbToLinear(vec3(0.35, 0.05, 0.15)), saturate(s * 1.6));+ return col * (0.6 + 0.4 * smoothstep(0.1, 0.5, s));+}++vec3 checker(vec2 p, float px) {+ // perspective floor: the filtered checker stays grey instead of moire in the distance+ float z = 1.0 / max(0.55 - p.y, 0.02);+ vec2 floorUV = vec2(p.x * z, z) * 1.5;+ float c = filteredChecker(floorUV, vec2(px * z * z * 1.5 + px * z * 1.5));+ return mix(vec3(0.05), vec3(0.8), c) * smoothstep(0.55, 0.3, p.y);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec2 uv = fragCoord / iResolution.y;+ float px = 1.0 / iResolution.y;+ float aspect = iResolution.x / iResolution.y;+ vec2 grid = vec2(3.0, 2.0);+ vec2 tileSize = vec2(aspect, 1.0) / grid;+ vec2 id = floor(uv / tileSize);+ vec2 local = (uv - id * tileSize) / tileSize.y; // 0..(tile aspect) x 0..1+ vec2 p = local - 0.5 * vec2(tileSize.x / tileSize.y, 1.0);+ float k = id.x + 3.0 * (1.0 - id.y);+ float lpx = px / tileSize.y;++ vec3 col;+ if (k < 0.5) col = marble(p + 0.05 * iTime);+ else if (k < 1.5) col = crackedEarth(p, lpx);+ else if (k < 2.5) col = hexTiles(p, lpx);+ else if (k < 3.5) col = truchet(p, lpx);+ else if (k < 4.5) col = organicCells(p + vec2(0.0, 0.03 * iTime));+ else col = checker(p, lpx);++ // tile frame+ vec2 e = min(local, vec2(tileSize.x / tileSize.y, 1.0) - local);+ col *= smoothstep(0.0, 0.02, min(e.x, e.y));++#if DEBUG_MODE == 3+ col = debugIdColor(k);+#endif+ fragColor = vec4(linearToSrgb(col) + ditherTPDF(fragCoord, iFrame), 1.0);+}diff --git a/skills/shader-art-coding/templates/raymarch-sdf.glsl b/skills/shader-art-coding/templates/raymarch-sdf.glslnew file mode 100644index 0000000..474b146--- /dev/null+++ b/skills/shader-art-coding/templates/raymarch-sdf.glsl@@ -0,0 +1,138 @@+// Studio still life: a smooth-blended sculpture on a plinth, with a gold ring.+// Shows: SDF modeling (smooth union whose blend weight also blends color), PBR key light with soft shadows,+// sky fill + bounce with AO, sky reflections, ray-footprint filtering, fog, AgX, supersampling, DEBUG_MODE.+// Paste-ready version: python3 scripts/glsl_tools.py bundle templates/raymarch-sdf.glsl -o scene.glsl+// @render time=1.2++#define DEBUG_MODE 0 // 0 final | 1 distance slice | 2 normals | 3 material ids | 4 steps | 5 shadow/AO/blend | 6 light terms+#define AA 1 // samples per pixel (4-8 for stills)++// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.7, 0.6, -0.4));+const vec3 SUN_COLOR = vec3(3.2, 2.8, 2.3);+const vec3 SKY_FILL = vec3(0.35, 0.45, 0.6);+const vec3 GROUND_FILL = vec3(0.18, 0.15, 0.12);+const float BLEND = 0.25; // smooth-union width: larger = softer, fleshier join+const float EXPOSURE = 1.0;+const float FOCAL = 2.2; // larger = more telephoto++// Material ids: integer part = material, fractional part = blend weight between the two glazes.+const float MAT_FLOOR = 1.0;+const float MAT_PLINTH = 2.0;+const float MAT_GLAZE = 3.0;+const float MAT_GOLD = 4.0;++vec2 map(vec3 p) {+ vec2 res = vec2(p.y, MAT_FLOOR);++ float plinth = sdRoundBox(p - vec3(0.0, 0.3, 0.0), vec3(0.9, 0.3, 0.9), 0.04);+ if (plinth < res.x) res = vec2(plinth, MAT_PLINTH);++ // Sculpture: a rounded block and a ball melted together. sminBlend's weight drives the glaze color.+ vec3 q = p - vec3(0.0, 1.0, 0.0);+ q.xz = rot2(0.6) * q.xz;+ float block = sdRoundBox(q, vec3(0.32, 0.38, 0.32), 0.08);+ float ball = sdSphere(q - vec3(0.16, 0.44, 0.05), 0.3);+ vec2 blob = sminBlend(block, ball, BLEND);+ blob.x = smoothSubtract(blob.x, sdTorus(q - vec3(0.0, -0.08, 0.0), vec2(0.4, 0.05)), 0.04);+ if (blob.x < res.x) res = vec2(blob.x, MAT_GLAZE + 0.99 * blob.y);++ // Gold ring standing on the plinth.+ vec3 r = p - vec3(-0.45, 0.8, -0.5);+ r.yz = rot2(1.25) * r.yz;+ float ring = sdTorus(r, vec2(0.17, 0.035));+ if (ring < res.x) res = vec2(ring, MAT_GOLD);+ return res;+}++// footprint = world-space size of one pixel at the hit, used to filter the floor pattern without derivatives.+void material(float id, vec3 p, float footprint, out vec3 albedo, out float rough, out float metal) {+ float m = floor(id);+ rough = 0.5;+ metal = 0.0;+ if (m == MAT_FLOOR) {+ float checker = filteredChecker(p.xz * 2.0, vec2(footprint * 2.0));+ albedo = mix(vec3(0.30, 0.28, 0.26), vec3(0.42, 0.40, 0.37), checker);+ rough = 0.7;+ } else if (m == MAT_PLINTH) {+ albedo = vec3(0.55, 0.53, 0.5);+ rough = 0.85;+ } else if (m == MAT_GLAZE) {+ float w = fract(id) / 0.99;+ albedo = mixOklab(srgbToLinear(vec3(0.95, 0.45, 0.25)), srgbToLinear(vec3(0.15, 0.55, 0.6)), w);+ rough = 0.25;+ } else {+ albedo = vec3(1.0, 0.78, 0.34);+ rough = 0.2;+ metal = 1.0;+ }+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ float an = 0.35 * iTime;+ vec3 ro = vec3(3.4 * sin(an), 1.9, -3.4 * cos(an));+ vec3 ta = vec3(0.0, 0.85, 0.0);+ mat3 cam = cameraMatrix(ro, ta, 0.0);+ vec3 rd = cameraRay(cam, uv, FOCAL);++#if DEBUG_MODE == 1+ return debugDistance(map(vec3(uv.x * 1.6, uv.y * 1.6 + 0.9, 0.0)).x); // slice at z = 0+#endif++ vec3 sky = simpleSky(rd, SUN_DIR);+ vec3 hit = raymarch(ro, rd, 0.1, 30.0, 1.0);+#if DEBUG_MODE == 4+ return debugHeat(hit.z / float(RAYMARCH_MAX_STEPS));+#endif+ if (hit.x < 0.0) return sky;++ float t = hit.x;+ vec3 p = ro + rd * t;+ vec3 n = calcNormal(p, 0.0005 * t);+ vec3 v = -rd;+ vec3 albedo;+ float rough, metal;+ material(hit.y, p, t * 2.0 / (iResolution.y * FOCAL), albedo, rough, metal);++ float sha = softShadow(p + n * 0.002, SUN_DIR, 0.01, 8.0, 12.0);+ float ao = calcAO(p, n, 0.15);+ vec3 refl = reflect(rd, n);+ vec3 f0 = mix(vec3(0.04), albedo, metal);++ vec3 key = shadePBR(n, v, SUN_DIR, albedo, rough, metal) * SUN_COLOR * sha;+ vec3 fill = albedo * (1.0 - metal) * hemisphereLight(n, SKY_FILL, GROUND_FILL) * ao;+ vec3 spec = envBRDFApprox(f0, max(dot(n, v), 0.0), rough) * simpleSky(refl, SUN_DIR)+ * ao * smoothstep(-0.1, 0.3, refl.y);+ vec3 bounceDir = normalize(vec3(-SUN_DIR.x, 0.0, -SUN_DIR.z));+ vec3 bounce = albedo * (1.0 - metal) * vec3(0.25, 0.18, 0.12) * clamp(dot(n, bounceDir), 0.0, 1.0) * ao;++#if DEBUG_MODE == 2+ return debugNormal(n);+#elif DEBUG_MODE == 3+ return debugIdColor(floor(hit.y));+#elif DEBUG_MODE == 5+ return vec3(sha, ao, fract(hit.y) / 0.99);+#elif DEBUG_MODE == 6+ return vec3(luminance(key), luminance(fill + bounce), luminance(spec));+#endif++ vec3 col = key + fill + spec + bounce;+ return mix(col, sky, distanceFog(t, 0.02));+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 acc = vec3(0.0);+ for (int i = 0; i < AA; i++) {+ vec3 c = render(fragCoord + (AA > 1 ? aaOffset(i) : vec2(0.0)));+#if DEBUG_MODE == 0+ c = tonemapAgX(c * EXPOSURE); // tonemap per sample so bright edges antialias+#endif+ acc += c;+ }+ vec3 col = acc / float(AA);+#if DEBUG_MODE == 0+ col = linearToSrgb(col) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/skills/shader-art-coding/templates/sdf-2d-poster.glsl b/skills/shader-art-coding/templates/sdf-2d-poster.glslnew file mode 100644index 0000000..bed4655--- /dev/null+++ b/skills/shader-art-coding/templates/sdf-2d-poster.glsl@@ -0,0 +1,76 @@+// Flat-graphic poster: dusk sky, striped sun, layered ridges, foliage and stars, all from 2D distance fields.+// Shows: 2D SDF primitives, antialiasing with a fixed pixel size, Oklab gradients, polar repetition for petals,+// per-cell randomness, layered composition back-to-front, film grain, Neutral tonemap for palette fidelity.+// @render time=3.0++#define DEBUG_MODE 0 // 0 final | 1 distance field of the foliage layer | 5 layer masks++// ---- palette (sRGB picks, decoded to linear before use) ----+const vec3 SKY_TOP = vec3(0.13, 0.10, 0.30);+const vec3 SKY_HORIZON = vec3(0.98, 0.52, 0.36);+const vec3 SUN = vec3(1.0, 0.86, 0.55);+const vec3 RIDGE_FAR = vec3(0.55, 0.30, 0.42);+const vec3 RIDGE_NEAR = vec3(0.20, 0.12, 0.26);+const vec3 FOLIAGE = vec3(0.07, 0.05, 0.12);++// Ridge silhouette: y below the line is "inside". Returns an approximate signed distance (good enough for AA).+float ridge(vec2 uv, float base, float amp, float freq, float seed) {+ float h = base + amp * fbm(vec2(uv.x * freq + seed, seed), 5);+ return (uv.y - h) / sqrt(1.0 + 4.0 * amp * amp * freq * freq); // divide by an approximate slope bound+}++// A palm-like plant: a curved trunk plus a fan of vesica leaves around its crown.+float plant(vec2 p) {+ float trunk = sdQuadraticBezier(p, vec2(0.0, -1.0), vec2(0.12, -0.45), vec2(0.02, 0.0)) - 0.025;+ vec2 q = p - vec2(0.02, 0.0);+ q = domPolar(q, 9.0); // 9 leaves, each pointing along +X in its sector+ q.y += 0.06 * q.x * q.x; // droop+ float leaf = sdVesica((q - vec2(0.24, 0.0)).yx, 0.32, 0.27);+ return min(trunk, leaf);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ float px = 2.0 / iResolution.y;++ // sky: perceptual gradient+ vec3 col = mixOklab(srgbToLinear(SKY_HORIZON), srgbToLinear(SKY_TOP), smoothstep(-0.3, 1.0, uv.y));++ // stars: one random star per grid cell, fading toward the horizon+ vec2 cell = floor(uv * 18.0);+ vec3 rnd = hash32(cell);+ float star = sdCircle(uv * 18.0 - cell - 0.2 - 0.6 * rnd.xy, 0.02 + 0.05 * rnd.z * rnd.z) / 18.0;+ float twinkle = 0.6 + 0.4 * sin(iTime * (1.0 + 3.0 * rnd.z) + 6.0 * rnd.x);+ col += vec3(1.0, 0.95, 0.9) * fillAA(star, px) * smoothstep(0.1, 0.8, uv.y) * twinkle;++ // sun with retro gaps that thicken toward its bottom edge+ vec2 sp = uv - vec2(0.42, 0.18);+ float sun = sdCircle(sp, 0.36);+ float gaps = filteredStripes(sp.y * 14.0 + 0.5, px * 14.0);+ float gapMask = mix(1.0, gaps, smoothstep(0.0, -0.3, sp.y)) ;+ col = mix(col, srgbToLinear(SUN) * 1.6, fillAA(sun, px) * gapMask);+ col += srgbToLinear(SUN) * 0.25 * exp(-6.0 * max(sun, 0.0)); // glow++ // ridges, back to front+ col = mix(col, srgbToLinear(RIDGE_FAR), fillAA(ridge(uv, -0.1, 0.18, 1.2, 3.0), px));+ col = mix(col, mixOklab(srgbToLinear(RIDGE_FAR), srgbToLinear(RIDGE_NEAR), 0.6),+ fillAA(ridge(uv, -0.32, 0.14, 1.8, 11.0), px));+ col = mix(col, srgbToLinear(RIDGE_NEAR), fillAA(ridge(uv, -0.55, 0.10, 2.6, 23.0), px));++ // foreground plants+ float plants = min(plant((uv - vec2(-0.95, 0.15)) / 0.9) * 0.9, plant((uv - vec2(1.25, -0.05)) * vec2(-1.0, 1.0) / 0.7) * 0.7);+ col = mix(col, srgbToLinear(FOLIAGE), fillAA(plants, px));++#if DEBUG_MODE == 1+ fragColor = vec4(debugDistance(plants), 1.0);+ return;+#elif DEBUG_MODE == 5+ fragColor = vec4(fillAA(sun, px), fillAA(ridge(uv, -0.1, 0.18, 1.2, 3.0), px), fillAA(plants, px), 1.0);+ return;+#endif++ // finish: grain in linear, palette-faithful tonemap, encode, dither+ col = filmGrain(col, 0.04, hash13(vec3(fragCoord, iFrame)) * 2.0 - 1.0);+ col = linearToSrgb(tonemapNeutral(col)) + ditherTPDF(fragCoord, iFrame);+ fragColor = vec4(col, 1.0);+}diff --git a/skills/shader-art-coding/templates/terrain.glsl b/skills/shader-art-coding/templates/terrain.glslnew file mode 100644index 0000000..809587d--- /dev/null+++ b/skills/shader-art-coding/templates/terrain.glsl@@ -0,0 +1,106 @@+// Eroded mountains at golden hour under a physically based sky.+// Shows: derivative-damped fBm terrain, heightfield marching as a scaled bound, slope/altitude material masks,+// soft terrain shadows, single-scattering atmosphere (Rayleigh/Mie/ozone), aerial perspective, sun disk, AgX.+// Units are kilometers so the atmosphere constants apply directly.+// @render time=0.0++#define DEBUG_MODE 0 // 0 final | 1 height map | 2 normals | 3 material masks | 4 steps | 5 shadow | 6 light terms++// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.85, 0.2, -0.45));+const float SUN_INTENSITY = 20.0;+const float TERRAIN_SCALE = 0.32; // horizontal frequency: smaller = broader mountains+const float TERRAIN_HEIGHT = 2.0; // vertical scale in km+const float SNOW_LINE = 1.05; // km+const float EXPOSURE = 1.4;+const float FOCAL = 1.8;++float terrainHeight(vec2 xz) { return TERRAIN_HEIGHT * erodedFbm(xz * TERRAIN_SCALE, 9); }++vec2 map(vec3 p) {+ // p.y - h(xz) is not a distance on slopes. Scaling by 0.45 keeps the march safe for slopes up to about 63 degrees.+ return vec2(0.45 * (p.y - terrainHeight(p.xz)), 1.0);+}++// Transmittance from a point at heightKm toward dir, through the atmosphere (colors the sunlight).+vec3 sunTransmittance(float heightKm, vec3 dir) {+ vec3 ro = vec3(0.0, ATMOSPHERE_GROUND_KM + heightKm, 0.0);+ if (iSphere(ro, dir, vec3(0.0), ATMOSPHERE_GROUND_KM).x > 0.0) return vec3(0.0);+ float tl = iSphere(ro, dir, vec3(0.0), ATMOSPHERE_TOP_KM).y;+ vec3 depth = vec3(0.0);+ for (int i = 0; i < 12; i++) {+ vec3 q = ro + dir * ((float(i) + 0.5) * tl / 12.0);+ depth += atmosphereExtinction(atmosphereDensity(length(q) - ATMOSPHERE_GROUND_KM)) * tl / 12.0;+ }+ return exp(-depth);+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;++#if DEBUG_MODE == 1+ return vec3(terrainHeight(uv * 8.0) / TERRAIN_HEIGHT * 0.5 + 0.3);+#endif++ vec3 ro = vec3(-3.0 + 0.2 * iTime, 0.0, 4.0 - 0.6 * iTime);+ ro.y = terrainHeight(ro.xz) + 0.9;+ vec3 ta = ro + vec3(0.25, -0.16, -1.0);+ mat3 cam = cameraMatrix(ro, ta, 0.0);+ vec3 rd = cameraRay(cam, uv, FOCAL);++ vec3 sky = atmosphereSky(rd, SUN_DIR, ro.y, SUN_INTENSITY);+ vec3 sunColor = SUN_INTENSITY * 0.12 * sunTransmittance(ro.y, SUN_DIR);+ vec3 hit = raymarch(ro, rd, 0.01, 40.0, 1.0);+#if DEBUG_MODE == 4+ return debugHeat(hit.z / float(RAYMARCH_MAX_STEPS));+#endif+ if (hit.x < 0.0) {+ return sky + sunColor * 40.0 * sunDisk(rd, SUN_DIR, 0.012, 2.0 / (iResolution.y * FOCAL));+ }++ float t = hit.x;+ vec3 p = ro + rd * t;+ vec3 n = calcNormal(p, 0.001 * t);++ // material masks: rock on steep slopes, grass on flats, snow on high upward-facing ground+ float flatness = smoothstep(0.72, 0.88, n.y);+ float snow = smoothstep(SNOW_LINE - 0.15, SNOW_LINE + 0.1, p.y + 0.25 * fbm(p.xz * 6.0, 3))+ * smoothstep(0.55, 0.8, n.y);+ float grain = 0.5 + 0.5 * fbm(p.xz * 40.0, 4);+ vec3 rock = mix(vec3(0.10, 0.085, 0.07), vec3(0.20, 0.17, 0.14), grain);+ vec3 grass = mix(vec3(0.06, 0.08, 0.03), vec3(0.11, 0.12, 0.05), grain);+ vec3 albedo = mix(rock, grass, flatness * (1.0 - smoothstep(0.6, 1.0, p.y)));+ albedo = mix(albedo, vec3(0.85, 0.88, 0.92), snow);++ float sha = softShadow(p + n * 0.01, SUN_DIR, 0.02, 20.0, 16.0);+ float NoL = clamp(dot(n, SUN_DIR), 0.0, 1.0);+ vec3 skyAmbient = atmosphereSky(vec3(0.0, 1.0, 0.0), SUN_DIR, p.y, SUN_INTENSITY);+ vec3 key = albedo * sunColor * NoL * sha;+ vec3 fill = albedo * skyAmbient * (0.5 + 0.5 * n.y) * 2.0;+ vec3 bounce = albedo * sunColor * 0.08 * clamp(dot(n, normalize(vec3(-SUN_DIR.x, 0.0, -SUN_DIR.z))), 0.0, 1.0);++#if DEBUG_MODE == 2+ return debugNormal(n);+#elif DEBUG_MODE == 3+ return vec3(1.0 - flatness, flatness, snow);+#elif DEBUG_MODE == 5+ return vec3(sha);+#elif DEBUG_MODE == 6+ return vec3(luminance(key), luminance(fill), luminance(bounce)) * 2.0;+#endif++ vec3 col = key + fill + bounce;+ // aerial perspective: attenuate by the air between camera and hit and fill with sky color. Use the sky at the+ // horizon-clamped direction: below the planet's horizon the sky integral jumps, which would print a seam.+ vec3 fogColor = atmosphereSky(normalize(vec3(rd.x, max(rd.y, 0.02), rd.z)), SUN_DIR, ro.y, SUN_INTENSITY);+ vec3 airT = exp(-t * atmosphereExtinction(atmosphereDensity(0.5 * (ro.y + p.y))) * 4.0);+ return col * airT + fogColor * (1.0 - airT);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 col = render(fragCoord);+#if DEBUG_MODE == 0+ col = linearToSrgb(tonemapAgX(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/skills/shader-art-coding/templates/volumetric-clouds.glsl b/skills/shader-art-coding/templates/volumetric-clouds.glslnew file mode 100644index 0000000..1f0376e--- /dev/null+++ b/skills/shader-art-coding/templates/volumetric-clouds.glsl@@ -0,0 +1,90 @@+// Cumulus cloud layer lit by a low sun, raymarched as a participating medium.+// Shows: coverage-remapped 3D fBm density with a height profile, energy-conserving integration (volumeStep),+// dual-lobe phase for silver linings, Beer-Powder self-shadowing from a short light march, cheap density for+// lighting, jittered start (no banding), sky and sun, AgX.+// @render time=4.0++#define DEBUG_MODE 0 // 0 final | 4 march cost | 5 density / transmittance | 6 light vs ambient++// ---- art controls ----+const vec3 SUN_DIR = normalize(vec3(0.6, 0.25, -0.75));+const vec3 SUN_COLOR = vec3(6.0, 5.2, 4.2);+const float CLOUD_BOTTOM = 1.5;+const float CLOUD_TOP = 3.2;+const float COVERAGE = 0.42; // 0 = clear, 1 = overcast+const float DENSITY = 9.0; // extinction scale: higher = darker, more opaque cores+const float WIND = 0.06;+const float EXPOSURE = 1.0;++// Density in [0, DENSITY]. Use fewer octaves for the light-march samples.+float cloudDensity(vec3 p, int octaves) {+ float h = (p.y - CLOUD_BOTTOM) / (CLOUD_TOP - CLOUD_BOTTOM);+ if (h < 0.0 || h > 1.0) return 0.0;+ float profile = smoothstep(0.0, 0.12, h) * smoothstep(1.0, 0.45, h); // flat-ish bottoms, rounded tops+ vec3 q = p * 0.55 + vec3(iTime * WIND, 0.0, 0.0);+ float n = 0.5 + 0.5 * fbm(q, octaves, 2.02, 0.5);+ float d = saturate((n * profile - (1.0 - COVERAGE)) / COVERAGE);+ return d * DENSITY;+}++vec3 render(vec2 fragCoord) {+ vec2 uv = (2.0 * fragCoord - iResolution.xy) / iResolution.y;+ vec3 ro = vec3(0.0, 0.3, 0.0);+ mat3 cam = cameraMatrix(ro, ro + vec3(0.35, 0.32, -1.0), 0.0);+ vec3 rd = cameraRay(cam, uv, 1.6);++ vec3 sky = simpleSky(rd, SUN_DIR) * 1.2;+ vec3 col = sky + SUN_COLOR * sunDisk(rd, SUN_DIR, 0.03, 2.0 / (iResolution.y * 1.6));+ if (rd.y <= 0.01) return col;++ // clip the march to the cloud slab+ float t0 = (CLOUD_BOTTOM - ro.y) / rd.y;+ float t1 = min((CLOUD_TOP - ro.y) / rd.y, 30.0);+ const int STEPS = 48;+ float dt = (t1 - t0) / float(STEPS);+ float t = t0 + dt * interleavedGradientNoise(floor(fragCoord), iFrame); // jitter hides slicing++ float mu = dot(rd, SUN_DIR);+ float phase = 4.0 * PI * phaseDualHG(mu, 0.75, -0.25, 0.75); // artist units: isotropic scattering = 1+ vec3 radiance = vec3(0.0), transmittance = vec3(1.0);+ float lightAcc = 0.0, ambientAcc = 0.0;+ int steps = 0;+ for (int i = 0; i < STEPS; i++) {+ vec3 p = ro + rd * t;+ float sigma = cloudDensity(p, 5);+ if (sigma > 0.001) {+ // short light march toward the sun with the cheap (3-octave) density+ float depth = 0.0;+ for (int j = 0; j < 5; j++) depth += cloudDensity(p + SUN_DIR * (0.1 + 0.25 * float(j)), 3) * 0.25;+ float h = (p.y - CLOUD_BOTTOM) / (CLOUD_TOP - CLOUD_BOTTOM);+ vec3 sunLight = SUN_COLOR * phase * mix(exp(-depth), beerPowder(depth), 0.5 - 0.5 * mu);+ vec3 ambient = vec3(0.22, 0.28, 0.38) * (0.3 + 0.7 * h);+ volumeStep(radiance, transmittance, vec3(sigma), sigma * (sunLight + ambient), dt);+ lightAcc += luminance(sunLight) * transmittance.x;+ ambientAcc += luminance(ambient) * transmittance.x;+ }+ steps++;+ if (transmittance.x < 0.01) break;+ t += dt;+ }++#if DEBUG_MODE == 4+ return debugHeat(float(steps) / float(STEPS));+#elif DEBUG_MODE == 5+ return vec3(1.0 - transmittance.x, cloudDensity(ro + rd * (t0 + 0.5 * (t1 - t0)), 5) / DENSITY, 0.0);+#elif DEBUG_MODE == 6+ return vec3(lightAcc, ambientAcc, 0.0) * 0.1;+#endif++ // distant clouds fade into the sky+ float fade = exp(-0.04 * max(t0, 0.0));+ return mix(col, col * transmittance + radiance, fade);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec3 col = render(fragCoord);+#if DEBUG_MODE == 0+ col = linearToSrgb(tonemapAgX(col * EXPOSURE)) + ditherTPDF(fragCoord, iFrame);+#endif+ fragColor = vec4(col, 1.0);+}diff --git a/tests/build_gallery.py b/tests/build_gallery.pynew file mode 100644index 0000000..46daf8e--- /dev/null+++ b/tests/build_gallery.py@@ -0,0 +1,41 @@+#!/usr/bin/env python3+"""Write gallery/<template>.glsl: each template bundled with its library dependencies, ready to paste into Shadertoy.++ python3 tests/build_gallery.py regenerate+ python3 tests/build_gallery.py --check fail if any bundle is stale (CI)+"""++from __future__ import annotations++import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "skills" / "shader-art-coding" / "scripts"))++import glsl_tools as gt # noqa: E402+++def main() -> int:+ check = "--check" in sys.argv+ lib = gt.Library()+ out_dir = ROOT / "gallery"+ out_dir.mkdir(exist_ok=True)+ stale = []+ for tpl in sorted(gt.TEMPLATE_DIR.glob("*.glsl")):+ text = gt.bundle_source(lib, tpl.read_text(encoding="utf-8"))+ target = out_dir / tpl.name+ if check:+ if not target.exists() or target.read_text(encoding="utf-8") != text:+ stale.append(target.name)+ else:+ target.write_text(text, encoding="utf-8")+ print(f"wrote gallery/{tpl.name} ({text.count(chr(10))} lines)")+ if stale:+ print("stale gallery bundles (run tests/build_gallery.py):", ", ".join(stale))+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/build_harness.py b/tests/build_harness.pynew file mode 100644index 0000000..e1f5787--- /dev/null+++ b/tests/build_harness.py@@ -0,0 +1,131 @@+#!/usr/bin/env python3+"""Build build/harness.html: a WebGL2 page that+ 1. compiles every unit the skill ships (library modules, reference snippets, templates),+ 2. runs the numerical property tests from tests/properties.py on the GPU,+ 3. renders each template and checks the image (no NaN, not black), optionally saving gallery PNGs.++Run it in a browser with tests/serve.py (local) or tests/run_webgl.py (headless Chromium, CI).+"""++from __future__ import annotations++import json+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "skills" / "shader-art-coding" / "scripts"))+sys.path.insert(0, str(ROOT / "tests"))++import glsl_tools as gt # noqa: E402+import properties as props # noqa: E402++PROP_MAIN = """+void main() {+ uvec4 s = pcg4d(uvec4(uvec2(gl_FragCoord.xy), 7u, 13u));+ uvec4 t = pcg4d(s ^ uvec4(0x9E3779B9u, 0x85EBCA6Bu, 0xC2B2AE35u, 0x27D4EB2Fu));+ int f = runTest(uintToUnit(s), uintToUnit(t));+ st_FragColor = vec4(float(f) / 255.0, 0.0, 0.0, 1.0);+}+"""+++def vec_literal(dim: int, pt: str) -> str:+ return f"vec{dim}({pt})"+++def exactness(lib: gt.Library, expr: str) -> str:+ """'exact' if every tagged function in expr is exact, 'approx' if any is approx, else 'bound'."""+ tagged = [it for name in lib.idents(expr) for it in lib.by_name[name]+ if it.tags.keys() & {"exact", "bound", "approx"}]+ if any("approx" in it.tags for it in tagged):+ return "approx"+ return "exact" if tagged and all("exact" in it.tags for it in tagged) else "bound"+++def sdf_property(lib: gt.Library, name: str, expr: str, dom: float, inside: list[str], outside: list[str],+ extra: dict | None = None, *, dim: int, brute: tuple | None) -> dict:+ T = f"vec{dim}"+ sw = ".xyz" if dim == 3 else ".xy"+ kind = exactness(lib, expr)+ if "domTwist" in expr or "domBend" in expr:+ kind = "bound"+ exact = kind == "exact"+ # approx fields only promise a bound outside the shape+ lip_guard = "dp > 0.0 && dq > 0.0 && " if kind == "approx" else ""+ code = [f"float F({T} p) {{ return {expr}; }}"]+ if brute:+ code.append(f"{T} curvePoint(float t) {{ return {brute[1]}; }}")+ body = [+ f"{T} p = (a{sw} * 2.0 - 1.0) * {dom:.4f};",+ f"{T} dir = normalize(b{sw} * 2.0 - 1.0 + 1e-4);",+ f"float len = {dom:.4f} * exp2(-12.0 * b.w);",+ f"{T} q = p + dir * len;",+ "float dp = F(p), dq = F(q);",+ "int f = 0;",+ "if (isnan(dp) || isinf(dp)) f |= 1;",+ f"if ({lip_guard}abs(dp - dq) > length(q - p) * 1.0005 + 1e-5) f |= 1;",+ ]+ if exact:+ axes = ["vec3(e, 0.0, 0.0)", "vec3(0.0, e, 0.0)", "vec3(0.0, 0.0, e)"] if dim == 3 else \+ ["vec2(e, 0.0)", "vec2(0.0, e)"]+ grad = ", ".join(f"F(p + {a}) - F(p - {a})" for a in axes)+ body += [+ "float e = 1e-3;",+ f"{T} g = {T}({grad}) / (2.0 * e);",+ "float gl = length(g);",+ "if (gl > 1e-3) {",+ f" {T} s = p - dp * g / gl;",+ " if (abs(F(s)) > 0.02 * abs(dp) + 2e-3) f |= 2;",+ "}",+ ]+ for pt in inside:+ body.append(f"if (!(F({vec_literal(dim, pt)}) < 0.0)) f |= 4;")+ for pt in outside:+ body.append(f"if (!(F({vec_literal(dim, pt)}) > 0.0)) f |= 4;")+ if brute:+ body += [+ "float bd = 1e9;",+ "for (int i = 0; i <= 1024; i++) bd = min(bd, length(p - curvePoint(float(i) / 1024.0)));",+ f"if (abs(dp + {brute[2]:.4f} - bd) > 0.004) f |= 8;",+ ]+ body.append("return f;")+ src = "\n".join(code) + "\nint runTest(vec4 a, vec4 b) {\n " + "\n ".join(body) + "\n}\n" + PROP_MAIN+ allow = {"2": props.EXACT_ALLOWANCE} if exact else {}+ allow.update((extra or {}).get("allow", {}))+ return {"name": f"{name} ({kind})", "code": gt.SHADERTOY_PRELUDE + gt.bundle_source(lib, src, keep_docs=False),+ "allow": allow}+++def build(save_gallery: bool = False) -> Path:+ lib = gt.Library()+ units, findings = gt.all_units(lib)+ tests = []+ for spec in props.SDF3:+ tests.append(sdf_property(lib, *spec, dim=3, brute=props.BRUTE.get(spec[0])))+ for spec in props.SDF2:+ tests.append(sdf_property(lib, *spec, dim=2, brute=props.BRUTE.get(spec[0])))+ for name, body, allow in props.PROPERTIES:+ src = f"int runTest(vec4 a, vec4 b) {{{body}\n}}\n" + PROP_MAIN+ tests.append({"name": name, "code": gt.SHADERTOY_PRELUDE + gt.bundle_source(lib, src, keep_docs=False),+ "allow": allow})+ renders = []+ for tpl in sorted(gt.TEMPLATE_DIR.glob("*.glsl")):+ src = tpl.read_text(encoding="utf-8")+ m = re.search(r"//\s*@render\s+time=([\d.]+)", src)+ renders.append({"name": tpl.stem, "time": float(m.group(1)) if m else 2.0,+ "code": gt.SHADERTOY_PRELUDE + gt.bundle_source(lib, src, keep_docs=False) + gt.MAIN_COMPLETE})+ data = {"units": units, "tests": tests, "renders": renders, "save": save_gallery,+ "lint": [str(f) for f in findings]}+ out_dir = ROOT / "build"+ out_dir.mkdir(exist_ok=True)+ html = (ROOT / "tests" / "harness_template.html").read_text(encoding="utf-8")+ out = out_dir / "harness.html"+ out.write_text(html.replace("/*__DATA__*/null", json.dumps(data)), encoding="utf-8")+ return out+++if __name__ == "__main__":+ path = build(save_gallery="--save-gallery" in sys.argv)+ print(f"wrote {path.relative_to(ROOT)}")diff --git a/tests/harness_template.html b/tests/harness_template.htmlnew file mode 100644index 0000000..220d9cc--- /dev/null+++ b/tests/harness_template.html@@ -0,0 +1,154 @@+<!doctype html>+<html>+<head>+<meta charset="utf-8">+<title>shader-skills WebGL2 checks</title>+<style>+ body { font: 12px/1.5 ui-monospace, Menlo, monospace; background: #101114; color: #d7d9de; margin: 16px; }+ h2 { font-size: 13px; margin: 18px 0 6px; color: #fff; }+ .ok { color: #7bd88f; } .bad { color: #ff7a7a; } .warn { color: #ffcf6b; }+ pre { white-space: pre-wrap; margin: 2px 0 8px 18px; color: #ffb38a; }+ .renders { display: flex; flex-wrap: wrap; gap: 12px; }+ .renders figure { margin: 0; } .renders img { width: 320px; border-radius: 4px; display: block; }+ figcaption { color: #9aa0aa; }+</style>+</head>+<body>+<div id="summary">running...</div>+<div id="out"></div>+<script>+const DATA = /*__DATA__*/null;+const out = document.getElementById('out');+const results = { renderer: '', compile: [], tests: [], renders: [], lint: DATA.lint };++function line(cls, text, detail) {+ const d = document.createElement('div'); d.className = cls; d.textContent = text; out.appendChild(d);+ if (detail) { const p = document.createElement('pre'); p.textContent = detail; out.appendChild(p); }+}+function section(t) { const h = document.createElement('h2'); h.textContent = t; out.appendChild(h); }++const canvas = document.createElement('canvas');+const gl = canvas.getContext('webgl2', { preserveDrawingBuffer: true, antialias: false });+const VS = `#version 300 es+in vec2 pos; void main() { gl_Position = vec4(pos, 0.0, 1.0); }`;++function shader(type, src) {+ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);+ return { s, ok: gl.getShaderParameter(s, gl.COMPILE_STATUS), log: gl.getShaderInfoLog(s) || '' };+}+let vs, quad;+function program(fsSrc) {+ const fs = shader(gl.FRAGMENT_SHADER, fsSrc);+ if (!fs.ok) return { ok: false, log: fs.log };+ const p = gl.createProgram(); gl.attachShader(p, vs.s); gl.attachShader(p, fs.s);+ gl.bindAttribLocation(p, 0, 'pos'); gl.linkProgram(p);+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) return { ok: false, log: gl.getProgramInfoLog(p) };+ return { ok: true, p };+}+function target(w, h, float) {+ const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.texImage2D(gl.TEXTURE_2D, 0, float ? gl.RGBA32F : gl.RGBA8, w, h, 0, gl.RGBA, float ? gl.FLOAT : gl.UNSIGNED_BYTE, null);+ const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb);+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);+ return { fb, tex };+}+function draw(p, w, h, uniforms) {+ gl.useProgram(p); gl.viewport(0, 0, w, h);+ for (const [k, v] of Object.entries(uniforms || {})) {+ const loc = gl.getUniformLocation(p, k); if (!loc) continue;+ if (k === 'iFrame') gl.uniform1i(loc, v);+ else if (Array.isArray(v)) gl['uniform' + v.length + 'f'](loc, ...v); else gl.uniform1f(loc, v);+ }+ gl.drawArrays(gl.TRIANGLES, 0, 3);+}+const sleep = () => new Promise(r => setTimeout(r, 0));++async function main() {+ if (!gl) { document.getElementById('summary').textContent = 'WebGL2 unavailable'; results.fatal = 'no webgl2'; return finish(); }+ const dbg = gl.getExtension('WEBGL_debug_renderer_info');+ results.renderer = dbg ? gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);+ const floatOK = !!gl.getExtension('EXT_color_buffer_float');+ vs = shader(gl.VERTEX_SHADER, VS);+ quad = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, quad);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);+ gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);++ section('Compile (' + Object.keys(DATA.units).length + ' units)');+ for (const [where, src] of Object.entries(DATA.units)) {+ const r = shader(gl.FRAGMENT_SHADER, src);+ results.compile.push({ where, ok: r.ok, log: r.ok ? '' : r.log });+ if (!r.ok) line('bad', 'FAIL ' + where, r.log);+ await sleep();+ }+ const compileFails = results.compile.filter(r => !r.ok).length;+ line(compileFails ? 'bad' : 'ok', `${results.compile.length - compileFails}/${results.compile.length} compiled`);++ section('Property tests (' + DATA.tests.length + ', 16384 samples each)');+ const N = 128; const tgt = target(N, N, false); const px = new Uint8Array(N * N * 4);+ for (const t of DATA.tests) {+ const pr = program(t.code);+ if (!pr.ok) { results.tests.push({ name: t.name, ok: false, error: pr.log }); line('bad', 'COMPILE ' + t.name, pr.log); continue; }+ gl.bindFramebuffer(gl.FRAMEBUFFER, tgt.fb); draw(pr.p, N, N, { iResolution: [N, N, 1], iFrame: 0 });+ gl.readPixels(0, 0, N, N, gl.RGBA, gl.UNSIGNED_BYTE, px);+ const counts = {};+ for (let i = 0; i < px.length; i += 4) for (let bit = 1; bit <= 128; bit <<= 1) if (px[i] & bit) counts[bit] = (counts[bit] || 0) + 1;+ const rates = {}; let ok = true; const notes = [];+ for (const [bit, c] of Object.entries(counts)) {+ const rate = c / (N * N); rates[bit] = rate;+ const allowed = (t.allow && t.allow[bit]) || 0;+ if (rate > allowed) { ok = false; notes.push(`bit ${bit}: ${(rate * 100).toFixed(3)}% > ${(allowed * 100).toFixed(2)}%`); }+ else notes.push(`bit ${bit}: ${(rate * 100).toFixed(3)}% (allowed)`);+ }+ results.tests.push({ name: t.name, ok, rates });+ line(ok ? 'ok' : 'bad', (ok ? 'PASS ' : 'FAIL ') + t.name + (notes.length ? ' [' + notes.join(', ') + ']' : ''));+ await sleep();+ }++ section('Renders (' + DATA.renders.length + ')');+ const div = document.createElement('div'); div.className = 'renders'; out.appendChild(div);+ const params = new URLSearchParams(location.search);+ const W = +(params.get('w') || 640), H = +(params.get('h') || 360);+ for (const r of DATA.renders) {+ const pr = program(r.code);+ if (!pr.ok) { results.renders.push({ name: r.name, ok: false, error: pr.log }); line('bad', 'COMPILE ' + r.name, pr.log); continue; }+ const t0 = performance.now();+ const ft = target(W, H, floatOK); gl.bindFramebuffer(gl.FRAMEBUFFER, ft.fb);+ draw(pr.p, W, H, { iResolution: [W, H, 1], iTime: r.time, iFrame: 0, iMouse: [0, 0, 0, 0] });+ const data = floatOK ? new Float32Array(W * H * 4) : new Uint8Array(W * H * 4);+ gl.readPixels(0, 0, W, H, gl.RGBA, floatOK ? gl.FLOAT : gl.UNSIGNED_BYTE, data);+ const ms = performance.now() - t0;+ let nan = 0, black = 0, sum = 0, over = 0; const scale = floatOK ? 1 : 1 / 255;+ for (let i = 0; i < data.length; i += 4) {+ const a = data[i] * scale, b = data[i + 1] * scale, c = data[i + 2] * scale;+ if (!isFinite(a) || !isFinite(b) || !isFinite(c)) { nan++; continue; }+ const l = (a + b + c) / 3; sum += l; if (l < 0.004) black++; if (a > 1.001 || b > 1.001 || c > 1.001) over++;+ }+ const n = W * H; const stats = { nanPct: 100 * nan / n, blackPct: 100 * black / n, mean: sum / n, overPct: 100 * over / n, ms };+ const ok = nan === 0 && stats.blackPct < 95 && stats.mean > 0.02;+ // visible PNG+ canvas.width = W; canvas.height = H; gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ draw(pr.p, W, H, { iResolution: [W, H, 1], iTime: r.time, iFrame: 0, iMouse: [0, 0, 0, 0] });+ const url = canvas.toDataURL('image/png');+ const fig = document.createElement('figure'); fig.innerHTML = `<img src="${url}"><figcaption>${r.name} · ${ms.toFixed(0)} ms · mean ${stats.mean.toFixed(3)}</figcaption>`;+ div.appendChild(fig);+ if (DATA.save) await fetch('/save?path=gallery/' + r.name + '.png', { method: 'POST', body: url });+ results.renders.push({ name: r.name, ok, stats });+ line(ok ? 'ok' : 'bad', `${ok ? 'PASS' : 'FAIL'} ${r.name} nan=${stats.nanPct.toFixed(2)}% black=${stats.blackPct.toFixed(1)}% mean=${stats.mean.toFixed(3)} >1=${stats.overPct.toFixed(2)}%`);+ await sleep();+ }+ finish();+}++async function finish() {+ const bad = results.compile.filter(r => !r.ok).length + results.tests.filter(r => !r.ok).length + results.renders.filter(r => !r.ok).length;+ results.failures = bad;+ document.getElementById('summary').innerHTML =+ `<b class="${bad ? 'bad' : 'ok'}">${bad ? bad + ' failure(s)' : 'all checks passed'}</b> · ${results.renderer}`;+ window.RESULTS = results;+ try { await fetch('/results', { method: 'POST', body: JSON.stringify(results) }); } catch (e) {}+ window.DONE = true;+}+main();+</script>+</body>+</html>diff --git a/tests/properties.py b/tests/properties.pynew file mode 100644index 0000000..00c55d3--- /dev/null+++ b/tests/properties.py@@ -0,0 +1,196 @@+"""Numerical property tests for the GLSL library, run on the GPU by the WebGL harness.++Each test becomes a fragment shader. Every pixel draws random inputs a, b (uniform in [0,1)^4) and runs+`int runTest(vec4 a, vec4 b)`, which returns failure bits. The harness counts failures per bit over a+128x128 grid and compares the rate with the test's allowance (default 0).++SDF tests are generated from compact specs. Bits:+ 1 Lipschitz: |f(p) - f(q)| <= |p - q|. Every SDF in the library must satisfy this (safe to march).+ 2 Exactness: projecting p onto the surface along the gradient lands on the zero set. Only @exact SDFs.+ Points on the medial axis legitimately fail, so a small rate is allowed.+ 4 Sign: listed inside points are negative and outside points are positive.+ 8 Brute force: matches a dense sampling of the curve (curves only).+"""++SDF3 = [+ # name, expression of p, domain half-size, inside points, outside points[, {"allow": {bit: rate}}]+ ("sdSphere", "sdSphere(p, 0.7)", 1.5, ["0,0,0", "0.5,0,0"], ["0.8,0,0", "1,1,1"]),+ ("sdBox", "sdBox(p, vec3(0.6, 0.3, 0.4))", 1.5, ["0,0,0", "0.55,0.25,0.35"], ["0.65,0,0", "0,0.35,0"]),+ ("sdRoundBox", "sdRoundBox(p, vec3(0.6, 0.4, 0.5), 0.1)", 1.5, ["0,0,0"], ["0.59,0.39,0.49", "0.7,0,0"]),+ ("sdBoxFrame", "sdBoxFrame(p, vec3(0.6, 0.5, 0.4), 0.05)", 1.5, ["0.58,0.48,0", "0.58,0,0.38"], ["0,0,0", "0.6,0,0"]),+ ("sdTorus", "sdTorus(p, vec2(0.6, 0.2))", 1.5, ["0.6,0,0", "0,0.1,0.6"], ["0,0,0", "0.6,0.25,0"]),+ ("sdCappedTorus", "sdCappedTorus(p, vec2(sin(1.2), cos(1.2)), 0.6, 0.15)", 1.5, ["0,0.6,0", "0.5,0.3,0"], ["0,-0.6,0", "0,0,0"]),+ ("sdLink", "sdLink(p, 0.3, 0.4, 0.1)", 1.5, ["0.4,0,0", "0,0.7,0"], ["0,0,0", "0.4,0,0.15"]),+ ("sdPlane", "sdPlane(p, normalize(vec3(0.3, 1.0, 0.2)), 0.2)", 1.5, ["0,-0.5,0"], ["0,0.5,0"]),+ ("sdCapsule", "sdCapsule(p, vec3(-0.5, -0.2, 0.1), vec3(0.4, 0.5, -0.2), 0.2)", 1.5, ["0,0.15,0", "-0.5,-0.2,0.1"], ["0,-0.5,0", "0.6,0.7,-0.2"]),+ ("sdVerticalCapsule", "sdVerticalCapsule(p, 0.8, 0.25)", 1.5, ["0,0.4,0", "0,-0.2,0"], ["0,1.1,0", "0.3,0.4,0"]),+ ("sdCylinder", "sdCylinder(p, 0.5, 0.4)", 1.5, ["0,0,0", "0.35,0.45,0"], ["0,0.55,0", "0.45,0,0"]),+ ("sdCappedCone", "sdCappedCone(p, 0.6, 0.6, 0.2)", 1.5, ["0,0,0", "0.5,-0.55,0", "0.15,0.55,0"], ["0,-0.65,0", "0,-1.2,0", "0.35,0.55,0", "0,0.65,0"]),+ ("sdCone", "sdCone(p, 1.2, 0.4)", 1.5, ["0,0.1,0", "0.3,0.05,0", "0,1.1,0"], ["0,-0.05,0", "0,-1.4,0", "0.1,-0.5,0", "0.35,0.5,0", "0,1.25,0"]),+ ("sdCone flat", "sdCone(p, 0.3, 1.2)", 1.5, ["0,0.1,0", "1.0,0.02,0"], ["0,-0.05,0", "0,0.35,0", "1.0,0.2,0"]),+ ("sdRoundCone", "sdRoundCone(p, 0.4, 0.15, 0.8)", 1.5, ["0,0,0", "0,0.8,0"], ["0,-0.45,0", "0,1.0,0", "0.4,0.4,0"]),+ ("sdEllipsoid", "sdEllipsoid(p, vec3(0.7, 0.35, 0.5))", 1.5, ["0,0,0", "0.6,0,0"], ["0.75,0,0", "0,0.4,0"]),+ ("sdCutHollowSphere", "sdCutHollowSphere(p, 0.6, 0.2, 0.05)", 1.5, ["0,-0.6,0", "0.6,0,0"], ["0,0,0", "0,0.6,0"]),+ ("sdHexPrism", "sdHexPrism(p, vec2(0.5, 0.3))", 1.5, ["0,0,0", "0,0.45,0.25"], ["0,0.55,0", "0,0,0.35"]),+ ("sdOctahedron", "sdOctahedron(p, 0.7)", 1.5, ["0,0,0", "0.6,0,0"], ["0.75,0,0", "0.3,0.3,0.3"]),+ ("sdGyroid", "sdGyroid(p, 6.0, 0.03)", 1.5, [], []),+ ("sdCutSphere", "sdCutSphere(p, 0.6, 0.2)", 1.5, ["0,0.4,0", "0.3,0.25,0"], ["0,0,0", "0,0.65,0", "0,-0.5,0"]),+ ("sdDeathStar", "sdDeathStar(p, 0.6, 0.45, 0.55)", 1.5, ["-0.4,0,0"], ["0.4,0,0", "0,0,0.7"]),+ ("sdQuadraticBezier 3D", "sdQuadraticBezier(p, vec3(-0.6, -0.3, 0.1), vec3(0.0, 0.9, -0.3), vec3(0.6, -0.2, 0.2)) - 0.1", 1.5, ["-0.6,-0.3,0.1"], ["0,-0.8,0"]),+ # operators and domain transforms on top of exact primitives+ ("smin", "smin(sdSphere(p - vec3(0.3, 0, 0), 0.4), sdBox(p + vec3(0.3, 0, 0), vec3(0.3)), 0.2)", 1.5, ["0,0,0"], ["0,0.6,0"]),+ ("sminCubic", "sminCubic(sdSphere(p - vec3(0.3, 0, 0), 0.4), sdSphere(p + vec3(0.3, 0, 0), 0.4), 0.2)", 1.5, ["0,0,0"], ["0,0.6,0"]),+ ("smoothSubtract", "smoothSubtract(sdBox(p, vec3(0.5)), sdSphere(p - vec3(0.5), 0.4), 0.1)", 1.5, ["-0.3,-0.3,-0.3"], ["0.45,0.45,0.45"]),+ ("opChamferUnion", "opChamferUnion(sdBox(p, vec3(0.5, 0.2, 0.5)), sdBox(p, vec3(0.2, 0.6, 0.2)), 0.1)", 1.5, ["0,0,0"], ["0.4,0.4,0"]),+ ("opStairsUnion", "opStairsUnion(sdBox(p, vec3(0.6, 0.1, 0.6)), sdBox(p, vec3(0.15, 0.6, 0.15)), 0.3, 4.0)", 1.5, ["0,0,0"], ["0.5,0.5,0"]),+ ("opEngrave", "opEngrave(sdBox(p, vec3(0.5)), sdPlane(p, vec3(1, 0, 0), 0.0), 0.05)", 1.5, ["0.3,0,0"], ["0,0,0.52", "0.6,0,0"]),+ ("opOnion", "opOnion(sdSphere(p, 0.6), 0.05)", 1.5, ["0.6,0,0"], ["0,0,0"]),+ ("opExtrude", "opExtrude(p, sdStar(p.xy, 0.6, 5, 2.5), 0.2)", 1.5, ["0,0,0"], ["0,0,0.3"]),+ ("opRevolve", "sdBox(opRevolve(p, 0.5), vec2(0.15, 0.3))", 1.5, ["0.5,0,0"], ["0,0,0", "0.5,0.35,0"]),+ ("opElongate", "sdSphere(opElongate(p, vec3(0.4, 0.0, 0.1)).xyz, 0.3) + opElongate(p, vec3(0.4, 0.0, 0.1)).w", 1.5, ["0,0,0", "0.6,0,0"], ["0.75,0,0", "0,0.35,0"]),+ ("domRepeat", "sdSphere(vec3(domRepeat(p.xz, vec2(0.5)), p.y).xzy, 0.15)", 1.5, ["0.5,0,0.5"], ["0.25,0,0.25"]),+ ("domPolar", "sdBox(vec3(domPolar(p.xz, 7.0) - vec2(0.6, 0.0), p.y).xzy, vec3(0.1, 0.3, 0.05))", 1.5, ["0.6,0,0"], ["0,0,0"]),+ ("domFold", "sdSphere(domFold(p, normalize(vec3(1, 1, 0))) - vec3(0.4, 0, 0), 0.2)", 1.5, ["0.4,0,0", "0,-0.4,0"], ["-0.4,0,0", "0,0.4,0"]),+ ("domTwist (scaled)", "sdBox(domTwist(p, 1.5), vec3(0.3, 0.6, 0.15)) / (0.75 * 0.335 / 1.0 + sqrt(1.0 + 0.25 * 0.5025 * 0.5025))", 1.5, ["0,0,0"], ["0,0.7,0"]),+]++SDF2 = [+ ("sdCircle", "sdCircle(p, 0.6)", 1.2, ["0,0"], ["0.7,0"]),+ ("sdBox 2D", "sdBox(p, vec2(0.6, 0.3))", 1.2, ["0,0", "0.55,0.25"], ["0.65,0", "0,0.35"]),+ ("sdRoundedBox", "sdRoundedBox(p, vec2(0.6, 0.4), vec4(0.1, 0.3, 0.0, 0.2))", 1.2, ["0,0"], ["0.65,0", "-0.59,-0.39"]),+ ("sdSegment", "sdSegment(p, vec2(-0.5, -0.2), vec2(0.4, 0.5)) - 0.1", 1.2, ["0,0.15"], ["0,-0.5"]),+ ("sdUnevenCapsule", "sdUnevenCapsule(p, 0.3, 0.1, 0.7)", 1.2, ["0,0", "0,0.7"], ["0,-0.35", "0,0.85", "0.3,0.5"]),+ ("sdArc", "sdArc(p, vec2(sin(2.0), cos(2.0)), 0.6, 0.08)", 1.2, ["0,0.6", "0.6,0"], ["0,0", "0,-0.6"]),+ ("sdEquilateralTriangle", "sdEquilateralTriangle(p, 0.6)", 1.2, ["0,0", "0,0.5"], ["0,-0.4", "0,0.8"]),+ ("sdTriangle", "sdTriangle(p, vec2(-0.6, -0.4), vec2(0.7, -0.2), vec2(0.1, 0.6))", 1.2, ["0,0"], ["0,-0.5", "-0.5,0.5"]),+ ("sdTriangle cw", "sdTriangle(p, vec2(0.1, 0.6), vec2(0.7, -0.2), vec2(-0.6, -0.4))", 1.2, ["0,0"], ["0,-0.5"]),+ ("sdRegularPolygon", "sdRegularPolygon(p, 0.6, 6)", 1.2, ["0,0", "0,0.55"], ["0,0.65", "0.6,0"]),+ ("sdStar", "sdStar(p, 0.7, 5, 2.5)", 1.2, ["0,0", "0,0.65"], ["0,0.75", "0,-0.6"]),+ ("sdVesica", "sdVesica(p, 0.8, 0.5)", 1.2, ["0,0", "0,0.55"], ["0.35,0", "0,0.65"]),+ ("sdMoon", "sdMoon(p, 0.3, 0.6, 0.5)", 1.2, ["-0.5,0"], ["0.1,0", "0.7,0"]),+ ("sdHeart", "sdHeart(p + vec2(0.0, 0.5))", 1.2, ["0,0", "0.3,0.2"], ["0,-0.6", "0,0.55"]),+ ("sdRhombus", "sdRhombus(p, vec2(0.6, 0.35))", 1.2, ["0,0", "0.5,0"], ["0.65,0", "0.4,0.25"]),+ ("sdEllipse", "sdEllipse(p, vec2(0.7, 0.35))", 1.2, ["0,0"], ["0.75,0", "0,0.4"]),+ ("sdQuadraticBezier 2D", "sdQuadraticBezier(p, vec2(-0.7, -0.3), vec2(0.0, 0.9), vec2(0.6, -0.4)) - 0.05", 1.2, ["-0.7,-0.3"], ["0,-0.5"],+ {"allow": {"1": 0.001, "2": 0.03}}), # ~1e-4 float noise in the cubic solve+ ("sdQuadraticBezier 2D straight", "sdQuadraticBezier(p, vec2(-0.6, -0.3), vec2(0.0, 0.0), vec2(0.6, 0.3)) - 0.05", 1.2, ["0,0"], ["0,0.3"]),+ ("hexEdgeDistance", "-hexEdgeDistance(hexGrid(p * 3.0).xy) / 3.0", 1.2, [], []),+ ("truchetArcs", "truchetArcs(p * 3.0, 0.1) / 3.0", 1.2, [], []),+]++# Curves checked against brute-force sampling (bit 8): name -> (expr of p, point on curve at parameter t).+BRUTE = {+ "sdQuadraticBezier 2D": ("vec2", "mix(mix(vec2(-0.7, -0.3), vec2(0.0, 0.9), t), mix(vec2(0.0, 0.9), vec2(0.6, -0.4), t), t)", 0.05),+ "sdQuadraticBezier 2D straight": ("vec2", "mix(vec2(-0.6, -0.3), vec2(0.6, 0.3), t)", 0.05),+ "sdQuadraticBezier 3D": ("vec3", "mix(mix(vec3(-0.6, -0.3, 0.1), vec3(0.0, 0.9, -0.3), t), mix(vec3(0.0, 0.9, -0.3), vec3(0.6, -0.2, 0.2), t), t)", 0.1),+}++# Allowed failure rates for the exactness bit (medial-axis noise). Everything else must be 0.+EXACT_ALLOWANCE = 0.01++# Hand-written properties. Each body is the inside of `int runTest(vec4 a, vec4 b)`; return failure bits.+PROPERTIES = [+ ("hash ranges and integer-input semantics", """+ vec2 cell = floor((a.xy - 0.5) * 2e5);+ int f = 0;+ float h = hash12(cell);+ if (!(h >= 0.0 && h < 1.0)) f |= 1;+ if (hash12(cell) != hash12(cell + 0.25)) f |= 2; // fractional part is ignored+ if (hash12(vec2(-0.0, cell.y)) != hash12(vec2(0.0, cell.y))) f |= 4; // -0.0 == 0.0+ vec3 h3 = hash33(vec3(cell, cell.x - cell.y));+ if (any(lessThan(h3, vec3(0.0))) || any(greaterThanEqual(h3, vec3(1.0)))) f |= 1;+ if (hash12(cell) == hash12(cell + vec2(1.0, 0.0)) && hash12(cell) == hash12(cell + vec2(0.0, 1.0))) f |= 8;+ return f;""", {}),+ ("valueNoiseD derivative matches finite difference", """+ vec2 p = (a.xy - 0.5) * 40.0;+ vec3 n = valueNoiseD(p);+ float e = 1e-3;+ vec2 fd = vec2(valueNoise(p + vec2(e, 0.0)) - valueNoise(p - vec2(e, 0.0)),+ valueNoise(p + vec2(0.0, e)) - valueNoise(p - vec2(0.0, e))) / (2.0 * e);+ int f = 0;+ if (length(n.yz - fd) > 0.02 * (1.0 + length(fd))) f |= 1;+ if (n.x < -1e-5 || n.x > 1.0 + 1e-5) f |= 2;+ return f;""", {}),+ ("gradientNoiseD derivative matches finite difference", """+ vec2 p = (a.xy - 0.5) * 40.0;+ vec3 n = gradientNoiseD(p);+ float e = 1e-3;+ vec2 fd = vec2(gradientNoise(p + vec2(e, 0.0)) - gradientNoise(p - vec2(e, 0.0)),+ gradientNoise(p + vec2(0.0, e)) - gradientNoise(p - vec2(0.0, e))) / (2.0 * e);+ int f = 0;+ if (length(n.yz - fd) > 0.02 * (1.0 + length(fd))) f |= 1;+ if (abs(n.x) > 0.75) f |= 2;+ return f;""", {}),+ ("curlNoise is divergence-free", """+ vec2 p = (a.xy - 0.5) * 20.0;+ float e = 1e-3;+ float div = (curlNoise(p + vec2(e, 0.0)).x - curlNoise(p - vec2(e, 0.0)).x+ + curlNoise(p + vec2(0.0, e)).y - curlNoise(p - vec2(0.0, e)).y) / (2.0 * e);+ return abs(div) > 0.05 ? 1 : 0;""", {}),+ ("noise and fbm ranges", """+ vec2 p = (a.xy - 0.5) * 200.0;+ vec3 q = (a.xyz - 0.5) * 50.0;+ int f = 0;+ float v = fbm(p, 6);+ if (isnan(v) || abs(v) > 1.5) f |= 1;+ float g = gradientNoise(q);+ if (isnan(g) || abs(g) > 1.2) f |= 2;+ float vn = valueNoise(q);+ if (vn < -1e-5 || vn > 1.0 + 1e-5) f |= 4;+ float er = erodedFbm(p, 8);+ if (isnan(er) || er < -1.5 || er > 1.5) f |= 8;+ return f;""", {}),+ ("voronoi: F1 <= F2, border distance non-negative", """+ vec2 p = (a.xy - 0.5) * 50.0;+ vec4 v = voronoi(p, 1.0);+ vec3 e = voronoiBorder(p, 1.0);+ int f = 0;+ if (v.x > v.y + 1e-5) f |= 1;+ if (e.x < -1e-4 || e.x > 1.0) f |= 2;+ if (abs(length(e.yz) - v.x) > 1e-3) f |= 4; // both agree on the nearest point+ return f;""", {}),+ ("hexGrid ids are integers and local stays inside the hexagon", """+ vec2 p = (a.xy - 0.5) * 60.0;+ vec4 h = hexGrid(p);+ int f = 0;+ if (any(greaterThan(abs(h.zw - floor(h.zw + 0.5)), vec2(1e-3)))) f |= 1;+ if (hexEdgeDistance(h.xy) < -1e-4) f |= 2;+ return f;""", {}),+ ("smooth unions never exceed min and match it far apart", """+ float x = (a.x - 0.5) * 4.0, y = (a.y - 0.5) * 4.0, k = 0.05 + a.z;+ int f = 0;+ if (smin(x, y, k) > min(x, y) + 1e-6 || sminCubic(x, y, k) > min(x, y) + 1e-6) f |= 1;+ if (abs(x - y) >= k && (abs(smin(x, y, k) - min(x, y)) > 1e-6 || abs(sminCubic(x, y, k) - min(x, y)) > 1e-6)) f |= 2;+ if (min(x, y) - smin(x, y, k) > 0.25 * k + 1e-6) f |= 4;+ if (abs(sminBlend(x, y, k).x - smin(x, y, k)) > 1e-6) f |= 8;+ return f;""", {}),+ ("domain transforms preserve distances", """+ vec2 p = (a.xy - 0.5) * 4.0;+ vec3 q = (b.xyz - 0.5) * 4.0;+ int f = 0;+ if (abs(length(domPolar(p, 7.0)) - length(p)) > 1e-4) f |= 1;+ if (abs(length(domFold(q, normalize(vec3(1.0, 2.0, -1.0)))) - length(q)) > 1e-4) f |= 2;+ if (abs(length(domTwist(q, 2.0)) - length(q)) > 1e-4) f |= 4;+ vec2 r = domRepeat(p, vec2(0.7));+ if (any(greaterThan(abs(r), vec2(0.35 + 1e-4)))) f |= 8;+ return f;""", {}),+ ("intersectors agree with SDFs", """+ vec3 ro = (a.xyz - 0.5) * 6.0;+ vec3 rd = normalize(b.xyz - 0.5 + 1e-4);+ int f = 0;+ vec2 ts = iSphere(ro, rd, vec3(0.2, -0.1, 0.3), 0.8);+ if (ts.x > 0.0 && abs(sdSphere(ro + rd * ts.x - vec3(0.2, -0.1, 0.3), 0.8)) > 1e-3) f |= 1;+ vec2 tb = iBox(ro, rd, vec3(0.7, 0.4, 0.5));+ if (tb.x > 0.0 && abs(sdBox(ro + rd * tb.x, vec3(0.7, 0.4, 0.5))) > 1e-3) f |= 2;+ float tp = iPlane(ro, rd, normalize(vec3(0.2, 1.0, 0.1)), 0.3);+ if (tp > 0.0 && abs(sdPlane(ro + rd * tp, normalize(vec3(0.2, 1.0, 0.1)), 0.3)) > 1e-3) f |= 4;+ return f;""", {}),+ ("cameraMatrix is orthonormal", """+ vec3 ro = (a.xyz - 0.5) * 10.0;+ vec3 ta = ro + normalize(b.xyz - 0.5 + 1e-3) * (0.5 + 5.0 * a.w);+ mat3 m = cameraMatrix(ro, ta, (b.w - 0.5) * 2.0);+ mat3 i = transpose(m) * m;+ int f = 0;+ if (abs(i[0][0] - 1.0) + abs(i[1][1] - 1.0) + abs(i[2][2] - 1.0) + abs(i[0][1]) + abs(i[0][2]) + abs(i[1][2]) > 1e-3) f |= 1;+ return f;""", {"1": 0.002}), # degenerate when looking straight up/down+]diff --git a/tests/run_webgl.py b/tests/run_webgl.pynew file mode 100644index 0000000..34906a7--- /dev/null+++ b/tests/run_webgl.py@@ -0,0 +1,70 @@+#!/usr/bin/env python3+"""Run the WebGL2 harness headless in Chromium (SwiftShader on machines without a GPU) and fail on any error.++ pip install playwright && python3 -m playwright install --with-deps chromium+ python3 tests/run_webgl.py [--save-gallery] [--size 320x180]++Writes build/webgl-results.json. Exit code 0 only if every unit compiles, every property test passes and every+template renders without NaNs or a black frame.+"""++from __future__ import annotations++import json+import sys+import threading+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "tests"))++import build_harness # noqa: E402+import serve # noqa: E402+++def main() -> int:+ save = "--save-gallery" in sys.argv+ size = "320x180"+ if "--size" in sys.argv:+ size = sys.argv[sys.argv.index("--size") + 1]+ width, height = (int(v) for v in size.split("x"))+ build_harness.build(save_gallery=save)++ port = 8799+ server = serve.serve(port)+ threading.Thread(target=server.serve_forever, daemon=True).start()++ from playwright.sync_api import sync_playwright++ with sync_playwright() as pw:+ browser = pw.chromium.launch(args=["--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"])+ page = browser.new_page()+ page.on("console", lambda msg: print("console:", msg.text) if msg.type == "error" else None)+ page.goto(f"http://127.0.0.1:{port}/build/harness.html?w={width}&h={height}")+ page.wait_for_function("window.DONE === true", timeout=20 * 60 * 1000, polling=1000)+ results = page.evaluate("window.RESULTS")+ browser.close()+ server.shutdown()++ (ROOT / "build" / "webgl-results.json").write_text(json.dumps(results, indent=2), encoding="utf-8")+ print(f"renderer: {results.get('renderer')}")+ compile_fail = [c for c in results["compile"] if not c["ok"]]+ test_fail = [t for t in results["tests"] if not t["ok"]]+ render_fail = [r for r in results["renders"] if not r["ok"]]+ print(f"compiled {len(results['compile']) - len(compile_fail)}/{len(results['compile'])} units")+ print(f"property tests {len(results['tests']) - len(test_fail)}/{len(results['tests'])} passed")+ print(f"renders {len(results['renders']) - len(render_fail)}/{len(results['renders'])} passed")+ for c in compile_fail:+ print(f"COMPILE FAIL {c['where']}\n{c['log']}")+ for t in test_fail:+ print(f"TEST FAIL {t['name']}: {t.get('rates') or t.get('error')}")+ for r in render_fail:+ print(f"RENDER FAIL {r['name']}: {r.get('stats') or r.get('error')}")+ if results.get("fatal"):+ print("FATAL:", results["fatal"])+ return 1+ return 1 if (compile_fail or test_fail or render_fail) else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/serve.py b/tests/serve.pynew file mode 100644index 0000000..8c91aeb--- /dev/null+++ b/tests/serve.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Serve the repo for the WebGL harness and accept its uploads.++ python3 tests/build_harness.py [--save-gallery]+ python3 tests/serve.py [port] then open http://127.0.0.1:8765/build/harness.html++POST /results -> build/webgl-results.json+POST /save?path=gallery/NAME.png (body: PNG data URL) -> writes the gallery image+"""++from __future__ import annotations++import base64+import sys+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from urllib.parse import parse_qs, urlparse++ROOT = Path(__file__).resolve().parents[1]+++class Handler(SimpleHTTPRequestHandler):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, directory=str(ROOT), **kwargs)++ def log_message(self, fmt, *args):+ if "POST" in (args[0] if args else ""):+ sys.stderr.write("%s\n" % (fmt % args))++ def do_POST(self):+ url = urlparse(self.path)+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))+ if url.path == "/results":+ target = ROOT / "build" / "webgl-results.json"+ target.parent.mkdir(exist_ok=True)+ target.write_bytes(body)+ elif url.path == "/save":+ rel = parse_qs(url.query).get("path", [""])[0]+ target = (ROOT / rel).resolve()+ if not (target.parent == (ROOT / "gallery").resolve() and target.suffix == ".png"):+ self.send_error(400, "only gallery/*.png")+ return+ payload = body.decode("ascii").split(",", 1)[-1]+ target.write_bytes(base64.b64decode(payload))+ else:+ self.send_error(404)+ return+ self.send_response(204)+ self.end_headers()+++def serve(port: int = 8765) -> ThreadingHTTPServer:+ return ThreadingHTTPServer(("127.0.0.1", port), Handler)+++if __name__ == "__main__":+ port = int(sys.argv[1]) if len(sys.argv) > 1 else 8765+ print(f"serving {ROOT} at http://127.0.0.1:{port}/build/harness.html")+ serve(port).serve_forever()