Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Load glTF files with optional extensions and line primitives, read lights and unlit

Nguyen Xuan An814440389887
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index f7d63083..41239fcb 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)",
+ "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); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681)",
"schemaTotalBytes": 190830,
"schemaToolBytes": {
"scene_create": 62945,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 16600,
+ "scene_capabilities": 16701,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/changes/280.md b/changes/280.md
new file mode 100644
index 00000000..9ddd4db4
--- /dev/null
+++ b/changes/280.md
@@ -0,0 +1 @@
+- Load glTF files that use optional extensions and line primitives instead of refusing them (closes #280). An optional extension 67js does not read, such as `EXT_texture_avif`, is ignored and named in `warnings`; one in `extensionsRequired` is still refused. POINTS, LINES, LINE_LOOP and LINE_STRIP primitives are skipped with a warning that names the mesh. `KHR_materials_unlit` loads as the `unlit` material tag, and `KHR_lights_punctual` comes back as `asset.lights`: point and spot lights and the first directional light as `Renderer67` environment options. Not done: drawing the skipped primitives, and a reference-image check of a Khronos lights sample.
diff --git a/docs/gltf.md b/docs/gltf.md
index c81f7d2c..0c19dd99 100644
--- a/docs/gltf.md
+++ b/docs/gltf.md
@@ -128,8 +128,8 @@ It also supports `KHR_mesh_quantization` and `KHR_materials_emissive_strength`.
Alpha masking, alpha blending and double-sided materials import onto `alphaMode`, `alphaCutoff`, `opacity` and `doubleSided` (see the material maps guide). Vertex alpha is not drawn: an RGBA `COLOR_0` loads with its RGB, and `warnings` names the meshes whose alpha was below one and was dropped.
It supports base-color, normal, metallic-roughness, occlusion and emissive texture channels.
-It rejects unknown extensions, including optional ones.
-Line and point primitives are unsupported.
+An optional extension that 67js does not read is ignored and named in `warnings`, as the glTF specification allows. An extension listed in `extensionsRequired` that 67js does not read still fails the load with `Unsupported glTF extension`.
+POINTS, LINES, LINE_LOOP and LINE_STRIP primitives are skipped with a warning that names the mesh and their count. Drawing them is not supported. TRIANGLE_STRIP and TRIANGLE_FAN primitives are still refused.
## Extensions
@@ -138,6 +138,9 @@ Line and point primitives are unsupported.
| `KHR_mesh_quantization`, `KHR_materials_emissive_strength` | Supported. |
| `KHR_texture_transform` | Offset, rotation and scale are baked into `geometry.uvs`. All maps of one material must share one transform, except the normal map: it may differ by an offset and a positive scale (same rotation), which the shader applies on top of the baked UVs (`normalMapTransform` in `material-layer-shaders`). Any other difference fails the import. `texCoord` overrides are rejected. |
| `EXT_mesh_gpu_instancing` | The node expands into one part per instance and primitive. Parts of one primitive share one geometry object, so the renderer batches them. Skinned or morphed instancing is rejected. |
+| `KHR_materials_unlit` | The material gets the renderer's `unlit` tag and shows its base color and base color map alone. Emissive, normal, occlusion and metallic-roughness maps and layers are dropped. |
+| `KHR_lights_punctual` | Point and spot lights (up to the renderer limits of 16 point and 8 spot lights, in candela like the renderer) and the first directional light become `asset.lights`, a partial `environment`: `pointLights`, `spotLights`, and `keyColor` (color times lux), `lightDirection` and `keyIntensity` for the key light. Pass it as `Renderer67`'s `environment` option or a `frame.environment`. A spot's `penumbra` is `(outer - inner) / outer`. A light over the limits, a second directional light and an invalid light are skipped with a warning. The renderer has no calibrated photometric units, so judge the level by eye. |
+| `KHR_materials_variants`, `KHR_materials_dispersion`, `KHR_materials_diffuse_roughness`, `EXT_materials_bump`, `EXT_texture_avif` and any other optional extension | Ignored, named in `warnings`. |
| `KHR_draco_mesh_compression` | Needs `options.decoders.draco`. |
| `EXT_meshopt_compression` | Needs `options.decoders.meshopt`. |
| `KHR_texture_basisu` | Needs `options.decoders.ktx2`. |
@@ -175,8 +178,8 @@ KTX2 dimensions count toward `maxTexturePixels` before decoding. KTX2 images are
`maxInstances` (default 4,096) caps the instances of one node, and `maxParts` still caps the total number of parts.
Both are checked from the accessor counts before any data is decoded.
-The bridge does not import cameras, lights or scene environments into Renderer67.
-The caller supplies its own camera and lighting.
+The bridge does not import cameras or scene environments into Renderer67. The caller supplies its own camera and base lighting.
+Lights from `KHR_lights_punctual` come back in `asset.lights` and are applied only when the caller passes them on (see the extension table).
## Verification
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index fc01c092..5b5bcb88 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -198,6 +198,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
rejects: 'On a skinned or morphed part an edit farther than maxTransferFraction of the part bounds diagonal from the original surface; booleans on open parts (fill_holes first).',
}),
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
+ gltfImport: 'Optional extensions and line primitives load with a warning; unlit and punctual lights are read.',
authoredLook: true, maxPointLights: MAX_POINT_LIGHTS,
lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,
ambientOcclusion: Object.freeze({ default: DEFAULT_AMBIENT_OCCLUSION, defaultRadius: 0.5, off: 0 }),
diff --git a/src/gltf-decode.js b/src/gltf-decode.js
index 739110c1..d8cd8050 100644
--- a/src/gltf-decode.js
+++ b/src/gltf-decode.js
@@ -27,6 +27,11 @@ const WEBP_SIGNATURE = [0x52, 0x49, 0x46, 0x46, null, null, null, null, 0x57, 0x
const LINEAR_SRGB = 'srgb-linear';
const COMPONENT_CODES = new Map(Object.entries(COMPONENT_TYPES).map(([code, ArrayType]) => [ArrayType, Number(code)]));
+/** POINTS, LINES, LINE_LOOP and LINE_STRIP (modes 0 to 3) are not drawn, so the decoder leaves them out. */
+export function isLinePrimitive(primitive) {
+ return primitive.mode >= 0 && primitive.mode <= 3;
+}
+
export function textureSourceIndex(texture) {
return texture.extensions?.KHR_texture_basisu?.source ?? texture.extensions?.EXT_texture_webp?.source ?? texture.source;
}
@@ -353,6 +358,7 @@ export async function decodeGltf({ document, glbBinary, resourceBytes, decoders,
const objects = [];
if (definition.mesh !== undefined) {
for (let primitiveIndex = 0; primitiveIndex < document.meshes[definition.mesh].primitives.length; primitiveIndex++) {
+ if (isLinePrimitive(document.meshes[definition.mesh].primitives[primitiveIndex])) continue;
objects.push(await createPrimitiveObject(definition, nodeIndex, definition.mesh, primitiveIndex));
}
}
diff --git a/src/gltf-lights.js b/src/gltf-lights.js
new file mode 100644
index 00000000..8f7590d3
--- /dev/null
+++ b/src/gltf-lights.js
@@ -0,0 +1,103 @@
+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from './light-limits.js';
+
+const MAX_LIGHT_INTENSITY = 1e5;
+const MAX_KEY_COLOR = 1000;
+const MIN_SPOT_ANGLE = 0.01;
+const MAX_SPOT_ANGLE = Math.PI / 2 - 0.01;
+const DEFAULT_OUTER_CONE_ANGLE = Math.PI / 4;
+const MIN_LIGHT_RANGE = 0.001;
+
+function lightLabel(definition, index) {
+ return definition.name ? `"${definition.name}"` : `light ${index}`;
+}
+
+function validColor(color) {
+ return Array.isArray(color) && color.length === 3 && color.every(value => Number.isFinite(value) && value >= 0 && value <= 1);
+}
+
+function spotCone(definition) {
+ const outer = definition.spot?.outerConeAngle ?? DEFAULT_OUTER_CONE_ANGLE;
+ const inner = definition.spot?.innerConeAngle ?? 0;
+ if (!Number.isFinite(outer) || !Number.isFinite(inner) || inner < 0 || inner >= outer || outer > Math.PI / 2) return null;
+ const angle = Math.min(Math.max(outer, MIN_SPOT_ANGLE), MAX_SPOT_ANGLE);
+ // The renderer blends the cone edge like Blender: penumbra is the share of the outer angle the fade covers.
+ return { angle, penumbra: (outer - inner) / outer };
+}
+
+/**
+ * Maps KHR_lights_punctual onto the renderer's existing light options. Point lights and spot lights go to
+ * pointLights and spotLights up to the renderer's limits. glTF intensity is candela for both, as in the renderer.
+ * The renderer has one directional key light, so the first directional light sets keyColor and lightDirection.
+ * Every light that does not fit is skipped with a warning.
+ * @param {object} document the glTF JSON
+ * @param {{ nodeIndex: number, matrix: ArrayLike<number> }[]} lightNodes nodes that reference a light, with their column-major world matrix
+ * @returns {{ lights: object, warnings: string[] }} lights is a partial environment: pointLights, spotLights, keyColor, lightDirection, keyIntensity
+ */
+export function readPunctualLights(document, lightNodes) {
+ const definitions = document.extensions?.KHR_lights_punctual?.lights ?? [];
+ const warnings = [];
+ const pointLights = [];
+ const spotLights = [];
+ let key = null;
+ for (const { nodeIndex, matrix } of lightNodes) {
+ const lightIndex = document.nodes[nodeIndex].extensions.KHR_lights_punctual.light;
+ const definition = definitions[lightIndex];
+ if (!definition) {
+ warnings.push(`Skipped the light of node ${nodeIndex}: KHR_lights_punctual has no light ${lightIndex}.`);
+ continue;
+ }
+ const label = lightLabel(definition, lightIndex);
+ const color = definition.color ?? [1, 1, 1];
+ const intensity = definition.intensity ?? 1;
+ if (!validColor(color) || !Number.isFinite(intensity) || intensity < 0) {
+ warnings.push(`Skipped ${label}: its color or intensity is invalid.`);
+ continue;
+ }
+ const position = [matrix[12], matrix[13], matrix[14]];
+ const towardLight = [matrix[8], matrix[9], matrix[10]];
+ const clampedIntensity = Math.min(intensity, MAX_LIGHT_INTENSITY);
+ if (clampedIntensity !== intensity) warnings.push(`Clamped the intensity of ${label} to ${MAX_LIGHT_INTENSITY}.`);
+ if (definition.type === 'directional') {
+ if (key) {
+ warnings.push(`Skipped directional ${label}: the renderer has one directional key light, already taken by ${key.label}.`);
+ continue;
+ }
+ const scaled = color.map(value => Math.min(value * intensity, MAX_KEY_COLOR));
+ key = { label, keyColor: scaled, lightDirection: towardLight, keyIntensity: 1 };
+ continue;
+ }
+ if (definition.type !== 'point' && definition.type !== 'spot') {
+ warnings.push(`Skipped ${label}: light type ${definition.type} is not point, spot or directional.`);
+ continue;
+ }
+ const range = definition.range === undefined ? 0 : Math.max(definition.range, MIN_LIGHT_RANGE);
+ const light = { position, color, intensity: clampedIntensity, range };
+ if (definition.type === 'point') {
+ if (pointLights.length >= MAX_POINT_LIGHTS) {
+ warnings.push(`Skipped point ${label}: the renderer draws at most ${MAX_POINT_LIGHTS} point lights.`);
+ continue;
+ }
+ pointLights.push(light);
+ continue;
+ }
+ const cone = spotCone(definition);
+ if (!cone) {
+ warnings.push(`Skipped spot ${label}: its cone angles are invalid.`);
+ continue;
+ }
+ if (spotLights.length >= MAX_SPOT_LIGHTS) {
+ warnings.push(`Skipped spot ${label}: the renderer draws at most ${MAX_SPOT_LIGHTS} spot lights.`);
+ continue;
+ }
+ spotLights.push({ ...light, direction: towardLight.map(value => -value), ...cone });
+ }
+ const lights = {};
+ if (pointLights.length) lights.pointLights = pointLights;
+ if (spotLights.length) lights.spotLights = spotLights;
+ if (key) {
+ lights.keyColor = key.keyColor;
+ lights.lightDirection = key.lightDirection;
+ lights.keyIntensity = key.keyIntensity;
+ }
+ return { lights, warnings };
+}
diff --git a/src/gltf.js b/src/gltf.js
index d1cd284f..aa0f9ba7 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -1,7 +1,8 @@
import { applyClip } from './gltf-animation.js';
import { GLTF_LAYER_EXTENSIONS, layerTextureReferences, materialLayersFromGltf } from './gltf-layers.js';
import { attributeFloats } from './gltf-accessors.js';
-import { decodeGltf, textureSourceIndex } from './gltf-decode.js';
+import { decodeGltf, isLinePrimitive, textureSourceIndex } from './gltf-decode.js';
+import { readPunctualLights } from './gltf-lights.js';
import { Matrix4 } from './gltf-nodes.js';
import { textureDescriptorInfo } from './renderer.js';
import { createSkinPose, updateSkinPose, validateSkinGeometry, validateSkinPose } from './skinning.js';
@@ -9,9 +10,11 @@ import { MAX_MORPH_TARGETS, createMorphPose, validateMorphGeometry, validateMorp
export const GLTF_CAPABILITIES = Object.freeze({
formats: ['glb', 'gltf'],
- supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG/WebP base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'TEXCOORD_1 for occlusion, emissive and metallic-roughness textures', 'clearcoat, clearcoat roughness, clearcoat normal, anisotropy, sheen color and sheen roughness textures', 'linear RGB vertex colors, with the alpha of RGBA colors ignored and reported in warnings','metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs, with a normal map that differs by scale and offset applied in the shader', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2', 'EXT_texture_webp, with the PNG or JPEG fallback source when the browser cannot decode WebP'],
+ supported: ['triangle meshes', 'world transforms', 'rigid node animations', 'four-influence skeletal skinning', 'joint node animations', 'relative POSITION/NORMAL morph targets', 'morph weight animations', 'PNG/JPEG/WebP base color textures', 'normal/occlusion/emissive/metallic-roughness textures', 'TEXCOORD_0', 'TEXCOORD_1 for occlusion, emissive and metallic-roughness textures', 'clearcoat, clearcoat roughness, clearcoat normal, anisotropy, sheen color and sheen roughness textures', 'linear RGB vertex colors, with the alpha of RGBA colors ignored and reported in warnings','metallic roughness factors', 'emissive factors', 'alpha mask and blend modes', 'double-sided materials', 'KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_materials_clearcoat, transmission, volume, ior, specular, sheen, anisotropy and iridescence factors', 'KHR_texture_transform baked into UVs, with a normal map that differs by scale and offset applied in the shader', 'EXT_mesh_gpu_instancing expanded into parts', 'KHR_draco_mesh_compression with options.decoders.draco', 'EXT_meshopt_compression with options.decoders.meshopt', 'KHR_texture_basisu with options.decoders.ktx2', 'EXT_texture_webp, with the PNG or JPEG fallback source when the browser cannot decode WebP', 'KHR_materials_unlit as the unlit material tag, with a base color map only', 'KHR_lights_punctual point and spot lights (up to eight each) and the first directional light, returned in lights as environment options'],
// The primitive's own material is drawn; the other variants are not selectable.
- ignoredExtensions: ['KHR_materials_variants'],
+ ignoredExtensions: ['KHR_materials_variants', 'KHR_materials_dispersion', 'KHR_materials_diffuse_roughness', 'EXT_materials_bump', 'EXT_texture_avif'],
+ optionalExtensions: 'Any other optional extension is ignored and named in warnings. One listed in extensionsRequired that 67js does not read is refused.',
+ skippedPrimitives: ['POINTS', 'LINES', 'LINE_LOOP', 'LINE_STRIP'],
unsupported: ['more than four skin influences', 'singular weighted skin transforms', 'reflected skin transforms', 'TANGENT morph targets', 'morph targets without authored base normals', 'drawing vertex alpha (it is ignored with a warning)','different texture transforms on one material, except a normal map that differs by scale and offset', 'skinned or morphed GPU instancing', 'transmission, iridescence and specular textures (their factors are used)', 'texture transforms on TEXCOORD_1'],
});
@@ -30,10 +33,8 @@ const DEFAULT_MAX_INSTANCES = 4096;
// KHR_xmp_json_ld and its earlier name KHR_xmp only carry metadata (authors, licences) and change nothing drawn: the
// Khronos sample assets list them, and a file must not be refused for them.
const METADATA_EXTENSIONS = ['KHR_xmp_json_ld', 'KHR_xmp'];
-const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing', 'EXT_texture_webp', ...METADATA_EXTENSIONS, ...GLTF_LAYER_EXTENSIONS]);
+const ALLOWED_EXTENSIONS = new Set(['KHR_mesh_quantization', 'KHR_materials_emissive_strength', 'KHR_texture_transform', 'EXT_mesh_gpu_instancing', 'EXT_texture_webp', 'KHR_materials_unlit', 'KHR_lights_punctual', ...METADATA_EXTENSIONS, ...GLTF_LAYER_EXTENSIONS]);
const DECODER_BY_EXTENSION = { KHR_draco_mesh_compression: 'draco', EXT_meshopt_compression: 'meshopt', KHR_texture_basisu: 'ktx2' };
-// Accepted when optional, because 67js does not render them. Rejected when listed in extensionsRequired.
-const IGNORED_EXTENSIONS = new Set(GLTF_CAPABILITIES.ignoredExtensions);
const IDENTITY_UV_TRANSFORM = Object.freeze({ offset: [0, 0], rotation: 0, scale: [1, 1] });
const IDENTITY_UV_TRANSFORM_KEY = JSON.stringify([IDENTITY_UV_TRANSFORM.offset, IDENTITY_UV_TRANSFORM.rotation, IDENTITY_UV_TRANSFORM.scale]);
const MATERIAL_TEXTURES = [
@@ -172,12 +173,16 @@ function unsupportedExtensionError(extension) {
return new Error(`Unsupported glTF extension: ${extension}.${hint}`);
}
-/** Rejects unknown extensions and returns the sorted names of accepted but unrendered ones. */
+/**
+ * Returns the sorted names of optional extensions that 67js does not use and loads the file without them, as the glTF
+ * specification allows. Rejects an extension listed in extensionsRequired that 67js does not read, and a compression
+ * extension whose decoder is missing, because its meshes or textures would arrive empty.
+ */
function scanExtensions(document, allowedExtensions) {
const ignored = new Set();
function checkOptional(extension) {
if (allowedExtensions.has(extension)) return;
- if (!IGNORED_EXTENSIONS.has(extension)) throw unsupportedExtensionError(extension);
+ if (DECODER_BY_EXTENSION[extension]) throw unsupportedExtensionError(extension);
ignored.add(extension);
}
const pending = [document];
@@ -274,10 +279,9 @@ function validateMaterialExtensions(material) {
/** Validates EXT_mesh_gpu_instancing on a node and returns how many instances it expands to. */
function nodeInstanceCount(document, node, limits) {
- const extensions = Object.keys(node.extensions ?? {});
- if (!extensions.length) return 1;
- if (extensions.length > 1 || extensions[0] !== 'EXT_mesh_gpu_instancing') throw new Error('Node extensions other than EXT_mesh_gpu_instancing are unsupported.');
- const attributes = node.extensions.EXT_mesh_gpu_instancing.attributes;
+ const instancing = node.extensions?.EXT_mesh_gpu_instancing;
+ if (!instancing) return 1;
+ const attributes = instancing.attributes;
if (node.mesh === undefined || node.skin !== undefined) throw new Error('EXT_mesh_gpu_instancing requires a static mesh node without a skin.');
if (morphCount(document.meshes?.[node.mesh])) throw new Error('EXT_mesh_gpu_instancing with morph targets is unsupported.');
const shapes = { TRANSLATION: 'VEC3', ROTATION: 'VEC4', SCALE: 'VEC3' };
@@ -311,7 +315,8 @@ function validateDocument(document, limits, allowedExtensions) {
if (targetCount > MAX_MORPH_TARGETS) throw new Error('Morph target count exceeds 64.');
validateDefaultWeights(mesh.weights, targetCount);
for (const primitive of mesh.primitives ?? []) {
- if ((primitive.mode ?? 4) !== 4) throw new Error('Only glTF TRIANGLES primitives are supported.');
+ if (isLinePrimitive(primitive)) continue;
+ if ((primitive.mode ?? 4) !== 4) throw new Error('Only glTF TRIANGLES primitives are supported. POINTS, LINES, LINE_LOOP and LINE_STRIP are skipped with a warning.');
const position = document.accessors?.[primitive.attributes?.POSITION];
if (!position || position.type !== 'VEC3' || !Number.isSafeInteger(position.count) || position.count < 3) {
throw new Error('Each mesh primitive requires a valid POSITION accessor.');
@@ -392,6 +397,7 @@ function validateDocument(document, limits, allowedExtensions) {
if (node.skin !== undefined) {
if (!Number.isInteger(node.skin) || !document.skins?.[node.skin] || !document.meshes?.[node.mesh]) throw new Error('Invalid skinned mesh or skin index.');
for (const primitive of document.meshes[node.mesh].primitives ?? []) {
+ if (isLinePrimitive(primitive)) continue;
if (primitive.attributes?.JOINTS_0 === undefined || primitive.attributes?.WEIGHTS_0 === undefined) throw new Error('Skinned meshes require JOINTS_0 and WEIGHTS_0.');
poseJointCount += document.skins[node.skin].joints.length;
if (poseJointCount > limits.maxJoints) throw new Error('Instanced skin poses exceed maxJoints.');
@@ -433,6 +439,7 @@ function validateDocument(document, limits, allowedExtensions) {
}
for (const mesh of document.meshes ?? []) {
for (const primitive of mesh.primitives ?? []) {
+ if (isLinePrimitive(primitive)) continue;
const material = document.materials?.[primitive.material];
for (const [, reference] of materialTextureReferences(material ?? {})) {
const attribute = `TEXCOORD_${uvChannelOf(reference)}`;
@@ -453,6 +460,26 @@ function validateDocument(document, limits, allowedExtensions) {
return { vertices, ignoredExtensions };
}
+const LINE_MODE_NAMES = ['POINTS', 'LINES', 'LINE_LOOP', 'LINE_STRIP'];
+
+/** One warning per mesh that has point or line primitives, which 67js does not draw. */
+function skippedPrimitiveWarnings(document) {
+ const warnings = [];
+ (document.meshes ?? []).forEach((mesh, meshIndex) => {
+ const counts = new Map();
+ for (const primitive of mesh.primitives ?? []) {
+ if (!isLinePrimitive(primitive)) continue;
+ const modeName = LINE_MODE_NAMES[primitive.mode];
+ counts.set(modeName, (counts.get(modeName) ?? 0) + 1);
+ }
+ if (!counts.size) return;
+ const summary = [...counts].map(([modeName, count]) => `${count} ${modeName}`).join(', ');
+ const meshLabel = mesh.name ? `"${mesh.name}"` : meshIndex;
+ warnings.push(`Skipped ${summary} primitive(s) in mesh ${meshLabel}: 67js draws triangles only.`);
+ });
+ return warnings;
+}
+
function validateHierarchy(nodes) {
const parents = new Set();
for (const node of nodes) {
@@ -862,8 +889,9 @@ function textureDescriptorFor(texture, field, { colorSpace, uvChannel, uvTransfo
}
function convertMaterial(source, limits, maps, definition = {}) {
+ const unlit = Boolean(definition.extensions?.KHR_materials_unlit);
const material = {
- tag: 'gltf',
+ tag: unlit ? 'unlit' : 'gltf',
color: [...source.color],
metallic: source.metalness,
roughness: source.roughness,
@@ -876,17 +904,20 @@ function convertMaterial(source, limits, maps, definition = {}) {
material.alphaCutoff = definition.alphaCutoff ?? 0.5;
material.opacity = definition.pbrMetallicRoughness?.baseColorFactor?.[3] ?? 1;
material.doubleSided = definition.doubleSided ?? false;
- Object.assign(material, materialLayersFromGltf(definition));
+ if (!unlit) Object.assign(material, materialLayersFromGltf(definition));
+ // An unlit surface shows its base color alone, and the renderer's unlit tag takes only a base map.
+ if (unlit) material.emissiveColor = [0, 0, 0];
if (!material.emissiveColor.some(value => value > 0)) material.emission = 0;
if (!Number.isFinite(Math.fround(material.emission)) || material.emission < 0) throw new Error('Emissive intensity must be a finite nonnegative float.');
for (const [field, property, colorSpace] of MATERIAL_TEXTURES) {
+ if (unlit && field !== 'map') continue;
const texture = source[field === 'metallicRoughnessMap' ? 'metalnessMap' : field === 'occlusionMap' ? 'aoMap' : field];
if (!texture) continue;
const uvChannel = uvChannelOf(materialTexture(definition, property));
const uvTransform = field === 'normalMap' ? materialUvTransforms(definition).normalRelative : null;
material[field] = textureDescriptorFor(texture, field, { colorSpace, uvChannel, uvTransform }, limits, maps);
}
- for (const [name, reference, colorSpace] of layerTextureReferences(definition)) {
+ for (const [name, reference, colorSpace] of unlit ? [] : layerTextureReferences(definition)) {
const texture = source.layerTextures?.[name];
if (!texture) continue;
material.layerMaps ??= {};
@@ -902,7 +933,7 @@ export async function parseGltf(data, options = {}) {
const decoders = options.decoders ?? {};
const { ignoredExtensions } = validateDocument(document, limits, allowedExtensionsFor(decoders));
await loadLayerShadersFor(document);
- const warnings = ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`);
+ const warnings = [...ignoredExtensions.map(extension => `${extension} is accepted but not rendered.`), ...skippedPrimitiveWarnings(document)];
const dataBytes = typeof data === 'string' ? new TextEncoder().encode(data).byteLength : data.byteLength;
const { resourceBytes, textureScaling } = await prepareResources(document, data, dataBytes, options, limits);
if (textureScaling.scaledTextures.length) {
@@ -928,6 +959,10 @@ export async function parseGltf(data, options = {}) {
let actualVertices = 0;
gltf.scene.traverse(node => {
nodes.push(node);
+ const sourceNodeIndex = node.association?.nodes;
+ if (sourceNodeIndex !== undefined && document.nodes?.[sourceNodeIndex]?.extensions?.KHR_lights_punctual) {
+ lightNodes.push({ nodeIndex: sourceNodeIndex, matrix: Array.from(node.matrixWorld.elements) });
+ }
if (!node.isMesh) return;
const association = node.association;
const primitive = document.meshes?.[association?.meshes]?.primitives?.[association?.primitives];
@@ -982,6 +1017,8 @@ export async function parseGltf(data, options = {}) {
});
validateNodeTransforms(nodes, pendingNodeMatrix, pendingTransform);
if (!parts.length) throw new Error('glTF scene contains no supported triangle meshes.');
+ const { lights, warnings: lightWarnings } = readPunctualLights(document, lightNodes);
+ warnings.push(...lightWarnings);
if (meshNamesWithIgnoredAlpha.size) {
warnings.push(`Ignored the alpha of RGBA COLOR_0 vertex colors in ${[...meshNamesWithIgnoredAlpha].join(', ')}; only the RGB is used.`);
}
@@ -1325,7 +1362,7 @@ export async function parseGltf(data, options = {}) {
}
return stagePose({ animation: { clip: clipIndex, time: Math.max(0, Math.min(time, clip.duration)) } }).commit();
}
- return { parts, warnings, scaledTextures: textureScaling.scaledTextures, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,
+ return { parts, warnings, lights, scaledTextures: textureScaling.scaledTextures, skins: skinBindings.map(binding => binding.skin), animations: gltf.animations,
get nodes() { return structuredClone(nodeMetadata); }, stagePose, applyAnimation, dispose, capabilities: GLTF_CAPABILITIES };
} catch (error) {
gltf?.release();
diff --git a/tests/gltf-extensions.test.js b/tests/gltf-extensions.test.js
index 4e96baea..a6c6b3c1 100644
--- a/tests/gltf-extensions.test.js
+++ b/tests/gltf-extensions.test.js
@@ -268,8 +268,8 @@ test('metadata extensions such as KHR_xmp_json_ld and the earlier KHR_xmp do not
});
test('required material extensions, bad layer values and missing decoders are rejected', async () => {
- const required = triangleDocument({ edit: document => { document.extensionsRequired = ['KHR_materials_unlit']; } });
- await assert.rejects(parseGltf(required), /Unsupported glTF extension: KHR_materials_unlit/);
+ const required = triangleDocument({ edit: document => { document.extensionsRequired = ['KHR_materials_made_up']; } });
+ await assert.rejects(parseGltf(required), /Unsupported glTF extension: KHR_materials_made_up/);
const badIridescence = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_iridescence: { iridescenceFactor: 2 } }; } });
await assert.rejects(parseGltf(badIridescence), /iridescence must be between 0 and 1/);
const badTransmission = triangleDocument({ edit: document => { document.materials[0].extensions = { KHR_materials_transmission: { transmissionFactor: 2 } }; } });
diff --git a/tests/gltf-optional.test.js b/tests/gltf-optional.test.js
new file mode 100644
index 00000000..61aaf400
--- /dev/null
+++ b/tests/gltf-optional.test.js
@@ -0,0 +1,131 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { parseGltf } from '../src/gltf.js';
+import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS } from '../src/lighting.js';
+
+const TRIANGLE_POSITIONS = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
+
+function triangleDocument(edit = () => {}) {
+ const bytes = new Uint8Array(TRIANGLE_POSITIONS.buffer);
+ const document = {
+ asset: { version: '2.0' },
+ scene: 0,
+ scenes: [{ nodes: [0] }],
+ nodes: [{ name: 'Triangle', mesh: 0 }],
+ meshes: [{ name: 'Body', primitives: [{ attributes: { POSITION: 0 }, material: 0 }] }],
+ materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.5, 0.25, 0.125, 1] } }],
+ accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] }],
+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: bytes.length }],
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${Buffer.from(bytes).toString('base64')}` }],
+ };
+ edit(document);
+ return JSON.stringify(document);
+}
+
+function addLights(document, lights, nodeEdits = []) {
+ document.extensionsUsed = ['KHR_lights_punctual'];
+ document.extensions = { KHR_lights_punctual: { lights } };
+ lights.forEach((light, index) => {
+ document.nodes.push({ name: `Light ${index}`, ...nodeEdits[index], extensions: { KHR_lights_punctual: { light: index } } });
+ document.scenes[0].nodes.push(document.nodes.length - 1);
+ });
+}
+
+test('a file that only lists KHR_lights_punctual, KHR_materials_unlit or EXT_texture_avif loads', async () => {
+ for (const extension of ['KHR_lights_punctual', 'KHR_materials_unlit']) {
+ const asset = await parseGltf(triangleDocument(document => { document.extensionsUsed = [extension]; }));
+ assert.equal(asset.parts.length, 1);
+ assert.deepEqual(asset.warnings, []);
+ }
+ const avif = await parseGltf(triangleDocument(document => { document.extensionsUsed = ['EXT_texture_avif']; }));
+ assert.equal(avif.parts.length, 1);
+ assert.deepEqual(avif.warnings, ['EXT_texture_avif is accepted but not rendered.']);
+});
+
+test('an optional extension that 67js does not know is ignored and named in the warnings', async () => {
+ const asset = await parseGltf(triangleDocument(document => {
+ document.extensionsUsed = ['VENDOR_made_up'];
+ document.materials[0].extensions = { VENDOR_made_up: {} };
+ }));
+ assert.deepEqual(asset.warnings, ['VENDOR_made_up is accepted but not rendered.']);
+});
+
+test('an unknown extension in extensionsRequired is still refused', async () => {
+ const data = triangleDocument(document => {
+ document.extensionsUsed = ['VENDOR_made_up'];
+ document.extensionsRequired = ['VENDOR_made_up'];
+ });
+ await assert.rejects(parseGltf(data), /Unsupported glTF extension: VENDOR_made_up\./);
+});
+
+test('line and point primitives are skipped with a warning that names the mesh', async () => {
+ const asset = await parseGltf(triangleDocument(document => {
+ document.meshes[0].primitives.push({ attributes: { POSITION: 0 }, mode: 1 }, { attributes: { POSITION: 0 }, mode: 0 });
+ }));
+ assert.equal(asset.parts.length, 1);
+ assert.deepEqual(asset.warnings, ['Skipped 1 LINES, 1 POINTS primitive(s) in mesh "Body": 67js draws triangles only.']);
+});
+
+test('a file with only line primitives has nothing to draw and says so', async () => {
+ const data = triangleDocument(document => { document.meshes[0].primitives[0].mode = 3; });
+ await assert.rejects(parseGltf(data), /no supported triangle meshes/);
+});
+
+test('triangle strips and fans are still refused', async () => {
+ const data = triangleDocument(document => { document.meshes[0].primitives[0].mode = 5; });
+ await assert.rejects(parseGltf(data), /Only glTF TRIANGLES primitives are supported/);
+});
+
+test('KHR_materials_unlit becomes the unlit tag and keeps only the base color', async () => {
+ const asset = await parseGltf(triangleDocument(document => {
+ document.extensionsUsed = ['KHR_materials_unlit'];
+ document.materials[0].extensions = { KHR_materials_unlit: {} };
+ document.materials[0].emissiveFactor = [1, 0, 0];
+ }));
+ const material = asset.parts[0].material;
+ assert.equal(material.tag, 'unlit');
+ assert.deepEqual(material.color, [0.5, 0.25, 0.125]);
+ assert.equal(material.emission, 0);
+ assert.deepEqual(asset.warnings, []);
+});
+
+test('KHR_lights_punctual lights map onto point, spot and key light options', async () => {
+ const asset = await parseGltf(triangleDocument(document => addLights(document, [
+ { type: 'point', color: [1, 0.5, 0.25], intensity: 40, range: 12, name: 'Lamp' },
+ { type: 'spot', intensity: 90, spot: { innerConeAngle: 0.2, outerConeAngle: 0.8 } },
+ { type: 'directional', color: [1, 1, 0.5], intensity: 3 },
+ ], [{ translation: [1, 2, 3] }, { translation: [0, 4, 0], rotation: [-Math.SQRT1_2, 0, 0, Math.SQRT1_2] }, {}])));
+ const { pointLights, spotLights, keyColor, lightDirection, keyIntensity } = asset.lights;
+ assert.equal(pointLights.length, 1);
+ assert.deepEqual(pointLights[0].position, [1, 2, 3]);
+ assert.deepEqual(pointLights[0].color, [1, 0.5, 0.25]);
+ assert.equal(pointLights[0].intensity, 40);
+ assert.equal(pointLights[0].range, 12);
+ assert.equal(spotLights.length, 1);
+ assert.deepEqual(spotLights[0].position, [0, 4, 0]);
+ assert.ok(Math.abs(spotLights[0].direction[1] + 1) < 1e-6, 'a spot turned to face down shines along -Y');
+ assert.equal(spotLights[0].angle, 0.8);
+ assert.ok(Math.abs(spotLights[0].penumbra - 0.75) < 1e-6);
+ assert.deepEqual(keyColor, [3, 3, 1.5]);
+ assert.deepEqual(lightDirection, [0, 0, 1], 'the key direction points toward the light, against its travel along -Z');
+ assert.equal(keyIntensity, 1);
+ assert.deepEqual(asset.warnings, []);
+});
+
+test('lights beyond the renderer limits are skipped, each with a warning', async () => {
+ const lights = Array.from({ length: MAX_POINT_LIGHTS + 2 }, () => ({ type: 'point' }));
+ lights.push(...Array.from({ length: MAX_SPOT_LIGHTS + 1 }, () => ({ type: 'spot' })));
+ lights.push({ type: 'directional' }, { type: 'directional', name: 'Second sun' }, { type: 'spot', spot: { innerConeAngle: 1, outerConeAngle: 0.5 } });
+ const asset = await parseGltf(triangleDocument(document => addLights(document, lights)));
+ assert.equal(asset.lights.pointLights.length, MAX_POINT_LIGHTS);
+ assert.equal(asset.warnings.filter(warning => /at most 8 point lights/.test(warning)).length, 2);
+ assert.equal(asset.warnings.filter(warning => /Second sun/.test(warning)).length, 1);
+ assert.equal(asset.warnings.filter(warning => /cone angles are invalid/.test(warning)).length, 1);
+ assert.equal(asset.lights.spotLights.length, MAX_SPOT_LIGHTS);
+ assert.equal(asset.warnings.filter(warning => /at most 8 spot lights/.test(warning)).length, 1);
+});
+
+test('a file without lights returns an empty lights object', async () => {
+ const asset = await parseGltf(triangleDocument());
+ assert.deepEqual(asset.lights, {});
+});
diff --git a/tests/gltf.test.js b/tests/gltf.test.js
index 44ab19e6..b967fda8 100644
--- a/tests/gltf.test.js
+++ b/tests/gltf.test.js
@@ -170,13 +170,13 @@ test('unsupported features fail explicitly before loading resources', async () =
primitive.targets = [{ TANGENT: 0 }];
}, /Unsupported morph/],
[document => { document.meshes[0].primitives[0].attributes.COLOR_0 = 1; }, /COLOR_0/],
- [document => { document.meshes[0].primitives[0].mode = 1; }, /TRIANGLES/],
+ [document => { document.meshes[0].primitives[0].mode = 5; }, /TRIANGLES/],
[document => { document.materials[0].alphaMode = 'DITHER'; }, /alpha mode/],
[document => { document.materials[0].alphaCutoff = 2; }, /alphaCutoff/],
[document => { document.materials[0].doubleSided = 'yes'; }, /doubleSided/],
[document => { document.materials[0].normalTexture = { index: 0 }; }, /normalTexture texture index/],
[document => { document.extensionsRequired = ['KHR_draco_mesh_compression']; }, /KHR_draco/],
- [document => { document.materials[0].extensions = { KHR_materials_unknown_vendor: {} }; }, /KHR_materials_unknown_vendor/],
+ [document => { document.extensionsRequired = ['KHR_materials_unknown_vendor']; }, /KHR_materials_unknown_vendor/],
[document => { document.buffers[0].uri = 'external.bin'; }, /baseUrl/],
[document => { document.nodes[2].children = [0]; }, /Cyclic/],
[document => { document.materials[0].pbrMetallicRoughness.metallicFactor = 2; }, /metallic/],