Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Merge remote-tracking branch 'origin/main' into HEAD

Nguyen Xuan An956b7918e752
diff --cc CHANGELOG.md
index 90fe25a2,7534a5ad..428475f5
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,8 -2,11 +2,13 @@@
## Unreleased
+- Add material layers: `clearcoat` and `clearcoatRoughness`, `transmission` with `thickness`, `ior`, `attenuationColor` and `attenuationDistance`, `sheenColor` and `sheenRoughness`, and `specular` and `specularColor`. Recipes, the MCP schema, glTF import and export (`KHR_materials_clearcoat`, `transmission`, `volume`, `ior`, `specular`, `sheen`) all take them, each checked at the boundary. Transmission refracts the opaque scene like the `liquid` material. Anisotropy and iridescence are not rendered yet. Import of those two still warns
+- Change the glTF import of the six layer extensions above from accepted-and-ignored to rendered, so `asset.warnings` no longer lists them
+ - Add spot lights (`environment.spotLights`, 8), rectangular area lights (`environment.areaLights`, 4) and shadows for point and spot lights (`castShadow: true`). Intensity of a spot light is candela, as for a point light, with Blender's cone mask. Area lights use a representative point, within 1.2 percent of Cycles on the axis. Shadows share one 2048 x 3072 depth atlas of 24 tiles (24 MiB, allocated on first use): a point light takes 6 and a spot light 1, and a request for more is an error. The shader code and the atlas exist only in a scene that uses them. Recipes get all of it through `set-environment`, the MCP schema and `scene_capabilities` (`maxSpotLights`, `maxAreaLights`, `localShadows`). Cascaded directional shadows and light linking are not part of this
+
+ - Add ten cutting and repair edits: `fill_holes`, `dissolve_faces`, `dissolve_edges`, `dissolve_verts`, `dissolve_limited`, `bisect_plane` (with `fill`, `clearInner`, `clearOuter`), `bridge_edge_loops` (with `segments`), `subdivide_edges`, `grid_fill` and `knife_project`. Each tags what it makes, and the edge rule `{ "open": true }` picks boundary edges. The lint message for an open boundary now suggests `fill_holes`. 18 new cases match Blender in counts, face sizes, area, volume and positions; the knife is compared only with a straight plane cut and differs where a face runs along the projection direction
+ - Export textures, skeletons and clips to GLB: `exportGlb(parts, { nodes, clips, maxTextureSize })` now writes `map`, `normalMap`, `metallicRoughnessMap`, `occlusionMap` and `emissiveMap` as embedded PNG (limit 2048 px by default, with an error that names the option), skins with joint nodes and inverse bind matrices, and animation clips (translation, rotation and scale tracks; SMOOTH becomes cubic with zero tangents). Pattern materials export their baked textures with box projected UVs, so the picture matches without `uv_unwrap`. It previously threw on skins and on every texture channel. The `entry:core` size budget goes from 67,100 to 70,500 bytes gzip (+3,400)
+ - Make the first frame and the SwiftShader frame cost less, with the same pixels. The main fragment shader now compiles only the features that a scene uses (maps, splat layers, moss, alpha and the special material tags), and a part that needs another feature later recompiles it. All programs, with the environment prefilter, now start together and use `KHR_parallel_shader_compile`. On an RTX 3060 the first frame went from 3.7 to 4.4 seconds down to 0.5 to 1.0 seconds, and a SwiftShader frame costs 0.4 to 0.5 times what it did. `bench/runtime/PROFILE.md` has the profile
- Add `subdivide` as a mesh edit and stack node: Catmull-Clark subdivision to 4 levels with semi-sharp creases picked by an edge rule, sharp boundaries, kept corners, n-gon support, and tags, UVs and edge attributes carried through each level. The size is checked before it allocates. Counts, area and positions match Blender at levels 1 to 3; the `pebble` task joins the agent modeling suite
- Remove `67js/addons/film` from the npm package. It held the 187-second trailer demo with its baked physics recording, 75 KB gzip of the archive. Nothing else in the package used it. To keep using it, copy `src/film.js`, `src/film-rig.js`, `src/film-character.js`, `src/film-physics-definition.js` and `src/film-physics-clip.json` from the repository, or read the trailer on the site at `/film.html`. The archive goes from 901,314 to 829,085 bytes
- Remove three.js from modeling and the agent scene: `lathe`, `extrude` and `tube` no longer import it, and `scene:agent-scene` drops from 185,681 to 117,290 bytes gzip. `lathe` and `tube` output is identical to before, vertex for vertex. `extrude` walls, bevels, UVs, normals and bounds are identical, and volume matches within 1e-4. Extrusion caps use a new ear-clipping triangulation, so a cap can split along other diagonals, and a cap with collinear points can add or drop a seam vertex. A clockwise hole under a clockwise contour is now flipped to face outward, where it used to keep inward walls
diff --cc bench/reference/baseline.json
index 1b961a1b,3a10752f..a31bdab8
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@@ -1,88 -1,120 +1,128 @@@
{
- "metric": "FLIP (LDR), mean error, lower is better",
- "blenderVersion": "5.2.2 LTS",
- "seconds": {
- "lit-interior": {
- "cycles": 14.5,
- "eevee": 2.4
- }
- },
- "graphics": {
- "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",
- "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"
- },
- "scores": {
- "car-paint": {
- "gpu-vs-cycles": 0.1521,
- "gpu-vs-eevee": 0.1323,
- "cpu-vs-cycles": 0.152,
- "cpu-vs-eevee": 0.1323,
- "eevee-vs-cycles": 0.0819,
- "gpu-vs-cpu": 0.0055
- },
- "character": {
- "gpu-vs-cycles": 0.0995,
- "gpu-vs-eevee": 0.0833,
- "cpu-vs-cycles": 0.099,
- "cpu-vs-eevee": 0.0826,
- "eevee-vs-cycles": 0.074,
- "gpu-vs-cpu": 0.0068
- },
- "fog": {
- "gpu-vs-cycles": 0.2612,
- "gpu-vs-eevee": 0.0542,
- "cpu-vs-cycles": 0.2608,
- "cpu-vs-eevee": 0.0542,
- "eevee-vs-cycles": 0.2662,
- "gpu-vs-cpu": 0.0085
- },
- "foliage": {
- "gpu-vs-cycles": 0.1594,
- "gpu-vs-eevee": 0.1386,
- "cpu-vs-cycles": 0.159,
- "cpu-vs-eevee": 0.1384,
- "eevee-vs-cycles": 0.0783,
- "gpu-vs-cpu": 0.0096
- },
- "glass": {
- "gpu-vs-cycles": 0.1326,
- "gpu-vs-eevee": 0.1472,
- "cpu-vs-cycles": 0.1323,
- "cpu-vs-eevee": 0.1474,
- "eevee-vs-cycles": 0.115,
- "gpu-vs-cpu": 0.0075
- },
- "lit-interior": {
- "gpu-vs-cycles": 0.4997,
- "gpu-vs-eevee": 0.1204,
- "cpu-vs-cycles": 0.4993,
- "cpu-vs-eevee": 0.1209,
- "eevee-vs-cycles": 0.5159,
- "gpu-vs-cpu": 0.006
- },
- "material-spheres": {
- "gpu-vs-cycles": 0.1598,
- "gpu-vs-eevee": 0.1196,
- "cpu-vs-cycles": 0.1595,
- "cpu-vs-eevee": 0.1194,
- "eevee-vs-cycles": 0.1006,
- "gpu-vs-cpu": 0.0069
+ "metric": "FLIP (LDR), mean error, lower is better",
+ "blenderVersion": "5.2.2 LTS",
+ "seconds": {
+ "character": {
+ "cycles": 4.5,
+ "eevee": 1.1
+ },
+ "fog": {
+ "cycles": 16.6,
+ "eevee": 1.1
+ },
+ "foliage": {
+ "cycles": 5.8,
+ "eevee": 1
+ },
+ "glass": {
+ "cycles": 5.8,
+ "eevee": 0.4
+ },
+ "lit-interior": {
+ "cycles": 10,
+ "eevee": 0.6
+ },
+ "material-spheres": {
+ "cycles": 6.7,
+ "eevee": 0.4
+ },
+ "metal": {
+ "cycles": 5,
+ "eevee": 0.3
+ },
+ "outdoor-hdri": {
+ "cycles": 4.1,
+ "eevee": 0.4
+ },
+ "spot-area": {
+ "cycles": 20.3,
+ "eevee": 13.2
+ }
},
- "metal": {
- "gpu-vs-cycles": 0.1868,
- "gpu-vs-eevee": 0.1565,
- "cpu-vs-cycles": 0.1867,
- "cpu-vs-eevee": 0.1565,
- "eevee-vs-cycles": 0.0934,
- "gpu-vs-cpu": 0.0063
+ "graphics": {
+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",
+ "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"
},
- "outdoor-hdri": {
- "gpu-vs-cycles": 0.0676,
- "gpu-vs-eevee": 0.052,
- "cpu-vs-cycles": 0.0672,
- "cpu-vs-eevee": 0.0515,
- "eevee-vs-cycles": 0.0383,
- "gpu-vs-cpu": 0.0058
+ "scores": {
++ "car-paint": {
++ "gpu-vs-cycles": 0.1521,
++ "gpu-vs-eevee": 0.1323,
++ "cpu-vs-cycles": 0.152,
++ "cpu-vs-eevee": 0.1323,
++ "eevee-vs-cycles": 0.0819,
++ "gpu-vs-cpu": 0.0055
++ },
+ "character": {
+ "gpu-vs-cycles": 0.0995,
+ "gpu-vs-eevee": 0.0833,
+ "cpu-vs-cycles": 0.099,
+ "cpu-vs-eevee": 0.0826,
+ "eevee-vs-cycles": 0.074,
+ "gpu-vs-cpu": 0.0068
+ },
+ "fog": {
+ "gpu-vs-cycles": 0.2612,
+ "gpu-vs-eevee": 0.0542,
+ "cpu-vs-cycles": 0.2608,
+ "cpu-vs-eevee": 0.0542,
+ "eevee-vs-cycles": 0.2662,
+ "gpu-vs-cpu": 0.0085
+ },
+ "foliage": {
+ "gpu-vs-cycles": 0.1594,
+ "gpu-vs-eevee": 0.1386,
+ "cpu-vs-cycles": 0.159,
+ "cpu-vs-eevee": 0.1384,
+ "eevee-vs-cycles": 0.0783,
+ "gpu-vs-cpu": 0.0096
+ },
+ "glass": {
+ "gpu-vs-cycles": 0.145,
+ "gpu-vs-eevee": 0.1469,
+ "cpu-vs-cycles": 0.1447,
+ "cpu-vs-eevee": 0.1471,
+ "eevee-vs-cycles": 0.115,
+ "gpu-vs-cpu": 0.0074
+ },
+ "lit-interior": {
+ "gpu-vs-cycles": 0.4997,
+ "gpu-vs-eevee": 0.1204,
+ "cpu-vs-cycles": 0.4993,
+ "cpu-vs-eevee": 0.1209,
+ "eevee-vs-cycles": 0.5159,
+ "gpu-vs-cpu": 0.006
+ },
+ "material-spheres": {
+ "gpu-vs-cycles": 0.1598,
+ "gpu-vs-eevee": 0.1196,
+ "cpu-vs-cycles": 0.1595,
+ "cpu-vs-eevee": 0.1194,
+ "eevee-vs-cycles": 0.1006,
+ "gpu-vs-cpu": 0.0069
+ },
+ "metal": {
+ "gpu-vs-cycles": 0.1868,
+ "gpu-vs-eevee": 0.1565,
+ "cpu-vs-cycles": 0.1867,
+ "cpu-vs-eevee": 0.1565,
+ "eevee-vs-cycles": 0.0934,
+ "gpu-vs-cpu": 0.0063
+ },
+ "outdoor-hdri": {
+ "gpu-vs-cycles": 0.0676,
+ "gpu-vs-eevee": 0.052,
+ "cpu-vs-cycles": 0.0672,
+ "cpu-vs-eevee": 0.0515,
+ "eevee-vs-cycles": 0.0383,
+ "gpu-vs-cpu": 0.0058
+ },
+ "spot-area": {
+ "gpu-vs-cycles": 0.1242,
+ "gpu-vs-eevee": 0.1707,
+ "cpu-vs-cycles": 0.1242,
+ "cpu-vs-eevee": 0.1709,
+ "eevee-vs-cycles": 0.1935,
+ "gpu-vs-cpu": 0.0032
+ }
}
- }
}
diff --cc bench/size/baseline.json
index 3d451328,05fb5094..8cd460f9
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@@ -14,9 -14,9 +14,9 @@@
},
"bundles": {
"entry:core": {
- "min": 232549,
- "gzip": 65747,
- "brotli": 56178
- "min": 261051,
- "gzip": 74713,
- "brotli": 63726
++ "min": 268768,
++ "gzip": 76732,
++ "brotli": 65413
},
"entry:model": {
"min": 40093,
@@@ -39,9 -39,9 +39,9 @@@
"brotli": 7331
},
"entry:gltf": {
- "min": 139564,
- "gzip": 43172,
- "brotli": 37021
- "min": 145701,
- "gzip": 44953,
- "brotli": 38503
++ "min": 151944,
++ "gzip": 46674,
++ "brotli": 39985
},
"entry:modeling": {
"min": 15517,
@@@ -129,14 -129,14 +129,14 @@@
"brotli": 762
},
"entry:agent-scene": {
- "min": 292317,
- "gzip": 93166,
- "brotli": 80011
- "min": 338801,
- "gzip": 107187,
- "brotli": 91567
++ "min": 344496,
++ "gzip": 108633,
++ "brotli": 92877
},
"entry:agent-asset": {
- "min": 318835,
- "gzip": 100520,
- "brotli": 85995
- "min": 365325,
- "gzip": 114605,
- "brotli": 98079
++ "min": 371020,
++ "gzip": 116055,
++ "brotli": 99302
},
"entry:hdri": {
"min": 8075,
@@@ -144,19 -144,19 +144,19 @@@
"brotli": 2801
},
"scene:lit-box": {
- "min": 178412,
- "gzip": 48762,
- "brotli": 41832
- "min": 194282,
- "gzip": 53065,
- "brotli": 45377
++ "min": 200858,
++ "gzip": 54820,
++ "brotli": 46863
},
"scene:gltf-box": {
- "min": 235553,
- "gzip": 67467,
- "brotli": 58083
- "min": 251444,
- "gzip": 71774,
- "brotli": 61619
++ "min": 258708,
++ "gzip": 73797,
++ "brotli": 63362
},
"scene:agent-scene": {
- "min": 384588,
- "gzip": 117290,
- "brotli": 100238
- "min": 437383,
- "gzip": 133081,
- "brotli": 113464
++ "min": 444099,
++ "gzip": 134816,
++ "brotli": 114839
}
}
}
diff --cc bench/size/budgets.json
index 9e792d52,1524ddf8..24bbc9e3
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@@ -5,18 -5,18 +5,18 @@@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 67800,
- "entry:core": 76300,
++ "entry:core": 78300,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 44900,
- "entry:gltf": 45900,
++ "entry:gltf": 47700,
"entry:modeling": 6600,
"entry:sculpt": 2500,
- "entry:surface": 74500,
- "entry:mesh-query": 87300,
- "entry:mesh": 34900,
- "entry:shrinkwrap": 88600,
+ "entry:surface": 10100,
+ "entry:mesh-query": 15900,
+ "entry:mesh": 44700,
+ "entry:shrinkwrap": 18300,
"entry:surface-attachment": 11800,
"entry:physics": 16500,
"entry:spume": 9000,
@@@ -28,11 -28,11 +28,11 @@@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 96700,
- "entry:agent-asset": 104100,
- "entry:agent-scene": 109400,
- "entry:agent-asset": 116900,
++ "entry:agent-scene": 110900,
++ "entry:agent-asset": 118400,
"entry:hdri": 3300,
- "scene:lit-box": 50500,
- "scene:gltf-box": 69400,
- "scene:agent-scene": 121200
- "scene:lit-box": 54200,
- "scene:gltf-box": 73300,
- "scene:agent-scene": 135800
++ "scene:lit-box": 56000,
++ "scene:gltf-box": 75300,
++ "scene:agent-scene": 137600
}
}
diff --cc docs/parity.md
index 91e07a45,e764f57b..39c2ccbe
--- a/docs/parity.md
+++ b/docs/parity.md
@@@ -188,10 -188,10 +188,10 @@@ To move to a new Blender release, run `
| Rendering > Render Engines > Cycles | missing | No path tracer and no render baking. | | #55, #57 |
| Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | |
| Rendering > Cameras | partial | Perspective, orthographic views, focal length and animated paths. There is no depth of field. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js) | #54 |
- | Rendering > Lights > Light Objects | partial | One directional light with a shadow, and 8 point lights without shadows. There are no spot or area lights. | [lighting](../tests/lighting.test.js) | #52 |
+ | Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
| Rendering > Lights > Light Linking | missing | No light linking. | | #52 |
| Rendering > Lights > World Environment | partial | Recipes have sky colors, daylight and fog. Code can load an HDRI, and recipes can not reach it. | [environment](../tests/environment.test.js) | #53 |
-| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps. There are no volume materials or displacement. | [texture-set](../tests/texture-set.test.js) | #50, #51 |
+| Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps, a clear coat, transmission with thickness, attenuation and IOR, sheen, and specular weight and tint. There is no anisotropy, iridescence, subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.test.js) | #50, #51 |
| Rendering > Materials > Assignment | done | A node names one material. | [agent-scene](../tests/agent-scene.test.js) | |
| Rendering > Materials > Preview | out of scope | Interface for a person. Agents use `scene_look`. | | |
| Rendering > Materials > Settings | partial | Opaque and blend in recipes, and mask on imported assets, with double-sided support. | [gltf-extensions](../tests/gltf-extensions.test.js) | #51 |
diff --cc src/export.js
index 324e0465,ccb95884..3e3c32d4
--- a/src/export.js
+++ b/src/export.js
@@@ -1,8 -1,11 +1,12 @@@
import { validateMorphGeometry, validateMorphPose } from './morph.js';
+import { gltfExtensionsFromLayers } from './gltf-layers.js';
+ import { validateSkinGeometry } from './skinning.js';
+ import { boxProjectedGeometry } from './export-box-uv.js';
+ import { createTextureWriter } from './export-textures.js';
+ import { createGlbWriter } from './export-writer.js';
+ import { buildHierarchy, decomposeMatrix, hierarchyNodeFields, hostOfPart, normalizedWeights, relativeMatrix, writeAnimations, writeSkin } from './export-skeleton.js';
const EMISSIVE_STRENGTH = 'KHR_materials_emissive_strength';
- const COMPONENT_COUNTS = { SCALAR: 1, VEC2: 2, VEC3: 3 };
function validateFloatChannel(values, length, label, bounded = false) {
if (!(values instanceof Float32Array) || values.length !== length) {
@@@ -105,12 -107,100 +108,105 @@@ function validateTransformColumns(matri
}
}
- function paddedLength(length) {
- return Math.ceil(length / 4) * 4;
+ const TEXTURE_CHANNELS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
+ const OPTION_NAMES = ['clips', 'nodes', 'maxTextureSize'];
+
+ function validateOptions(options) {
+ if (!options || typeof options !== 'object') throw new TypeError('GLB export options must be an object.');
+ for (const name of Object.keys(options)) {
+ if (!OPTION_NAMES.includes(name)) throw new TypeError(`GLB export does not take ${name}. Options: ${OPTION_NAMES.join(', ')}.`);
+ }
+ if (options.clips !== undefined && !Array.isArray(options.clips)) throw new TypeError('GLB export clips must be an array.');
+ if (options.nodes !== undefined && !Array.isArray(options.nodes)) throw new TypeError('GLB export nodes must be an array.');
+ }
+
+ function validateSkinnedPart(part) {
+ validateSkinGeometry(part.geometry, part.skin);
+ }
+
+ function columnLengths(matrix) {
+ return [0, 4, 8].map(offset => Math.hypot(matrix[offset], matrix[offset + 1], matrix[offset + 2]));
+ }
+
+ function createIdentityTracker() {
+ const identities = new WeakMap();
+ let next = 0;
+ return object => {
+ if (!identities.has(object)) identities.set(object, next++);
+ return identities.get(object);
+ };
+ }
+
+ function materialKeyOf(material, identify) {
+ const textures = TEXTURE_CHANNELS.map(channel => material[channel] ? identify(material[channel]) : null);
+ const fields = { ...material };
+ for (const channel of [...TEXTURE_CHANNELS, 'pattern', 'boxMapScale', 'boxMapAxis']) delete fields[channel];
+ return JSON.stringify([fields, textures, material.boxMapScale ?? 0, material.boxMapAxis ?? 1]);
+ }
+
+ function writeMaterial(writer, textureWriter, material) {
+ const pbr = { baseColorFactor: [...material.color, 1], metallicFactor: material.metallic, roughnessFactor: material.roughness };
+ const gltfMaterial = {
+ pbrMetallicRoughness: pbr,
+ emissiveFactor: (material.emission ?? 0) === 0 ? [0, 0, 0] : Array.from(material.emissiveColor ?? material.color),
+ };
+ writeAlphaFields(gltfMaterial, material);
++ const layerExtensions = gltfExtensionsFromLayers(material);
++ if (Object.keys(layerExtensions).length > 0) {
++ gltfMaterial.extensions = layerExtensions;
++ for (const extensionName of Object.keys(layerExtensions)) writer.addExtension(extensionName);
++ }
+ const strength = material.emission ?? 0;
+ if (strength !== 0 && strength !== 1) {
- gltfMaterial.extensions = { [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
++ gltfMaterial.extensions = { ...gltfMaterial.extensions, [EMISSIVE_STRENGTH]: { emissiveStrength: strength } };
+ writer.addExtension(EMISSIVE_STRENGTH, { required: true });
+ }
+ const textureOf = channel => ({ index: textureWriter.textureIndex(material[channel], channel) });
+ if (material.map) pbr.baseColorTexture = textureOf('map');
+ if (material.metallicRoughnessMap) pbr.metallicRoughnessTexture = textureOf('metallicRoughnessMap');
+ if (material.normalMap) gltfMaterial.normalTexture = { ...textureOf('normalMap'), scale: material.normalScale?.[0] ?? 1 };
+ if (material.occlusionMap) gltfMaterial.occlusionTexture = { ...textureOf('occlusionMap'), strength: material.occlusionStrength ?? 1 };
+ if (material.emissiveMap) gltfMaterial.emissiveTexture = textureOf('emissiveMap');
+ return gltfMaterial;
}
- export function exportGlb(parts) {
+ function writeGeometry(writer, geometry) {
+ const ARRAY_BUFFER = 34962;
+ const attributes = { POSITION: writer.addAccessor(geometry.positions, 'VEC3', ARRAY_BUFFER), NORMAL: writer.addAccessor(geometry.normals, 'VEC3', ARRAY_BUFFER) };
+ const primitive = { attributes, indices: writer.addAccessor(geometry.indices, 'SCALAR', 34963) };
+ if (geometry.colors) attributes.COLOR_0 = writer.addAccessor(geometry.colors, 'VEC3', ARRAY_BUFFER);
+ if (geometry.uvs) attributes.TEXCOORD_0 = writer.addAccessor(geometry.uvs, 'VEC2', ARRAY_BUFFER);
+ if (geometry.skinIndices) {
+ attributes.JOINTS_0 = writer.addAccessor(Uint16Array.from(geometry.skinIndices), 'VEC4', ARRAY_BUFFER, { bounds: false });
+ attributes.WEIGHTS_0 = writer.addAccessor(normalizedWeights(geometry.skinWeights), 'VEC4', ARRAY_BUFFER, { bounds: false });
+ }
+ if (geometry.morphTargets) {
+ primitive.targets = geometry.morphTargets.map(target => {
+ const channels = {};
+ if (target.positions) channels.POSITION = writer.addAccessor(target.positions, 'VEC3', ARRAY_BUFFER);
+ if (target.normals) channels.NORMAL = writer.addAccessor(target.normals, 'VEC3', ARRAY_BUFFER);
+ return channels;
+ });
+ }
+ return primitive;
+ }
+
+ function requireUvsForTextures(part) {
+ const textured = TEXTURE_CHANNELS.some(channel => part.material[channel]);
+ const boxMapped = (part.material.boxMapScale ?? 0) > 0;
+ if (textured && !boxMapped && !part.geometry.uvs) {
+ throw new RangeError(`GLB part ${part.name} has textures but its geometry has no uvs. Add a uv_unwrap node to the mesh stack, or set geometry.uvs.`);
+ }
+ }
+
+ /**
+ * Returns a self-contained GLB ArrayBuffer for the parts.
+ * Options: `clips` (createAnimationClip form, track targets are node names), `nodes` (the `nodes` of a parsed asset,
+ * which hold joints and groups, so skinned parts and clips keep their hierarchy), `maxTextureSize` (default 2048).
+ */
+ export function exportGlb(parts, options = {}) {
if (!Array.isArray(parts) || parts.length === 0) throw new TypeError('GLB export requires a nonempty parts array.');
+ validateOptions(options);
const validatedGeometries = new Set();
const morphMetadata = new Map();
for (const part of parts) {
diff --cc src/renderer.js
index 19849fb6,c7a4a4db..46c06408
--- a/src/renderer.js
+++ b/src/renderer.js
@@@ -5,11 -5,11 +5,12 @@@ import { planRenderSize, estimateTextur
import { applyProjection } from './camera.js';
import { resolveEffects } from './effects.js';
import { createLightingState, updateLightingState } from './lighting.js';
+ import { SHADOW_ATLAS_WIDTH, SHADOW_ATLAS_HEIGHT, tileViewport, writeShadowTile } from './local-shadows.js';
import { resolveVolumeFog } from './volumetric.js';
- import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, estimateEnvironmentBytes } from './environment.js';
+ import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, environmentBrdfFragment, environmentPrefilterFragment, estimateEnvironmentBytes } from './environment.js';
import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';
import { validateSplatMaterial, splatBatchState, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';
+import { materialLayerState } from './material-layers.js';
import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';
const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };
@@@ -30,8 -28,33 +31,34 @@@ const PROCEDURAL_MATERIAL_TAGS = new Se
// Tags whose vertices sway in the wind; the shadow pass must be redrawn when time moves.
const SWAYING_TAGS = new Set(['foliage', 'grass']);
+ const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
+ // Tags whose look the main fragment shader draws with code that other tags never reach.
+ const TAG_SHADER_FEATURES = new Set(['floor', 'water', 'foliage', 'terrain', 'grass', 'fire', 'smoke', 'unlit']);
+
+ function shaderFeaturesOfLighting(lighting) {
+ const features = [];
+ if (lighting.spotCount > 0) features.push('spotLights');
+ if (lighting.areaCount > 0) features.push('areaLights');
+ if (lighting.shadowCasters.length > 0) features.push('localShadows');
+ return features;
+ }
+
+ function shaderFeaturesOfParts(parts) {
+ const features = new Set();
+ for (const { material } of parts) {
+ MATERIAL_MAPS.forEach((field, index) => {
+ if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
+ });
+ if (material.layers) features.add('splat');
+ if (material.moss > 0) features.add('moss');
+ if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');
+ if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);
+ }
+ return features;
+ }
+
function renderPass(material) {
+ if (material.transmission > 0) return 'liquid';
return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';
}
@@@ -416,14 -457,14 +461,14 @@@ export class Renderer67
this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
this.depthMorphUniforms = Object.fromEntries(MORPH_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
if (!benchmark) {
- this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);
- this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);
+ this.postProgram = finishProgram(this.context, pending.post);
+ this.skyProgram = finishProgram(this.context, pending.sky);
this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));
- this.bloomProgram = compileProgram(this.context, fullscreenVertex, bloomFragment);
+ this.bloomProgram = finishProgram(this.context, pending.bloom);
this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));
this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
- this.liquidProgram = compileProgram(this.context, vertexShader, liquidFragmentShader);
+ this.liquidProgram = finishProgram(this.context, pending.liquid);
- this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
+ this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'glassState', 'glassTint', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
}
this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
@@@ -455,6 -496,26 +500,26 @@@
if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);
}
+ // 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);
+ return startProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, fragmentSource);
+ }
+
+ buildMainProgram() {
+ this.finishMainProgram(this.startMainProgram());
+ }
+
+ finishMainProgram(pendingProgram) {
+ this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
++ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ for (const name of LIGHT_UNIFORMS) {
+ this.uniforms[name] = this.context.getUniformLocation(this.program, name);
+ }
+ for (const name of ENVIRONMENT_UNIFORMS) this.uniforms[name] = this.context.getUniformLocation(this.program, name);
+ }
+
get samples() {
return Math.max(1, this.multisampleSamples);
}
diff --cc src/shaders.js
index bc4480b7,5c8609c4..8f708643
--- a/src/shaders.js
+++ b/src/shaders.js
@@@ -318,32 -315,26 +318,34 @@@ void main()
float roughness = clamp(surface.y, 0.02, 1.0);
vec2 screen = gl_FragCoord.xy / resolution;
// A convex body is thickest where it faces the camera and thins to nothing at its silhouette.
- float thickness = liquidOptics.x * mix(0.15, 1.0, facing);
- vec3 bent = refract(-viewDirection, normal, 1.0 / liquidOptics.y);
+ bool glass = glassState.x > 0.0;
+ float indexOfRefraction = glass ? glassState.y : liquidOptics.y;
+ float thickness = (glass ? glassState.z : liquidOptics.x) * mix(0.15, 1.0, facing);
+ vec3 bent = refract(-viewDirection, normal, 1.0 / indexOfRefraction);
vec4 projected = viewProjection * vec4(worldPosition + bent * thickness, 1.0);
vec2 refracted = projected.w > 0.0 ? projected.xy / projected.w * 0.5 + 0.5 : screen;
- refracted = clamp(mix(screen, refracted, liquidOptics.z), vec2(0.001), vec2(0.999));
+ refracted = clamp(mix(screen, refracted, glass ? 1.0 : liquidOptics.z), vec2(0.001), vec2(0.999));
vec3 behind = texture(sceneColor, refracted).rgb;
// The material colour is what one metre of this liquid lets through.
- vec3 transmittance = pow(clamp(color, vec3(0.001), vec3(1.0)), vec3(thickness));
- float reflectance = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
- vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * liquidOptics.w * (1.0 - transmittance);
+ // For a PBR material the colour tints what passes through and the attenuation colour is what attenuationDistance metres let through.
+ vec3 absorption = pow(clamp(glass ? glassTint : color, vec3(0.001), vec3(1.0)), vec3(glass ? thickness / glassState.w : thickness));
+ vec3 transmittance = glass ? color * absorption : absorption;
+ float surfaceReflectance = pow((indexOfRefraction - 1.0) / (indexOfRefraction + 1.0), 2.0);
+ float reflectance = surfaceReflectance + (1.0 - surfaceReflectance) * pow(1.0 - facing, 5.0);
+ vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * (glass ? 0.0 : liquidOptics.w) * (1.0 - transmittance);
+ // The share of a PBR material that does not transmit is lit like a diffuse surface.
+ vec3 diffuseShare = glass ? color * (1.0 - glassState.x) * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) / PI) : vec3(0.0);
vec3 reflection = environmentColor(reflect(-viewDirection, normal), roughness) * ambientIntensity;
vec3 highlight = keyColor * specularLobe(normal, viewDirection, light, roughness);
- vec3 surfaceLight = inScatter * (1.0 - reflectance) + reflection * reflectance + highlight;
+ vec3 surfaceLight = (inScatter + diffuseShare) * (1.0 - reflectance) + reflection * reflectance + highlight;
surfaceLight = mix(surfaceLight, fogColor, fog);
- outputColor = vec4(behind * transmittance * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);
+ float transmitted = glass ? glassState.x : 1.0;
+ outputColor = vec4(behind * transmittance * transmitted * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);
}`;
- export const fragmentShader = `#version 300 es
+ function buildFragmentShader(featureDefines) {
+ return `#version 300 es
+ ${featureDefines}
precision highp float;
in vec3 worldPosition;
in vec3 worldNormal;
@@@ -713,22 -720,60 +769,60 @@@ void main()
vec3 offset = pointLightPositions[index].xyz - worldPosition;
float distanceSquared = dot(offset, offset);
if (distanceSquared < 1e-12 || pointLightColors[index].w == 0.0) continue;
- float range = pointLightPositions[index].w;
- float cutoff = 1.0;
- if (range > 0.0) {
- float squaredRatio = distanceSquared / (range * range);
- float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);
- cutoff = fade * fade;
- }
- if (cutoff == 0.0) continue;
- float radius = pointLightRadii[index];
- float attenuation = cutoff / max(distanceSquared, radius * radius);
+ float attenuation = localAttenuation(distanceSquared, pointLightPositions[index].w, pointLightRadii[index]);
+ if (attenuation == 0.0) continue;
vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;
+ if (USES_LOCAL_SHADOWS && pointLightShadowTiles[index] >= 0.0) {
+ float tile = pointLightShadowTiles[index] + pointShadowFace(-offset);
+ lightRadiance *= localShadowVisibility(tile, worldPosition, normal, sqrt(distanceSquared));
+ }
radiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);
}
+ if (USES_SPOT_LIGHTS) {
+ for (int index = 0; index < 8; index++) {
+ if (index >= spotLightCount) break;
+ vec3 offset = spotLightPositions[index].xyz - worldPosition;
+ float distanceSquared = dot(offset, offset);
+ if (distanceSquared < 1e-12 || spotLightColors[index].w == 0.0) continue;
+ vec3 toLight = offset * inversesqrt(distanceSquared);
+ float coneCosine = dot(-toLight, spotLightDirections[index].xyz);
+ // The same cone mask as Blender: smoothstep between the outer and inner cosines.
+ float cone = smoothstep(spotLightDirections[index].w, spotLightParameters[index].y, coneCosine);
+ float attenuation = localAttenuation(distanceSquared, spotLightPositions[index].w, spotLightParameters[index].x) * cone;
+ if (attenuation == 0.0) continue;
+ vec3 lightRadiance = spotLightColors[index].rgb * spotLightColors[index].w * attenuation;
+ if (USES_LOCAL_SHADOWS && spotLightParameters[index].z >= 0.0) {
+ lightRadiance *= localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));
+ }
+ radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);
+ }
+ }
+ if (USES_AREA_LIGHTS) {
+ for (int index = 0; index < 4; index++) {
+ if (index >= areaLightCount) break;
+ vec3 lightNormal = areaLightNormals[index].xyz;
+ vec3 widthAxis = areaLightTangents[index].xyz;
+ vec3 heightAxis = cross(lightNormal, widthAxis);
+ vec2 halfSize = vec2(areaLightNormals[index].w, areaLightTangents[index].w) * 0.5;
+ vec3 fromCenter = worldPosition - areaLightPositions[index].xyz;
+ // Representative point: the closest point of the rectangle stands in for the whole source.
+ vec3 closest = areaLightPositions[index].xyz
+ + widthAxis * clamp(dot(fromCenter, widthAxis), -halfSize.x, halfSize.x)
+ + heightAxis * clamp(dot(fromCenter, heightAxis), -halfSize.y, halfSize.y);
+ vec3 offset = closest - worldPosition;
+ float distanceSquared = dot(offset, offset);
+ vec3 toLight = offset * inversesqrt(max(distanceSquared, 1e-12));
+ float emission = max(dot(-toLight, lightNormal), 0.0);
+ float area = 4.0 * halfSize.x * halfSize.y;
+ // Adding area / pi keeps the term finite at the surface and matches a disc source on its axis.
+ float attenuation = emission / (distanceSquared + area / PI);
+ vec3 lightRadiance = areaLightColors[index].rgb * areaLightColors[index].w * attenuation;
+ radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);
+ }
+ }
- vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));
+ vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(materialDielectric, color, metallic));
float occlusion = 1.0;
- if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
+ if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);
occlusion *= splatCavity;
// Leaf and grass cards keep a faint sheen; full sky reflection washed grazing cards grey-blue.
float skyReflection = canopyShaded ? 0.3 : 1.0;
@@@ -756,10 -801,8 +850,10 @@@
float thinness = textureUV.x > -0.5 ? 1.0 - textureUV.y * 0.8 : 0.6;
radiance += color * vec3(1.1, 1.25, 0.55) * towardSun * thinness * 1.4 * keyResponse * visibility;
}
+ if (materialSheen.rgb != vec3(0.0)) radiance = sheenLayer(radiance, normal, viewDirection, visibility);
+ if (materialCoat.x > 0.0) radiance = clearCoatLayer(radiance, normal, viewDirection, visibility);
radiance += emission;
- if (surface.w == 3.0) {
+ if (TAG_WATER) {
float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);
vec3 reflection = mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(reflect(-viewDirection, normal).y, 0.0, 1.0));
radiance = mix(radiance * 0.6, reflection * daylight * ambientIntensity, reflectivity);
diff --cc tests/reference-baseline.test.js
index b4aa3d5b,bc9bc5ea..30178fca
--- a/tests/reference-baseline.test.js
+++ b/tests/reference-baseline.test.js
@@@ -4,7 -4,7 +4,7 @@@ import test from 'node:test'
const REFERENCE_DIRECTORY = new URL('../bench/reference/', import.meta.url);
const baseline = JSON.parse(readFileSync(new URL('baseline.json', REFERENCE_DIRECTORY), 'utf8'));
- const EXPECTED_SCENES = ['car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri'];
-const EXPECTED_SCENES = ['character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
++const EXPECTED_SCENES = ['car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
const EXPECTED_SCORES = ['cpu-vs-cycles', 'cpu-vs-eevee', 'eevee-vs-cycles', 'gpu-vs-cpu', 'gpu-vs-cycles', 'gpu-vs-eevee'];
test('the render baseline scores every scene with every renderer pair', () => {