Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add AgX and Khronos PBR Neutral view transforms and .cube looks (part of #282)

Nguyen Xuan Ancb38d89db596
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 459b421b..57016625 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -46,6 +46,8 @@
"entry:material-layer-shaders": 21400,
"entry:light-linking": 19720,
"entry:cascaded-shadows": 28530,
+ "entry:view-transform-shader": 20650,
+ "entry:view-transform": 2120,
"scene:lit-box": 65870,
"scene:gltf-box": 90150,
"scene:gltf-box+lazy": 93480,
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 0ff57b3c..8caa8ff6 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,5 +1,5 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681)",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681); view transforms and looks (issue #282): one viewTransform line in scene_capabilities, so the result is raised to 17020 (measured 16996)",
"schemaTotalBytes": 191040,
"schemaToolBytes": {
"scene_create": 63450,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 16701,
+ "scene_capabilities": 17020,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/changes/282.md b/changes/282.md
new file mode 100644
index 00000000..e2b3f6ad
--- /dev/null
+++ b/changes/282.md
@@ -0,0 +1 @@
+Add `environment.viewTransform` (`aces`, `agx`, `neutral`) and `.cube` or named looks in the renderer, the recipe and the path tracer, checked against Blender 5.2 on a colour ramp (closes #282, except the two scored reference scenes).
diff --git a/docs/lighting.md b/docs/lighting.md
index f28e8b8f..d55f4d7f 100644
--- a/docs/lighting.md
+++ b/docs/lighting.md
@@ -136,6 +136,10 @@ Options: `count` (1 to 4, default 3), `resolution` (256 to 4096, default 2048),
Recipes reach it through `environment.shadowCascades` (an integer from 1 to 4, or 0 for the single map). Without the field a scene gets three cascades when `shadow.extent` is above 40, because the single map then covers more than 80 m and a texel is 4 cm or wider (`extent / 1024` metres); a scene with the default extent of 3.5 and any scene at or below 40 draws exactly as before. The rule reads only recipe numbers, so a recipe always resolves the same way; set `shadowCascades: 0` to keep the single map on a wide scene. The preview loads the cascade code only for a scene that gets cascades, and rebuilds its renderer when the count changes.
+### View transform and look
+
+`environment.viewTransform` picks the display curve: `aces` (default, contrasty), `agx` (Blender's default, keeps bright saturated colour without clipping; pick it for a lit scene or to compare with Blender) or `neutral` (Khronos PBR Neutral, base colours show as authored; pick it for product shots and brand colours). `environment.look` adds a graded look after the curve: `warm`, `cool`, `contrast` or `faded`. In code, `new Renderer67(canvas, parts, { viewTransform: 'agx', look })` takes a look from `parseCube(text)` (a 3D `.cube` file, up to size 65) in `@codepawlhq/67js/addons/view-transform`; recipes and MCP never take a file path. The curves and the look live in `@codepawlhq/67js/addons/view-transform-shader`, which a recipe loads through `loadAgentSceneModules`; the default curve costs nothing extra. The path tracer takes the same `viewTransform` and `look` options, so a still and its path-traced image match. The look is not applied to Gaussian splats.
+
## Light linking
A light can be limited to some parts, as Blender's receiver collection does. Give a light an `affects` list of part names (and `environment.keyAffects` for the sun) and pass the parts through `applyLightLinks`:
diff --git a/docs/parity.md b/docs/parity.md
index a003da04..a8f93f3c 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -207,7 +207,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Shader Nodes > Color | partial | Color ramp, mix and invert. There is no hue, curves, gamma or blend modes. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Utilities | partial | Maths on numbers and vectors: add, sub, mul, div, min, max, pow, abs, floor, fract, sqrt, clamp and smoothstep. There is no vector maths, mapping, map range or separate and combine nodes. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Group | missing | No node graph. | | #50 |
-| Rendering > Color Management | partial | ACES tone mapping and grading. There is no choice of color space or display. | [effects](../tests/effects.test.js) | |
+| Rendering > Color Management | partial | View transforms `aces` (default), `agx` and `neutral` (Khronos PBR Neutral) in the rasterizer and the path tracer, and `.cube` look LUTs or four named looks; grading as before. Neutral matches Blender 5.2 within 0.01 on a ramp, AgX within 0.09 (the Filament fit used here is about 0.04 lighter in the mid-tones than Blender 5.2). No choice of working color space or display device; no Filmic or Standard. | [view transforms](../tests/view-transform.test.js), [effects](../tests/effects.test.js) | AgX looks and exact Blender AgX curve |
| Rendering > Freestyle | missing | No line rendering. | | |
| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth and object ID passes as PNG files. There are no view layers, no cryptomatte and no lighting passes (diffuse, glossy, shadow). | [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration (to 60 s) and size, and a CPU or NVENC encoder. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 |
diff --git a/package.json b/package.json
index 2ed1dd62..7de43e2d 100644
--- a/package.json
+++ b/package.json
@@ -84,6 +84,8 @@
"./addons/water-reflection": "./build/water-reflection.js",
"./addons/render-passes": "./build/render-passes.js",
"./addons/material-layer-shaders": "./build/material-layer-shaders.js",
+ "./addons/view-transform-shader": "./build/view-transform-shader.js",
+ "./addons/view-transform": "./build/view-transform.js",
"./addons/light-linking": "./build/light-linking.js",
"./addons/cascaded-shadows": "./build/cascaded-shadows.js",
"./addons/gaussian-splats": "./build/gaussian-splats.js",
diff --git a/scripts/blender-view-transform-golden.py b/scripts/blender-view-transform-golden.py
new file mode 100644
index 00000000..039009e9
--- /dev/null
+++ b/scripts/blender-view-transform-golden.py
@@ -0,0 +1,102 @@
+# Writes tests/fixtures/blender/view-transform-golden.json: Blender's AgX and Khronos PBR Neutral view transforms applied
+# to a ramp of linear colours. Each colour is an emissive plane seen by an orthographic camera, so the scene-linear value
+# reaches the view transform unchanged; the render is saved as a 16-bit PNG with the view transform applied and read back.
+# Run it when Blender moves to a new release (through the GPU lock, Cycles runs on the CPU here):
+# blender -b --factory-startup -t 6 --python scripts/blender-view-transform-golden.py
+import json
+import tempfile
+from pathlib import Path
+
+import bpy
+
+OUTPUT_PATH = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "blender" / "view-transform-golden.json"
+PATCH_PIXELS = 16
+VIEW_TRANSFORMS = {"agx": "AgX", "neutral": "Khronos PBR Neutral"}
+GREY_LEVELS = [0.0, 0.002, 0.01, 0.03, 0.09, 0.18, 0.36, 0.5, 0.76, 1.0, 1.5, 2.0, 4.0, 8.0, 16.0]
+COLORS = [
+ [0.8, 0.1, 0.05], [0.05, 0.6, 0.1], [0.05, 0.1, 0.8], [0.9, 0.7, 0.1], [0.1, 0.7, 0.8],
+ [0.6, 0.15, 0.5], [2.0, 0.8, 0.1], [0.2, 4.0, 0.3], [5.0, 0.1, 0.1], [0.5, 0.35, 0.25],
+ [0.04, 0.02, 0.01], [3.0, 3.0, 1.0],
+]
+PATCHES = [[level, level, level] for level in GREY_LEVELS] + COLORS
+
+
+def build_scene():
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ scene.render.engine = "CYCLES"
+ scene.cycles.device = "CPU"
+ scene.cycles.samples = 8
+ scene.cycles.use_denoising = False
+ scene.cycles.filter_width = 0.01
+ scene.render.resolution_x = PATCH_PIXELS * len(PATCHES)
+ scene.render.resolution_y = PATCH_PIXELS
+ scene.render.resolution_percentage = 100
+ scene.render.image_settings.file_format = "PNG"
+ scene.render.image_settings.color_depth = "16"
+ scene.render.image_settings.color_mode = "RGB"
+ scene.display_settings.display_device = "sRGB"
+ world = bpy.data.worlds.new("black")
+ world.use_nodes = True
+ world.node_tree.nodes["Background"].inputs["Color"].default_value = (0, 0, 0, 1)
+ scene.world = world
+ camera_data = bpy.data.cameras.new("camera")
+ camera_data.type = "ORTHO"
+ camera_data.ortho_scale = len(PATCHES)
+ camera = bpy.data.objects.new("camera", camera_data)
+ camera.location = (len(PATCHES) / 2, 0, 5)
+ scene.collection.objects.link(camera)
+ scene.camera = camera
+ for index, color in enumerate(PATCHES):
+ mesh = bpy.data.meshes.new(f"patch{index}")
+ mesh.from_pydata([(-0.5, -0.5, 0), (0.5, -0.5, 0), (0.5, 0.5, 0), (-0.5, 0.5, 0)], [], [(0, 1, 2, 3)])
+ plane = bpy.data.objects.new(f"patch{index}", mesh)
+ plane.location = (index + 0.5, 0, 0)
+ scene.collection.objects.link(plane)
+ material = bpy.data.materials.new(f"patch{index}")
+ material.use_nodes = True
+ nodes = material.node_tree.nodes
+ nodes.clear()
+ emission = nodes.new("ShaderNodeEmission")
+ emission.inputs["Color"].default_value = (color[0], color[1], color[2], 1)
+ emission.inputs["Strength"].default_value = 1.0
+ output = nodes.new("ShaderNodeOutputMaterial")
+ material.node_tree.links.new(emission.outputs["Emission"], output.inputs["Surface"])
+ mesh.materials.append(material)
+ return scene
+
+
+def render_patches(scene, view_transform, directory):
+ scene.view_settings.view_transform = view_transform
+ scene.view_settings.look = "None"
+ scene.view_settings.exposure = 0.0
+ scene.view_settings.gamma = 1.0
+ path = str(Path(directory) / (view_transform.replace(" ", "_") + ".png"))
+ scene.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+ image = bpy.data.images.load(path)
+ image.colorspace_settings.name = "Non-Color"
+ pixels = list(image.pixels)
+ width = image.size[0]
+ results = []
+ for index in range(len(PATCHES)):
+ x = index * PATCH_PIXELS + PATCH_PIXELS // 2
+ y = PATCH_PIXELS // 2
+ offset = (y * width + x) * 4
+ results.append([round(pixels[offset + channel], 6) for channel in range(3)])
+ bpy.data.images.remove(image)
+ return results
+
+
+def main():
+ scene = build_scene()
+ golden = {"blenderVersion": bpy.app.version_string, "displayDevice": "sRGB", "patches": [{"input": color} for color in PATCHES]}
+ with tempfile.TemporaryDirectory() as directory:
+ for name, view_transform in VIEW_TRANSFORMS.items():
+ for patch, encoded in zip(golden["patches"], render_patches(scene, view_transform, directory)):
+ patch[name] = encoded
+ OUTPUT_PATH.write_text(json.dumps(golden, indent=1) + "\n", encoding="utf-8")
+ print("wrote", OUTPUT_PATH, golden["blenderVersion"])
+
+
+main()
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index bc8f6552..9996f1d7 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -69,6 +69,8 @@ Local `environment.pointLights` support 16 world-space sources with inverse-squa
Each light provides `position` and optional `color`, `intensity`, `radius`, `range` and `castShadow`.
`environment.spotLights` (eight) take `position`, `direction`, and optional `angle` (outer half angle in radians, default 0.785), `penumbra` (0 to 1, default 0.15), `color`, `intensity`, `radius`, `range` and `castShadow`. Intensity is candela, the same unit as a point light.
`environment.areaLights` (four) are rectangles with `position`, `direction` (the side that emits), `width`, `height`, optional `up`, `color` and `intensity` (candela seen head on). They cast no shadow.
+`environment.viewTransform` (`aces` default, `agx` for lit scenes and Blender comparisons, `neutral` for product and brand colour) and `environment.look` (`warm`, `cool`, `contrast`, `faded`) set the display curve and a grade; `scene_capabilities.viewTransform` says when to pick each, and a recipe using them needs `loadAgentSceneModules`.
+
`castShadow: true` on a point light uses 6 of the 24 shadow tiles, on a spot light 1. Past 24 the edit is rejected. Shadows reach `range`, or 30 units when `range` is 0. Set `castShadow` on the few lights that show a visible shadow, because each one adds a depth pass. `affects: ['node-id', ...]` on a point, spot or area light, and `environment.keyAffects` for the sun, limit a light to those nodes (a light without it lights every node; an unknown ID is rejected; the bake honours it, the path tracer ignores it and says so). `environment.shadowCascades` (1 to 4, 0 for one map) sharpens a long sun shadow near the camera; it turns on by itself at 3 when `shadow.extent` is above 40, so set it only to choose another count or 0. Details: docs/lighting.md.
`keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.
Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.
diff --git a/src/agent-look.js b/src/agent-look.js
index e5c693df..4218b310 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -4,6 +4,7 @@ import { resolveEffects } from './effects.js';
import { resolveVolumeFog } from './volumetric.js';
import { resolveLiquidOptics } from './renderer.js';
import { createLightingSetupMap, lightingSetupFields } from './lighting-setups.js';
+import { VIEW_TRANSFORM_NAMES, LOOK_NAMES } from './view-transform-names.js';
import { DEFAULT_LIGHTING_SETUP, LIGHTING_SETUP_NAMES, DEFAULT_AMBIENT_OCCLUSION } from './agent-scene-capabilities.js';
// The longest list in a look is the longest light list.
@@ -11,7 +12,7 @@ const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_A
const ENVIRONMENT_FIELDS = [
'world', 'ground', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',
- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections',
+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'viewTransform', 'look',
];
const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];
const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];
@@ -280,6 +281,18 @@ function environmentFrom(input = {}) {
if (input.shadowCascades !== undefined) {
environment.shadowCascades = shadowCascadesFrom(input.shadowCascades);
}
+ if (input.viewTransform !== undefined) {
+ if (!VIEW_TRANSFORM_NAMES.includes(input.viewTransform)) {
+ throw new RangeError(`environment.viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
+ }
+ environment.viewTransform = input.viewTransform;
+ }
+ if (input.look !== undefined && input.look !== null) {
+ if (!LOOK_NAMES.includes(input.look)) {
+ throw new RangeError(`environment.look must be one of ${LOOK_NAMES.join(', ')}.`);
+ }
+ environment.look = input.look;
+ }
if (input.keyAffects !== undefined) {
environment.keyAffects = affectsFrom({ affects: input.keyAffects }, 'environment keyAffects').affects;
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 5b5bcb88..3b891a09 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -1,3 +1,4 @@
+import { VIEW_TRANSFORM_NAMES, LOOK_NAMES } from './view-transform-names.js';
import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';
import {
MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES,
@@ -208,6 +209,10 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),
lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),
shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),
+ viewTransform: Object.freeze({
+ field: 'environment.viewTransform', names: VIEW_TRANSFORM_NAMES, default: 'aces', look: 'environment.look', looks: LOOK_NAMES,
+ choose: 'agx for lit scenes and Blender comparisons, neutral for product and brand colour, aces for contrast; needs loadAgentSceneModules',
+ }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
// Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 7f6a43eb..cb78ef7e 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -21,6 +21,7 @@ const MODULE_LOADERS = {
navigation: () => import('./agent-navigation.js'),
lightLinking: () => import('./light-linking.js'),
cascades: () => import('./cascaded-shadows.js'),
+ viewTransform: () => import('./view-transform-shader.js'),
};
const loadedModules = {};
@@ -49,6 +50,7 @@ const MODULE_MARKERS = {
navigation: [],
lightLinking: ['"affects"', '"keyAffects"'],
cascades: ['"shadowCascades"'],
+ viewTransform: ['"viewTransform":"agx"', '"viewTransform":"neutral"', '"look":"'],
};
/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 3bc1912b..259e1998 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1347,7 +1347,7 @@ export function createAgentScene(input, inputLimits = {}) {
knownKeys(operation, ['type', lookField], 'operation');
const patch = operation[lookField];
// Spot and area lights, cascades and sun links are absent from a recipe until it sets them.
- const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections'] : [];
+ const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections', 'viewTransform', 'look'] : [];
knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);
const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;
const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };
diff --git a/src/path-tracer.js b/src/path-tracer.js
index 968ca817..a31b7547 100644
--- a/src/path-tracer.js
+++ b/src/path-tracer.js
@@ -1,6 +1,8 @@
import { pointLightFalloff } from './ray-query.js';
import { buildTraceScene, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';
import { denoiseRadiance } from './path-tracer-denoise.js';
+import { acesChannel, displayColor } from './view-transform.js';
+import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
import {
buildFrame, createSurface, environmentPdf, environmentRadiance, evaluateSurface, luminance, mirrorWeight, prepareSurface,
roughnessToAlpha, sampleEnvironment, sampleGlass, sampleSurface,
@@ -93,8 +95,11 @@ export function normalizePathTracerOptions(options = {}) {
fireflyClamp: boundedNumber(options, 'fireflyClamp'),
noiseThreshold: boundedNumber(options, 'noiseThreshold'),
denoiser: denoiserNamed(options.denoise ?? true),
+ viewTransform: options.viewTransform ?? 'aces',
+ look: options.look ?? null,
};
result.denoise = result.denoiser !== 'none';
+ if (!VIEW_TRANSFORM_NAMES.includes(result.viewTransform)) throw new RangeError(`Path tracer viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
if (result.width * result.height > MAX_TRACE_PIXELS) throw new RangeError(`A path trace takes at most ${MAX_TRACE_PIXELS} pixels.`);
if (result.width * result.height * result.samples * (result.bounces + 1) > MAX_TRACE_RAY_WORK) throw new RangeError('This path trace would need too much ray work: lower the size, samples or bounces.');
return result;
@@ -781,17 +786,15 @@ function createPathTracer(scene, options) {
// ---- Image ----
-function toneMap(linear) {
- const color = Math.max(linear, 0);
- const mapped = Math.min(1, Math.max(0, (color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14)));
- return mapped ** (1 / 2.2);
-}
-
-/** The display transform of the rasterizer's post pass (filmic curve and gamma 2.2) applied to linear pixels. */
-export function toneMapToRgba8(linear, width, height) {
+/** The display transform of the rasterizer's post pass (view transform, gamma 2.2, optional look) applied to linear pixels. */
+export function toneMapToRgba8(linear, width, height, { viewTransform = 'aces', look = null } = {}) {
const rgba = new Uint8ClampedArray(width * height * 4);
+ const plainCurve = viewTransform === 'aces' && !look;
for (let pixel = 0; pixel < width * height; pixel++) {
- for (let channel = 0; channel < 3; channel++) rgba[pixel * 4 + channel] = Math.round(toneMap(linear[pixel * 3 + channel]) * 255);
+ const color = plainCurve
+ ? [0, 1, 2].map(channel => acesChannel(linear[pixel * 3 + channel]) ** (1 / 2.2))
+ : displayColor([linear[pixel * 3], linear[pixel * 3 + 1], linear[pixel * 3 + 2]], { viewTransform, look });
+ for (let channel = 0; channel < 3; channel++) rgba[pixel * 4 + channel] = Math.round(color[channel] * 255);
rgba[pixel * 4 + 3] = 255;
}
return rgba;
@@ -1002,7 +1005,7 @@ export async function renderPathTracedImage({ parts, environment = {}, camera },
const { samplesTaken, ...denoiseInputs } = buffers;
const linear = options.denoiser === 'wavelet' ? denoiseRadiance({ width, height, ...denoiseInputs }) : buffers.color;
return {
- width, height, linear, rgba: toneMapToRgba8(linear, width, height), features: denoiseInputs,
+ width, height, linear, rgba: toneMapToRgba8(linear, width, height, options), features: denoiseInputs,
report: {
width, height, samples: options.samples, bounces: options.bounces, seed: options.seed, denoised: options.denoiser === 'wavelet',
denoiser: options.denoiser, threads,
diff --git a/src/renderer.js b/src/renderer.js
index 8ec77ca2..5eac886d 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { layerTextureSupport, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, vertexShader, createVertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
+import { layerTextureSupport, viewTransformShader, LIGHT_SHADING_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, vertexShader, createVertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
import { postFragment, createPostFragment, POST_STEPS, skyFragment, bloomFragment } from './post.js';
import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
@@ -440,7 +440,7 @@ function allFinite(values) {
}
export class Renderer67 {
- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full' } = {}) {
+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null } = {}) {
this.canvas = canvas;
this.sceneParts = parts;
// `skyOpenness` from closed-room.js is passed in, which keeps the ray code out of scenes without volume fog.
@@ -477,6 +477,9 @@ export class Renderer67 {
this.diagnostics = [];
this.activeLightDirection = environment.lightDirection ?? [-3, 6, 4];
this.shadowCascades = shadowCascades;
+ this.viewTransform = viewTransform;
+ this.look = look;
+ if ((viewTransform !== 'aces' || look) && !viewTransformShader.apply) throw new Error("viewTransform and look need their shader code: add import '@codepawlhq/67js/addons/view-transform-shader' (a recipe: await loadAgentSceneModules(recipe)).");
this.memoryBudgetMiB = memoryBudgetMiB;
this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));
if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');
@@ -583,10 +586,10 @@ export class Renderer67 {
depth: startProgram(this.context, depthVertexShader, depthFragmentShader),
};
if (!benchmark) {
- pending.post = startProgram(this.context, fullscreenVertex, postFragment);
+ pending.post = startProgram(this.context, fullscreenVertex, this.withViewTransform(postFragment, 'post'));
pending.sky = startProgram(this.context, fullscreenVertex, skyFragment);
pending.bloom = startProgram(this.context, fullscreenVertex, bloomFragment);
- pending.liquid = startProgram(this.context, vertexShader, liquidFragmentShader);
+ pending.liquid = startProgram(this.context, vertexShader, this.withViewTransform(liquidFragmentShader, 'liquid'));
if (environment.map) this.startEnvironmentPrograms();
}
this.finishMainProgram(pending.main);
@@ -634,10 +637,16 @@ export class Renderer67 {
if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);
}
+ // The display curve and look of this renderer, spliced into one of its programs (view-transform-shader.js); the default curve changes nothing.
+ withViewTransform(source, kind) {
+ if (this.viewTransform === 'aces' && !this.look) return source;
+ return viewTransformShader.apply(source, kind, this.viewTransform, Boolean(this.look));
+ }
+
// Compiles the main program with only the shader features that this renderer's parts use, and finds its uniforms.
startMainProgram() {
const benchmark = this.benchmark;
- const fragmentSource = benchmark ? benchmarkFragmentShader : createFragmentShader(this.shaderFeatures);
+ const fragmentSource = benchmark ? benchmarkFragmentShader : this.withViewTransform(createFragmentShader(this.shaderFeatures), 'main');
return startProgram(this.context, benchmark ? benchmarkVertexShader : createVertexShader(this.shaderFeatures), fragmentSource);
}
@@ -1649,7 +1658,7 @@ export class Renderer67 {
if (!map?.showBackground || this.transparent) return false;
const context = this.context;
if (!this.environmentBackgroundProgram) {
- this.environmentBackgroundProgram = compileProgram(context, fullscreenVertex, environmentBackgroundFragment);
+ this.environmentBackgroundProgram = compileProgram(context, fullscreenVertex, this.withViewTransform(environmentBackgroundFragment, 'background'));
const names = ['inverseViewProjection', 'eye', 'backgroundLevel', 'exposure', 'hdrEnabled', 'environmentSpecular', 'environmentRotation', 'environmentIntensity', 'environmentLevelMax'];
this.environmentBackgroundUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.environmentBackgroundProgram, name)]));
}
@@ -1712,7 +1721,7 @@ export class Renderer67 {
const key = steps.join(',');
let variant = this.postVariants.get(key);
if (!variant) {
- variant = { pending: startProgram(this.context, fullscreenVertex, createPostFragment(steps)) };
+ variant = { pending: startProgram(this.context, fullscreenVertex, this.withViewTransform(createPostFragment(steps), 'post')) };
this.postVariants.set(key, variant);
}
if (variant.pending) {
@@ -1744,6 +1753,7 @@ export class Renderer67 {
const fogSky = this.fogSkyVisibility?.(this.sceneParts, volume, context, environment);
const post = this.selectPostProgram(this.postStepsOf(frame, effects, volume, occluded, fogSky));
context.useProgram(post.program);
+ if (this.look) viewTransformShader.bindLook(this, post.program);
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, sourceTexture);
// The fog's glow reads blurred copies of the frame from its mip chain, so a tap is smooth instead of one speckled pixel.
@@ -2222,6 +2232,7 @@ export class Renderer67 {
dispose() {
this.releaseFrameTargets();
this.shadowCascades?.dispose(this.context);
+ viewTransformShader.dispose?.(this);
if (this.localShadowTexture) this.context.deleteTexture(this.localShadowTexture);
if (this.localShadowFramebuffer) this.context.deleteFramebuffer(this.localShadowFramebuffer);
this.batches.forEach((batch) => {
diff --git a/src/shaders.js b/src/shaders.js
index 5ef1c55d..c36dce05 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -1019,6 +1019,9 @@ const registeredFeatureCode = new Map();
// material-layer-shaders.js sets bind(renderer, layerMaps): it binds the textures of material.layerMaps for one batch.
export const layerTextureSupport = {};
+// view-transform-shader.js sets apply(source, kind, viewTransform, hasLook), bindLook(renderer, program) and dispose(renderer).
+export const viewTransformShader = {};
+
/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */
export function registerShaderFeatureCode(feature, slots) {
registeredFeatureCode.set(feature, slots);
diff --git a/src/view-transform-names.js b/src/view-transform-names.js
new file mode 100644
index 00000000..b0a643a6
--- /dev/null
+++ b/src/view-transform-names.js
@@ -0,0 +1,7 @@
+// The names a recipe may use, kept apart from the curves so that validating a recipe does not pull the curves in.
+
+/** Display transforms: aces is the built-in curve and the default. */
+export const VIEW_TRANSFORM_NAMES = Object.freeze(['aces', 'agx', 'neutral']);
+
+/** Looks a recipe can name. They are built in code, so no file path crosses the recipe or the MCP boundary. */
+export const LOOK_NAMES = Object.freeze(['warm', 'cool', 'contrast', 'faded']);
diff --git a/src/view-transform-shader.js b/src/view-transform-shader.js
new file mode 100644
index 00000000..521987b7
--- /dev/null
+++ b/src/view-transform-shader.js
@@ -0,0 +1,112 @@
+import { viewTransformShader } from './shaders.js';
+import { AGX_CONSTANTS, NEUTRAL_CONSTANTS } from './view-transform.js';
+import { VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
+
+// The GLSL of the AgX and Khronos PBR Neutral view transforms and of the look LUT. It lives outside shaders.js so a
+// scene on the default curve never downloads it: the renderer asks for it only when it is given viewTransform: 'agx' or
+// 'neutral', or a look, and importing this module (or loading it through loadAgentSceneModules) registers it.
+// The constants are printed from view-transform.js, which the path tracer and the tests read, so the curves cannot drift.
+// The renderer carries the display curve in four programs (the main fragment, the liquid fragment, the environment
+// background and the HDR post pass). Each holds the ACES fit as one expression, which apply swaps for a call to
+// selectedViewTransform; the look is a 3D texture read at the end of the post pass, on the display-encoded colour.
+
+const ACES_EXPRESSION = 'clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0)';
+const POST_FINISH_LINE = ' float alpha = POST_TRANSPARENT ? coverage : 1.0;';
+const LOOK_TEXTURE_UNIT = 6;
+const LOOK_UNIFORM = 'viewLookTexture';
+
+const glslNumber = value => (Number.isInteger(value) ? value.toFixed(1) : String(value));
+const glslVector = values => `vec3(${values.map(glslNumber).join(', ')})`;
+const glslMatrix = columns => `mat3(${columns.map(glslVector).join(', ')})`;
+
+const AGX_GLSL = `const mat3 agxToRec2020 = ${glslMatrix(AGX_CONSTANTS.toRec2020)};
+const mat3 agxFromRec2020 = ${glslMatrix(AGX_CONSTANTS.fromRec2020)};
+const mat3 agxInset = ${glslMatrix(AGX_CONSTANTS.inset)};
+const mat3 agxOutset = ${glslMatrix(AGX_CONSTANTS.outset)};
+vec3 agxContrast(vec3 x) {
+ vec3 x2 = x * x;
+ vec3 x4 = x2 * x2;
+ return ${glslNumber(AGX_CONSTANTS.contrast[0])} * x4 * x2 + ${glslNumber(AGX_CONSTANTS.contrast[1])} * x4 * x + ${glslNumber(AGX_CONSTANTS.contrast[2])} * x4 + ${glslNumber(AGX_CONSTANTS.contrast[3])} * x2 * x + ${glslNumber(AGX_CONSTANTS.contrast[4])} * x2 + ${glslNumber(AGX_CONSTANTS.contrast[5])} * x + ${glslNumber(AGX_CONSTANTS.contrast[6])};
+}
+vec3 selectedViewTransform(vec3 color) {
+ color = agxInset * (agxToRec2020 * color);
+ color = clamp((log2(max(color, vec3(1e-10))) - ${glslNumber(AGX_CONSTANTS.minimumEv)}) / ${glslNumber(AGX_CONSTANTS.maximumEv - AGX_CONSTANTS.minimumEv)}, 0.0, 1.0);
+ color = pow(max(vec3(0.0), agxOutset * agxContrast(color)), vec3(2.2));
+ return clamp(agxFromRec2020 * color, 0.0, 1.0);
+}`;
+
+const NEUTRAL_GLSL = `vec3 selectedViewTransform(vec3 color) {
+ float lowest = min(color.r, min(color.g, color.b));
+ float offset = lowest < 0.08 ? lowest - 6.25 * lowest * lowest : 0.04;
+ color -= offset;
+ float peak = max(color.r, max(color.g, color.b));
+ if (peak < ${glslNumber(NEUTRAL_CONSTANTS.startCompression)}) return clamp(color, 0.0, 1.0);
+ float distance = ${glslNumber(1 - NEUTRAL_CONSTANTS.startCompression)};
+ float newPeak = 1.0 - distance * distance / (peak + distance - ${glslNumber(NEUTRAL_CONSTANTS.startCompression)});
+ color *= newPeak / peak;
+ float desaturate = 1.0 - 1.0 / (${glslNumber(NEUTRAL_CONSTANTS.desaturation)} * (peak - newPeak) + 1.0);
+ return clamp(mix(color, vec3(newPeak), desaturate), 0.0, 1.0);
+}`;
+
+const LOOK_GLSL = `uniform highp sampler3D ${LOOK_UNIFORM};
+vec3 applyLook(vec3 color) {
+ float size = float(textureSize(${LOOK_UNIFORM}, 0).x);
+ return texture(${LOOK_UNIFORM}, clamp(color, 0.0, 1.0) * ((size - 1.0) / size) + 0.5 / size).rgb;
+}`;
+
+function insertAfterPrecision(source, code) {
+ const marker = 'precision highp float;';
+ if (!source.includes(marker)) throw new Error('A shader that takes a view transform needs a precision statement.');
+ return source.replace(marker, `${marker}\n${code}`);
+}
+
+/** The source of one program with the chosen display curve, and for the post pass the look. */
+function apply(source, kind, viewTransform, hasLook) {
+ if (!VIEW_TRANSFORM_NAMES.includes(viewTransform)) throw new RangeError(`viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
+ let result = source;
+ if (viewTransform !== 'aces') {
+ if (!result.includes(ACES_EXPRESSION)) throw new Error(`The ${kind} shader no longer holds the ACES expression that a view transform replaces.`);
+ result = insertAfterPrecision(result.replaceAll(ACES_EXPRESSION, 'selectedViewTransform(color)'), viewTransform === 'agx' ? AGX_GLSL : NEUTRAL_GLSL);
+ }
+ if (hasLook && kind === 'post') {
+ if (!result.includes(POST_FINISH_LINE)) throw new Error('The post shader no longer holds the line that a look is applied before.');
+ result = insertAfterPrecision(result.replace(POST_FINISH_LINE, ` color = applyLook(color);\n${POST_FINISH_LINE}`), LOOK_GLSL);
+ }
+ return result;
+}
+
+const lookTextures = new WeakMap();
+
+function createLookTexture(context, look) {
+ const { size, data } = look;
+ const bytes = new Uint8Array(size ** 3 * 4);
+ for (let index = 0; index < size ** 3; index++) {
+ for (let channel = 0; channel < 3; channel++) bytes[index * 4 + channel] = Math.round(data[index * 3 + channel] * 255);
+ bytes[index * 4 + 3] = 255;
+ }
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_3D, texture);
+ context.texImage3D(context.TEXTURE_3D, 0, context.RGBA8, size, size, size, 0, context.RGBA, context.UNSIGNED_BYTE, bytes);
+ context.texParameteri(context.TEXTURE_3D, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_3D, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ for (const wrap of [context.TEXTURE_WRAP_S, context.TEXTURE_WRAP_T, context.TEXTURE_WRAP_R]) context.texParameteri(context.TEXTURE_3D, wrap, context.CLAMP_TO_EDGE);
+ return texture;
+}
+
+/** Binds the renderer's look to the post program that was just made current. */
+function bindLook(renderer, program) {
+ const context = renderer.context;
+ if (!lookTextures.has(renderer)) lookTextures.set(renderer, createLookTexture(context, renderer.look));
+ context.activeTexture(context.TEXTURE0 + LOOK_TEXTURE_UNIT);
+ context.bindTexture(context.TEXTURE_3D, lookTextures.get(renderer));
+ context.uniform1i(context.getUniformLocation(program, LOOK_UNIFORM), LOOK_TEXTURE_UNIT);
+}
+
+function dispose(renderer) {
+ if (lookTextures.has(renderer)) renderer.context.deleteTexture(lookTextures.get(renderer));
+ lookTextures.delete(renderer);
+}
+
+Object.assign(viewTransformShader, { apply, bindLook, dispose });
+
+export { apply as applyViewTransformToShader };
diff --git a/src/view-transform.js b/src/view-transform.js
new file mode 100644
index 00000000..5bdf16f8
--- /dev/null
+++ b/src/view-transform.js
@@ -0,0 +1,165 @@
+import { LOOK_NAMES, VIEW_TRANSFORM_NAMES } from './view-transform-names.js';
+
+// Display transforms and look LUTs as plain functions, shared by the path tracer, the tests and the GLSL in
+// view-transform-shader.js (which prints the constants below, so the three cannot drift apart).
+// - aces is the Narkowicz fit the rasterizer has always used, applied per channel.
+// - agx follows Blender's AgX through the Filament port that three.js ships: Rec.2020 inset, log2 between -12.47393 and
+// 4.026069 EV, a polynomial for the default contrast, outset, then a 2.2 power back to linear sRGB.
+// - neutral is the Khronos PBR Neutral tone mapper: base colours below 0.76 pass unchanged.
+// All three take linear sRGB and return linear sRGB in 0 to 1; the caller encodes with a power of 1 / 2.2.
+
+/** Columns of each matrix, as GLSL writes them. */
+export const AGX_CONSTANTS = Object.freeze({
+ toRec2020: [[0.6274, 0.0691, 0.0164], [0.3293, 0.9195, 0.0880], [0.0433, 0.0113, 0.8956]],
+ fromRec2020: [[1.6605, -0.1246, -0.0182], [-0.5876, 1.1329, -0.1006], [-0.0728, -0.0083, 1.1187]],
+ inset: [[0.856627153315983, 0.137318972929847, 0.11189821299995], [0.0951212405381588, 0.761241990602591, 0.0767994186031903], [0.0482516061458583, 0.101439036467562, 0.811302368396859]],
+ outset: [[1.1271005818144368, -0.1413297634984383, -0.14132976349843826], [-0.11060664309660323, 1.157823702216272, -0.11060664309660294], [-0.016493938717834573, -0.016493938717834257, 1.2519364065950405]],
+ minimumEv: -12.47393,
+ maximumEv: 4.026069,
+ contrast: [15.5, -40.14, 31.96, -6.868, 0.4298, 0.1191, -0.00232],
+});
+export const NEUTRAL_CONSTANTS = Object.freeze({ startCompression: 0.8 - 0.04, desaturation: 0.15 });
+
+function multiply(columns, vector) {
+ const result = [0, 0, 0];
+ for (let column = 0; column < 3; column++) {
+ for (let row = 0; row < 3; row++) result[row] += columns[column][row] * vector[column];
+ }
+ return result;
+}
+
+const clampUnit = value => Math.min(1, Math.max(0, value));
+
+/** The rasterizer's ACES fit for one channel. */
+export function acesChannel(value) {
+ const color = Math.max(value, 0);
+ return clampUnit((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14));
+}
+
+function agxContrast(value) {
+ const [sixth, fifth, fourth, third, second, first, zeroth] = AGX_CONSTANTS.contrast;
+ const square = value * value;
+ const quartic = square * square;
+ return sixth * quartic * square + fifth * quartic * value + fourth * quartic + third * square * value + second * square + first * value + zeroth;
+}
+
+export function agxColor(rgb) {
+ const { toRec2020, fromRec2020, inset, outset, minimumEv, maximumEv } = AGX_CONSTANTS;
+ const encoded = multiply(inset, multiply(toRec2020, rgb)).map(channel => {
+ const logged = (Math.log2(Math.max(channel, 1e-10)) - minimumEv) / (maximumEv - minimumEv);
+ return agxContrast(clampUnit(logged));
+ });
+ const linear = multiply(outset, encoded).map(channel => Math.max(0, channel) ** 2.2);
+ return multiply(fromRec2020, linear).map(clampUnit);
+}
+
+export function neutralColor(rgb) {
+ const { startCompression, desaturation } = NEUTRAL_CONSTANTS;
+ const lowest = Math.min(...rgb);
+ const offset = lowest < 0.08 ? lowest - 6.25 * lowest * lowest : 0.04;
+ const shifted = rgb.map(channel => channel - offset);
+ const peak = Math.max(...shifted);
+ if (peak < startCompression) return shifted.map(clampUnit);
+ const distance = 1 - startCompression;
+ const newPeak = 1 - distance * distance / (peak + distance - startCompression);
+ const mix = 1 - 1 / (desaturation * (peak - newPeak) + 1);
+ return shifted.map(channel => clampUnit(channel * newPeak / peak * (1 - mix) + newPeak * mix));
+}
+
+/** Linear sRGB in, display transform out, still linear: the part before the 1 / 2.2 power. */
+export function applyViewTransform(name, rgb) {
+ if (name === 'agx') return agxColor(rgb);
+ if (name === 'neutral') return neutralColor(rgb);
+ if (name === 'aces' || name === undefined) return rgb.map(acesChannel);
+ throw new RangeError(`viewTransform must be one of ${VIEW_TRANSFORM_NAMES.join(', ')}.`);
+}
+
+// ---- Looks ----
+
+export const MAXIMUM_LOOK_SIZE = 65;
+const MAXIMUM_LOOK_TEXT = 16 * 1024 * 1024;
+
+/** A look is { size, data }: size cubed RGB triples in 0 to 1, red varying fastest, applied to display-encoded colour. */
+export function parseCube(text) {
+ if (typeof text !== 'string' || text.length > MAXIMUM_LOOK_TEXT) throw new RangeError('A .cube look must be text of at most 16 MiB.');
+ let size = 0;
+ let domainMinimum = [0, 0, 0];
+ let domainMaximum = [1, 1, 1];
+ const values = [];
+ for (const rawLine of text.split(/\r?\n/)) {
+ const line = rawLine.replace(/#.*/, '').trim();
+ if (line === '' || line.startsWith('TITLE')) continue;
+ const [keyword, ...rest] = line.split(/\s+/);
+ if (keyword === 'LUT_3D_SIZE') size = Number(rest[0]);
+ else if (keyword === 'LUT_1D_SIZE') throw new RangeError('Only 3D .cube looks are supported (LUT_3D_SIZE).');
+ else if (keyword === 'DOMAIN_MIN') domainMinimum = rest.map(Number);
+ else if (keyword === 'DOMAIN_MAX') domainMaximum = rest.map(Number);
+ else if (/^[-+0-9.]/.test(keyword)) values.push(Number(keyword), Number(rest[0]), Number(rest[1]));
+ else throw new RangeError(`Unknown .cube line: ${keyword}`);
+ }
+ if (!Number.isInteger(size) || size < 2 || size > MAXIMUM_LOOK_SIZE) throw new RangeError(`LUT_3D_SIZE must be an integer from 2 to ${MAXIMUM_LOOK_SIZE}.`);
+ if (values.length !== size ** 3 * 3 || values.some(value => !Number.isFinite(value))) throw new RangeError(`A ${size}x${size}x${size} .cube look needs ${size ** 3} finite RGB rows.`);
+ const data = new Float32Array(values.length);
+ for (let index = 0; index < values.length; index++) {
+ const channel = index % 3;
+ const range = domainMaximum[channel] - domainMinimum[channel];
+ data[index] = clampUnit((values[index] - domainMinimum[channel]) / (range || 1));
+ }
+ return { size, data };
+}
+
+function lookFromFunction(size, grade) {
+ const data = new Float32Array(size ** 3 * 3);
+ let offset = 0;
+ for (let blue = 0; blue < size; blue++) {
+ for (let green = 0; green < size; green++) {
+ for (let red = 0; red < size; red++) {
+ data.set(grade([red / (size - 1), green / (size - 1), blue / (size - 1)]).map(clampUnit), offset);
+ offset += 3;
+ }
+ }
+ }
+ return { size, data };
+}
+
+const smooth = value => value * value * (3 - 2 * value);
+const NAMED_LOOK_GRADES = {
+ warm: ([red, green, blue]) => [red * 1.06 + 0.01, green, blue * 0.92],
+ cool: ([red, green, blue]) => [red * 0.93, green, blue * 1.07 + 0.01],
+ contrast: color => color.map(channel => channel * 0.5 + smooth(channel) * 0.5),
+ faded: color => {
+ const gray = color[0] * 0.2126 + color[1] * 0.7152 + color[2] * 0.0722;
+ return color.map(channel => 0.06 + 0.88 * (channel * 0.85 + gray * 0.15));
+ },
+};
+
+/** One of the LOOK_NAMES, as a 17-point look. */
+export function namedLook(name) {
+ if (!LOOK_NAMES.includes(name)) throw new RangeError(`look must be one of ${LOOK_NAMES.join(', ')}.`);
+ return lookFromFunction(17, NAMED_LOOK_GRADES[name]);
+}
+
+/** Trilinear lookup of a display-encoded colour, as the GPU filters the 3D texture. */
+export function sampleLook(look, rgb) {
+ const { size, data } = look;
+ const position = rgb.map(channel => clampUnit(channel) * (size - 1));
+ const base = position.map(value => Math.min(Math.floor(value), size - 2));
+ const result = [0, 0, 0];
+ for (let corner = 0; corner < 8; corner++) {
+ const offsets = [corner & 1, (corner >> 1) & 1, (corner >> 2) & 1];
+ let weight = 1;
+ for (let axis = 0; axis < 3; axis++) {
+ const fraction = position[axis] - base[axis];
+ weight *= offsets[axis] ? fraction : 1 - fraction;
+ }
+ const index = ((base[2] + offsets[2]) * size * size + (base[1] + offsets[1]) * size + base[0] + offsets[0]) * 3;
+ for (let channel = 0; channel < 3; channel++) result[channel] += data[index + channel] * weight;
+ }
+ return result;
+}
+
+/** Linear radiance to the display-encoded colour in 0 to 1 that the rasterizer's frame holds for it. */
+export function displayColor(rgb, { viewTransform = 'aces', look = null } = {}) {
+ const encoded = applyViewTransform(viewTransform, rgb).map(channel => channel ** (1 / 2.2));
+ return look ? sampleLook(look, encoded) : encoded;
+}
diff --git a/tests/fixtures/blender/view-transform-golden.json b/tests/fixtures/blender/view-transform-golden.json
new file mode 100644
index 00000000..f734a842
--- /dev/null
+++ b/tests/fixtures/blender/view-transform-golden.json
@@ -0,0 +1,465 @@
+{
+ "blenderVersion": "5.2.2 LTS",
+ "displayDevice": "sRGB",
+ "patches": [
+ {
+ "input": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "agx": [
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ "neutral": [
+ 0.000305,
+ 0.000305,
+ 0.000305
+ ]
+ },
+ {
+ "input": [
+ 0.002,
+ 0.002,
+ 0.002
+ ],
+ "agx": [
+ 0.010071,
+ 0.010071,
+ 0.010086
+ ],
+ "neutral": [
+ 0.00032,
+ 0.00032,
+ 0.00032
+ ]
+ },
+ {
+ "input": [
+ 0.01,
+ 0.01,
+ 0.01
+ ],
+ "agx": [
+ 0.072496,
+ 0.072496,
+ 0.072511
+ ],
+ "neutral": [
+ 0.008118,
+ 0.008118,
+ 0.008118
+ ]
+ },
+ {
+ "input": [
+ 0.03,
+ 0.03,
+ 0.03
+ ],
+ "agx": [
+ 0.164752,
+ 0.164736,
+ 0.164767
+ ],
+ "neutral": [
+ 0.068116,
+ 0.068116,
+ 0.068116
+ ]
+ },
+ {
+ "input": [
+ 0.09,
+ 0.09,
+ 0.09
+ ],
+ "agx": [
+ 0.320424,
+ 0.320424,
+ 0.320455
+ ],
+ "neutral": [
+ 0.249134,
+ 0.249134,
+ 0.249134
+ ]
+ },
+ {
+ "input": [
+ 0.18,
+ 0.18,
+ 0.18
+ ],
+ "agx": [
+ 0.461326,
+ 0.461326,
+ 0.461372
+ ],
+ "neutral": [
+ 0.411307,
+ 0.411307,
+ 0.411307
+ ]
+ },
+ {
+ "input": [
+ 0.36,
+ 0.36,
+ 0.36
+ ],
+ "agx": [
+ 0.605478,
+ 0.605478,
+ 0.605509
+ ],
+ "neutral": [
+ 0.602579,
+ 0.602579,
+ 0.602579
+ ]
+ },
+ {
+ "input": [
+ 0.5,
+ 0.5,
+ 0.5
+ ],
+ "agx": [
+ 0.665171,
+ 0.665171,
+ 0.665202
+ ],
+ "neutral": [
+ 0.710674,
+ 0.710674,
+ 0.710674
+ ]
+ },
+ {
+ "input": [
+ 0.76,
+ 0.76,
+ 0.76
+ ],
+ "agx": [
+ 0.732464,
+ 0.732464,
+ 0.732494
+ ],
+ "neutral": [
+ 0.863539,
+ 0.863539,
+ 0.863539
+ ]
+ },
+ {
+ "input": [
+ 1.0,
+ 1.0,
+ 1.0
+ ],
+ "agx": [
+ 0.770977,
+ 0.770977,
+ 0.770993
+ ],
+ "neutral": [
+ 0.936385,
+ 0.936385,
+ 0.936385
+ ]
+ },
+ {
+ "input": [
+ 1.5,
+ 1.5,
+ 1.5
+ ],
+ "agx": [
+ 0.820706,
+ 0.820706,
+ 0.820722
+ ],
+ "neutral": [
+ 0.972107,
+ 0.972107,
+ 0.972107
+ ]
+ },
+ {
+ "input": [
+ 2.0,
+ 2.0,
+ 2.0
+ ],
+ "agx": [
+ 0.851804,
+ 0.851804,
+ 0.85182
+ ],
+ "neutral": [
+ 0.981903,
+ 0.981903,
+ 0.981903
+ ]
+ },
+ {
+ "input": [
+ 4.0,
+ 4.0,
+ 4.0
+ ],
+ "agx": [
+ 0.913695,
+ 0.913695,
+ 0.91371
+ ],
+ "neutral": [
+ 0.992523,
+ 0.992523,
+ 0.992523
+ ]
+ },
+ {
+ "input": [
+ 8.0,
+ 8.0,
+ 8.0
+ ],
+ "agx": [
+ 0.961578,
+ 0.961578,
+ 0.961593
+ ],
+ "neutral": [
+ 0.996567,
+ 0.996567,
+ 0.996567
+ ]
+ },
+ {
+ "input": [
+ 16.0,
+ 16.0,
+ 16.0
+ ],
+ "agx": [
+ 0.998566,
+ 0.998566,
+ 0.998566
+ ],
+ "neutral": [
+ 0.998352,
+ 0.998352,
+ 0.998352
+ ]
+ },
+ {
+ "input": [
+ 0.8,
+ 0.1,
+ 0.05
+ ],
+ "agx": [
+ 0.795178,
+ 0.382345,
+ 0.281056
+ ],
+ "neutral": [
+ 0.884611,
+ 0.286183,
+ 0.139422
+ ]
+ },
+ {
+ "input": [
+ 0.05,
+ 0.6,
+ 0.1
+ ],
+ "agx": [
+ 0.393347,
+ 0.689708,
+ 0.390951
+ ],
+ "neutral": [
+ 0.132815,
+ 0.779431,
+ 0.285344
+ ]
+ },
+ {
+ "input": [
+ 0.05,
+ 0.1,
+ 0.8
+ ],
+ "agx": [
+ 0.27187,
+ 0.435019,
+ 0.776699
+ ],
+ "neutral": [
+ 0.139422,
+ 0.286183,
+ 0.884611
+ ]
+ },
+ {
+ "input": [
+ 0.9,
+ 0.7,
+ 0.1
+ ],
+ "agx": [
+ 0.7691,
+ 0.701137,
+ 0.468055
+ ],
+ "neutral": [
+ 0.920134,
+ 0.819226,
+ 0.276738
+ ]
+ },
+ {
+ "input": [
+ 0.1,
+ 0.7,
+ 0.8
+ ],
+ "agx": [
+ 0.514702,
+ 0.720653,
+ 0.745769
+ ],
+ "neutral": [
+ 0.273838,
+ 0.827085,
+ 0.882322
+ ]
+ },
+ {
+ "input": [
+ 0.6,
+ 0.15,
+ 0.5
+ ],
+ "agx": [
+ 0.706157,
+ 0.492714,
+ 0.670161
+ ],
+ "neutral": [
+ 0.775967,
+ 0.367208,
+ 0.710674
+ ]
+ },
+ {
+ "input": [
+ 2.0,
+ 0.8,
+ 0.1
+ ],
+ "agx": [
+ 0.885801,
+ 0.716701,
+ 0.548501
+ ],
+ "neutral": [
+ 0.981903,
+ 0.701595,
+ 0.42594
+ ]
+ },
+ {
+ "input": [
+ 0.2,
+ 4.0,
+ 0.3
+ ],
+ "agx": [
+ 0.751675,
+ 0.91603,
+ 0.719387
+ ],
+ "neutral": [
+ 0.610986,
+ 0.992523,
+ 0.624933
+ ]
+ },
+ {
+ "input": [
+ 5.0,
+ 0.1,
+ 0.1
+ ],
+ "agx": [
+ 0.999725,
+ 0.659159,
+ 0.623575
+ ],
+ "neutral": [
+ 0.994217,
+ 0.647044,
+ 0.647044
+ ]
+ },
+ {
+ "input": [
+ 0.5,
+ 0.35,
+ 0.25
+ ],
+ "agx": [
+ 0.667765,
+ 0.595575,
+ 0.53904
+ ],
+ "neutral": [
+ 0.710674,
+ 0.593149,
+ 0.497337
+ ]
+ },
+ {
+ "input": [
+ 0.04,
+ 0.02,
+ 0.01
+ ],
+ "agx": [
+ 0.192569,
+ 0.12282,
+ 0.06949
+ ],
+ "neutral": [
+ 0.192294,
+ 0.104067,
+ 0.008118
+ ]
+ },
+ {
+ "input": [
+ 3.0,
+ 3.0,
+ 1.0
+ ],
+ "agx": [
+ 0.893126,
+ 0.884184,
+ 0.797375
+ ],
+ "neutral": [
+ 0.989471,
+ 0.989471,
+ 0.715251
+ ]
+ }
+ ]
+}
diff --git a/tests/view-transform.test.js b/tests/view-transform.test.js
new file mode 100644
index 00000000..f6d234ba
--- /dev/null
+++ b/tests/view-transform.test.js
@@ -0,0 +1,134 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { toneMapToRgba8 } from '../src/path-tracer.js';
+import { normalizeAgentLook } from '../src/agent-look.js';
+import { fragmentShader, liquidFragmentShader, viewTransformShader } from '../src/shaders.js';
+import { environmentBackgroundFragment } from '../src/environment.js';
+import { postFragment } from '../src/post.js';
+import {
+ acesChannel, AGX_CONSTANTS, applyViewTransform, displayColor, namedLook, neutralColor, NEUTRAL_CONSTANTS, parseCube, sampleLook,
+} from '../src/view-transform.js';
+import { LOOK_NAMES } from '../src/view-transform-names.js';
+import '../src/view-transform-shader.js';
+
+const golden = JSON.parse(readFileSync(new URL('./fixtures/blender/view-transform-golden.json', import.meta.url), 'utf8'));
+
+// Blender writes sRGB-encoded 16-bit values; the curves return linear values, so both sides meet in sRGB encoding.
+const srgbEncode = value => (value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055);
+
+// Tolerance per channel in sRGB-encoded units (0 to 1), measured on this ramp against Blender 5.2.2: neutral 0.0079 at most
+// (mean 0.0013), as Blender runs the Khronos formula. agx 0.0885 at most (mean 0.025): it is the Filament/three.js port of
+// AgX (a polynomial for the contrast, 4-digit Rec.2020 matrices), and Blender 5.2 is about 0.04 darker in the mid-tones
+// (0.18 maps to 0.461, the port gives 0.501) and more saturated for strong colours (0.8, 0.1, 0.05 is the worst patch).
+// Closing that gap needs Blender's own AgX curve; the bounds stay at the measured error so a regression shows.
+const TOLERANCE = { agx: 0.09, neutral: 0.01 };
+
+for (const name of ['agx', 'neutral']) {
+ test(`${name} matches Blender ${golden.blenderVersion} on the colour ramp within ${TOLERANCE[name]}`, () => {
+ let worst = 0;
+ for (const patch of golden.patches) {
+ const mine = applyViewTransform(name, patch.input).map(srgbEncode);
+ for (let channel = 0; channel < 3; channel++) worst = Math.max(worst, Math.abs(mine[channel] - patch[name][channel]));
+ }
+ assert.ok(worst <= TOLERANCE[name], `${name} differs from Blender by ${worst.toFixed(5)}`);
+ });
+}
+
+test('the ramp covers greys from black to 16 and saturated colours', () => {
+ assert.ok(golden.patches.length >= 25);
+ assert.match(golden.blenderVersion, /^5\.2/);
+});
+
+function acesFromGlsl(source) {
+ const match = source.match(/clamp\(\(color \* \(([\d.]+) \* color \+ ([\d.]+)\)\) \/ \(color \* \(([\d.]+) \* color \+ ([\d.]+)\) \+ ([\d.]+)\), 0\.0, 1\.0\)/);
+ assert.ok(match, 'the shader holds the ACES expression');
+ const [a, b, c, d, e] = match.slice(1).map(Number);
+ return x => Math.min(1, Math.max(0, (x * (a * x + b)) / (x * (c * x + d) + e)));
+}
+
+test('the rasterizer shaders and the path tracer apply the same default curve', () => {
+ for (const source of [fragmentShader, liquidFragmentShader, environmentBackgroundFragment, postFragment]) {
+ const shaderCurve = acesFromGlsl(source);
+ for (const value of [0, 0.01, 0.18, 0.5, 1, 2, 8, 100]) assert.equal(shaderCurve(value), acesChannel(value));
+ }
+ const ramp = new Float32Array([0, 0.18, 1, 4, 0.02, 0.5, 8, 0.3, 0.001]);
+ const pixels = toneMapToRgba8(ramp, 3, 1);
+ for (let index = 0; index < 9; index++) {
+ const channel = index % 3;
+ assert.equal(pixels[Math.floor(index / 3) * 4 + channel], Math.round(acesChannel(ramp[index]) ** (1 / 2.2) * 255));
+ }
+});
+
+test('the GLSL of agx and neutral prints the constants the path tracer uses', () => {
+ const agx = viewTransformShader.apply(fragmentShader, 'main', 'agx', false);
+ const numbers = [...AGX_CONSTANTS.toRec2020, ...AGX_CONSTANTS.fromRec2020, ...AGX_CONSTANTS.inset, ...AGX_CONSTANTS.outset].flat();
+ for (const value of [...numbers, AGX_CONSTANTS.minimumEv, ...AGX_CONSTANTS.contrast]) assert.ok(agx.includes(String(value)) || agx.includes(value.toFixed(1)), `agx GLSL holds ${value}`);
+ const neutral = viewTransformShader.apply(fragmentShader, 'main', 'neutral', false);
+ for (const value of [NEUTRAL_CONSTANTS.startCompression, NEUTRAL_CONSTANTS.desaturation, 1 - NEUTRAL_CONSTANTS.startCompression]) assert.ok(neutral.includes(String(value)), `neutral GLSL holds ${value}`);
+});
+
+test('the display curve is replaced in all four programs, and the look only in the post pass', () => {
+ const sources = { main: fragmentShader, liquid: liquidFragmentShader, background: environmentBackgroundFragment, post: postFragment };
+ for (const [kind, source] of Object.entries(sources)) {
+ for (const name of ['agx', 'neutral']) {
+ const changed = viewTransformShader.apply(source, kind, name, false);
+ assert.ok(!changed.includes('2.51 * color'), `${kind} ${name} drops the ACES fit`);
+ assert.ok(changed.includes('selectedViewTransform(color)'));
+ }
+ assert.equal(viewTransformShader.apply(source, kind, 'aces', true).includes('applyLook'), kind === 'post');
+ }
+ assert.throws(() => viewTransformShader.apply(fragmentShader, 'main', 'filmic', false), /viewTransform must be one of/);
+});
+
+test('neutral leaves base colours below the compression start as authored, minus the 0.04 shadow offset', () => {
+ neutralColor([0.5, 0.3, 0.2]).forEach((value, channel) => assert.ok(Math.abs(value - [0.46, 0.26, 0.16][channel]) < 1e-12));
+ assert.ok(neutralColor([8, 8, 8]).every(value => value <= 1 && value > 0.95));
+});
+
+test('recipes take a view transform and a named look, and refuse anything else', () => {
+ const look = normalizeAgentLook({ environment: { viewTransform: 'agx', look: 'warm' } });
+ assert.equal(look.environment.viewTransform, 'agx');
+ assert.equal(look.environment.look, 'warm');
+ assert.equal(normalizeAgentLook({}).environment.viewTransform, undefined);
+ assert.throws(() => normalizeAgentLook({ environment: { viewTransform: 'filmic' } }), /viewTransform must be one of aces, agx, neutral/);
+ assert.throws(() => normalizeAgentLook({ environment: { look: '../grade.cube' } }), /look must be one of/);
+});
+
+const IDENTITY_CUBE = (size) => {
+ const rows = [];
+ for (let blue = 0; blue < size; blue++) for (let green = 0; green < size; green++) for (let red = 0; red < size; red++) rows.push(`${red / (size - 1)} ${green / (size - 1)} ${blue / (size - 1)}`);
+ return `# identity\nTITLE "identity"\nLUT_3D_SIZE ${size}\n${rows.join('\n')}\n`;
+};
+
+test('a .cube look parses, samples as the identity, and reaches the path tracer image', () => {
+ const identity = parseCube(IDENTITY_CUBE(4));
+ assert.equal(identity.size, 4);
+ for (const color of [[0, 0, 0], [0.2, 0.7, 0.4], [1, 1, 1], [0.33, 0.01, 0.99]]) {
+ sampleLook(identity, color).forEach((value, channel) => assert.ok(Math.abs(value - color[channel]) < 1e-6));
+ }
+ const inverted = parseCube(IDENTITY_CUBE(2).replace(/^[01] [01] [01]$/gm, row => row.split(' ').map(value => 1 - Number(value)).join(' ')));
+ assert.deepEqual(sampleLook(inverted, [0, 0, 0]).map(Math.round), [1, 1, 1]);
+ const linear = new Float32Array([0.18, 0.18, 0.18]);
+ const plain = toneMapToRgba8(linear, 1, 1);
+ assert.deepEqual([...toneMapToRgba8(linear, 1, 1, { look: identity }).slice(0, 3)], [...plain.slice(0, 3)]);
+ assert.notDeepEqual([...toneMapToRgba8(linear, 1, 1, { look: inverted }).slice(0, 3)], [...plain.slice(0, 3)]);
+});
+
+test('cube text is bounded and 1D looks are refused', () => {
+ assert.throws(() => parseCube('LUT_1D_SIZE 4\n0 0 0\n'), /3D/);
+ assert.throws(() => parseCube('LUT_3D_SIZE 2\n0 0 0\n'), /needs 8/);
+ assert.throws(() => parseCube('LUT_3D_SIZE 200\n'), /from 2 to 65/);
+ assert.throws(() => parseCube('MYSTERY 1\n'), /Unknown/);
+});
+
+test('every named look is a 17-point cube that changes a mid grey', () => {
+ for (const name of LOOK_NAMES) {
+ const look = namedLook(name);
+ assert.equal(look.size, 17);
+ const graded = displayColor([0.18, 0.18, 0.18], { look });
+ const plain = displayColor([0.18, 0.18, 0.18]);
+ assert.ok(graded.some((value, channel) => Math.abs(value - plain[channel]) > 0.005), `${name} changes the picture`);
+ }
+ assert.throws(() => namedLook('grade.cube'), /look must be one of/);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index d4ffbb63..7b5b962b 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -51,6 +51,8 @@ export default defineConfig({
'water-reflection': 'src/water-reflection.js',
'render-passes': 'src/render-passes.js',
'material-layer-shaders': 'src/material-layer-shaders.js',
+ 'view-transform-shader': 'src/view-transform-shader.js',
+ 'view-transform': 'src/view-transform.js',
'light-linking': 'src/light-linking.js',
'cascaded-shadows': 'src/cascaded-shadows.js',
'gaussian-splats': 'src/gaussian-splats.js',