Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Qualify an opt-in community glTF exporter and engine import checks (#115)

Matthew Kissingere1f1e3d6274a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aedcdd96..f8be07c9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -59,6 +59,14 @@ jobs:
- name: Unit tests and coverage gate
run: bun run test:coverage
+ - name: Verify experimental exporter worker and cache isolation
+ run: node scripts/exporter-cli-check.mjs
+
+ - name: Engine regressions with the community exporter selected
+ env:
+ KILN_GLTF_EXPORTER: three
+ run: bun run test
+
- name: Upload coverage report
if: ${{ always() && hashFiles('coverage/lcov.info') != '' }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
@@ -127,6 +135,9 @@ jobs:
- name: Unit tests
run: bun run test
+ - name: Verify experimental exporter worker and cache isolation
+ run: node scripts/exporter-cli-check.mjs
+
# Diagnostic only, and deliberately failure-tolerant: it exists so that IF the
# GLib fault returns, the libvips/GLib versions arrive attached to that run
# rather than needing a second investigation to reconstruct. It must never be
@@ -226,7 +237,9 @@ jobs:
env:
EXPECTED_ARCH: ${{ matrix.arch }}
run: node -e "if(process.platform!=='darwin'||process.arch!==process.env.EXPECTED_ARCH)process.exit(1);console.log(process.platform,process.arch,process.version)"
- - name: Install and exercise the end-user distribution
+ # Includes opt-in community export through the sanitized worker with native
+ # texture encoding, glTF validation and reload; no renderer or GPU required.
+ - name: Install and exercise default and community exporter distribution
shell: bash
run: |
set -euo pipefail
@@ -268,7 +281,7 @@ jobs:
path: candidate
- name: Verify native host
run: node -e "if(process.platform!=='linux')process.exit(1);console.log(process.platform,process.arch,process.version)"
- - name: Install and exercise the end-user distribution
+ - name: Install and exercise default and community exporter distribution
shell: bash
run: |
set -euo pipefail
@@ -306,7 +319,7 @@ jobs:
# bash, not pwsh: the glob expansion and the single-tarball assertion below are the
# same on every platform, and Windows runners ship Git bash. 13.4's Windows reds
# were real defects, so this job gets the same 30-minute bound that one does.
- - name: Install and exercise the end-user distribution
+ - name: Install and exercise default and community exporter distribution
shell: bash
run: |
set -euo pipefail
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc68e79a..ce34b15d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,18 @@
Changes to `@kiln/engine`. Source and installable packages are distributed through
GitHub. The package is not published on the npm registry.
+## Unreleased: Experimental community exporter and engine handoff
+
+- The established GLB exporter remains the default. Builds containing this integration also
+ provide an experimental Three.js exporter for explicit comparison; no separate repository
+ is needed. See the [Blender/Unity handoff guide](docs/engine-handoff.md) for scoped CLI/MCP
+ activation, restoration of the default, tested import routes and known limitations.
+- Authoring and QA skills include the handoff guide so agents can discover the option when
+ destination requirements call for it. Blender/Unity does not automatically select it.
+- Expanded export, GPU, deformation and clean-package checks are documented in the
+ [qualification report](docs/evaluation/community-exporter.md). The candidate is not yet
+ qualified to replace the default for all supported workflows.
+
## 0.7.1: Preserve CLI outputs on failed writes
- GLB, preview PNG, and generated source replacements are written to unique sibling
diff --git a/README.md b/README.md
index a9698b69..f918d9c7 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,12 @@ This writes a GLB and a six-view image of an existing program. It makes no model
Rendering uses the CPU unless a compatible local GPU service is available.
Use `--render cpu` to select the CPU explicitly.
+**Using assets in Blender or Unity?** Read the [handoff guide](docs/engine-handoff.md) for direct GLB import,
+materials, backfaces, named pivots and animation checks. The established exporter remains
+the default. An **experimental community exporter** is available for explicit comparison
+when you need its additional feature preservation; the guide includes activation, rollback
+and known limitations. No separate repository is required once this integration is on main.
+
History was rewritten on 2026-09-10 to drop 288 MB of gallery renders and launch
video that no tool reads, taking a clone from 440 MB to 60 MB, or 49 MB with
`--filter=blob:none`; measured 2026-09-12. Every commit survived and the tree is
diff --git a/bun.lock b/bun.lock
index b9da708c..4d293b83 100644
--- a/bun.lock
+++ b/bun.lock
@@ -35,6 +35,9 @@
"openai": "^6.49.0",
"typescript": "^7.0.2",
},
+ "optionalDependencies": {
+ "@napi-rs/canvas": "1.0.9",
+ },
"peerDependencies": {
"@ai-sdk/provider": "^3.0.0",
"@strands-agents/sdk": "^1.4.0",
@@ -201,6 +204,30 @@
"@modelcontextprotocol/server": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
+ "@napi-rs/canvas": ["@napi-rs/[email protected]", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.9", "@napi-rs/canvas-darwin-arm64": "1.0.9", "@napi-rs/canvas-darwin-x64": "1.0.9", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.9", "@napi-rs/canvas-linux-arm64-gnu": "1.0.9", "@napi-rs/canvas-linux-arm64-musl": "1.0.9", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.9", "@napi-rs/canvas-linux-x64-gnu": "1.0.9", "@napi-rs/canvas-linux-x64-musl": "1.0.9", "@napi-rs/canvas-win32-arm64-msvc": "1.0.9", "@napi-rs/canvas-win32-x64-msvc": "1.0.9" } }, "sha512-QviPdJImDi/jMAvBfqaw+19BndMd/sizXVW3NnpMd3VJGz++QXkOHcP9kWR/smHG0hNjHeyuHFyrx/5lD0oNcQ=="],
+
+ "@napi-rs/canvas-android-arm64": ["@napi-rs/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-4LGXk2/0HVzE29K8SzML5WubgCp++B1FH3qgl35XmSZE+lLdr6P9VRQEnZ0MCLZMTSuJP41yyhtoiVNEuvrTIA=="],
+
+ "@napi-rs/canvas-darwin-arm64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-YNdfLBzY0W/Pep9fo2L6RmoNlNksnn05LRnX66W63R3ij58S25QOTcjdtEt2v8+PnCESzqZsYzUo+QPeIR44NA=="],
+
+ "@napi-rs/canvas-darwin-x64": ["@napi-rs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-ceZQSknTEcy3dOXoekv59LTCkXjvnLsq+VW5PeNNDHEPQbRS5Ervkm1EaDa7WLAjiYWMLuSQTRTHao1dEX4prg=="],
+
+ "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-XhfI0Wwv4llhd6nnWDtY3kQKjq0r+y1i91PlJlJI24ag2U9WrnwbG1qS3+fDLEyouwEVFchiKkTEHozK+5iUNA=="],
+
+ "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-012oiYtKaE7i9oxc8q7nraT7kDOpLcaCmFLzVe9Ty34RHDdoDzbWLrVh827CNxYh/EADX1eSikA3ymLjo/nNuw=="],
+
+ "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ls5UWYFFn63casTZEczbeyEg3vRDRkv9lscuGwfchtY5yLLQhgOB8SN4YGxmfJ5vTaBwZ2YUxBS3NtmjJmFXdA=="],
+
+ "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-hLKEGxV7ZiRHqndePTokgDMdBlo/rDfzg7P4p4QIv9pUhuYobnu3R2NIFLCRghG0nwfo+s2sw+c1xZFeCmEAsw=="],
+
+ "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-6kaz3w0QMy77PDWk6rJ1ksIihdad3qzEyX2o2oGT8GwCaypfT5mhjr8buOO5hstyLxcWXDScuz56RsINLtBPIQ=="],
+
+ "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-xrGvmS3v55hmZ86ls/kBLVNMUTYio3f6Ik0DireemG994VfPAwiA3ZXA0Uf1bByctkB3NQ1Sfb+H5bkdUnnzfQ=="],
+
+ "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-yjmVS3ArZeRVCP7jqbPq4rpZa/BhTeI7ELE2XqJg3snICQBDevLZyArxswHkiTnT34KRic33/4fLirrHI+SY8A=="],
+
+ "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-QlSYQdMQslB81nlABo9wNfQ6npFhE7/O+saCZdqVGueGanyRk4jCogD5EwQenfP3kIq9e+mm6GreQBjX5MrA8g=="],
+
"@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="],
"@openrouter/ai-sdk-provider": ["@openrouter/[email protected]", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-FMsAEjLUt5pWuRE2LDC/LCvVrFjLlrEzUITH5+5SZtfq7KZ2wrOHjQVxzz92sju8S9ltpzW87CLW8/b0oBXVCw=="],
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 1f72e519..d3d17348 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -8260,7 +8260,238 @@ var init_types = __esm(() => {
];
});
+// src/gltf-io.ts
+import { WebIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+function createGltfIO() {
+ return new WebIO().registerExtensions(ALL_EXTENSIONS);
+}
+var init_gltf_io = () => {};
+
+// src/community-exporter.ts
+import * as THREE4 from "three";
+import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
+function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
+ if (value === undefined || value === "legacy")
+ return "legacy";
+ if (value === "three")
+ return "three";
+ throw new Error(`Invalid KILN_GLTF_EXPORTER ${JSON.stringify(value)}; use legacy or three.`);
+}
+function cleanClone(source) {
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ return shadow.clone();
+}
+async function communitySceneDocument(root, clips, platform = browserPlatform) {
+ const materials = new Map;
+ const textures = new Map;
+ const nodes = new Map;
+ const encoded = [];
+ function texture(source) {
+ const found = textures.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ normalizeTextureTransform(copy);
+ copy.source = new THREE4.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData["encoded"];
+ if (bytes?.bytes) {
+ encoded.push((async () => {
+ copy.image = await platform.decode(bytes.bytes);
+ Object.defineProperty(copy, "isDataTexture", { value: true });
+ copy.format = THREE4.RGBAFormat;
+ copy.type = THREE4.UnsignedByteType;
+ })());
+ }
+ return copy;
+ }
+ function material(source) {
+ const found = materials.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ const physical = copy;
+ if (physical.isMeshPhysicalMaterial && physical.sheen > 0) {
+ physical.sheenColor.multiplyScalar(physical.sheen);
+ physical.sheen = 1;
+ }
+ for (const [key, value] of Object.entries(copy)) {
+ if (value instanceof THREE4.Texture)
+ copy[key] = texture(value);
+ }
+ materials.set(source, copy);
+ return copy;
+ }
+ function node(source) {
+ if (source.isLine || source.isPoints)
+ throw new Error("Experimental glTF exporter supports triangle meshes and sprites, not lines or points.");
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ let copy = shadow.clone(false);
+ if (source.isScene) {
+ copy = new THREE4.Group;
+ copy.copy(shadow, false);
+ }
+ if (source.isSprite) {
+ const sprite = source;
+ const geometry = new THREE4.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE4.MeshBasicMaterial({
+ name: sprite.material.name,
+ color: sprite.material.color,
+ opacity: sprite.material.opacity,
+ transparent: sprite.material.transparent,
+ alphaTest: sprite.material.alphaTest,
+ side: sprite.material.side,
+ map: sprite.material.map ? texture(sprite.material.map) : null
+ });
+ copy = new THREE4.Mesh(geometry, spriteMaterial);
+ THREE4.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ if (semantic !== undefined) {
+ const checked = validateSemanticMetadataV1(semantic);
+ if (!checked.valid || !checked.value)
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on ${source.name}`);
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(checked.value);
+ }
+ if (source.isSprite) {
+ const metadata = copy.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = createSemanticMetadataV1({
+ ...metadata,
+ roles: [
+ ...(metadata?.roles ?? []).filter((role) => !role.startsWith("vfx.facing.")),
+ "vfx.facing.camera-spherical",
+ ...metadata?.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
+ ]
+ });
+ }
+ if (source.isMesh) {
+ const original = source;
+ const mesh = copy;
+ mesh.geometry = cleanClone(original.geometry);
+ mesh.material = Array.isArray(original.material) ? original.material.map(material) : material(original.material);
+ }
+ nodes.set(source, copy);
+ for (const child of source.children)
+ copy.add(node(child));
+ return copy;
+ }
+ const copy = node(root);
+ for (const [source, target] of nodes) {
+ if (!source.isSkinnedMesh)
+ continue;
+ const original = source;
+ const mesh = target;
+ mesh.skeleton = original.skeleton.clone();
+ mesh.skeleton.bones = original.skeleton.bones.map((bone) => {
+ const mapped = nodes.get(bone);
+ if (!mapped)
+ throw new Error(`Skin bone ${bone.name} is outside the exported hierarchy.`);
+ return mapped;
+ });
+ mesh.bind(mesh.skeleton, original.bindMatrix);
+ }
+ await Promise.all(encoded);
+ await platform.prepare(textures.size > 0);
+ const exportClips = clips.map((clip) => {
+ const cloned = cleanClone(clip);
+ for (const track of cloned.tracks) {
+ for (const [source, target] of nodes) {
+ if (track.name.startsWith(`${source.uuid}.`))
+ track.name = target.uuid + track.name.slice(source.uuid.length);
+ }
+ }
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE4.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE4.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ } catch {
+ return false;
+ }
+ });
+ return cloned;
+ });
+ const bytes = await new GLTFExporter().parseAsync(copy, {
+ binary: true,
+ trs: true,
+ onlyVisible: false,
+ animations: exportClips.filter((clip) => clip.tracks.length > 0)
+ });
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(new Uint8Array(bytes));
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name)
+ continue;
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name)
+ image.name = binding.name;
+ }
+ return io.readJSON(json);
+}
+function normalizeTextureTransform(texture) {
+ if (texture.matrixAutoUpdate)
+ texture.updateMatrix();
+ const e = texture.matrix.elements;
+ const sx = Math.hypot(e[0], e[1]);
+ const rotation = sx > 0 ? Math.atan2(-e[1], e[0]) : Math.atan2(e[3], e[4]);
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ const sy = e[3] * s + e[4] * c;
+ const reconstructed = [sx * c, -sx * s, 0, sy * s, sy * c, 0, e[6], e[7], 1];
+ const tolerance = 0.0000001 * Math.max(1, ...e.map(Math.abs));
+ if (e.some((value, i) => !Number.isFinite(value) || Math.abs(value - reconstructed[i]) > tolerance)) {
+ throw new Error(`Texture ${texture.name || "<unnamed>"}: UV matrix contains shear or perspective that KHR_texture_transform cannot represent; lossless UV baking is not yet qualified.`);
+ }
+ texture.offset.set(e[6], e[7]);
+ texture.repeat.set(sx, sy);
+ texture.rotation = rotation;
+ texture.center.set(0, 0);
+ texture.matrixAutoUpdate = false;
+}
+var browserPlatform;
+var init_community_exporter = __esm(() => {
+ init_gltf_io();
+ init_contracts();
+ browserPlatform = {
+ async prepare() {},
+ async decode(bytes) {
+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]), {
+ colorSpaceConversion: "none"
+ });
+ try {
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("A 2D canvas is required to decode export textures.");
+ context.drawImage(bitmap, 0, 0);
+ const image = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ return { data: new Uint8Array(image.data), width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ }
+ };
+});
+
// src/geometry-export.ts
+function validateMaterialGroups(geometry, materialCount, name) {
+ const length = geometry.getIndex()?.count ?? geometry.getAttribute("position").count;
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ const materialIndex = group.materialIndex ?? 0;
+ if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > length || !Number.isInteger(materialIndex) || materialIndex < 0 || materialIndex >= materialCount)
+ throw new TypeError(`${name}: material groups must cover every triangle exactly once with valid material indices.`);
+ covered = group.start + group.count;
+ }
+ if (covered !== length)
+ throw new TypeError(`${name}: material groups do not cover every triangle.`);
+ return groups;
+}
function geometryAttributeValues(attribute) {
const values = new Float32Array(attribute.count * attribute.itemSize);
for (let vertex = 0;vertex < attribute.count; vertex++) {
@@ -8270,7 +8501,7 @@ function geometryAttributeValues(attribute) {
}
return values;
}
-function inspectGeometryExport(root, policy = "warn") {
+function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
const warnings = [];
root.traverse((node) => {
const mesh = node;
@@ -8288,7 +8519,14 @@ function inspectGeometryExport(root, policy = "warn") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];
+ const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key] ?? (exporter === "three" ? {
+ color: attribute.itemSize === 4 ? 4 : 3,
+ uv1: 2,
+ uv2: 2,
+ uv3: 2,
+ skinIndex: 4,
+ skinWeight: 4
+ }[key] : undefined);
if (expected === undefined) {
unsupported(key);
continue;
@@ -8314,10 +8552,14 @@ function inspectGeometryExport(root, policy = "warn") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
- for (const key of Object.keys(geometry.morphAttributes))
- unsupported(`morph ${key}`);
- if (mesh.isSkinnedMesh)
- unsupported("skinning");
+ if (exporter === "three" && Array.isArray(mesh.material))
+ validateMaterialGroups(geometry, mesh.material.length, name);
+ if (exporter === "legacy") {
+ for (const key of Object.keys(geometry.morphAttributes))
+ unsupported(`morph ${key}`);
+ if (mesh.isSkinnedMesh)
+ unsupported("skinning");
+ }
for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {
const notes = geometry.userData[key];
if (!Array.isArray(notes))
@@ -8451,7 +8693,7 @@ var dE2 = (a, b) => {
}, chroma = (lab) => Math.hypot(lab[1], lab[2]), REL_CHROMA_GATE = 0.04, relChroma = (lab) => chroma(lab) / Math.max(lab[0], 0.25);
// src/architecture.ts
-import * as THREE4 from "three";
+import * as THREE5 from "three";
function positive2(value, name) {
if (!Number.isFinite(value) || value <= 0)
throw new RangeError(`${name} must be finite and > 0`);
@@ -8516,17 +8758,17 @@ function buildFace(roofRoot, profile, sideSign) {
const verticalRun = profile.ridgeY - profile.eaveY;
const downhillLength = Math.hypot(horizontalRun, verticalRun);
const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;
- const downhill = profile.ridgeAxis === "x" ? new THREE4.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE4.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
- const tangent = profile.ridgeAxis === "x" ? new THREE4.Vector3(sideSign, 0, 0) : new THREE4.Vector3(0, 0, -sideSign);
+ const downhill = profile.ridgeAxis === "x" ? new THREE5.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE5.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
+ const tangent = profile.ridgeAxis === "x" ? new THREE5.Vector3(sideSign, 0, 0) : new THREE5.Vector3(0, 0, -sideSign);
const normal = downhill.clone().cross(tangent).normalize();
- const localToRoof = new THREE4.Matrix4().makeBasis(tangent, normal, downhill);
+ const localToRoof = new THREE5.Matrix4().makeBasis(tangent, normal, downhill);
localToRoof.setPosition(0, profile.ridgeY, 0);
const world = () => {
roofRoot.updateWorldMatrix(true, false);
return roofRoot.matrixWorld.clone().multiply(localToRoof);
};
const direction = (axis) => axis.clone().transformDirection(world());
- const point = (x, z) => new THREE4.Vector3(x, 0, z).applyMatrix4(world());
+ const point = (x, z) => new THREE5.Vector3(x, 0, z).applyMatrix4(world());
return {
side,
ridgeAxis: profile.ridgeAxis,
@@ -8536,13 +8778,13 @@ function buildFace(roofRoot, profile, sideSign) {
return world();
},
get ridgeTangent() {
- return direction(new THREE4.Vector3(1, 0, 0));
+ return direction(new THREE5.Vector3(1, 0, 0));
},
get downhillDirection() {
- return direction(new THREE4.Vector3(0, 0, 1));
+ return direction(new THREE5.Vector3(0, 0, 1));
},
get outwardNormal() {
- return direction(new THREE4.Vector3(0, 1, 0));
+ return direction(new THREE5.Vector3(0, 1, 0));
},
get ridgeStart() {
return point(-alongRidge / 2, 0);
@@ -8560,17 +8802,17 @@ function buildFace(roofRoot, profile, sideSign) {
};
}
function buildRoof(name, material, profile, parent) {
- const root = new THREE4.Object3D;
+ const root = new THREE5.Object3D;
root.name = name;
if (parent)
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));
const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];
const buildSlope = (face) => {
- const geometry = new THREE4.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
- const mesh = new THREE4.Mesh(geometry, material);
+ const geometry = new THREE5.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
+ const mesh = new THREE5.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${face.side}`;
- const center = new THREE4.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
+ const center = new THREE5.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
setTransform(mesh, face.localToRoof.clone().multiply(center));
const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";
stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [
@@ -8640,7 +8882,7 @@ function createGableEndPanel(name, material, options) {
const ridgeAxis = options.ridgeAxis ?? "x";
const side = options.side ?? "positive";
const half = span / 2;
- const shape = new THREE4.Shape;
+ const shape = new THREE5.Shape;
shape.moveTo(-half, 0);
shape.lineTo(half, 0);
shape.lineTo(0, rise);
@@ -8659,7 +8901,7 @@ function createGableEndPanel(name, material, options) {
const right = opening.offset + opening.width / 2;
const bottom = opening.bottom;
const top = bottom + opening.height;
- const hole = new THREE4.Path;
+ const hole = new THREE5.Path;
hole.moveTo(left, bottom);
hole.lineTo(left, top);
hole.lineTo(right, top);
@@ -8667,7 +8909,7 @@ function createGableEndPanel(name, material, options) {
hole.closePath();
shape.holes.push(hole);
}
- const geometry = new THREE4.ExtrudeGeometry(shape, {
+ const geometry = new THREE5.ExtrudeGeometry(shape, {
depth: thickness,
bevelEnabled: false,
steps: 1
@@ -8676,7 +8918,7 @@ function createGableEndPanel(name, material, options) {
if (ridgeAxis === "x")
geometry.rotateY(-Math.PI / 2);
geometry.computeVertexNormals();
- const root = new THREE4.Mesh(geometry, material);
+ const root = new THREE5.Mesh(geometry, material);
root.name = `Mesh_${name}`;
stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [
relationship("adjacent-to", "roof.slope.positive"),
@@ -8692,7 +8934,7 @@ function createGableEndPanel(name, material, options) {
}
]));
const markers = normalized.map((opening, index) => {
- const marker = new THREE4.Object3D;
+ const marker = new THREE5.Object3D;
marker.name = `Opening_${name}_${opening.id ?? index + 1}`;
marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);
marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);
@@ -8712,7 +8954,7 @@ function wallNeighbors(wall) {
}
function createShellWall(name, wall, material, length, height, thickness, openings) {
const axis = wallRunAxis(wall);
- const root = new THREE4.Object3D;
+ const root = new THREE5.Object3D;
root.name = `${name}_Wall_${wall}`;
const neighbors = wallNeighbors(wall);
stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [
@@ -8735,8 +8977,8 @@ function createShellWall(name, wall, material, length, height, thickness, openin
const panel = (suffix, lo, hi, y0, y1) => {
if (hi - lo <= EPSILON || y1 - y0 <= EPSILON)
return;
- const geometry = axis === "x" ? new THREE4.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE4.BoxGeometry(thickness, y1 - y0, hi - lo);
- const mesh = new THREE4.Mesh(geometry, material);
+ const geometry = axis === "x" ? new THREE5.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE5.BoxGeometry(thickness, y1 - y0, hi - lo);
+ const mesh = new THREE5.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${wall}_${suffix}`;
mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);
root.add(mesh);
@@ -8756,7 +8998,7 @@ function createShellWall(name, wall, material, length, height, thickness, openin
panel("lintel", left, right, top, height);
if (opening.sill > 0)
panel("sill", left, right, 0, opening.sill);
- const marker = new THREE4.Object3D;
+ const marker = new THREE5.Object3D;
marker.name = `Opening_${wall}_${opening.id}`;
marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);
marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);
@@ -8779,7 +9021,7 @@ function createGableShell(name, materials, options) {
const closedEnds = options.closedEnds ?? true;
const enterable = options.enterable ?? true;
const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);
- const root = new THREE4.Object3D;
+ const root = new THREE5.Object3D;
root.name = name;
if (options.parent)
options.parent.add(root);
@@ -8799,7 +9041,7 @@ function createGableShell(name, materials, options) {
walls[wall] = built.root;
openingMarkers.push(...built.openings);
}
- const floor = new THREE4.Mesh(new THREE4.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
+ const floor = new THREE5.Mesh(new THREE5.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
floor.name = `Mesh_${name}_Floor`;
floor.position.y = -floorThickness / 2;
stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));
@@ -8845,7 +9087,7 @@ function createGableShell(name, materials, options) {
}
function createRoofSurfaceLayout(name, material, options) {
const parent = options.parent ?? options.face.roofRoot;
- const root = new THREE4.Object3D;
+ const root = new THREE5.Object3D;
root.name = name;
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));
@@ -8897,9 +9139,9 @@ function createRoofSurfaceLayout(name, material, options) {
});
}
const items = specs.map((spec, index) => {
- const mesh = new THREE4.Mesh(new THREE4.BoxGeometry(spec.width, thickness, spec.length), material);
+ const mesh = new THREE5.Mesh(new THREE5.BoxGeometry(spec.width, thickness, spec.length), material);
mesh.name = `Mesh_${name}_${index + 1}`;
- const local = new THREE4.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
+ const local = new THREE5.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
setTransform(mesh, faceToRoot.clone().multiply(local));
root.add(mesh);
return mesh;
@@ -8913,7 +9155,7 @@ var init_architecture = __esm(() => {
});
// src/gears.ts
-import * as THREE5 from "three";
+import * as THREE6 from "three";
function gearGeo(opts = {}) {
const {
teeth = 12,
@@ -9007,8 +9249,8 @@ function gearGeo(opts = {}) {
indices.push(tA, bA, bB);
indices.push(tA, bB, tB);
}
- const geo = new THREE5.BufferGeometry;
- geo.setAttribute("position", new THREE5.Float32BufferAttribute(positions, 3));
+ const geo = new THREE6.BufferGeometry;
+ geo.setAttribute("position", new THREE6.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -9096,8 +9338,8 @@ function bladeGeo(opts = {}) {
}
}
}
- const geo = new THREE5.BufferGeometry;
- geo.setAttribute("position", new THREE5.Float32BufferAttribute(positions, 3));
+ const geo = new THREE6.BufferGeometry;
+ geo.setAttribute("position", new THREE6.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -9108,7 +9350,7 @@ var init_gears = __esm(() => {
});
// src/ops.ts
-import * as THREE6 from "three";
+import * as THREE7 from "three";
import { LoopSubdivision } from "three-subdivide/build/index.module.js";
import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";
function arrayLinear(namePrefix, source, count, offset, parent) {
@@ -9128,19 +9370,19 @@ function arrayLinear(namePrefix, source, count, offset, parent) {
}
function degreesOf(euler) {
return [
- THREE6.MathUtils.radToDeg(euler.x),
- THREE6.MathUtils.radToDeg(euler.y),
- THREE6.MathUtils.radToDeg(euler.z)
+ THREE7.MathUtils.radToDeg(euler.x),
+ THREE7.MathUtils.radToDeg(euler.y),
+ THREE7.MathUtils.radToDeg(euler.z)
];
}
function arrayRadial(namePrefix, source, count, axis = "y", parent, center) {
const out = [];
- const pivot = center ? new THREE6.Vector3(...center) : new THREE6.Vector3;
+ const pivot = center ? new THREE7.Vector3(...center) : new THREE7.Vector3;
const basePos = source.position.clone().sub(pivot);
- const axisVec = axis === "x" ? new THREE6.Vector3(1, 0, 0) : axis === "z" ? new THREE6.Vector3(0, 0, 1) : new THREE6.Vector3(0, 1, 0);
+ const axisVec = axis === "x" ? new THREE7.Vector3(1, 0, 0) : axis === "z" ? new THREE7.Vector3(0, 0, 1) : new THREE7.Vector3(0, 1, 0);
for (let i = 1;i < count; i++) {
const angle = i / count * Math.PI * 2;
- const m = new THREE6.Matrix4().makeRotationAxis(axisVec, angle);
+ const m = new THREE7.Matrix4().makeRotationAxis(axisVec, angle);
const rotated = basePos.clone().applyMatrix4(m).add(pivot);
const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];
out.push(createInstance(`${namePrefix}${i}`, source, {
@@ -9169,25 +9411,25 @@ function mergeVertices(geometry, opts = {}) {
const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;
if (!positionOnly)
return threeMergeVertices(geometry, tolerance);
- const stripped = new THREE6.BufferGeometry;
+ const stripped = new THREE7.BufferGeometry;
const pos = geometry.getAttribute("position");
if (!pos)
return geometry;
- stripped.setAttribute("position", new THREE6.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
+ stripped.setAttribute("position", new THREE7.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
if (geometry.index) {
- stripped.setIndex(new THREE6.BufferAttribute(new Uint32Array(geometry.index.array), 1));
+ stripped.setIndex(new THREE7.BufferAttribute(new Uint32Array(geometry.index.array), 1));
}
return threeMergeVertices(stripped, tolerance);
}
function subdivide(geometry, iterations = 1, opts = {}) {
const { weld = true, preserveUV = false, ...subOpts } = opts;
const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();
- const center = new THREE6.Vector3;
+ const center = new THREE7.Vector3;
let normalizationScale = 1;
if (preserveUV) {
subOpts.uvSmooth = false;
input.computeBoundingBox();
- const extent = input.boundingBox.getSize(new THREE6.Vector3);
+ const extent = input.boundingBox.getSize(new THREE7.Vector3);
input.boundingBox.getCenter(center);
const size = Math.max(extent.x, extent.y, extent.z);
normalizationScale = size > 0 ? 1e4 / size : 1;
@@ -9221,9 +9463,9 @@ function subdivide(geometry, iterations = 1, opts = {}) {
return output;
}
function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {
- const vectors = points.map((p) => new THREE6.Vector3(p[0], p[1], p[2]));
- const curve = new THREE6.CatmullRomCurve3(vectors, closed);
- return new THREE6.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = points.map((p) => new THREE7.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE7.CatmullRomCurve3(vectors, closed);
+ return new THREE7.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function normalizeSurfaceNormals(geo) {
const normal = geo.getAttribute("normal");
@@ -9250,20 +9492,20 @@ function normalizeSurfaceNormals(geo) {
return geo;
}
function lathe(profile, segments = 12) {
- const points2d = profile.map((p) => new THREE6.Vector2(p[0], p[1]));
- return normalizeSurfaceNormals(new THREE6.LatheGeometry(points2d, segments));
+ const points2d = profile.map((p) => new THREE7.Vector2(p[0], p[1]));
+ return normalizeSurfaceNormals(new THREE7.LatheGeometry(points2d, segments));
}
function revolveGeo(profile, options = {}) {
const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
- const points2d = profile.map((p) => new THREE6.Vector2(p[0], p[1]));
- const geo = normalizeSurfaceNormals(new THREE6.LatheGeometry(points2d, segments, 0, angle));
- const n = new THREE6.Vector3(axis[0], axis[1], axis[2]);
+ const points2d = profile.map((p) => new THREE7.Vector2(p[0], p[1]));
+ const geo = normalizeSurfaceNormals(new THREE7.LatheGeometry(points2d, segments, 0, angle));
+ const n = new THREE7.Vector3(axis[0], axis[1], axis[2]);
if (n.lengthSq() < 0.000000000001) {
throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);
}
n.normalize();
if (n.x !== 0 || n.y !== 1 || n.z !== 0) {
- const q = new THREE6.Quaternion().setFromUnitVectors(new THREE6.Vector3(0, 1, 0), n);
+ const q = new THREE7.Quaternion().setFromUnitVectors(new THREE7.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
}
return geo;
@@ -9278,9 +9520,9 @@ function pipeAlongPath(points, radius, options = {}) {
const smoothed = [];
smoothed.push(points[0]);
for (let i = 1;i < points.length - 1; i++) {
- const prev = new THREE6.Vector3(...points[i - 1]);
- const cur = new THREE6.Vector3(...points[i]);
- const next = new THREE6.Vector3(...points[i + 1]);
+ const prev = new THREE7.Vector3(...points[i - 1]);
+ const cur = new THREE7.Vector3(...points[i]);
+ const next = new THREE7.Vector3(...points[i + 1]);
const inDir = cur.clone().sub(prev);
const outDir = next.clone().sub(cur);
const inLen = inDir.length();
@@ -9295,17 +9537,17 @@ function pipeAlongPath(points, radius, options = {}) {
smoothed.push(points[points.length - 1]);
pathPoints = smoothed;
}
- const vectors = pathPoints.map((p) => new THREE6.Vector3(p[0], p[1], p[2]));
- const curve = new THREE6.CatmullRomCurve3(vectors, closed);
- return new THREE6.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = pathPoints.map((p) => new THREE7.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE7.CatmullRomCurve3(vectors, closed);
+ return new THREE7.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function bezierCurve(controlPoints, samples = 32) {
- const vecs = controlPoints.map((p) => new THREE6.Vector3(p[0], p[1], p[2]));
+ const vecs = controlPoints.map((p) => new THREE7.Vector3(p[0], p[1], p[2]));
let curve;
if (vecs.length === 3) {
- curve = new THREE6.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
+ curve = new THREE7.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
} else if (vecs.length === 4) {
- curve = new THREE6.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
+ curve = new THREE7.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
} else {
throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);
}
@@ -9316,7 +9558,7 @@ var init_ops = __esm(() => {
});
// src/geometry.ts
-import * as THREE7 from "three";
+import * as THREE8 from "three";
function finiteArray(values, label, length) {
const result = Array.from(values);
if (length !== undefined && result.length !== length)
@@ -9330,8 +9572,8 @@ function meshGeo(data) {
if (positions.length < 9 || positions.length % 3)
throw new Error("meshGeo positions: need at least three xyz vertices");
const count = positions.length / 3;
- const geometry = new THREE7.BufferGeometry;
- geometry.setAttribute("position", new THREE7.Float32BufferAttribute(positions, 3));
+ const geometry = new THREE8.BufferGeometry;
+ geometry.setAttribute("position", new THREE8.Float32BufferAttribute(positions, 3));
if (data.indices) {
const indices = Array.from(data.indices);
if (!indices.length || indices.length % 3)
@@ -9343,7 +9585,7 @@ function meshGeo(data) {
throw new Error("meshGeo: non-indexed positions must form complete triangles");
if (data.normals) {
const normals = finiteArray(data.normals, "meshGeo normals", count * 3);
- geometry.setAttribute("normal", new THREE7.Float32BufferAttribute(normals, 3));
+ geometry.setAttribute("normal", new THREE8.Float32BufferAttribute(normals, 3));
for (let i = 0;i < count; i++)
if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)
throw new Error("meshGeo normals: zero-length normal");
@@ -9351,14 +9593,14 @@ function meshGeo(data) {
} else
geometry.computeVertexNormals();
if (data.uvs)
- geometry.setAttribute("uv", new THREE7.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
+ geometry.setAttribute("uv", new THREE8.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
if (data.tangents) {
const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);
for (let i = 0;i < count; i++) {
if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)
throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");
}
- geometry.setAttribute("tangent", new THREE7.Float32BufferAttribute(tangents, 4));
+ geometry.setAttribute("tangent", new THREE8.Float32BufferAttribute(tangents, 4));
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
@@ -9393,7 +9635,7 @@ function geometryDiagnostics(geometry, tolerance = 0.000001) {
}
const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);
const edges = new Map;
- const a = new THREE7.Vector3, b = new THREE7.Vector3, c = new THREE7.Vector3;
+ const a = new THREE8.Vector3, b = new THREE8.Vector3, c = new THREE8.Vector3;
for (let i = 0;i < indices.length; i += 3) {
result.triangles++;
const triangle = indices.slice(i, i + 3);
@@ -9497,8 +9739,8 @@ function parametricSurface(sample, options = {}) {
const sums = new Map;
for (let i = 0;i < normal.count; i++) {
const id = find(i);
- const sum = sums.get(id) ?? new THREE7.Vector3;
- sum.add(new THREE7.Vector3().fromBufferAttribute(normal, i));
+ const sum = sums.get(id) ?? new THREE8.Vector3;
+ sum.add(new THREE8.Vector3().fromBufferAttribute(normal, i));
sums.set(id, sum);
}
for (let i = 0;i < normal.count; i++) {
@@ -9517,7 +9759,7 @@ function creaseNormals(geometry, options = {}) {
if (position?.itemSize !== 3 || position.count % 3 !== 0)
throw new Error("creaseNormals requires complete xyz triangles");
out.computeBoundingBox();
- const diagonal = out.boundingBox.getSize(new THREE7.Vector3).length();
+ const diagonal = out.boundingBox.getSize(new THREE8.Vector3).length();
const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);
if (!Number.isFinite(tolerance) || tolerance <= 0)
throw new Error("creaseNormals tolerance must be positive and finite");
@@ -9525,13 +9767,13 @@ function creaseNormals(geometry, options = {}) {
const keys = [];
const faces = [];
for (let i = 0;i < position.count; i += 3) {
- const a = new THREE7.Vector3().fromBufferAttribute(position, i);
- const b = new THREE7.Vector3().fromBufferAttribute(position, i + 1);
- const c = new THREE7.Vector3().fromBufferAttribute(position, i + 2);
+ const a = new THREE8.Vector3().fromBufferAttribute(position, i);
+ const b = new THREE8.Vector3().fromBufferAttribute(position, i + 1);
+ const c = new THREE8.Vector3().fromBufferAttribute(position, i + 2);
const face = b.sub(a).cross(c.sub(a)).normalize();
faces.push(face);
for (let j = i;j < i + 3; j++) {
- const point = new THREE7.Vector3().fromBufferAttribute(position, j);
+ const point = new THREE8.Vector3().fromBufferAttribute(position, j);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("creaseNormals positions must be finite");
const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");
@@ -9542,15 +9784,15 @@ function creaseNormals(geometry, options = {}) {
}
}
const normals = new Float32Array(position.count * 3);
- const threshold = Math.cos(THREE7.MathUtils.degToRad(angle));
+ const threshold = Math.cos(THREE8.MathUtils.degToRad(angle));
for (let i = 0;i < position.count; i++) {
- const face = faces[Math.floor(i / 3)], sum = new THREE7.Vector3;
+ const face = faces[Math.floor(i / 3)], sum = new THREE8.Vector3;
for (const other of adjacent.get(keys[i]))
if (face.dot(faces[other]) >= threshold - 0.000000000001)
sum.add(faces[other]);
sum.normalize().toArray(normals, i * 3);
}
- out.setAttribute("normal", new THREE7.BufferAttribute(normals, 3));
+ out.setAttribute("normal", new THREE8.BufferAttribute(normals, 3));
out.deleteAttribute("tangent");
out.computeBoundingSphere();
return out;
@@ -9560,19 +9802,19 @@ var init_geometry = __esm(() => {
});
// src/deform.ts
-import * as THREE8 from "three";
+import * as THREE9 from "three";
function geometryFrameMatrix(frame = {}) {
const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];
if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))
throw new Error("geometry frame requires finite xyz origin and rotation");
- return new THREE8.Matrix4().compose(new THREE8.Vector3(...origin), new THREE8.Quaternion().setFromEuler(new THREE8.Euler(...rotation.map(THREE8.MathUtils.degToRad), "XYZ")), new THREE8.Vector3(1, 1, 1));
+ return new THREE9.Matrix4().compose(new THREE9.Vector3(...origin), new THREE9.Quaternion().setFromEuler(new THREE9.Euler(...rotation.map(THREE9.MathUtils.degToRad), "XYZ")), new THREE9.Vector3(1, 1, 1));
}
function deform(geometry, options, map) {
const source = geometry.getAttribute("position");
if (source?.itemSize !== 3 || source.count === 0)
throw new Error("deformation requires nonempty xyz positions");
const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();
- const points = Array.from({ length: source.count }, (_, i) => new THREE8.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
+ const points = Array.from({ length: source.count }, (_, i) => new THREE9.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))
throw new Error("deformation positions must be finite");
let low = Infinity, high = -Infinity;
@@ -9593,7 +9835,7 @@ function deform(geometry, options, map) {
const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;
if (point.y < low - epsilon || point.y > high + epsilon)
continue;
- const t = length > epsilon ? THREE8.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
+ const t = length > epsilon ? THREE9.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
const weight = options.falloff?.(t) ?? 1;
if (!Number.isFinite(weight) || weight < 0 || weight > 1)
throw new Error("deformation falloff must return a finite weight between 0 and 1");
@@ -9615,41 +9857,41 @@ function deform(geometry, options, map) {
function twist(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("twist angle must be finite degrees");
- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE8.Vector3(0, 1, 0), THREE8.MathUtils.degToRad(options.angle) * t));
+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE9.Vector3(0, 1, 0), THREE9.MathUtils.degToRad(options.angle) * t));
}
function bend(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("bend angle must be finite degrees");
- const angle = THREE8.MathUtils.degToRad(options.angle);
+ const angle = THREE9.MathUtils.degToRad(options.angle);
return deform(geometry, options, (p, t, low, length) => {
if (Math.abs(angle) < 0.0000000001 || length === 0)
return p;
const radius = length / angle, theta = angle * t;
- return new THREE8.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
+ return new THREE9.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
});
}
function taper(geometry, options) {
const start = options.startScale ?? [1, 1], end = options.endScale;
if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))
throw new Error("taper scales must be two finite positive values");
- return deform(geometry, options, (p, t) => p.set(p.x * THREE8.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE8.MathUtils.lerp(start[1], end[1], t)));
+ return deform(geometry, options, (p, t) => p.set(p.x * THREE9.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE9.MathUtils.lerp(start[1], end[1], t)));
}
function displace(geometry, offset, options = {}) {
return deform(geometry, options, (p, t) => {
const delta = offset([p.x, p.y, p.z], t);
if (delta.length !== 3 || !delta.every(Number.isFinite))
throw new Error("displace callback must return three finite offsets");
- return p.add(new THREE8.Vector3(...delta));
+ return p.add(new THREE9.Vector3(...delta));
});
}
var init_deform = () => {};
// src/sweep.ts
-import * as THREE9 from "three";
+import * as THREE10 from "three";
function profilePoints(profile) {
if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
throw new Error("profile requires at least three finite xy points");
- const points = profile.map((p) => new THREE9.Vector2(...p));
+ const points = profile.map((p) => new THREE10.Vector2(...p));
if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)
points.pop();
if (points.length < 3)
@@ -9667,7 +9909,7 @@ function profilePoints(profile) {
throw new Error("profile self-intersects or touches itself");
}
}
- const area = THREE9.ShapeUtils.area(points);
+ const area = THREE10.ShapeUtils.area(points);
if (Math.abs(area) < 0.000000000001)
throw new Error("profile area must be nonzero");
if (area < 0)
@@ -9676,7 +9918,7 @@ function profilePoints(profile) {
}
function buildLoft(rings, profiles, closed, cap) {
const n = rings[0].length, positions = [], uvs = [], indices = [];
- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE9.Vector3).multiplyScalar(1 / n));
+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE10.Vector3).multiplyScalar(1 / n));
const lengths = [0];
for (let i = 1;i < centers.length; i++)
lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));
@@ -9701,13 +9943,13 @@ function buildLoft(rings, profiles, closed, cap) {
for (const station of [0, rings.length - 1]) {
const ring = rings[station], profile = profiles[station];
const start = positions.length / 3;
- const bounds = new THREE9.Box2().setFromPoints(profile);
- const size = bounds.getSize(new THREE9.Vector2);
+ const bounds = new THREE10.Box2().setFromPoints(profile);
+ const size = bounds.getSize(new THREE10.Vector2);
for (let j = 0;j < n; j++) {
positions.push(...ring[j].toArray());
uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));
}
- for (const tri of THREE9.ShapeUtils.triangulateShape(profile, [])) {
+ for (const tri of THREE10.ShapeUtils.triangulateShape(profile, [])) {
if (station === 0)
indices.push(...tri.map((j) => start + j));
else
@@ -9718,14 +9960,14 @@ function buildLoft(rings, profiles, closed, cap) {
const normal = out.getAttribute("normal");
for (let i = 0;i < rings.length; i++) {
const a = i * (n + 1), b = a + n;
- const sum = new THREE9.Vector3().fromBufferAttribute(normal, a).add(new THREE9.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE10.Vector3().fromBufferAttribute(normal, a).add(new THREE10.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
if (closed)
for (let j = 0;j <= n; j++) {
const a = j, b = (rings.length - 1) * (n + 1) + j;
- const sum = new THREE9.Vector3().fromBufferAttribute(normal, a).add(new THREE9.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE10.Vector3().fromBufferAttribute(normal, a).add(new THREE10.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
@@ -9739,7 +9981,7 @@ function loftProfiles(sections, options = {}) {
throw new Error("loftProfiles sections must have the same point count and correspondence");
const rings = sections.map((section, i) => {
const frame = geometryFrameMatrix(section.frame);
- return profiles[i].map((p) => new THREE9.Vector3(p.x, 0, p.y).applyMatrix4(frame));
+ return profiles[i].map((p) => new THREE10.Vector3(p.x, 0, p.y).applyMatrix4(frame));
});
const out = buildLoft(rings, profiles, false, options.cap ?? true);
out.userData.kilnGeometryWarnings = [
@@ -9758,7 +10000,7 @@ function sweepProfile(profile, path, options = {}) {
throw new Error("closed sweep twist must be a multiple of 360 degrees");
if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))
throw new Error("sweepProfile requires finite path points (two open or three closed)");
- const stations = path.map((p) => new THREE9.Vector3(...p));
+ const stations = path.map((p) => new THREE10.Vector3(...p));
if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)
throw new Error("closed sweep path should omit its repeated endpoint");
const segments = [];
@@ -9795,7 +10037,7 @@ function sweepProfile(profile, path, options = {}) {
});
if (Array.isArray(options.scale) && options.scale.length !== stations.length)
throw new Error("sweepProfile scale needs one pair per path station");
- const up = options.up ? new THREE9.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE9.Vector3(0, 0, 1) : new THREE9.Vector3(1, 0, 0);
+ const up = options.up ? new THREE10.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE10.Vector3(0, 0, 1) : new THREE10.Vector3(1, 0, 0);
if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)
throw new Error("sweepProfile up must be a finite nonzero vector");
let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));
@@ -9810,7 +10052,7 @@ function sweepProfile(profile, path, options = {}) {
}
const distances = [0];
for (let i = 1;i < stations.length; i++) {
- z = z.clone().applyQuaternion(new THREE9.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
+ z = z.clone().applyQuaternion(new THREE10.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
normals.push(z);
distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));
}
@@ -9820,7 +10062,7 @@ function sweepProfile(profile, path, options = {}) {
correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));
const rings = stations.map((station, i) => {
const tangent = tangents[i], t = distances[i] / total;
- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE9.MathUtils.degToRad(twist)) * t);
+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE10.MathUtils.degToRad(twist)) * t);
const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];
return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));
});
@@ -9840,7 +10082,7 @@ var init_sweep = __esm(() => {
});
// src/solids.ts
-import * as THREE10 from "three";
+import * as THREE11 from "three";
async function getManifoldModule() {
if (_module)
return _module;
@@ -9900,7 +10142,7 @@ function threeToManifold(src, mod, label, context) {
else
context.missingUV.add(mesh.name || label);
}
- const point = new THREE10.Vector3;
+ const point = new THREE11.Vector3;
for (let i = 0;i < position.count; i++) {
point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))
@@ -9969,11 +10211,11 @@ function manifoldToGeometry(m, opts = {}) {
if (uvs)
uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);
}
- const geometry = new THREE10.BufferGeometry;
- geometry.setAttribute("position", new THREE10.BufferAttribute(positions, 3));
- geometry.setIndex(new THREE10.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
+ const geometry = new THREE11.BufferGeometry;
+ geometry.setAttribute("position", new THREE11.BufferAttribute(positions, 3));
+ geometry.setIndex(new THREE11.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
if (uvs)
- geometry.setAttribute("uv", new THREE10.BufferAttribute(uvs, 2));
+ geometry.setAttribute("uv", new THREE11.BufferAttribute(uvs, 2));
const out = opts.smooth ? geometry : geometry.toNonIndexed();
out.computeVertexNormals();
if (opts.smooth && uvs) {
@@ -9994,7 +10236,7 @@ function firstMaterial(src) {
if (!material && mesh.isMesh)
material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
});
- return material ?? new THREE10.MeshStandardMaterial;
+ return material ?? new THREE11.MeshStandardMaterial;
}
function outputMesh(result, name, parts, opts, context, isHull) {
const geometry = manifoldToGeometry(result, {
@@ -10049,7 +10291,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {
message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."
});
geometry.userData.kilnAttributeWarnings = warnings;
- const output = new THREE10.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
+ const output = new THREE11.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
output.name = `Mesh_${name}`;
return output;
}
@@ -10868,7 +11110,7 @@ var init_procedural_material_v2 = __esm(() => {
});
// src/procedural-texture.ts
-import * as THREE11 from "three";
+import * as THREE12 from "three";
function hash2(x, y, seed) {
let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;
h = h ^ h >>> 13;
@@ -11009,14 +11251,14 @@ function compileProceduralTextureSpecV2(input) {
function proceduralTexture(spec) {
const compiled = compileProceduralTextureSpecV2(spec);
const { size, usage, name, layers } = compiled.spec;
- const tex = new THREE11.DataTexture(compiled.pixels, size, size, THREE11.RGBAFormat, THREE11.UnsignedByteType);
+ const tex = new THREE12.DataTexture(compiled.pixels, size, size, THREE12.RGBAFormat, THREE12.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE11.SRGBColorSpace : THREE11.NoColorSpace;
- tex.wrapS = THREE11.RepeatWrapping;
- tex.wrapT = THREE11.RepeatWrapping;
- tex.minFilter = THREE11.LinearMipmapLinearFilter;
- tex.magFilter = THREE11.LinearFilter;
+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE12.SRGBColorSpace : THREE12.NoColorSpace;
+ tex.wrapS = THREE12.RepeatWrapping;
+ tex.wrapT = THREE12.RepeatWrapping;
+ tex.minFilter = THREE12.LinearMipmapLinearFilter;
+ tex.magFilter = THREE12.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -11070,13 +11312,13 @@ function normalMapFromHeight(source, opts = {}) {
out[o + 3] = 255;
}
}
- const tex = new THREE11.DataTexture(out, width, height, THREE11.RGBAFormat, THREE11.UnsignedByteType);
+ const tex = new THREE12.DataTexture(out, width, height, THREE12.RGBAFormat, THREE12.UnsignedByteType);
tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");
- tex.colorSpace = THREE11.NoColorSpace;
- tex.wrapS = THREE11.RepeatWrapping;
- tex.wrapT = THREE11.RepeatWrapping;
- tex.minFilter = THREE11.LinearMipmapLinearFilter;
- tex.magFilter = THREE11.LinearFilter;
+ tex.colorSpace = THREE12.NoColorSpace;
+ tex.wrapS = THREE12.RepeatWrapping;
+ tex.wrapT = THREE12.RepeatWrapping;
+ tex.minFilter = THREE12.LinearMipmapLinearFilter;
+ tex.magFilter = THREE12.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
return tex;
@@ -11155,7 +11397,7 @@ var init_portable_material_runtime = __esm(() => {
});
// src/uv.ts
-import * as THREE12 from "three";
+import * as THREE13 from "three";
async function getXatlas() {
if (!_xatlasReady) {
_xatlasReady = (async () => {
@@ -11201,16 +11443,16 @@ async function autoUnwrap(geometry, opts = {}) {
xa.destroyAtlas();
throw new Error("autoUnwrap: xatlas returned no meshes");
}
- const out = new THREE12.BufferGeometry;
- out.setAttribute("position", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
+ const out = new THREE13.BufferGeometry;
+ out.setAttribute("position", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
if (mesh.vertex.normals) {
- out.setAttribute("normal", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
+ out.setAttribute("normal", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
}
if (mesh.vertex.coords1) {
- out.setAttribute("uv", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
+ out.setAttribute("uv", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
}
if (mesh.index) {
- out.setIndex(new THREE12.BufferAttribute(new Uint32Array(mesh.index), 1));
+ out.setIndex(new THREE13.BufferAttribute(new Uint32Array(mesh.index), 1));
}
out.userData["atlas"] = {
width: result.width,
@@ -11233,7 +11475,7 @@ function toIndexed(geo) {
for (let i = 0;i < posAttr.count; i++)
indices[i] = i;
const out = geo.clone();
- out.setIndex(new THREE12.BufferAttribute(indices, 1));
+ out.setIndex(new THREE13.BufferAttribute(indices, 1));
return out;
}
function repairZeroNormals(geo) {
@@ -11253,11 +11495,11 @@ function repairZeroNormals(geo) {
if (broken.size === 0)
return;
const acc = new Float32Array(normal.count * 3);
- const a = new THREE12.Vector3;
- const b = new THREE12.Vector3;
- const c = new THREE12.Vector3;
- const face = new THREE12.Vector3;
- const edge = new THREE12.Vector3;
+ const a = new THREE13.Vector3;
+ const b = new THREE13.Vector3;
+ const c = new THREE13.Vector3;
+ const face = new THREE13.Vector3;
+ const edge = new THREE13.Vector3;
for (let t = 0;t + 2 < index.count; t += 3) {
const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];
if (!tri.some((i) => broken.has(i)))
@@ -11291,7 +11533,7 @@ var _xatlasReady = null;
var init_uv = () => {};
// src/uv-shapes.ts
-import * as THREE13 from "three";
+import * as THREE14 from "three";
function boxUnwrap(geo) {
const cloned = geo.clone();
if (!cloned.getAttribute("uv")) {
@@ -11348,7 +11590,7 @@ function cylindricalProjectToUVs(geo) {
uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;
uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uv, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uv, 2));
}
function planeUnwrap(geo) {
const cloned = geo.clone();
@@ -11371,7 +11613,7 @@ function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {
function planarProjectToUVs(geo) {
geo.computeBoundingBox();
const bb = geo.boundingBox;
- const size = new THREE13.Vector3;
+ const size = new THREE14.Vector3;
bb.getSize(size);
const w = size.x || 1;
const h = size.y || 1;
@@ -11381,12 +11623,12 @@ function planarProjectToUVs(geo) {
uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;
uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uvs, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uvs, 2));
}
var init_uv_shapes = () => {};
// src/material-recipe-runtime.ts
-import * as THREE14 from "three";
+import * as THREE15 from "three";
async function applyMaterialRecipeV1(request, options = {}) {
const resolved = resolveMaterialRecipeV1(request);
const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;
@@ -11409,9 +11651,9 @@ async function applyMaterialRecipeV1(request, options = {}) {
};
const material = pbrMaterial(materialOptions);
material.name = options.name ?? request.id;
- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);
+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE15.LinearSRGBColorSpace);
material.opacity = resolved.baseColorFactor[3];
- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);
+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE15.LinearSRGBColorSpace);
const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));
const provenance = {
schemaVersion: 1,
@@ -11462,17 +11704,17 @@ var init_material_recipe_runtime = __esm(() => {
});
// src/primitives.ts
-import * as THREE15 from "three";
+import * as THREE16 from "three";
function vectorToTuple(v) {
return [v.x, v.y, v.z];
}
function createRoot(name) {
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
return root;
}
function createPivot(name, position = [0, 0, 0], parent) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.position.set(...position);
if (parent)
@@ -11504,16 +11746,16 @@ function assertPartArgs(name, geometry2, material) {
}
function createPart(name, geometry2, material, options = {}) {
assertPartArgs(name, geometry2, material);
- const mesh = new THREE15.Mesh(geometry2, material);
+ const mesh = new THREE16.Mesh(geometry2, material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.pivot) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.add(mesh);
mesh.position.set(0, 0, 0);
@@ -11532,7 +11774,7 @@ function createPart(name, geometry2, material, options = {}) {
return mesh;
}
function capsuleGeo(radius, height, segments = 6) {
- return new THREE15.CapsuleGeometry(radius, height, 2, segments);
+ return new THREE16.CapsuleGeometry(radius, height, 2, segments);
}
function capsuleXGeo(radius, length, segments = 6) {
const geo = capsuleGeo(radius, length, segments);
@@ -11545,7 +11787,7 @@ function capsuleZGeo(radius, length, segments = 6) {
return geo;
}
function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {
- return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ return new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
}
function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
@@ -11558,13 +11800,13 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {
return geo;
}
function boxGeo(width, height, depth) {
- return new THREE15.BoxGeometry(width, height, depth);
+ return new THREE16.BoxGeometry(width, height, depth);
}
function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {
- return new THREE15.SphereGeometry(radius, widthSegments, heightSegments);
+ return new THREE16.SphereGeometry(radius, widthSegments, heightSegments);
}
function coneGeo(radius, height, segments = 8) {
- return new THREE15.ConeGeometry(radius, height, segments);
+ return new THREE16.ConeGeometry(radius, height, segments);
}
function coneXGeo(radius, length, segments = 8) {
const geo = coneGeo(radius, length, segments);
@@ -11579,20 +11821,20 @@ function coneZGeo(radius, length, segments = 8) {
function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {
const radiusTop = options.radiusTop ?? radiusBottom;
const segments = options.segments ?? 8;
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
- const n = new THREE15.Vector3(normal[0], normal[1], normal[2]);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const n = new THREE16.Vector3(normal[0], normal[1], normal[2]);
const len = n.length();
if (len < 0.000001) {
throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);
}
n.divideScalar(len);
- const q = new THREE15.Quaternion().setFromUnitVectors(new THREE15.Vector3(0, 1, 0), n);
+ const q = new THREE16.Quaternion().setFromUnitVectors(new THREE16.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
geo.translate(center[0], center[1], center[2]);
return geo;
}
function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
if (axis === "x")
geo.rotateZ(-Math.PI / 2);
else if (axis === "z")
@@ -11600,20 +11842,20 @@ function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8)
return geo;
}
function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {
- return new THREE15.TorusGeometry(radius, tube, radialSegments, tubularSegments);
+ return new THREE16.TorusGeometry(radius, tube, radialSegments, tubularSegments);
}
function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {
- return new THREE15.PlaneGeometry(width, height, widthSegments, heightSegments);
+ return new THREE16.PlaneGeometry(width, height, widthSegments, heightSegments);
}
function decalBox(width, height, depth = 0.01) {
const d = Math.max(depth, 0.002);
- return new THREE15.BoxGeometry(width, height, d);
+ return new THREE16.BoxGeometry(width, height, d);
}
function foliageCardGeo(opts = {}) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
geom.userData["kilnGeometryRole"] = "foliageCard";
return geom;
@@ -11626,12 +11868,12 @@ function crossedQuadsGeo(opts = {}) {
const geometries = [];
for (let i = 0;i < planes; i++) {
const angle = i / planes * Math.PI;
- const quad = new THREE15.PlaneGeometry(w, h);
+ const quad = new THREE16.PlaneGeometry(w, h);
quad.translate(0, h * (0.5 - yPivot), 0);
quad.rotateY(angle);
geometries.push(quad);
}
- const out = new THREE15.BufferGeometry;
+ const out = new THREE16.BufferGeometry;
const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);
const positions = new Float32Array(posCount * 3);
const normals = new Float32Array(posCount * 3);
@@ -11658,9 +11900,9 @@ function crossedQuadsGeo(opts = {}) {
}
vOffset += p.count;
}
- out.setAttribute("position", new THREE15.BufferAttribute(positions, 3));
- out.setAttribute("normal", new THREE15.BufferAttribute(normals, 3));
- out.setAttribute("uv", new THREE15.BufferAttribute(uvs, 2));
+ out.setAttribute("position", new THREE16.BufferAttribute(positions, 3));
+ out.setAttribute("normal", new THREE16.BufferAttribute(normals, 3));
+ out.setAttribute("uv", new THREE16.BufferAttribute(uvs, 2));
out.setIndex(indices);
out.userData["kilnGeometryRole"] = "foliageCard";
return out;
@@ -11669,7 +11911,7 @@ function octaGridPlane(opts) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
const uv = geom.attributes.uv;
const du = 1 / opts.tilesX;
@@ -11757,8 +11999,8 @@ function wingGeo(options = {}) {
7,
6
];
- const geo = new THREE15.BufferGeometry;
- geo.setAttribute("position", new THREE15.BufferAttribute(vertices, 3));
+ const geo = new THREE16.BufferGeometry;
+ geo.setAttribute("position", new THREE16.BufferAttribute(vertices, 3));
geo.setIndex(indices);
geo.computeVertexNormals();
return geo;
@@ -11781,17 +12023,17 @@ function createWingPair(name, material, options) {
};
}
function beamBetween(name, start, end, radius, material, options = {}) {
- const a = new THREE15.Vector3(...start);
- const b = new THREE15.Vector3(...end);
+ const a = new THREE16.Vector3(...start);
+ const b = new THREE16.Vector3(...end);
const direction = b.clone().sub(a);
const length = direction.length();
if (length <= 0.0001) {
throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);
}
- const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
+ const mesh = new THREE16.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
mesh.name = `Mesh_${name}`;
mesh.position.copy(a.add(b).multiplyScalar(0.5));
- mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());
+ mesh.quaternion.setFromUnitVectors(new THREE16.Vector3(0, 1, 0), direction.normalize());
if (options.parent)
options.parent.add(mesh);
return mesh;
@@ -11800,11 +12042,11 @@ function snapTo(part, host, options = {}) {
const overlap = options.overlap ?? 0.02;
part.updateMatrixWorld(true);
host.updateMatrixWorld(true);
- const a = new THREE15.Box3().setFromObject(part);
- const b = new THREE15.Box3().setFromObject(host);
+ const a = new THREE16.Box3().setFromObject(part);
+ const b = new THREE16.Box3().setFromObject(host);
if (a.isEmpty() || b.isEmpty())
return part;
- const delta = new THREE15.Vector3;
+ const delta = new THREE16.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
delta[axis] = b.max[axis] - a.min[axis];
@@ -11820,7 +12062,7 @@ function snapTo(part, host, options = {}) {
delta[dominant] = -overlap;
const parent = part.parent;
if (parent) {
- const p0 = new THREE15.Vector3;
+ const p0 = new THREE16.Vector3;
part.getWorldPosition(p0);
const p1 = p0.clone().add(delta);
const l0 = parent.worldToLocal(p0.clone());
@@ -11845,9 +12087,9 @@ function createLadder(name, options) {
widthAxis = "x",
parent
} = options;
- const bottomVec = new THREE15.Vector3(...bottom);
- const topVec = new THREE15.Vector3(...top);
- const offset = widthAxis === "x" ? new THREE15.Vector3(width / 2, 0, 0) : new THREE15.Vector3(0, 0, width / 2);
+ const bottomVec = new THREE16.Vector3(...bottom);
+ const topVec = new THREE16.Vector3(...top);
+ const offset = widthAxis === "x" ? new THREE16.Vector3(width / 2, 0, 0) : new THREE16.Vector3(0, 0, width / 2);
const leftBottom = bottomVec.clone().sub(offset);
const leftTop = topVec.clone().sub(offset);
const rightBottom = bottomVec.clone().add(offset);
@@ -11864,7 +12106,7 @@ function createLadder(name, options) {
}
function wallWithOpening(name, material, options) {
const { length, height, thickness, axis = "z", opening, parent } = options;
- const group = new THREE15.Object3D;
+ const group = new THREE16.Object3D;
group.name = name;
const overlap = 0.02;
const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {
@@ -11909,7 +12151,7 @@ function room(name, material, options = {}) {
parent
} = options;
const openings = options.openings ?? [{ wall: "front", kind: "door" }];
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const openingFor = (wall) => {
const found = openings.find((op) => op.wall === wall);
@@ -11953,7 +12195,7 @@ function createRoofPlanes2(name, material, options) {
result.slopes[0].name = `Mesh_${name}A`;
result.slopes[1].name = `Mesh_${name}B`;
for (let index = 0;index < result.slopes.length; index++) {
- const normal = new THREE15.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
+ const normal = new THREE16.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);
}
if ((options.ridgeAxis ?? "x") === "x") {
@@ -11980,7 +12222,7 @@ function createStairs(name, material, options) {
if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {
throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);
}
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const stepRise = totalRise / steps;
const stepRun = totalRun / steps;
@@ -12010,7 +12252,7 @@ function requireColor(color, fn) {
}
function gameMaterial(color, options = {}) {
requireColor(color, "gameMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
metalness: options.metalness ?? 0,
roughness: options.roughness ?? 0.8,
@@ -12021,7 +12263,7 @@ function gameMaterial(color, options = {}) {
}
function basicMaterial(color, options = {}) {
requireColor(color, "basicMaterial");
- return new THREE15.MeshBasicMaterial({
+ return new THREE16.MeshBasicMaterial({
color,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
@@ -12029,38 +12271,38 @@ function basicMaterial(color, options = {}) {
}
function glassMaterial(color, options = {}) {
requireColor(color, "glassMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
transparent: true,
opacity: options.opacity ?? 0.35,
roughness: options.roughness ?? 0.1,
metalness: options.metalness ?? 0,
- side: THREE15.DoubleSide
+ side: THREE16.DoubleSide
});
}
function lambertMaterial(color, options = {}) {
requireColor(color, "lambertMaterial");
- return new THREE15.MeshLambertMaterial({
+ return new THREE16.MeshLambertMaterial({
color,
flatShading: options.flatShading ?? true,
emissive: options.emissive ?? 0
});
}
function threeInterpolation(mode) {
- return mode === "STEP" ? THREE15.InterpolateDiscrete : THREE15.InterpolateLinear;
+ return mode === "STEP" ? THREE16.InterpolateDiscrete : THREE16.InterpolateLinear;
}
function rotationTrack(jointName, keyframes, interpolation) {
const times = [];
const values = [];
- const euler = new THREE15.Euler;
- const quat = new THREE15.Quaternion;
+ const euler = new THREE16.Euler;
+ const quat = new THREE16.Quaternion;
for (const kf of keyframes) {
times.push(kf.time);
- euler.set(THREE15.MathUtils.degToRad(kf.rotation[0]), THREE15.MathUtils.degToRad(kf.rotation[1]), THREE15.MathUtils.degToRad(kf.rotation[2]));
+ euler.set(THREE16.MathUtils.degToRad(kf.rotation[0]), THREE16.MathUtils.degToRad(kf.rotation[1]), THREE16.MathUtils.degToRad(kf.rotation[2]));
quat.setFromEuler(euler);
values.push(quat.x, quat.y, quat.z, quat.w);
}
- return new THREE15.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
+ return new THREE16.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
}
function positionTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -12069,7 +12311,7 @@ function positionTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.position);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
}
function scaleTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -12078,10 +12320,10 @@ function scaleTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.scale);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
}
function createClip(name, duration, tracks) {
- return new THREE15.AnimationClip(name, duration, tracks);
+ return new THREE16.AnimationClip(name, duration, tracks);
}
function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {
const y = 0;
@@ -12131,12 +12373,12 @@ function createInstance(name, source, options = {}) {
if (!sourceMesh) {
throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);
}
- const mesh = new THREE15.Mesh(sourceMesh.geometry, sourceMesh.material);
+ const mesh = new THREE16.Mesh(sourceMesh.geometry, sourceMesh.material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.parent)
@@ -12380,7 +12622,7 @@ function buildSandboxGlobals(usage, options = {}) {
countMaterials: wrap("countMaterials", countMaterials),
getJointNames: wrap("getJointNames", getJointNames),
validateAsset: wrap("validateAsset", validateAsset),
- THREE: THREE15,
+ THREE: THREE16,
Math,
console
};
@@ -12908,7 +13150,7 @@ var init_registry = __esm(() => {
});
// src/qa/material.ts
-import * as THREE16 from "three";
+import * as THREE17 from "three";
function textureMeta(texture) {
return texture.userData["kilnTexture"];
}
@@ -12956,7 +13198,7 @@ function validateTextureSlot(findings, mesh, material, texture, slot, expected)
if (!texture)
return;
const meta = textureMeta(texture);
- const actual = texture.colorSpace === THREE16.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE16.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
+ const actual = texture.colorSpace === THREE17.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE17.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
if (!meta || !encodedTextureIsExportable(texture)) {
findings.push({
code: "MAT_TEXTURE_DECODE_FAILED",
@@ -13057,7 +13299,7 @@ function validateMaterial2(mesh, material, requiresPrecomputedTangents) {
}
if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {
const validMask = standard.alphaTest > 0 && !standard.transparent;
- if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE16.DoubleSide || !mesh.geometry.getAttribute("uv")) {
+ if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE17.DoubleSide || !mesh.geometry.getAttribute("uv")) {
findings.push({
code: "MAT_FOLIAGE_CARD_CONTRACT",
disposition: "block",
@@ -13171,14 +13413,14 @@ var init_architecture_repairs = __esm(() => {
});
// src/qa/architecture.ts
-import * as THREE17 from "three";
+import * as THREE18 from "three";
function semanticMetadata(node) {
return readSemanticMetadataV1FromExtras(node.userData);
}
function markerBounds(matrix) {
const bounds = emptyBounds();
for (let corner = 0;corner < 8; corner++) {
- expandBounds(bounds, new THREE17.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
+ expandBounds(bounds, new THREE18.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
}
return bounds;
}
@@ -13187,7 +13429,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const local = geometry.boundingBox;
if (!local)
return;
- const size = local.getSize(new THREE17.Vector3);
+ const size = local.getSize(new THREE18.Vector3);
const dimensions = [
["x", size.x],
["y", size.y],
@@ -13197,7 +13439,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const axis = dimensions[0]?.[0];
if (!axis)
return;
- const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
+ const normal = new THREE18.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
if (normal.y < 0)
normal.multiplyScalar(-1);
return normal.normalize();
@@ -13209,7 +13451,7 @@ function geometryEvidence(geometry, relativeMatrix) {
if (position?.itemSize !== 3)
return { bounds, vertices, triangles: [] };
for (let index = 0;index < position.count; index++) {
- const point = new THREE17.Vector3(position.getX(index), position.getY(index), position.getZ(index));
+ const point = new THREE18.Vector3(position.getX(index), position.getY(index), position.getZ(index));
point.applyMatrix4(relativeMatrix);
vertices.push(point);
expandBounds(bounds, point);
@@ -13236,7 +13478,7 @@ function geometryEvidence(geometry, relativeMatrix) {
return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };
}
function collectArchitectureEvidence(scene) {
- if (!(scene instanceof THREE17.Object3D))
+ if (!(scene instanceof THREE18.Object3D))
return;
scene.updateMatrixWorld(true);
const rootInverse = scene.matrixWorld.clone().invert();
@@ -13254,7 +13496,7 @@ function collectArchitectureEvidence(scene) {
const nodePath = parentPath ? `${parentPath}/${segment}` : segment;
const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);
const mesh = node;
- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE17.BufferGeometry;
+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE18.BufferGeometry;
const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {
bounds: markerBounds(relativeMatrix),
vertices: [],
@@ -13313,7 +13555,7 @@ function architectureFinding(context, value) {
function averageNormal(normals) {
if (normals.length === 0)
return;
- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE17.Vector3);
+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE18.Vector3);
return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;
}
function intervalCoverage(min, max, expectedMin, expectedMax) {
@@ -14022,8 +14264,8 @@ function evaluateArchitectureQa(context) {
];
}
var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({
- min: new THREE17.Vector3(Infinity, Infinity, Infinity),
- max: new THREE17.Vector3(-Infinity, -Infinity, -Infinity)
+ min: new THREE18.Vector3(Infinity, Infinity, Infinity),
+ max: new THREE18.Vector3(-Infinity, -Infinity, -Infinity)
}), expandBounds = (bounds, point) => {
bounds.min.min(point);
bounds.max.max(point);
@@ -14113,7 +14355,7 @@ var init_character_repairs = __esm(() => {
});
// src/qa/character.ts
-import * as THREE18 from "three";
+import * as THREE19 from "three";
function isClipLike(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -14351,7 +14593,7 @@ function contactFindings(intent, root) {
const tolerance = Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0 ? trusted.contactTolerance : CONTACT_TOLERANCE;
const findings = [];
for (const contact of contacts) {
- const point = contact.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(rootInverse);
+ const point = contact.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(rootInverse);
if (point.y > tolerance) {
findings.push(block(intent, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`, {
dimension: "categoryReadiness",
@@ -14612,13 +14854,13 @@ function declaredHeldItem(nodes) {
function characterJointScale(root) {
root.updateMatrixWorld(true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE18.Box3;
+ const bounds = new THREE19.Box3;
for (const joint of collectCharacterJointNodes(root)) {
- bounds.expandByPoint(joint.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse));
+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse));
}
if (bounds.isEmpty())
return 1;
- const size = bounds.getSize(new THREE18.Vector3);
+ const size = bounds.getSize(new THREE19.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function heldItemMotionFindings(intent, root, clips) {
@@ -14654,8 +14896,8 @@ function heldItemMotionFindings(intent, root, clips) {
if (!cloneItem || !cloneAttachment)
continue;
const inverse = clone.matrixWorld.clone().invert();
- const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
- const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
+ const itemPoint = cloneItem.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
+ const gripPoint = cloneAttachment.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
const distance = itemPoint.distanceTo(gripPoint);
baseline ??= distance;
const drift = Math.abs(distance - baseline);
@@ -14688,7 +14930,7 @@ function heldItemMotionFindings(intent, root, clips) {
function evaluateCharacterQa(context) {
if (context.intent.category !== "character")
return [];
- const root = context.scene instanceof THREE18.Object3D ? context.scene : undefined;
+ const root = context.scene instanceof THREE19.Object3D ? context.scene : undefined;
const clips = (context.clips ?? []).filter(isClipLike);
const findings = [];
if (root) {
@@ -14727,7 +14969,7 @@ var init_character2 = __esm(() => {
});
// src/qa/character-advisory.ts
-import * as THREE19 from "three";
+import * as THREE20 from "three";
function isClipLike2(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -14753,16 +14995,16 @@ function jointPoints(root) {
const inverse = rootInverse(root);
return collectCharacterJointNodes(root).map((evidence) => ({
evidence,
- local: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse)
+ local: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse)
}));
}
function characterScale(points) {
if (points.length === 0)
return 1;
- const bounds = new THREE19.Box3;
+ const bounds = new THREE20.Box3;
for (const point of points)
bounds.expandByPoint(point.local);
- const size = bounds.getSize(new THREE19.Vector3);
+ const size = bounds.getSize(new THREE20.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function pairKey(descriptor) {
@@ -14861,12 +15103,12 @@ function restChainFindings(context, root) {
}
function forwardMarkerFindings(context, root) {
root.updateMatrixWorld(true);
- const expected = new THREE19.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
+ const expected = new THREE20.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));
return markers.flatMap((marker) => {
- const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);
- const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
- const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));
+ const quaternion = marker.node.getWorldQuaternion(new THREE20.Quaternion);
+ const actual = new THREE20.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
+ const angle = THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(actual.dot(expected), -1, 1)));
if (angle <= FORWARD_ANGLE_DEGREES)
return [];
return [
@@ -14920,7 +15162,7 @@ function sampleClip(root, clip) {
byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [
evidence.descriptor.role,
{
- point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),
+ point: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse),
evidence
}
]))
@@ -15032,12 +15274,12 @@ function phaseOppositionFindings(context, root, clips) {
return findings;
}
function signedBendDegrees(descriptor, quaternion) {
- const rest = new THREE19.Quaternion(...descriptor.rest.rotation);
+ const rest = new THREE20.Quaternion(...descriptor.rest.rotation);
const delta = rest.invert().multiply(quaternion).normalize();
- const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);
- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));
+ const axis = new THREE20.Vector3(delta.x, delta.y, delta.z);
+ const signedMagnitude = axis.dot(new THREE20.Vector3(...descriptor.localBendAxis));
const angle = 2 * Math.atan2(signedMagnitude, delta.w);
- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
+ return THREE20.MathUtils.radToDeg(THREE20.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
}
function bendDirectionFindings(context, root, clips) {
const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));
@@ -15051,7 +15293,7 @@ function bendDirectionFindings(context, root, clips) {
let maximumFraction = 0;
for (const fraction of SAMPLE_FRACTIONS) {
const value = track.createInterpolant().evaluate(fraction * clip.duration);
- const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());
+ const bend = signedBendDegrees(joint.descriptor, new THREE20.Quaternion().fromArray(value).normalize());
if (Math.abs(bend) > Math.abs(maximum)) {
maximum = bend;
maximumFraction = fraction;
@@ -15134,7 +15376,7 @@ function footSlideFindings(context, root, clips) {
return findings;
}
function evaluateCharacterAdvisoryQa(context) {
- if (context.intent.category !== "character" || !(context.scene instanceof THREE19.Object3D)) {
+ if (context.intent.category !== "character" || !(context.scene instanceof THREE20.Object3D)) {
return [];
}
const root = context.scene;
@@ -15417,7 +15659,7 @@ var EPSILON3 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value
];
// src/qa/vehicle-advisory.ts
-import * as THREE20 from "three";
+import * as THREE21 from "three";
function advisory2(context, value) {
return {
...value,
@@ -15491,7 +15733,7 @@ function isFender(node) {
return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);
}
function isChassisMesh(node) {
- if (!(node instanceof THREE20.Mesh) || isFender(node))
+ if (!(node instanceof THREE21.Mesh) || isFender(node))
return false;
return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);
}
@@ -15499,10 +15741,10 @@ function objectBoundsInFrame2(object, frame) {
object.updateWorldMatrix(true, true);
frame.updateWorldMatrix(true, false);
const worldToFrame = frame.matrixWorld.clone().invert();
- const bounds = new THREE20.Box3;
+ const bounds = new THREE21.Box3;
let found = false;
object.traverse((part) => {
- if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))
+ if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -15512,7 +15754,7 @@ function objectBoundsInFrame2(object, frame) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -15523,15 +15765,15 @@ function tuple2(value) {
}
function probeBox(id, root, bounds) {
root.updateWorldMatrix(true, false);
- const center = bounds.getCenter(new THREE20.Vector3).applyMatrix4(root.matrixWorld);
- const size = bounds.getSize(new THREE20.Vector3);
- const position = new THREE20.Vector3;
- const quaternion = new THREE20.Quaternion;
- const scale = new THREE20.Vector3;
+ const center = bounds.getCenter(new THREE21.Vector3).applyMatrix4(root.matrixWorld);
+ const size = bounds.getSize(new THREE21.Vector3);
+ const position = new THREE21.Vector3;
+ const quaternion = new THREE21.Quaternion;
+ const scale = new THREE21.Vector3;
root.matrixWorld.decompose(position, quaternion, scale);
- const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
- const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
- const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
+ const xAxis = new THREE21.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
+ const yAxis = new THREE21.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
+ const zAxis = new THREE21.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
return createOrientedProbeBox3({
id,
frame: createProbeLocalFrame3({
@@ -15600,7 +15842,7 @@ function orientationFindings(context, root, intent) {
const bounds = wholeAssetBounds(root);
if (!bounds)
return [];
- const size = bounds.getSize(new THREE20.Vector3);
+ const size = bounds.getSize(new THREE21.Vector3);
const ratio = size.z / Math.max(size.x, 0.000000001);
if (ratio <= ORIENTATION_RATIO)
return [];
@@ -15644,13 +15886,13 @@ function weldedBoundaryEdges(root, loop) {
let triangleCount = 0;
const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");
loop.traverse((node) => {
- if (!(node instanceof THREE20.Mesh) || !(node.geometry instanceof THREE20.BufferGeometry))
+ if (!(node instanceof THREE21.Mesh) || !(node.geometry instanceof THREE21.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (!positions)
return;
const matrix = inverse.clone().multiply(node.matrixWorld);
- const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE21.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
const index = node.geometry.getIndex();
const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);
for (let offset = 0;offset + 2 < indices.length; offset += 3) {
@@ -15720,7 +15962,7 @@ function trackProfileFindings(context, root, intent) {
const wheelBounds = objectBoundsInFrame2(roadWheel, root);
if (!wheelBounds)
continue;
- const center = wheelBounds.getCenter(new THREE20.Vector3);
+ const center = wheelBounds.getCenter(new THREE21.Vector3);
if (expanded.containsPoint(center))
continue;
const clamped = center.clone().clamp(expanded.min, expanded.max);
@@ -15746,7 +15988,7 @@ function trackProfileFindings(context, root, intent) {
return findings;
}
function evaluateVehicleAdvisoryQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE20.Object3D)) {
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D)) {
return [];
}
const intent = context.intent.vehicle;
@@ -15784,7 +16026,7 @@ var init_vehicle_advisory = __esm(() => {
});
// src/qa/vehicle.ts
-import * as THREE21 from "three";
+import * as THREE22 from "three";
function finding(context, value) {
return {
...value,
@@ -15801,7 +16043,7 @@ function rootAxis(root, axis) {
return axis.clone().transformDirection(root.matrixWorld);
}
function angleDegrees(a, b) {
- return THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
+ return THREE22.MathUtils.radToDeg(Math.acos(THREE22.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
}
function isDescendant(node, ancestor) {
let current = node;
@@ -15849,7 +16091,7 @@ function wheelCountFindings(context, intent, wheels) {
}
function wheelGeometryFindings(context, root, wheels) {
const findings = [];
- const expectedAxle = rootAxis(root, new THREE21.Vector3(0, 0, 1));
+ const expectedAxle = rootAxis(root, new THREE22.Vector3(0, 0, 1));
for (const wheel of wheels) {
const disposition = componentDisposition(wheel);
const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);
@@ -16038,7 +16280,7 @@ function contactFindings2(context, root, intent, wheels) {
function renderableMinYInRoot(rootInverse, node) {
let minimum = Infinity;
node.traverse((part) => {
- if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
+ if (!(part instanceof THREE22.Mesh) || !(part.geometry instanceof THREE22.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const bounds = part.geometry.boundingBox;
@@ -16048,7 +16290,7 @@ function renderableMinYInRoot(rootInverse, node) {
for (const x of [bounds.min.x, bounds.max.x]) {
for (const y of [bounds.min.y, bounds.max.y]) {
for (const z of [bounds.min.z, bounds.max.z]) {
- minimum = Math.min(minimum, new THREE21.Vector3(x, y, z).applyMatrix4(matrix).y);
+ minimum = Math.min(minimum, new THREE22.Vector3(x, y, z).applyMatrix4(matrix).y);
}
}
}
@@ -16068,7 +16310,7 @@ function supportContactFindings(context, root, intent) {
if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {
explicitContacts.push({
node,
- contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
+ contactY: localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
source: "contact"
});
}
@@ -16148,7 +16390,7 @@ function steeringFindings(context, root, intent, wheels) {
return [];
root.updateWorldMatrix(true, false);
const inverse = root.matrixWorld.clone().invert();
- const expectedAxis = rootAxis(root, new THREE21.Vector3(0, 1, 0));
+ const expectedAxis = rootAxis(root, new THREE22.Vector3(0, 1, 0));
const localCenters = wheels.map((wheel) => ({
wheel,
center: localPoint2(inverse, wheel.centerWorld)
@@ -16158,8 +16400,8 @@ function steeringFindings(context, root, intent, wheels) {
const findings = [];
for (const { wheel } of targets) {
const steering = wheel.steeringPivot;
- const centerDelta = steering ? localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
- const axisAngle = steering ? angleDegrees(new THREE21.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
+ const centerDelta = steering ? localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
+ const axisAngle = steering ? angleDegrees(new THREE22.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {
const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;
findings.push(finding(context, {
@@ -16214,14 +16456,14 @@ function propulsionFindings(context, root, intent) {
}
for (const component of candidates) {
const pivot = pivots.get(component.id);
- const box = new THREE21.Box3().setFromObject(component.node);
- const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);
- const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
+ const box = new THREE22.Box3().setFromObject(component.node);
+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE22.Vector3);
+ const pivotCenter = pivot ? new THREE22.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;
const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";
const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);
- const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);
- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE21.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
+ const canonicalAxis = kind === "rotor" ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(1, 0, 0);
+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE22.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {
findings.push(finding(context, {
code: "VEH_ROTOR_PIVOT",
@@ -16243,7 +16485,7 @@ function propulsionFindings(context, root, intent) {
return findings;
}
function evaluateVehicleQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D))
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE22.Object3D))
return [];
const intent = context.intent.vehicle;
if (!intent)
@@ -16307,7 +16549,7 @@ var init_vehicle2 = __esm(() => {
});
// src/qa/vegetation.ts
-import * as THREE22 from "three";
+import * as THREE23 from "three";
function rolesOf(node) {
return readSemanticMetadataV1(node)?.roles ?? [];
}
@@ -16323,21 +16565,21 @@ function pathOf(node, root) {
return names.reverse().join("/");
}
function localPoint3(rootInverse, node) {
- return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);
+ return node.getWorldPosition(new THREE23.Vector3).applyMatrix4(rootInverse);
}
function meshLocalBox(mesh, rootInverse) {
- if (!(mesh.geometry instanceof THREE22.BufferGeometry))
+ if (!(mesh.geometry instanceof THREE23.BufferGeometry))
return;
mesh.geometry.computeBoundingBox();
const source = mesh.geometry.boundingBox;
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(mesh.matrixWorld);
- const result = new THREE22.Box3;
+ const result = new THREE23.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -16348,7 +16590,7 @@ function collectRenderableBounds(root) {
const inverse = root.matrixWorld.clone().invert();
const values = [];
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (!box)
@@ -16366,7 +16608,7 @@ function vegetationIntent(intent) {
}
function evaluateVegetationContactQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.grounded || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.grounded || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
root.updateWorldMatrix(true, true);
@@ -16403,7 +16645,7 @@ function evaluateVegetationContactQa(context) {
}
const findings = [];
for (const contact of contacts) {
- const contactPoint = contact.frameTranslation ? new THREE22.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
+ const contactPoint = contact.frameTranslation ? new THREE23.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
const y = contactPoint.y;
if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS)
continue;
@@ -16431,7 +16673,7 @@ function evaluateVegetationContactQa(context) {
for (const support of semanticSupports) {
let minimumY = Infinity;
support.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (box)
@@ -16459,25 +16701,25 @@ function evaluateVegetationContactQa(context) {
return findings;
}
function materialNames(node) {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return [];
const materials = Array.isArray(node.material) ? node.material : [node.material];
return materials.filter(Boolean).map((material) => material.name ?? "");
}
function evaluateVegetationScopeQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.standalone || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.standalone || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
const renderables = collectRenderableBounds(root);
if (renderables.length === 0)
return [];
- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const overallSize = overall.getSize(new THREE22.Vector3);
+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const overallSize = overall.getSize(new THREE23.Vector3);
const findings = [];
for (const value of renderables) {
- const size = value.box.getSize(new THREE22.Vector3);
- const center = value.box.getCenter(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
+ const center = value.box.getCenter(new THREE23.Vector3);
const names = [value.node.name, ...value.roles];
const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));
const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));
@@ -16514,8 +16756,8 @@ function evaluateVegetationScopeQa(context) {
function unionVolume(boxes) {
if (boxes.length === 0)
return 0;
- const union = boxes.reduce((result, box) => result.union(box), new THREE22.Box3);
- const size = union.getSize(new THREE22.Vector3);
+ const union = boxes.reduce((result, box) => result.union(box), new THREE23.Box3);
+ const size = union.getSize(new THREE23.Vector3);
return size.x * size.y * size.z;
}
function projectedOccupancy(boxes, axes) {
@@ -16585,7 +16827,7 @@ function boxDistanceToPoint(box, point) {
function endpointRadius(position, axis, axisValue, tolerance, scale) {
const radialAxes = [0, 1, 2].filter((value) => value !== axis);
const points = [];
- const point = new THREE22.Vector3;
+ const point = new THREE23.Vector3;
for (let index = 0;index < position.count; index++) {
point.fromBufferAttribute(position, index);
if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)
@@ -16593,7 +16835,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
}
if (points.length === 0)
return;
- const center = new THREE22.Vector3;
+ const center = new THREE23.Vector3;
center.setComponent(axis, axisValue);
for (const radialAxis of radialAxes) {
center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);
@@ -16607,7 +16849,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
return { center, radius };
}
function growthNodeMeasurement(root, candidate, allCandidates, band) {
- if (!(candidate.node instanceof THREE22.Mesh))
+ if (!(candidate.node instanceof THREE23.Mesh))
return;
const geometry = candidate.node.geometry;
const position = geometry.getAttribute("position");
@@ -16619,9 +16861,9 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {
return;
root.updateWorldMatrix(true, true);
const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);
- const relativeScale = new THREE22.Vector3;
- relative.decompose(new THREE22.Vector3, new THREE22.Quaternion, relativeScale);
- const size = geometryBox.getSize(new THREE22.Vector3);
+ const relativeScale = new THREE23.Vector3;
+ relative.decompose(new THREE23.Vector3, new THREE23.Quaternion, relativeScale);
+ const size = geometryBox.getSize(new THREE23.Vector3);
const scaledSizes = [
Math.abs(size.x * relativeScale.x),
Math.abs(size.y * relativeScale.y),
@@ -16688,7 +16930,7 @@ function measureVegetationGrowth(intent, root) {
};
}
function evaluateVegetationGrowthQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationGrowth(context.intent, context.scene);
const findings = [];
@@ -16739,7 +16981,7 @@ function measureVegetationFoliageAttachment(root) {
const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));
const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));
const clusters = foliage.map((value) => {
- const size = value.box.getSize(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));
const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];
const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";
@@ -16762,7 +17004,7 @@ function measureVegetationFoliageAttachment(root) {
};
}
function evaluateVegetationFoliageAttachmentQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {
code: "VEG_FOLIAGE_DETACHED",
@@ -16782,9 +17024,9 @@ function evaluateVegetationFoliageAttachmentQa(context) {
}
function relativeTransformSignature(root, node) {
const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
- const scale = new THREE22.Vector3;
- const quaternion = new THREE22.Quaternion;
- matrix.decompose(new THREE22.Vector3, quaternion, scale);
+ const scale = new THREE23.Vector3;
+ const quaternion = new THREE23.Quaternion;
+ matrix.decompose(new THREE23.Vector3, quaternion, scale);
if (quaternion.w < 0)
quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);
const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));
@@ -16805,9 +17047,9 @@ function measureVegetationRepetition(intent, root) {
nodes: values.map((value) => value.node.name || "foliage-cluster").sort()
})).sort((a, b) => a.signature.localeCompare(b.signature));
const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));
- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const centers = foliage.map((value) => value.box.getCenter(new THREE22.Vector3));
- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE22.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE22.Vector3);
+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const centers = foliage.map((value) => value.box.getCenter(new THREE23.Vector3));
+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE23.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE23.Vector3);
const radial = centers.map((value) => ({
angle: Math.atan2(value.z - center.z, value.x - center.x),
radius: Math.hypot(value.x - center.x, value.z - center.z)
@@ -16842,7 +17084,7 @@ function measureVegetationRepetition(intent, root) {
};
}
function evaluateVegetationRepetitionQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationRepetition(context.intent, context.scene);
if (measured.suppressedForTopiary)
@@ -16901,7 +17143,7 @@ function measureVegetationCanopy(intent, root) {
}
function evaluateVegetationCanopyQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted || !(context.scene instanceof THREE23.Object3D))
return [];
const measurements = measureVegetationCanopy(context.intent, context.scene);
const bands = PROFILE_BANDS[measurements.profile];
@@ -16962,7 +17204,7 @@ function evaluateVegetationCanopyQa(context) {
return findings;
}
function materialValue(material) {
- if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {
+ if (!(material instanceof THREE23.MeshStandardMaterial) && !(material instanceof THREE23.MeshBasicMaterial)) {
return;
}
const color = material.color;
@@ -16972,11 +17214,11 @@ function measureVegetationFoliageMaterials(intent, root) {
const values = [];
let foliageNodeCount = 0;
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const bounds = {
node,
- box: new THREE22.Box3,
+ box: new THREE23.Box3,
roles: rolesOf(node),
source: rolesOf(node).length > 0 ? "semantic" : "fallback"
};
@@ -17003,7 +17245,7 @@ function measureVegetationFoliageMaterials(intent, root) {
};
}
function evaluateVegetationMaterialQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationFoliageMaterials(context.intent, context.scene);
if (measured.foliageNodeCount === 0 || measured.coherent)
@@ -17139,7 +17381,7 @@ var init_vegetation = __esm(() => {
});
// src/qa/prop.ts
-import * as THREE23 from "three";
+import * as THREE24 from "three";
function finding3(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE3 };
}
@@ -17158,11 +17400,11 @@ function nodePath2(root, node) {
return names.reverse().join("/");
}
function transformedBox(source, transform) {
- const result = new THREE23.Box3;
+ const result = new THREE24.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE24.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -17174,15 +17416,15 @@ function collectParts(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf2(node);
- const renderable = node instanceof THREE23.Mesh;
+ const renderable = node instanceof THREE24.Mesh;
let box;
- if (renderable && node.geometry instanceof THREE23.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE24.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));
}
} else if (roles.length > 0) {
- box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
+ box = transformedBox(new THREE24.Box3(new THREE24.Vector3(-0.5, -0.5, -0.5), new THREE24.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
}
if (box?.isEmpty())
box = undefined;
@@ -17272,14 +17514,14 @@ function legacyArticulationEvidence(context, root) {
});
if (joints.length === 0)
return false;
- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE23.AnimationClip);
+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE24.AnimationClip);
if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)
return true;
const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));
return joints.some((joint) => targets.has(joint));
}
function evaluatePropArticulationQa(context) {
- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE23.Object3D)) {
+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE24.Object3D)) {
return [];
}
const root = context.scene;
@@ -17393,11 +17635,11 @@ function rolePart(parts, expression) {
return parts.find((part) => part.roles.some((role) => expression.test(role)));
}
function interiorUsable(box) {
- const size = box.getSize(new THREE23.Vector3);
+ const size = box.getSize(new THREE24.Vector3);
return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;
}
function evaluatePropContainerQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const explicitlyOpen = context.intent.capabilities.includes("openable");
const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");
@@ -17447,7 +17689,7 @@ function evaluatePropContainerQa(context) {
repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."
}));
} else if (!interiorUsable(interior.box)) {
- const size = interior.box.getSize(new THREE23.Vector3);
+ const size = interior.box.getSize(new THREE24.Vector3);
findings.push(finding3(context, {
code: "PROP_CONTAINER_INTERIOR_UNUSABLE",
disposition: "block",
@@ -17505,21 +17747,21 @@ function evaluatePropContainerQa(context) {
return findings;
}
function horizontalDirection(part, root) {
- if (!(part.node instanceof THREE23.Mesh) || !(part.node.geometry instanceof THREE23.BufferGeometry)) {
+ if (!(part.node instanceof THREE24.Mesh) || !(part.node.geometry instanceof THREE24.BufferGeometry)) {
return;
}
part.node.geometry.computeBoundingBox();
const box = part.node.geometry.boundingBox;
if (!box)
return;
- const size = box.getSize(new THREE23.Vector3);
- const axis = size.x >= size.z ? new THREE23.Vector3(1, 0, 0) : new THREE23.Vector3(0, 0, 1);
+ const size = box.getSize(new THREE24.Vector3);
+ const axis = size.x >= size.z ? new THREE24.Vector3(1, 0, 0) : new THREE24.Vector3(0, 0, 1);
root.updateWorldMatrix(true, true);
- const rootQuaternion = root.getWorldQuaternion(new THREE23.Quaternion).invert();
- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE23.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
+ const rootQuaternion = root.getWorldQuaternion(new THREE24.Quaternion).invert();
+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE24.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
}
function evaluatePropCircularAssemblyQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
@@ -17530,8 +17772,8 @@ function evaluatePropCircularAssemblyQa(context) {
const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));
if (memberParts.length < 3)
return [];
- const centers = memberParts.map((part) => part.box.getCenter(new THREE23.Vector3));
- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE23.Vector3).multiplyScalar(1 / centers.length);
+ const centers = memberParts.map((part) => part.box.getCenter(new THREE24.Vector3));
+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE24.Vector3).multiplyScalar(1 / centers.length);
const members = memberParts.map((part, index) => {
const center = centers[index];
return {
@@ -17570,7 +17812,7 @@ function evaluatePropCircularAssemblyQa(context) {
if (!member.horizontalDirection)
return false;
const radial = member.center.clone().sub(ringCenter).setY(0).normalize();
- const tangent = new THREE23.Vector3(-radial.z, 0, radial.x);
+ const tangent = new THREE24.Vector3(-radial.z, 0, radial.x);
const radialScore = Math.abs(member.horizontalDirection.dot(radial));
const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));
return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;
@@ -17597,15 +17839,15 @@ function evaluatePropCircularAssemblyQa(context) {
return findings;
}
function evaluatePropScalePivotQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
const renderable = parts.filter((part) => part.renderable && part.box);
if (renderable.length === 0)
return [];
- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE23.Box3);
- const size = bounds.getSize(new THREE23.Vector3);
+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE24.Box3);
+ const size = bounds.getSize(new THREE24.Vector3);
const findings = [];
for (const axis of ["x", "y", "z"]) {
const expected = context.intent.bounds?.[axis];
@@ -17652,7 +17894,7 @@ function evaluatePropScalePivotQa(context) {
}
const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));
if (placement) {
- const point = placement.node.getWorldPosition(new THREE23.Vector3);
+ const point = placement.node.getWorldPosition(new THREE24.Vector3);
point.applyMatrix4(root.matrixWorld.clone().invert());
const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;
const verticalDelta = Math.abs(point.y - bounds.min.y);
@@ -17715,7 +17957,7 @@ var init_prop = __esm(() => {
});
// src/qa/part-connectivity.ts
-import * as THREE24 from "three";
+import * as THREE25 from "three";
function collectParts2(root, exempt) {
const parts = [];
root.updateWorldMatrix(true, true);
@@ -17728,7 +17970,7 @@ function collectParts2(root, exempt) {
exempt.push(name);
return;
}
- const box = new THREE24.Box3().setFromObject(mesh);
+ const box = new THREE25.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, box });
@@ -17823,7 +18065,7 @@ var init_part_connectivity = __esm(() => {
owner: KILN_ENGINE_QA_OWNER,
defaultMode: "observe",
evaluate(context) {
- if (!(context.scene instanceof THREE24.Object3D))
+ if (!(context.scene instanceof THREE25.Object3D))
return [];
const report = analyzePartConnectivity(context.scene);
if (report.groups.length === 0)
@@ -17913,7 +18155,7 @@ var init_reference_comparison = __esm(() => {
});
// src/qa/self-intersection.ts
-import * as THREE25 from "three";
+import * as THREE26 from "three";
function triangleCount(geometry) {
const index = geometry.getIndex();
const position = geometry.getAttribute("position");
@@ -17939,7 +18181,7 @@ function collectParts3(root, skipped) {
});
return;
}
- const box = new THREE25.Box3().setFromObject(mesh);
+ const box = new THREE26.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, mesh, box, triangles });
@@ -17952,7 +18194,7 @@ function meshToArrays(mesh) {
if (!position)
return null;
const matrix = mesh.matrixWorld;
- const v = new THREE25.Vector3;
+ const v = new THREE26.Vector3;
const verts = new Float32Array(position.count * 3);
for (let i = 0;i < position.count; i++) {
v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);
@@ -18115,7 +18357,7 @@ var init_self_intersection = __esm(() => {
});
// src/qa/environment.ts
-import * as THREE26 from "three";
+import * as THREE27 from "three";
function finding4(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE4 };
}
@@ -18134,11 +18376,11 @@ function nodePath3(root, node) {
return names.reverse().join("/");
}
function transformedBox2(source, transform) {
- const result = new THREE26.Box3;
+ const result = new THREE27.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -18148,16 +18390,16 @@ function orientedBoxFromLocalBounds(root, node, source) {
const relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
if (!relative.elements.every(Number.isFinite))
return;
- const position = new THREE26.Vector3;
- const rotation = new THREE26.Quaternion;
- const scale = new THREE26.Vector3;
+ const position = new THREE27.Vector3;
+ const rotation = new THREE27.Quaternion;
+ const scale = new THREE27.Vector3;
relative.decompose(position, rotation, scale);
- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);
+ const recomposed = new THREE27.Matrix4().compose(position, rotation, scale);
const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));
if (residual > 0.00001)
return;
- const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);
- const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);
+ const center = source.getCenter(new THREE27.Vector3).applyMatrix4(relative);
+ const sourceHalf = source.getSize(new THREE27.Vector3).multiplyScalar(0.5);
const halfExtents = [
Math.abs(sourceHalf.x * scale.x),
Math.abs(sourceHalf.y * scale.y),
@@ -18178,17 +18420,17 @@ function collectParts4(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf3(node);
- const renderable = node instanceof THREE26.Mesh;
+ const renderable = node instanceof THREE27.Mesh;
let box;
let orientedBox;
let source;
- if (renderable && node.geometry instanceof THREE26.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE27.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
source = node.geometry.boundingBox;
}
} else if (roles.length > 0) {
- source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));
+ source = new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.5), new THREE27.Vector3(0.5, 0.5, 0.5));
}
if (source) {
box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));
@@ -18216,9 +18458,9 @@ function resolveSocket(root, node, socket) {
return;
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();
- const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
+ const point = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rotation = node.getWorldQuaternion(new THREE27.Quaternion).multiply(new THREE27.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
return {
id: socket.id,
type: socket.type,
@@ -18247,7 +18489,7 @@ function socketByType(sockets, type) {
return sockets.find((socket) => socket.type === type);
}
function evaluateEnvironmentSocketQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18311,7 +18553,7 @@ function materialSignature(material) {
function boundarySamples(root, axis, side, bins = 12) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE26.Box3().setFromObject(root);
+ const bounds = new THREE27.Box3().setFromObject(root);
const localBounds = transformedBox2(bounds, root.matrixWorld.clone().invert());
const edge = side === "negative" ? localBounds.min[axis] : localBounds.max[axis];
const axisExtent = localBounds.max[axis] - localBounds.min[axis];
@@ -18321,22 +18563,22 @@ function boundarySamples(root, axis, side, bins = 12) {
const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);
const byBin = new Map;
root.traverse((node) => {
- if (!(node instanceof THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))
+ if (!(node instanceof THREE27.Mesh) || !(node.geometry instanceof THREE27.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (positions?.itemSize !== 3)
return;
const normals = node.geometry.getAttribute("normal");
const transform = inverse.clone().multiply(node.matrixWorld);
- const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);
+ const normalMatrix = new THREE27.Matrix3().getNormalMatrix(transform);
const material = materialSignature(node.material);
for (let index = 0;index < positions.count; index++) {
- const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
+ const point = new THREE27.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
if (Math.abs(point[axis] - edge) > band)
continue;
- const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
+ const t = THREE27.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
const bin = Math.min(bins - 1, Math.floor(t * bins));
- const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);
+ const normal = normals ? new THREE27.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE27.Vector3(0, 1, 0);
const current = byBin.get(bin);
if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {
byBin.set(bin, { bin, height: point.y, normal, material });
@@ -18358,7 +18600,7 @@ function edgePairMeasurements(root, axis, sockets) {
...positive.map((sample) => sample.bin)
]);
const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;
- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE27.MathUtils.radToDeg(Math.acos(THREE27.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);
const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);
const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);
@@ -18375,7 +18617,7 @@ function edgePairMeasurements(root, axis, sockets) {
};
}
function evaluateEnvironmentTileEdgeQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18458,7 +18700,7 @@ function isCorridor(part) {
return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));
}
function evaluateEnvironmentNavigabilityQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18572,7 +18814,7 @@ function functionalLayer(part) {
return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));
}
function evaluateEnvironmentGroundQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18619,7 +18861,7 @@ function evaluateEnvironmentGroundQa(context) {
}));
}
}
- const size = box.getSize(new THREE26.Vector3);
+ const size = box.getSize(new THREE27.Vector3);
if (box.min.y < -0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {
findings.push(finding4(context, {
code: "ENV_GROUND_UNDECLARED_SKIRT",
@@ -19146,7 +19388,7 @@ var init_breadth2 = __esm(() => {
});
// src/qa/breadth-evidence.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
function record3(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -19168,7 +19410,7 @@ function isAnimationClip(value) {
function localRenderableBox(rootInverse, node) {
if (isSpriteNode(node)) {
const transform = rootInverse.clone().multiply(node.matrixWorld);
- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
+ return new THREE28.Box3(new THREE28.Vector3(-0.5, -0.5, -0.0005), new THREE28.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
}
if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)
return;
@@ -19177,11 +19419,11 @@ function localRenderableBox(rootInverse, node) {
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(node.matrixWorld);
- const result = new THREE27.Box3;
+ const result = new THREE28.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE28.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -19269,10 +19511,10 @@ function isEffectSurface(nodes) {
function coverageRatio(boxes, overall) {
if (boxes.length === 0 || overall.isEmpty())
return 0;
- const overallSize = overall.getSize(new THREE27.Vector3);
+ const overallSize = overall.getSize(new THREE28.Vector3);
const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);
const area = boxes.reduce((sum, box) => {
- const size = box.getSize(new THREE27.Vector3);
+ const size = box.getSize(new THREE28.Vector3);
return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);
}, 0);
return stable7(Math.min(1, area / denominator));
@@ -19281,7 +19523,7 @@ function collectMaterialEvidence(root, intent) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
const byMaterial = new Map;
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (!box || !isMeshNode(node) && !isSpriteNode(node))
@@ -19306,7 +19548,7 @@ function collectMaterialEvidence(root, intent) {
effectSurface: isEffectSurface(value.nodes),
alphaMode: mode,
alphaData: alphaData(material),
- doubleSided: material.side === THREE27.DoubleSide,
+ doubleSided: material.side === THREE28.DoubleSide,
...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},
screenAreaRatio: coverageRatio(value.boxes, overall),
transparentLayers: mode === "blend" ? value.nodes.length : 0,
@@ -19334,23 +19576,23 @@ function dominantGeometryAxis(root, mode) {
const bounds = node.geometry.boundingBox;
if (!bounds || bounds.isEmpty())
return;
- const size = bounds.getSize(new THREE27.Vector3);
+ const size = bounds.getSize(new THREE28.Vector3);
const axes = [
- { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },
- { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },
- { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }
+ { score: size.x, direction: new THREE28.Vector3(1, 0, 0) },
+ { score: size.y, direction: new THREE28.Vector3(0, 1, 0) },
+ { score: size.z, direction: new THREE28.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const relative = inverse.clone().multiply(node.matrixWorld);
const direction = selected.direction.transformDirection(relative);
- const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();
+ const score = selected.score * node.getWorldScale(new THREE28.Vector3).length();
if (!best || (mode === "length" ? score > best.score : score < best.score)) {
best = { score, direction };
}
});
if (best)
return signedAxis(best.direction);
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (box)
@@ -19358,8 +19600,8 @@ function dominantGeometryAxis(root, mode) {
});
if (overall.isEmpty())
return "+X";
- const size = overall.getSize(new THREE27.Vector3);
- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);
+ const size = overall.getSize(new THREE28.Vector3);
+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE28.Vector3(1, 0, 0) : size.y >= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE28.Vector3(1, 0, 0) : size.y <= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1);
return signedAxis(vector);
}
function analyzedFacing(root, intent) {
@@ -19481,21 +19723,21 @@ function pathOf2(root, node) {
function analyzeSockets(root) {
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rootWorldRotation = root.getWorldQuaternion(new THREE28.Quaternion).invert();
const values = [];
root.traverse((node) => {
const metadata = readSemanticMetadataV1(node);
if (!metadata)
return;
- const nodeWorldRotation = node.getWorldQuaternion(new THREE27.Quaternion);
+ const nodeWorldRotation = node.getWorldQuaternion(new THREE28.Quaternion);
for (const socket of metadata.sockets) {
const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);
if (!frame)
continue;
- const frameRotation = new THREE27.Quaternion(...frame.rotation);
+ const frameRotation = new THREE28.Quaternion(...frame.rotation);
const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);
- const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
+ const position = new THREE28.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const normal = new THREE28.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
values.push({
contract: {
id: socket.id,
@@ -19528,8 +19770,8 @@ function analyzeModularEvidenceV1(root, trustedGrid) {
if (!pair)
return { kit };
const relative = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);
- const euler = new THREE27.Euler().setFromQuaternion(relative, "YXZ");
- const rotation = THREE27.MathUtils.euclideanModulo(THREE27.MathUtils.radToDeg(euler.y), 360);
+ const euler = new THREE28.Euler().setFromQuaternion(relative, "YXZ");
+ const rotation = THREE28.MathUtils.euclideanModulo(THREE28.MathUtils.radToDeg(euler.y), 360);
return {
kit,
join: {
@@ -20085,9 +20327,7 @@ var init_run = __esm(() => {
});
// src/qa/breadth-final.ts
-import { WebIO } from "@gltf-transform/core";
-import { EXTMeshGPUInstancing } from "@gltf-transform/extensions";
-import * as THREE28 from "three";
+import * as THREE29 from "three";
function bytesContainAscii(bytes, value) {
const needle = new TextEncoder().encode(value);
outer:
@@ -20146,7 +20386,7 @@ function finalEffectAxis(nodes, mode) {
if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {
continue;
}
- const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());
+ const matrix = new THREE29.Matrix4().fromArray(node.getWorldMatrix());
const scale = node.getWorldScale();
const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
@@ -20156,9 +20396,9 @@ function finalEffectAxis(nodes, mode) {
const min = position.getMin([]);
const max = position.getMax([]);
const axes = [
- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },
- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },
- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }
+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE29.Vector3(1, 0, 0) },
+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE29.Vector3(0, 1, 0) },
+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE29.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const candidate = {
@@ -20173,7 +20413,7 @@ function finalEffectAxis(nodes, mode) {
return best ? signedAxis2(best.direction) : undefined;
}
async function analyzeFinalVfxGlbBytesV1(bytes) {
- const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+ const io = createGltfIO();
const document = await io.readBinary(bytes);
const root = document.getRoot();
const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);
@@ -20409,6 +20649,7 @@ async function appendFinalVfxGlbQa(intent, report, bytes) {
}
var stable8 = (value) => Math.round(value * 1e6) / 1e6;
var init_breadth_final = __esm(() => {
+ init_gltf_io();
init_contracts();
init_types();
});
@@ -21536,7 +21777,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash4 } from "node:crypto";
-import * as THREE29 from "three";
+import * as THREE30 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -21628,7 +21869,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE30.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -21709,10 +21950,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE29.Vector3;
- const t = new THREE29.Vector3;
- const tmp = new THREE29.Vector3;
- const tmp2 = new THREE29.Vector3;
+ const n = new THREE30.Vector3;
+ const t = new THREE30.Vector3;
+ const tmp = new THREE30.Vector3;
+ const tmp2 = new THREE30.Vector3;
for (let v = 0;v < vertexCount; v++) {
n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
@@ -21732,7 +21973,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE30.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -21778,7 +22019,7 @@ var init_texture_bake = __esm(() => {
});
// src/views/character.ts
-import * as THREE30 from "three";
+import * as THREE31 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -21820,9 +22061,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE30.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE31.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE31.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE31.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -22752,24 +22993,18 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive,
- WebIO as WebIO2
+ Primitive
} from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
- KHRMaterialsVariants as KHRMaterialsVariants2,
- KHRTextureBasisu as KHRTextureBasisu2
-} from "@gltf-transform/extensions";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry14,
- Group,
+ Group as Group2,
Matrix4 as Matrix47,
- Mesh as Mesh10,
+ Mesh as Mesh11,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
SRGBColorSpace as SRGBColorSpace5,
- Texture,
+ Texture as Texture2,
AnimationClip as AnimationClip3,
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
@@ -22887,7 +23122,7 @@ function preserveTexture(source, usage, cache) {
const existing = byUsage.get(usage);
if (existing)
return existing;
- const texture = new Texture;
+ const texture = new Texture2;
texture.name = source.getName();
texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;
texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };
@@ -23054,7 +23289,7 @@ async function loadGlbReviewScene(bytes) {
if (!sourceScene)
throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
const reasons = new Set;
- const root = new Group;
+ const root = new Group2;
root.name = sourceScene.getName() || "Scene";
const nodeMap = new Map;
const textureCache = new Map;
@@ -23064,7 +23299,7 @@ async function loadGlbReviewScene(bytes) {
const existing = nodeMap.get(source);
if (existing)
return existing;
- const target = new Group;
+ const target = new Group2;
target.name = source.getName();
target.position.fromArray(source.getTranslation());
target.quaternion.fromArray(source.getRotation());
@@ -23129,7 +23364,7 @@ async function loadGlbReviewScene(bytes) {
threeMaterial.aoMapIntensity = material.getOcclusionStrength();
}
for (const [index, matrix] of matrices.entries()) {
- const mesh = new Mesh10(geometry, threeMaterial);
+ const mesh = new Mesh11(geometry, threeMaterial);
const baseName = source.getName() || sourceMesh.getName() || "Mesh";
mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;
mesh.matrixAutoUpdate = false;
@@ -23169,8 +23404,9 @@ async function loadGlbReviewScene(bytes) {
instanceCount
};
}
-var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO = () => new WebIO2().registerExtensions([EXTMeshGPUInstancing2, KHRMaterialsVariants2, KHRTextureBasisu2]);
+var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO;
var init_glb = __esm(() => {
+ init_gltf_io();
GLB_GEOMETRY_FLAT_REASON = {
TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
@@ -23199,6 +23435,7 @@ var init_glb = __esm(() => {
this.name = "GlbGeometryFlatError";
}
};
+ glbIO = createGltfIO;
});
// src/evaluator/handler.ts
@@ -23255,7 +23492,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE31 from "three";
+import * as THREE32 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -23266,18 +23503,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE32 from "three";
+import * as THREE33 from "three";
function hasRole2(node, prefix) {
return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
}
function chassisBounds(root, inverse) {
- const bounds = new THREE32.Box3;
+ const bounds = new THREE33.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
+ if (!(part instanceof THREE33.Mesh) || !(part.geometry instanceof THREE33.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -23287,7 +23524,7 @@ function chassisBounds(root, inverse) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE33.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -23355,33 +23592,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE32.Vector3(...start);
- const to = new THREE32.Vector3(...end);
+ const from = new THREE33.Vector3(...start);
+ const to = new THREE33.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);
- const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE33.CylinderGeometry(radius, radius, length, 8) : new THREE33.SphereGeometry(radius, 8, 6);
+ const result = new THREE33.Mesh(geometry, new THREE33.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE32.Group;
+ const overlay = new THREE33.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE32.Group;
+ const arrow = new THREE33.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE33.Mesh(new THREE33.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE33.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), new THREE33.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -23389,18 +23626,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE33.Mesh(new THREE33.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE33.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE32.Vector3(...wheel.axle);
+ const axle = new THREE33.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE32.Group;
+ const chassis = new THREE33.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -23434,7 +23671,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE32.Group;
+ const plane = new THREE33.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -23986,7 +24223,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE33 from "three";
+import * as THREE34 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -24023,22 +24260,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE33.Box3().setFromObject(root);
+ const bounds = new THREE34.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE33.Vector3);
- const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
- const upHint = new THREE33.Vector3(0, 1, 0);
- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE34.Vector3(-0.5, 0, -0.5), new THREE34.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE34.Vector3);
+ const camera = cameraId === "front" ? new THREE34.Vector3(1, 0, 0) : new THREE34.Vector3(0, 0, 1);
+ const upHint = new THREE34.Vector3(0, 1, 0);
+ const xAxis = new THREE34.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE34.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
+ const point = new THREE34.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE34.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -24161,14 +24398,74 @@ var init_character_capture = __esm(() => {
init_pose();
});
+// src/exporter-node.ts
+var exports_exporter_node = {};
+__export(exports_exporter_node, {
+ nodeExportPlatform: () => nodeExportPlatform
+});
+async function prepareNodeExport(hasTextures) {
+ const host = globalThis;
+ if (!host["FileReader"])
+ host["FileReader"] = ExportFileReader;
+ if (!hasTextures || host["OffscreenCanvas"] || host["document"])
+ return;
+ const { Canvas, ImageData } = await import("@napi-rs/canvas");
+
+ class ExportCanvas extends Canvas {
+ async convertToBlob(options = {}) {
+ const type = options.type ?? options.mime ?? "image/png";
+ if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")
+ throw new Error(`Unsupported export image type: ${type}`);
+ const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);
+ return new Blob([new Uint8Array(bytes)], { type });
+ }
+ }
+ host["OffscreenCanvas"] = ExportCanvas;
+ if (!host["ImageData"])
+ host["ImageData"] = ImageData;
+}
+
+class ExportFileReader {
+ result = null;
+ error = null;
+ onloadend = null;
+ onerror = null;
+ readAsArrayBuffer(blob) {
+ this.read(blob, false);
+ }
+ readAsDataURL(blob) {
+ this.read(blob, true);
+ }
+ read(blob, dataUrl) {
+ blob.arrayBuffer().then((bytes) => {
+ this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;
+ this.onloadend?.();
+ }, (error) => {
+ this.error = error;
+ this.onerror?.();
+ this.onloadend?.();
+ });
+ }
+}
+var nodeExportPlatform;
+var init_exporter_node = __esm(() => {
+ nodeExportPlatform = {
+ prepare: prepareNodeExport,
+ async decode(bytes) {
+ const { default: sharp } = await import("sharp");
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return {
+ data: new Uint8Array(decoded.data),
+ width: decoded.info.width,
+ height: decoded.info.height
+ };
+ }
+ };
+});
+
// src/render.ts
-import * as THREE34 from "three";
-import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
- KHRMaterialsVariants as KHRMaterialsVariants3,
- KHRTextureBasisu as KHRTextureBasisu3
-} from "@gltf-transform/extensions";
+import * as THREE35 from "three";
+import { Document, getBounds } from "@gltf-transform/core";
import {
dedup,
instance,
@@ -24302,7 +24599,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE34.DoubleSide) {
+ if (stdMat.side === THREE35.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -24371,7 +24668,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE34.DoubleSide)
+ if (threeMat.side === THREE35.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -24424,22 +24721,15 @@ function bridgeGeometry(doc, buf, geometry, material, meshName) {
if (!Array.isArray(material))
return mesh.addPrimitive(prim);
const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
- const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
+ const groups = validateMaterialGroups(geometry, material.length, meshName);
for (const group of groups) {
- if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
- throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
- }
const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
for (const semantic of prim.listSemantics())
part.setAttribute(semantic, prim.getAttribute(semantic));
const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
part.setIndices(doc.createAccessor(`${meshName}_group_indices`).setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
mesh.addPrimitive(part);
- covered += group.count;
}
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
prim.dispose();
return mesh;
}
@@ -24506,7 +24796,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE34.PlaneGeometry(1, 1);
+ const geometry = new THREE35.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -24658,7 +24948,8 @@ async function renderSceneToGLB(root, opts = {}) {
const clips = opts.clips ?? [];
if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
const tris = countTriangles(root);
const intent = opts.intent ?? createAssetIntentV1({
category: isAssetCategory(opts.category) ? opts.category : "prop"
@@ -24692,19 +24983,28 @@ async function renderSceneToGLB(root, opts = {}) {
throw blocked;
warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
}
- const doc = new Document;
+ const doc = exporter === "three" ? await communitySceneDocument(root, clips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform) : new Document;
doc.getRoot().getAsset().generator = "Kiln";
- const buf = doc.createBuffer();
- const matCache = new Map;
- const meshCache = new Map;
- const texCache = new Map;
- const nodeMap = new Map;
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ if (exporter === "legacy") {
+ const buf = doc.createBuffer();
+ const matCache = new Map;
+ const meshCache = new Map;
+ const texCache = new Map;
+ const nodeMap = new Map;
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ } else {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ throw new Error("Community exporter produced no scene.");
+ scene.setName(opts.sceneName ?? "Scene");
+ if (clips.length > 0)
+ scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
}
if (opts.dedup !== false) {
try {
@@ -24824,6 +25124,7 @@ async function renderGLBInProcess(code, opts = {}) {
});
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
+ gltfExporter: opts.gltfExporter,
sceneName: meta.name || "Scene",
geometryPolicy: opts.geometryPolicy,
clips,
@@ -24900,12 +25201,12 @@ function collectMeshStats(root) {
return;
const idx = geo.getIndex();
const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
- const box = new THREE34.Box3().setFromObject(obj);
+ const box = new THREE35.Box3().setFromObject(obj);
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE34.Vector3;
- const size = new THREE34.Vector3;
+ const center = new THREE35.Vector3;
+ const size = new THREE35.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -24920,7 +25221,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE34.Vector3;
+ const v = new THREE35.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -24938,10 +25239,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE34.Box3;
+ const all = new THREE35.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE34.Vector3;
+ const size = new THREE35.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -25002,9 +25303,11 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
var init_render = __esm(() => {
init_authoring_diagnostic();
+ init_gltf_io();
+ init_community_exporter();
init_geometry_export();
init_primitives();
init_contracts();
@@ -25021,6 +25324,7 @@ var init_render = __esm(() => {
init_texture_bake();
init_character_capture();
init_vehicle3();
+ engineIO = createGltfIO;
REVIEW_CLIP_LIMITS2 = {
clips: 32,
tracks: 256,
@@ -26756,7 +27060,7 @@ init_render();
init_list_primitives();
init_evaluator();
init_material_resources();
-import * as THREE35 from "three";
+import * as THREE36 from "three";
// src/edit-buffer.ts
class KilnDraftBuffer {
@@ -27059,7 +27363,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE35.DoubleSide;
+ copy.side = THREE36.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -27358,16 +27662,16 @@ function collectSceneMetrics(root) {
} else if (mat) {
materialSet.add(mat);
}
- const mb = new THREE35.Box3().setFromObject(node);
+ const mb = new THREE36.Box3().setFromObject(node);
if (!mb.isEmpty() && (!lowestPart || mb.min.y < lowestPart.y)) {
lowestPart = { name: node.name || "(unnamed mesh)", y: mb.min.y };
}
}
});
- const box = new THREE35.Box3().setFromObject(root);
+ const box = new THREE36.Box3().setFromObject(root);
let bbox;
if (!box.isEmpty()) {
- const size = new THREE35.Vector3;
+ const size = new THREE36.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -28692,7 +28996,7 @@ function toCachedSystemPrompt(text, model) {
// src/agent/grade-refine.ts
init_run();
init_evaluator();
-import { WebIO as WebIO4 } from "@gltf-transform/core";
+import { WebIO as WebIO2 } from "@gltf-transform/core";
var GRADE_REFINE_TARGET = "B";
var GRADE_REFINE_MIN_HEADROOM = 4;
var GRADE_ORDER = ["A", "B", "C", "D", "F"];
@@ -28706,7 +29010,7 @@ function srgb255(linear) {
}
async function listMaterialLabels(glb) {
try {
- const doc = await new WebIO4().readBinary(glb);
+ const doc = await new WebIO2().readBinary(glb);
const labels = new Set;
for (const material of doc.getRoot().listMaterials()) {
const name = material.getName();
diff --git a/dist/build.json b/dist/build.json
index c251bed2..3ca38764 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,11 +2,11 @@
"schemaVersion": 1,
"entries": {
"mcp": {
- "identity": "sha256:7e87b9a7eb7d5aab29563c36d689a813ed128616209732a0de703a2993aee9ab",
+ "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "9497a1ce68d79cada5164864afb3421e8bfd3f756a448c09695bb51751ef221d",
- "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541",
+ "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",
+ "dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
"@gltf-transform/extensions": "4.5.0",
@@ -28,14 +28,14 @@
},
"target": "node",
"file": "mcp-server.mjs",
- "bundleHash": "sha256:c931317e14e7d65ec4209179a405d06feddd192ef6e98bbc1808b817ae816249"
+ "bundleHash": "sha256:9a32a2dcd15e237ad0ad10aeb0c389d436a569cda70d5793cf243ab63cc86b34"
},
"cli": {
- "identity": "sha256:7e87b9a7eb7d5aab29563c36d689a813ed128616209732a0de703a2993aee9ab",
+ "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "9497a1ce68d79cada5164864afb3421e8bfd3f756a448c09695bb51751ef221d",
- "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541",
+ "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",
+ "dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
"@gltf-transform/extensions": "4.5.0",
@@ -57,14 +57,14 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:001494a3e6351a77f8477d5e1d41976baf620160c346473bd3650d05c1d55468"
+ "bundleHash": "sha256:9e7e7fc81233f4bb34584eabfa5a82a82f5c0f636965ec0f3b78872df5c539ed"
},
"worker": {
- "identity": "sha256:7e87b9a7eb7d5aab29563c36d689a813ed128616209732a0de703a2993aee9ab",
+ "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "9497a1ce68d79cada5164864afb3421e8bfd3f756a448c09695bb51751ef221d",
- "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541",
+ "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",
+ "dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
"@gltf-transform/extensions": "4.5.0",
@@ -86,14 +86,14 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:03c4ce7c118e4bca76c8feb1f70dff31533dacb1a77541af3f474697df59bdc5"
+ "bundleHash": "sha256:791ac0f53486e31487bf731a24be45e74048436cec203d3d25c9df8343de374f"
},
"agent-run": {
- "identity": "sha256:7e87b9a7eb7d5aab29563c36d689a813ed128616209732a0de703a2993aee9ab",
+ "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "9497a1ce68d79cada5164864afb3421e8bfd3f756a448c09695bb51751ef221d",
- "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541",
+ "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",
+ "dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
"@gltf-transform/extensions": "4.5.0",
@@ -115,14 +115,14 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:c90f03948131e6396530d8abaa3e569574c71dfbfba368b1ff3453cae7534b88"
+ "bundleHash": "sha256:4bbdfa2c89ce3f25cfb829be3aba0ff6ce5bf9c33a77a33355754af421935fad"
},
"agent-providers": {
- "identity": "sha256:7e87b9a7eb7d5aab29563c36d689a813ed128616209732a0de703a2993aee9ab",
+ "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",
"engineVersion": "0.7.1",
"toolchain": "[email protected]",
- "sourceHash": "9497a1ce68d79cada5164864afb3421e8bfd3f756a448c09695bb51751ef221d",
- "dependencyHash": "ec89db810fc1196f4058317df0fd1b59ac0fd3ffea2ac52def221406488c6541",
+ "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",
+ "dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc",
"dependencies": {
"@gltf-transform/core": "4.5.0",
"@gltf-transform/extensions": "4.5.0",
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 2685c8a0..fe35e00a 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -10816,7 +10816,238 @@ var init_run = __esm(() => {
};
});
+// src/gltf-io.ts
+import { WebIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+function createGltfIO() {
+ return new WebIO().registerExtensions(ALL_EXTENSIONS);
+}
+var init_gltf_io = () => {};
+
+// src/community-exporter.ts
+import * as THREE15 from "three";
+import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
+function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
+ if (value === undefined || value === "legacy")
+ return "legacy";
+ if (value === "three")
+ return "three";
+ throw new Error(`Invalid KILN_GLTF_EXPORTER ${JSON.stringify(value)}; use legacy or three.`);
+}
+function cleanClone(source) {
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ return shadow.clone();
+}
+async function communitySceneDocument(root, clips, platform = browserPlatform) {
+ const materials = new Map;
+ const textures = new Map;
+ const nodes = new Map;
+ const encoded = [];
+ function texture(source) {
+ const found = textures.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ normalizeTextureTransform(copy);
+ copy.source = new THREE15.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData["encoded"];
+ if (bytes?.bytes) {
+ encoded.push((async () => {
+ copy.image = await platform.decode(bytes.bytes);
+ Object.defineProperty(copy, "isDataTexture", { value: true });
+ copy.format = THREE15.RGBAFormat;
+ copy.type = THREE15.UnsignedByteType;
+ })());
+ }
+ return copy;
+ }
+ function material(source) {
+ const found = materials.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ const physical = copy;
+ if (physical.isMeshPhysicalMaterial && physical.sheen > 0) {
+ physical.sheenColor.multiplyScalar(physical.sheen);
+ physical.sheen = 1;
+ }
+ for (const [key, value] of Object.entries(copy)) {
+ if (value instanceof THREE15.Texture)
+ copy[key] = texture(value);
+ }
+ materials.set(source, copy);
+ return copy;
+ }
+ function node(source) {
+ if (source.isLine || source.isPoints)
+ throw new Error("Experimental glTF exporter supports triangle meshes and sprites, not lines or points.");
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ let copy = shadow.clone(false);
+ if (source.isScene) {
+ copy = new THREE15.Group;
+ copy.copy(shadow, false);
+ }
+ if (source.isSprite) {
+ const sprite = source;
+ const geometry = new THREE15.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE15.MeshBasicMaterial({
+ name: sprite.material.name,
+ color: sprite.material.color,
+ opacity: sprite.material.opacity,
+ transparent: sprite.material.transparent,
+ alphaTest: sprite.material.alphaTest,
+ side: sprite.material.side,
+ map: sprite.material.map ? texture(sprite.material.map) : null
+ });
+ copy = new THREE15.Mesh(geometry, spriteMaterial);
+ THREE15.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ if (semantic !== undefined) {
+ const checked = validateSemanticMetadataV1(semantic);
+ if (!checked.valid || !checked.value)
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on ${source.name}`);
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(checked.value);
+ }
+ if (source.isSprite) {
+ const metadata = copy.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = createSemanticMetadataV1({
+ ...metadata,
+ roles: [
+ ...(metadata?.roles ?? []).filter((role) => !role.startsWith("vfx.facing.")),
+ "vfx.facing.camera-spherical",
+ ...metadata?.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
+ ]
+ });
+ }
+ if (source.isMesh) {
+ const original = source;
+ const mesh = copy;
+ mesh.geometry = cleanClone(original.geometry);
+ mesh.material = Array.isArray(original.material) ? original.material.map(material) : material(original.material);
+ }
+ nodes.set(source, copy);
+ for (const child of source.children)
+ copy.add(node(child));
+ return copy;
+ }
+ const copy = node(root);
+ for (const [source, target] of nodes) {
+ if (!source.isSkinnedMesh)
+ continue;
+ const original = source;
+ const mesh = target;
+ mesh.skeleton = original.skeleton.clone();
+ mesh.skeleton.bones = original.skeleton.bones.map((bone) => {
+ const mapped = nodes.get(bone);
+ if (!mapped)
+ throw new Error(`Skin bone ${bone.name} is outside the exported hierarchy.`);
+ return mapped;
+ });
+ mesh.bind(mesh.skeleton, original.bindMatrix);
+ }
+ await Promise.all(encoded);
+ await platform.prepare(textures.size > 0);
+ const exportClips = clips.map((clip) => {
+ const cloned = cleanClone(clip);
+ for (const track of cloned.tracks) {
+ for (const [source, target] of nodes) {
+ if (track.name.startsWith(`${source.uuid}.`))
+ track.name = target.uuid + track.name.slice(source.uuid.length);
+ }
+ }
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE15.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE15.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ } catch {
+ return false;
+ }
+ });
+ return cloned;
+ });
+ const bytes = await new GLTFExporter().parseAsync(copy, {
+ binary: true,
+ trs: true,
+ onlyVisible: false,
+ animations: exportClips.filter((clip) => clip.tracks.length > 0)
+ });
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(new Uint8Array(bytes));
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name)
+ continue;
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name)
+ image.name = binding.name;
+ }
+ return io.readJSON(json);
+}
+function normalizeTextureTransform(texture) {
+ if (texture.matrixAutoUpdate)
+ texture.updateMatrix();
+ const e = texture.matrix.elements;
+ const sx = Math.hypot(e[0], e[1]);
+ const rotation = sx > 0 ? Math.atan2(-e[1], e[0]) : Math.atan2(e[3], e[4]);
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ const sy = e[3] * s + e[4] * c;
+ const reconstructed = [sx * c, -sx * s, 0, sy * s, sy * c, 0, e[6], e[7], 1];
+ const tolerance = 0.0000001 * Math.max(1, ...e.map(Math.abs));
+ if (e.some((value, i) => !Number.isFinite(value) || Math.abs(value - reconstructed[i]) > tolerance)) {
+ throw new Error(`Texture ${texture.name || "<unnamed>"}: UV matrix contains shear or perspective that KHR_texture_transform cannot represent; lossless UV baking is not yet qualified.`);
+ }
+ texture.offset.set(e[6], e[7]);
+ texture.repeat.set(sx, sy);
+ texture.rotation = rotation;
+ texture.center.set(0, 0);
+ texture.matrixAutoUpdate = false;
+}
+var browserPlatform;
+var init_community_exporter = __esm(() => {
+ init_gltf_io();
+ init_contracts();
+ browserPlatform = {
+ async prepare() {},
+ async decode(bytes) {
+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]), {
+ colorSpaceConversion: "none"
+ });
+ try {
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("A 2D canvas is required to decode export textures.");
+ context.drawImage(bitmap, 0, 0);
+ const image = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ return { data: new Uint8Array(image.data), width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ }
+ };
+});
+
// src/geometry-export.ts
+function validateMaterialGroups(geometry, materialCount, name) {
+ const length = geometry.getIndex()?.count ?? geometry.getAttribute("position").count;
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ const materialIndex = group.materialIndex ?? 0;
+ if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > length || !Number.isInteger(materialIndex) || materialIndex < 0 || materialIndex >= materialCount)
+ throw new TypeError(`${name}: material groups must cover every triangle exactly once with valid material indices.`);
+ covered = group.start + group.count;
+ }
+ if (covered !== length)
+ throw new TypeError(`${name}: material groups do not cover every triangle.`);
+ return groups;
+}
function geometryAttributeValues(attribute) {
const values = new Float32Array(attribute.count * attribute.itemSize);
for (let vertex = 0;vertex < attribute.count; vertex++) {
@@ -10826,7 +11057,7 @@ function geometryAttributeValues(attribute) {
}
return values;
}
-function inspectGeometryExport(root, policy = "warn") {
+function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
const warnings = [];
root.traverse((node) => {
const mesh = node;
@@ -10844,7 +11075,14 @@ function inspectGeometryExport(root, policy = "warn") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];
+ const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key] ?? (exporter === "three" ? {
+ color: attribute.itemSize === 4 ? 4 : 3,
+ uv1: 2,
+ uv2: 2,
+ uv3: 2,
+ skinIndex: 4,
+ skinWeight: 4
+ }[key] : undefined);
if (expected === undefined) {
unsupported(key);
continue;
@@ -10870,10 +11108,14 @@ function inspectGeometryExport(root, policy = "warn") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
- for (const key of Object.keys(geometry.morphAttributes))
- unsupported(`morph ${key}`);
- if (mesh.isSkinnedMesh)
- unsupported("skinning");
+ if (exporter === "three" && Array.isArray(mesh.material))
+ validateMaterialGroups(geometry, mesh.material.length, name);
+ if (exporter === "legacy") {
+ for (const key of Object.keys(geometry.morphAttributes))
+ unsupported(`morph ${key}`);
+ if (mesh.isSkinnedMesh)
+ unsupported("skinning");
+ }
for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {
const notes = geometry.userData[key];
if (!Array.isArray(notes))
@@ -11007,7 +11249,7 @@ var dE2 = (a, b) => {
}, chroma = (lab) => Math.hypot(lab[1], lab[2]), REL_CHROMA_GATE = 0.04, relChroma = (lab) => chroma(lab) / Math.max(lab[0], 0.25);
// src/architecture.ts
-import * as THREE15 from "three";
+import * as THREE16 from "three";
function positive2(value, name) {
if (!Number.isFinite(value) || value <= 0)
throw new RangeError(`${name} must be finite and > 0`);
@@ -11072,17 +11314,17 @@ function buildFace(roofRoot, profile, sideSign) {
const verticalRun = profile.ridgeY - profile.eaveY;
const downhillLength = Math.hypot(horizontalRun, verticalRun);
const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;
- const downhill = profile.ridgeAxis === "x" ? new THREE15.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE15.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
- const tangent = profile.ridgeAxis === "x" ? new THREE15.Vector3(sideSign, 0, 0) : new THREE15.Vector3(0, 0, -sideSign);
+ const downhill = profile.ridgeAxis === "x" ? new THREE16.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE16.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
+ const tangent = profile.ridgeAxis === "x" ? new THREE16.Vector3(sideSign, 0, 0) : new THREE16.Vector3(0, 0, -sideSign);
const normal = downhill.clone().cross(tangent).normalize();
- const localToRoof = new THREE15.Matrix4().makeBasis(tangent, normal, downhill);
+ const localToRoof = new THREE16.Matrix4().makeBasis(tangent, normal, downhill);
localToRoof.setPosition(0, profile.ridgeY, 0);
const world = () => {
roofRoot.updateWorldMatrix(true, false);
return roofRoot.matrixWorld.clone().multiply(localToRoof);
};
const direction = (axis) => axis.clone().transformDirection(world());
- const point = (x, z) => new THREE15.Vector3(x, 0, z).applyMatrix4(world());
+ const point = (x, z) => new THREE16.Vector3(x, 0, z).applyMatrix4(world());
return {
side,
ridgeAxis: profile.ridgeAxis,
@@ -11092,13 +11334,13 @@ function buildFace(roofRoot, profile, sideSign) {
return world();
},
get ridgeTangent() {
- return direction(new THREE15.Vector3(1, 0, 0));
+ return direction(new THREE16.Vector3(1, 0, 0));
},
get downhillDirection() {
- return direction(new THREE15.Vector3(0, 0, 1));
+ return direction(new THREE16.Vector3(0, 0, 1));
},
get outwardNormal() {
- return direction(new THREE15.Vector3(0, 1, 0));
+ return direction(new THREE16.Vector3(0, 1, 0));
},
get ridgeStart() {
return point(-alongRidge / 2, 0);
@@ -11116,17 +11358,17 @@ function buildFace(roofRoot, profile, sideSign) {
};
}
function buildRoof(name, material, profile, parent) {
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
if (parent)
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));
const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];
const buildSlope = (face) => {
- const geometry = new THREE15.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
- const mesh = new THREE15.Mesh(geometry, material);
+ const geometry = new THREE16.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
+ const mesh = new THREE16.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${face.side}`;
- const center = new THREE15.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
+ const center = new THREE16.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
setTransform(mesh, face.localToRoof.clone().multiply(center));
const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";
stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [
@@ -11196,7 +11438,7 @@ function createGableEndPanel(name, material, options) {
const ridgeAxis = options.ridgeAxis ?? "x";
const side = options.side ?? "positive";
const half = span / 2;
- const shape = new THREE15.Shape;
+ const shape = new THREE16.Shape;
shape.moveTo(-half, 0);
shape.lineTo(half, 0);
shape.lineTo(0, rise);
@@ -11215,7 +11457,7 @@ function createGableEndPanel(name, material, options) {
const right = opening.offset + opening.width / 2;
const bottom = opening.bottom;
const top = bottom + opening.height;
- const hole = new THREE15.Path;
+ const hole = new THREE16.Path;
hole.moveTo(left, bottom);
hole.lineTo(left, top);
hole.lineTo(right, top);
@@ -11223,7 +11465,7 @@ function createGableEndPanel(name, material, options) {
hole.closePath();
shape.holes.push(hole);
}
- const geometry = new THREE15.ExtrudeGeometry(shape, {
+ const geometry = new THREE16.ExtrudeGeometry(shape, {
depth: thickness,
bevelEnabled: false,
steps: 1
@@ -11232,7 +11474,7 @@ function createGableEndPanel(name, material, options) {
if (ridgeAxis === "x")
geometry.rotateY(-Math.PI / 2);
geometry.computeVertexNormals();
- const root = new THREE15.Mesh(geometry, material);
+ const root = new THREE16.Mesh(geometry, material);
root.name = `Mesh_${name}`;
stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [
relationship("adjacent-to", "roof.slope.positive"),
@@ -11248,7 +11490,7 @@ function createGableEndPanel(name, material, options) {
}
]));
const markers = normalized.map((opening, index) => {
- const marker = new THREE15.Object3D;
+ const marker = new THREE16.Object3D;
marker.name = `Opening_${name}_${opening.id ?? index + 1}`;
marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);
marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);
@@ -11268,7 +11510,7 @@ function wallNeighbors(wall) {
}
function createShellWall(name, wall, material, length, height, thickness, openings) {
const axis = wallRunAxis(wall);
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = `${name}_Wall_${wall}`;
const neighbors = wallNeighbors(wall);
stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [
@@ -11291,8 +11533,8 @@ function createShellWall(name, wall, material, length, height, thickness, openin
const panel = (suffix, lo, hi, y0, y1) => {
if (hi - lo <= EPSILON3 || y1 - y0 <= EPSILON3)
return;
- const geometry = axis === "x" ? new THREE15.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE15.BoxGeometry(thickness, y1 - y0, hi - lo);
- const mesh = new THREE15.Mesh(geometry, material);
+ const geometry = axis === "x" ? new THREE16.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE16.BoxGeometry(thickness, y1 - y0, hi - lo);
+ const mesh = new THREE16.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${wall}_${suffix}`;
mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);
root.add(mesh);
@@ -11312,7 +11554,7 @@ function createShellWall(name, wall, material, length, height, thickness, openin
panel("lintel", left, right, top, height);
if (opening.sill > 0)
panel("sill", left, right, 0, opening.sill);
- const marker = new THREE15.Object3D;
+ const marker = new THREE16.Object3D;
marker.name = `Opening_${wall}_${opening.id}`;
marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);
marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);
@@ -11335,7 +11577,7 @@ function createGableShell(name, materials, options) {
const closedEnds = options.closedEnds ?? true;
const enterable = options.enterable ?? true;
const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
if (options.parent)
options.parent.add(root);
@@ -11355,7 +11597,7 @@ function createGableShell(name, materials, options) {
walls[wall] = built.root;
openingMarkers.push(...built.openings);
}
- const floor = new THREE15.Mesh(new THREE15.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
+ const floor = new THREE16.Mesh(new THREE16.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
floor.name = `Mesh_${name}_Floor`;
floor.position.y = -floorThickness / 2;
stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));
@@ -11401,7 +11643,7 @@ function createGableShell(name, materials, options) {
}
function createRoofSurfaceLayout(name, material, options) {
const parent = options.parent ?? options.face.roofRoot;
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));
@@ -11453,9 +11695,9 @@ function createRoofSurfaceLayout(name, material, options) {
});
}
const items = specs.map((spec, index) => {
- const mesh = new THREE15.Mesh(new THREE15.BoxGeometry(spec.width, thickness, spec.length), material);
+ const mesh = new THREE16.Mesh(new THREE16.BoxGeometry(spec.width, thickness, spec.length), material);
mesh.name = `Mesh_${name}_${index + 1}`;
- const local = new THREE15.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
+ const local = new THREE16.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
setTransform(mesh, faceToRoot.clone().multiply(local));
root.add(mesh);
return mesh;
@@ -11469,7 +11711,7 @@ var init_architecture2 = __esm(() => {
});
// src/gears.ts
-import * as THREE16 from "three";
+import * as THREE17 from "three";
function gearGeo(opts = {}) {
const {
teeth = 12,
@@ -11563,8 +11805,8 @@ function gearGeo(opts = {}) {
indices.push(tA, bA, bB);
indices.push(tA, bB, tB);
}
- const geo = new THREE16.BufferGeometry;
- geo.setAttribute("position", new THREE16.Float32BufferAttribute(positions, 3));
+ const geo = new THREE17.BufferGeometry;
+ geo.setAttribute("position", new THREE17.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -11652,8 +11894,8 @@ function bladeGeo(opts = {}) {
}
}
}
- const geo = new THREE16.BufferGeometry;
- geo.setAttribute("position", new THREE16.Float32BufferAttribute(positions, 3));
+ const geo = new THREE17.BufferGeometry;
+ geo.setAttribute("position", new THREE17.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -11664,7 +11906,7 @@ var init_gears = __esm(() => {
});
// src/ops.ts
-import * as THREE17 from "three";
+import * as THREE18 from "three";
import { LoopSubdivision } from "three-subdivide/build/index.module.js";
import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";
function arrayLinear(namePrefix, source, count, offset, parent) {
@@ -11684,19 +11926,19 @@ function arrayLinear(namePrefix, source, count, offset, parent) {
}
function degreesOf(euler) {
return [
- THREE17.MathUtils.radToDeg(euler.x),
- THREE17.MathUtils.radToDeg(euler.y),
- THREE17.MathUtils.radToDeg(euler.z)
+ THREE18.MathUtils.radToDeg(euler.x),
+ THREE18.MathUtils.radToDeg(euler.y),
+ THREE18.MathUtils.radToDeg(euler.z)
];
}
function arrayRadial(namePrefix, source, count, axis = "y", parent, center) {
const out = [];
- const pivot = center ? new THREE17.Vector3(...center) : new THREE17.Vector3;
+ const pivot = center ? new THREE18.Vector3(...center) : new THREE18.Vector3;
const basePos = source.position.clone().sub(pivot);
- const axisVec = axis === "x" ? new THREE17.Vector3(1, 0, 0) : axis === "z" ? new THREE17.Vector3(0, 0, 1) : new THREE17.Vector3(0, 1, 0);
+ const axisVec = axis === "x" ? new THREE18.Vector3(1, 0, 0) : axis === "z" ? new THREE18.Vector3(0, 0, 1) : new THREE18.Vector3(0, 1, 0);
for (let i = 1;i < count; i++) {
const angle = i / count * Math.PI * 2;
- const m = new THREE17.Matrix4().makeRotationAxis(axisVec, angle);
+ const m = new THREE18.Matrix4().makeRotationAxis(axisVec, angle);
const rotated = basePos.clone().applyMatrix4(m).add(pivot);
const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];
out.push(createInstance(`${namePrefix}${i}`, source, {
@@ -11725,25 +11967,25 @@ function mergeVertices(geometry, opts = {}) {
const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;
if (!positionOnly)
return threeMergeVertices(geometry, tolerance);
- const stripped = new THREE17.BufferGeometry;
+ const stripped = new THREE18.BufferGeometry;
const pos = geometry.getAttribute("position");
if (!pos)
return geometry;
- stripped.setAttribute("position", new THREE17.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
+ stripped.setAttribute("position", new THREE18.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
if (geometry.index) {
- stripped.setIndex(new THREE17.BufferAttribute(new Uint32Array(geometry.index.array), 1));
+ stripped.setIndex(new THREE18.BufferAttribute(new Uint32Array(geometry.index.array), 1));
}
return threeMergeVertices(stripped, tolerance);
}
function subdivide(geometry, iterations = 1, opts = {}) {
const { weld = true, preserveUV = false, ...subOpts } = opts;
const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();
- const center = new THREE17.Vector3;
+ const center = new THREE18.Vector3;
let normalizationScale = 1;
if (preserveUV) {
subOpts.uvSmooth = false;
input.computeBoundingBox();
- const extent = input.boundingBox.getSize(new THREE17.Vector3);
+ const extent = input.boundingBox.getSize(new THREE18.Vector3);
input.boundingBox.getCenter(center);
const size = Math.max(extent.x, extent.y, extent.z);
normalizationScale = size > 0 ? 1e4 / size : 1;
@@ -11777,9 +12019,9 @@ function subdivide(geometry, iterations = 1, opts = {}) {
return output;
}
function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {
- const vectors = points.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));
- const curve = new THREE17.CatmullRomCurve3(vectors, closed);
- return new THREE17.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = points.map((p) => new THREE18.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE18.CatmullRomCurve3(vectors, closed);
+ return new THREE18.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function normalizeSurfaceNormals(geo) {
const normal = geo.getAttribute("normal");
@@ -11806,20 +12048,20 @@ function normalizeSurfaceNormals(geo) {
return geo;
}
function lathe(profile, segments = 12) {
- const points2d = profile.map((p) => new THREE17.Vector2(p[0], p[1]));
- return normalizeSurfaceNormals(new THREE17.LatheGeometry(points2d, segments));
+ const points2d = profile.map((p) => new THREE18.Vector2(p[0], p[1]));
+ return normalizeSurfaceNormals(new THREE18.LatheGeometry(points2d, segments));
}
function revolveGeo(profile, options = {}) {
const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
- const points2d = profile.map((p) => new THREE17.Vector2(p[0], p[1]));
- const geo = normalizeSurfaceNormals(new THREE17.LatheGeometry(points2d, segments, 0, angle));
- const n = new THREE17.Vector3(axis[0], axis[1], axis[2]);
+ const points2d = profile.map((p) => new THREE18.Vector2(p[0], p[1]));
+ const geo = normalizeSurfaceNormals(new THREE18.LatheGeometry(points2d, segments, 0, angle));
+ const n = new THREE18.Vector3(axis[0], axis[1], axis[2]);
if (n.lengthSq() < 0.000000000001) {
throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);
}
n.normalize();
if (n.x !== 0 || n.y !== 1 || n.z !== 0) {
- const q = new THREE17.Quaternion().setFromUnitVectors(new THREE17.Vector3(0, 1, 0), n);
+ const q = new THREE18.Quaternion().setFromUnitVectors(new THREE18.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
}
return geo;
@@ -11834,9 +12076,9 @@ function pipeAlongPath(points, radius, options = {}) {
const smoothed = [];
smoothed.push(points[0]);
for (let i = 1;i < points.length - 1; i++) {
- const prev = new THREE17.Vector3(...points[i - 1]);
- const cur = new THREE17.Vector3(...points[i]);
- const next = new THREE17.Vector3(...points[i + 1]);
+ const prev = new THREE18.Vector3(...points[i - 1]);
+ const cur = new THREE18.Vector3(...points[i]);
+ const next = new THREE18.Vector3(...points[i + 1]);
const inDir = cur.clone().sub(prev);
const outDir = next.clone().sub(cur);
const inLen = inDir.length();
@@ -11851,17 +12093,17 @@ function pipeAlongPath(points, radius, options = {}) {
smoothed.push(points[points.length - 1]);
pathPoints = smoothed;
}
- const vectors = pathPoints.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));
- const curve = new THREE17.CatmullRomCurve3(vectors, closed);
- return new THREE17.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = pathPoints.map((p) => new THREE18.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE18.CatmullRomCurve3(vectors, closed);
+ return new THREE18.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function bezierCurve(controlPoints, samples = 32) {
- const vecs = controlPoints.map((p) => new THREE17.Vector3(p[0], p[1], p[2]));
+ const vecs = controlPoints.map((p) => new THREE18.Vector3(p[0], p[1], p[2]));
let curve;
if (vecs.length === 3) {
- curve = new THREE17.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
+ curve = new THREE18.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
} else if (vecs.length === 4) {
- curve = new THREE17.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
+ curve = new THREE18.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
} else {
throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);
}
@@ -11872,7 +12114,7 @@ var init_ops = __esm(() => {
});
// src/geometry.ts
-import * as THREE18 from "three";
+import * as THREE19 from "three";
function finiteArray(values, label, length) {
const result = Array.from(values);
if (length !== undefined && result.length !== length)
@@ -11886,8 +12128,8 @@ function meshGeo(data) {
if (positions.length < 9 || positions.length % 3)
throw new Error("meshGeo positions: need at least three xyz vertices");
const count = positions.length / 3;
- const geometry = new THREE18.BufferGeometry;
- geometry.setAttribute("position", new THREE18.Float32BufferAttribute(positions, 3));
+ const geometry = new THREE19.BufferGeometry;
+ geometry.setAttribute("position", new THREE19.Float32BufferAttribute(positions, 3));
if (data.indices) {
const indices = Array.from(data.indices);
if (!indices.length || indices.length % 3)
@@ -11899,7 +12141,7 @@ function meshGeo(data) {
throw new Error("meshGeo: non-indexed positions must form complete triangles");
if (data.normals) {
const normals = finiteArray(data.normals, "meshGeo normals", count * 3);
- geometry.setAttribute("normal", new THREE18.Float32BufferAttribute(normals, 3));
+ geometry.setAttribute("normal", new THREE19.Float32BufferAttribute(normals, 3));
for (let i = 0;i < count; i++)
if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)
throw new Error("meshGeo normals: zero-length normal");
@@ -11907,14 +12149,14 @@ function meshGeo(data) {
} else
geometry.computeVertexNormals();
if (data.uvs)
- geometry.setAttribute("uv", new THREE18.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
+ geometry.setAttribute("uv", new THREE19.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
if (data.tangents) {
const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);
for (let i = 0;i < count; i++) {
if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)
throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");
}
- geometry.setAttribute("tangent", new THREE18.Float32BufferAttribute(tangents, 4));
+ geometry.setAttribute("tangent", new THREE19.Float32BufferAttribute(tangents, 4));
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
@@ -11949,7 +12191,7 @@ function geometryDiagnostics(geometry, tolerance = 0.000001) {
}
const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);
const edges = new Map;
- const a = new THREE18.Vector3, b = new THREE18.Vector3, c = new THREE18.Vector3;
+ const a = new THREE19.Vector3, b = new THREE19.Vector3, c = new THREE19.Vector3;
for (let i = 0;i < indices.length; i += 3) {
result.triangles++;
const triangle = indices.slice(i, i + 3);
@@ -12053,8 +12295,8 @@ function parametricSurface(sample, options = {}) {
const sums = new Map;
for (let i = 0;i < normal.count; i++) {
const id = find(i);
- const sum = sums.get(id) ?? new THREE18.Vector3;
- sum.add(new THREE18.Vector3().fromBufferAttribute(normal, i));
+ const sum = sums.get(id) ?? new THREE19.Vector3;
+ sum.add(new THREE19.Vector3().fromBufferAttribute(normal, i));
sums.set(id, sum);
}
for (let i = 0;i < normal.count; i++) {
@@ -12073,7 +12315,7 @@ function creaseNormals(geometry, options = {}) {
if (position?.itemSize !== 3 || position.count % 3 !== 0)
throw new Error("creaseNormals requires complete xyz triangles");
out.computeBoundingBox();
- const diagonal = out.boundingBox.getSize(new THREE18.Vector3).length();
+ const diagonal = out.boundingBox.getSize(new THREE19.Vector3).length();
const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);
if (!Number.isFinite(tolerance) || tolerance <= 0)
throw new Error("creaseNormals tolerance must be positive and finite");
@@ -12081,13 +12323,13 @@ function creaseNormals(geometry, options = {}) {
const keys = [];
const faces = [];
for (let i = 0;i < position.count; i += 3) {
- const a = new THREE18.Vector3().fromBufferAttribute(position, i);
- const b = new THREE18.Vector3().fromBufferAttribute(position, i + 1);
- const c = new THREE18.Vector3().fromBufferAttribute(position, i + 2);
+ const a = new THREE19.Vector3().fromBufferAttribute(position, i);
+ const b = new THREE19.Vector3().fromBufferAttribute(position, i + 1);
+ const c = new THREE19.Vector3().fromBufferAttribute(position, i + 2);
const face = b.sub(a).cross(c.sub(a)).normalize();
faces.push(face);
for (let j = i;j < i + 3; j++) {
- const point = new THREE18.Vector3().fromBufferAttribute(position, j);
+ const point = new THREE19.Vector3().fromBufferAttribute(position, j);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("creaseNormals positions must be finite");
const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");
@@ -12098,15 +12340,15 @@ function creaseNormals(geometry, options = {}) {
}
}
const normals = new Float32Array(position.count * 3);
- const threshold = Math.cos(THREE18.MathUtils.degToRad(angle));
+ const threshold = Math.cos(THREE19.MathUtils.degToRad(angle));
for (let i = 0;i < position.count; i++) {
- const face = faces[Math.floor(i / 3)], sum = new THREE18.Vector3;
+ const face = faces[Math.floor(i / 3)], sum = new THREE19.Vector3;
for (const other of adjacent.get(keys[i]))
if (face.dot(faces[other]) >= threshold - 0.000000000001)
sum.add(faces[other]);
sum.normalize().toArray(normals, i * 3);
}
- out.setAttribute("normal", new THREE18.BufferAttribute(normals, 3));
+ out.setAttribute("normal", new THREE19.BufferAttribute(normals, 3));
out.deleteAttribute("tangent");
out.computeBoundingSphere();
return out;
@@ -12116,19 +12358,19 @@ var init_geometry = __esm(() => {
});
// src/deform.ts
-import * as THREE19 from "three";
+import * as THREE20 from "three";
function geometryFrameMatrix(frame = {}) {
const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];
if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))
throw new Error("geometry frame requires finite xyz origin and rotation");
- return new THREE19.Matrix4().compose(new THREE19.Vector3(...origin), new THREE19.Quaternion().setFromEuler(new THREE19.Euler(...rotation.map(THREE19.MathUtils.degToRad), "XYZ")), new THREE19.Vector3(1, 1, 1));
+ return new THREE20.Matrix4().compose(new THREE20.Vector3(...origin), new THREE20.Quaternion().setFromEuler(new THREE20.Euler(...rotation.map(THREE20.MathUtils.degToRad), "XYZ")), new THREE20.Vector3(1, 1, 1));
}
function deform(geometry, options, map) {
const source = geometry.getAttribute("position");
if (source?.itemSize !== 3 || source.count === 0)
throw new Error("deformation requires nonempty xyz positions");
const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();
- const points = Array.from({ length: source.count }, (_, i) => new THREE19.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
+ const points = Array.from({ length: source.count }, (_, i) => new THREE20.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))
throw new Error("deformation positions must be finite");
let low = Infinity, high = -Infinity;
@@ -12149,7 +12391,7 @@ function deform(geometry, options, map) {
const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;
if (point.y < low - epsilon || point.y > high + epsilon)
continue;
- const t = length > epsilon ? THREE19.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
+ const t = length > epsilon ? THREE20.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
const weight = options.falloff?.(t) ?? 1;
if (!Number.isFinite(weight) || weight < 0 || weight > 1)
throw new Error("deformation falloff must return a finite weight between 0 and 1");
@@ -12171,41 +12413,41 @@ function deform(geometry, options, map) {
function twist(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("twist angle must be finite degrees");
- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE19.Vector3(0, 1, 0), THREE19.MathUtils.degToRad(options.angle) * t));
+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE20.Vector3(0, 1, 0), THREE20.MathUtils.degToRad(options.angle) * t));
}
function bend(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("bend angle must be finite degrees");
- const angle = THREE19.MathUtils.degToRad(options.angle);
+ const angle = THREE20.MathUtils.degToRad(options.angle);
return deform(geometry, options, (p, t, low, length) => {
if (Math.abs(angle) < 0.0000000001 || length === 0)
return p;
const radius = length / angle, theta = angle * t;
- return new THREE19.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
+ return new THREE20.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
});
}
function taper(geometry, options) {
const start = options.startScale ?? [1, 1], end = options.endScale;
if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))
throw new Error("taper scales must be two finite positive values");
- return deform(geometry, options, (p, t) => p.set(p.x * THREE19.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE19.MathUtils.lerp(start[1], end[1], t)));
+ return deform(geometry, options, (p, t) => p.set(p.x * THREE20.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE20.MathUtils.lerp(start[1], end[1], t)));
}
function displace(geometry, offset, options = {}) {
return deform(geometry, options, (p, t) => {
const delta = offset([p.x, p.y, p.z], t);
if (delta.length !== 3 || !delta.every(Number.isFinite))
throw new Error("displace callback must return three finite offsets");
- return p.add(new THREE19.Vector3(...delta));
+ return p.add(new THREE20.Vector3(...delta));
});
}
var init_deform = () => {};
// src/sweep.ts
-import * as THREE20 from "three";
+import * as THREE21 from "three";
function profilePoints(profile) {
if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
throw new Error("profile requires at least three finite xy points");
- const points = profile.map((p) => new THREE20.Vector2(...p));
+ const points = profile.map((p) => new THREE21.Vector2(...p));
if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)
points.pop();
if (points.length < 3)
@@ -12223,7 +12465,7 @@ function profilePoints(profile) {
throw new Error("profile self-intersects or touches itself");
}
}
- const area = THREE20.ShapeUtils.area(points);
+ const area = THREE21.ShapeUtils.area(points);
if (Math.abs(area) < 0.000000000001)
throw new Error("profile area must be nonzero");
if (area < 0)
@@ -12232,7 +12474,7 @@ function profilePoints(profile) {
}
function buildLoft(rings, profiles, closed, cap) {
const n = rings[0].length, positions = [], uvs = [], indices = [];
- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE20.Vector3).multiplyScalar(1 / n));
+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE21.Vector3).multiplyScalar(1 / n));
const lengths = [0];
for (let i = 1;i < centers.length; i++)
lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));
@@ -12257,13 +12499,13 @@ function buildLoft(rings, profiles, closed, cap) {
for (const station of [0, rings.length - 1]) {
const ring = rings[station], profile = profiles[station];
const start = positions.length / 3;
- const bounds = new THREE20.Box2().setFromPoints(profile);
- const size = bounds.getSize(new THREE20.Vector2);
+ const bounds = new THREE21.Box2().setFromPoints(profile);
+ const size = bounds.getSize(new THREE21.Vector2);
for (let j = 0;j < n; j++) {
positions.push(...ring[j].toArray());
uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));
}
- for (const tri of THREE20.ShapeUtils.triangulateShape(profile, [])) {
+ for (const tri of THREE21.ShapeUtils.triangulateShape(profile, [])) {
if (station === 0)
indices.push(...tri.map((j) => start + j));
else
@@ -12274,14 +12516,14 @@ function buildLoft(rings, profiles, closed, cap) {
const normal = out.getAttribute("normal");
for (let i = 0;i < rings.length; i++) {
const a = i * (n + 1), b = a + n;
- const sum = new THREE20.Vector3().fromBufferAttribute(normal, a).add(new THREE20.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE21.Vector3().fromBufferAttribute(normal, a).add(new THREE21.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
if (closed)
for (let j = 0;j <= n; j++) {
const a = j, b = (rings.length - 1) * (n + 1) + j;
- const sum = new THREE20.Vector3().fromBufferAttribute(normal, a).add(new THREE20.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE21.Vector3().fromBufferAttribute(normal, a).add(new THREE21.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
@@ -12295,7 +12537,7 @@ function loftProfiles(sections, options = {}) {
throw new Error("loftProfiles sections must have the same point count and correspondence");
const rings = sections.map((section, i) => {
const frame = geometryFrameMatrix(section.frame);
- return profiles[i].map((p) => new THREE20.Vector3(p.x, 0, p.y).applyMatrix4(frame));
+ return profiles[i].map((p) => new THREE21.Vector3(p.x, 0, p.y).applyMatrix4(frame));
});
const out = buildLoft(rings, profiles, false, options.cap ?? true);
out.userData.kilnGeometryWarnings = [
@@ -12314,7 +12556,7 @@ function sweepProfile(profile, path, options = {}) {
throw new Error("closed sweep twist must be a multiple of 360 degrees");
if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))
throw new Error("sweepProfile requires finite path points (two open or three closed)");
- const stations = path.map((p) => new THREE20.Vector3(...p));
+ const stations = path.map((p) => new THREE21.Vector3(...p));
if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)
throw new Error("closed sweep path should omit its repeated endpoint");
const segments = [];
@@ -12351,7 +12593,7 @@ function sweepProfile(profile, path, options = {}) {
});
if (Array.isArray(options.scale) && options.scale.length !== stations.length)
throw new Error("sweepProfile scale needs one pair per path station");
- const up = options.up ? new THREE20.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE20.Vector3(0, 0, 1) : new THREE20.Vector3(1, 0, 0);
+ const up = options.up ? new THREE21.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE21.Vector3(0, 0, 1) : new THREE21.Vector3(1, 0, 0);
if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)
throw new Error("sweepProfile up must be a finite nonzero vector");
let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));
@@ -12366,7 +12608,7 @@ function sweepProfile(profile, path, options = {}) {
}
const distances = [0];
for (let i = 1;i < stations.length; i++) {
- z = z.clone().applyQuaternion(new THREE20.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
+ z = z.clone().applyQuaternion(new THREE21.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
normals.push(z);
distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));
}
@@ -12376,7 +12618,7 @@ function sweepProfile(profile, path, options = {}) {
correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));
const rings = stations.map((station, i) => {
const tangent = tangents[i], t = distances[i] / total;
- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE20.MathUtils.degToRad(twist)) * t);
+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE21.MathUtils.degToRad(twist)) * t);
const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];
return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));
});
@@ -12396,7 +12638,7 @@ var init_sweep = __esm(() => {
});
// src/solids.ts
-import * as THREE21 from "three";
+import * as THREE22 from "three";
async function getManifoldModule() {
if (_module)
return _module;
@@ -12456,7 +12698,7 @@ function threeToManifold(src, mod, label, context) {
else
context.missingUV.add(mesh.name || label);
}
- const point = new THREE21.Vector3;
+ const point = new THREE22.Vector3;
for (let i = 0;i < position.count; i++) {
point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))
@@ -12525,11 +12767,11 @@ function manifoldToGeometry(m, opts = {}) {
if (uvs)
uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);
}
- const geometry = new THREE21.BufferGeometry;
- geometry.setAttribute("position", new THREE21.BufferAttribute(positions, 3));
- geometry.setIndex(new THREE21.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
+ const geometry = new THREE22.BufferGeometry;
+ geometry.setAttribute("position", new THREE22.BufferAttribute(positions, 3));
+ geometry.setIndex(new THREE22.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
if (uvs)
- geometry.setAttribute("uv", new THREE21.BufferAttribute(uvs, 2));
+ geometry.setAttribute("uv", new THREE22.BufferAttribute(uvs, 2));
const out = opts.smooth ? geometry : geometry.toNonIndexed();
out.computeVertexNormals();
if (opts.smooth && uvs) {
@@ -12550,7 +12792,7 @@ function firstMaterial(src) {
if (!material && mesh.isMesh)
material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
});
- return material ?? new THREE21.MeshStandardMaterial;
+ return material ?? new THREE22.MeshStandardMaterial;
}
function outputMesh(result, name, parts, opts, context, isHull) {
const geometry = manifoldToGeometry(result, {
@@ -12605,7 +12847,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {
message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."
});
geometry.userData.kilnAttributeWarnings = warnings;
- const output = new THREE21.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
+ const output = new THREE22.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
output.name = `Mesh_${name}`;
return output;
}
@@ -12954,7 +13196,7 @@ var init_profile = __esm(() => {
});
// src/textures.ts
-import * as THREE22 from "three";
+import * as THREE23 from "three";
async function loadTexture(source, opts = {}) {
let bytes;
if (typeof source === "string") {
@@ -12975,7 +13217,7 @@ async function loadTexture(source, opts = {}) {
if (!meta.width || !meta.height) {
throw new Error("loadTexture: could not read image dimensions");
}
- const tex = new THREE22.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE22.RGBAFormat, THREE22.UnsignedByteType);
+ const tex = new THREE23.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE23.RGBAFormat, THREE23.UnsignedByteType);
const usage = opts.usage ?? "albedo";
const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";
let hasAlpha = false;
@@ -12985,14 +13227,14 @@ async function loadTexture(source, opts = {}) {
break;
}
}
- tex.colorSpace = colorSpace === "srgb" ? THREE22.SRGBColorSpace : THREE22.NoColorSpace;
+ tex.colorSpace = colorSpace === "srgb" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;
if (opts.name)
tex.name = opts.name;
tex.needsUpdate = true;
- tex.wrapS = THREE22.RepeatWrapping;
- tex.wrapT = THREE22.RepeatWrapping;
- tex.minFilter = THREE22.LinearMipmapLinearFilter;
- tex.magFilter = THREE22.LinearFilter;
+ tex.wrapS = THREE23.RepeatWrapping;
+ tex.wrapT = THREE23.RepeatWrapping;
+ tex.minFilter = THREE23.LinearMipmapLinearFilter;
+ tex.magFilter = THREE23.LinearFilter;
tex.generateMipmaps = true;
tex.userData["encoded"] = {
mime,
@@ -13027,17 +13269,17 @@ function requireTextureUsage(texture, usage) {
if (meta && meta.usage !== usage) {
throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);
}
- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE22.SRGBColorSpace : THREE22.NoColorSpace;
+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;
}
function pbrMaterial(opts = {}) {
- const mat = new THREE22.MeshStandardMaterial;
+ const mat = new THREE23.MeshStandardMaterial;
const isTex = (v) => !!v?.isTexture;
if (isTex(opts.albedo)) {
requireTextureUsage(opts.albedo, "albedo");
mat.map = opts.albedo;
- mat.color = new THREE22.Color(16777215);
+ mat.color = new THREE23.Color(16777215);
} else if (opts.albedo !== undefined) {
- mat.color = new THREE22.Color(opts.albedo);
+ mat.color = new THREE23.Color(opts.albedo);
}
if (opts.normal) {
requireTextureUsage(opts.normal, "normal");
@@ -13075,9 +13317,9 @@ function pbrMaterial(opts = {}) {
if (isTex(opts.emissive)) {
requireTextureUsage(opts.emissive, "emissive");
mat.emissiveMap = opts.emissive;
- mat.emissive = new THREE22.Color(16777215);
+ mat.emissive = new THREE23.Color(16777215);
} else if (opts.emissive !== undefined) {
- mat.emissive = new THREE22.Color(opts.emissive);
+ mat.emissive = new THREE23.Color(opts.emissive);
}
if (opts.emissiveIntensity !== undefined) {
mat.emissiveIntensity = opts.emissiveIntensity;
@@ -13109,7 +13351,7 @@ function pbrMaterial(opts = {}) {
mat.transparent = true;
}
if (opts.doubleSided)
- mat.side = THREE22.DoubleSide;
+ mat.side = THREE23.DoubleSide;
mat.userData["kilnMaterial"] = {
alphaMode,
...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},
@@ -13611,7 +13853,7 @@ var init_procedural_material_v2 = __esm(() => {
});
// src/procedural-texture.ts
-import * as THREE23 from "three";
+import * as THREE24 from "three";
function hash2(x, y, seed) {
let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;
h = h ^ h >>> 13;
@@ -13752,14 +13994,14 @@ function compileProceduralTextureSpecV2(input) {
function proceduralTexture(spec) {
const compiled = compileProceduralTextureSpecV2(spec);
const { size, usage, name, layers } = compiled.spec;
- const tex = new THREE23.DataTexture(compiled.pixels, size, size, THREE23.RGBAFormat, THREE23.UnsignedByteType);
+ const tex = new THREE24.DataTexture(compiled.pixels, size, size, THREE24.RGBAFormat, THREE24.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE23.SRGBColorSpace : THREE23.NoColorSpace;
- tex.wrapS = THREE23.RepeatWrapping;
- tex.wrapT = THREE23.RepeatWrapping;
- tex.minFilter = THREE23.LinearMipmapLinearFilter;
- tex.magFilter = THREE23.LinearFilter;
+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE24.SRGBColorSpace : THREE24.NoColorSpace;
+ tex.wrapS = THREE24.RepeatWrapping;
+ tex.wrapT = THREE24.RepeatWrapping;
+ tex.minFilter = THREE24.LinearMipmapLinearFilter;
+ tex.magFilter = THREE24.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -13813,13 +14055,13 @@ function normalMapFromHeight(source, opts = {}) {
out[o + 3] = 255;
}
}
- const tex = new THREE23.DataTexture(out, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);
+ const tex = new THREE24.DataTexture(out, width, height, THREE24.RGBAFormat, THREE24.UnsignedByteType);
tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");
- tex.colorSpace = THREE23.NoColorSpace;
- tex.wrapS = THREE23.RepeatWrapping;
- tex.wrapT = THREE23.RepeatWrapping;
- tex.minFilter = THREE23.LinearMipmapLinearFilter;
- tex.magFilter = THREE23.LinearFilter;
+ tex.colorSpace = THREE24.NoColorSpace;
+ tex.wrapS = THREE24.RepeatWrapping;
+ tex.wrapT = THREE24.RepeatWrapping;
+ tex.minFilter = THREE24.LinearMipmapLinearFilter;
+ tex.magFilter = THREE24.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
return tex;
@@ -16007,7 +16249,7 @@ var init_portable_material_runtime = __esm(() => {
});
// src/uv.ts
-import * as THREE24 from "three";
+import * as THREE25 from "three";
async function getXatlas() {
if (!_xatlasReady) {
_xatlasReady = (async () => {
@@ -16053,16 +16295,16 @@ async function autoUnwrap(geometry, opts = {}) {
xa.destroyAtlas();
throw new Error("autoUnwrap: xatlas returned no meshes");
}
- const out = new THREE24.BufferGeometry;
- out.setAttribute("position", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
+ const out = new THREE25.BufferGeometry;
+ out.setAttribute("position", new THREE25.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
if (mesh.vertex.normals) {
- out.setAttribute("normal", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
+ out.setAttribute("normal", new THREE25.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
}
if (mesh.vertex.coords1) {
- out.setAttribute("uv", new THREE24.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
+ out.setAttribute("uv", new THREE25.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
}
if (mesh.index) {
- out.setIndex(new THREE24.BufferAttribute(new Uint32Array(mesh.index), 1));
+ out.setIndex(new THREE25.BufferAttribute(new Uint32Array(mesh.index), 1));
}
out.userData["atlas"] = {
width: result.width,
@@ -16085,7 +16327,7 @@ function toIndexed(geo) {
for (let i = 0;i < posAttr.count; i++)
indices[i] = i;
const out = geo.clone();
- out.setIndex(new THREE24.BufferAttribute(indices, 1));
+ out.setIndex(new THREE25.BufferAttribute(indices, 1));
return out;
}
function repairZeroNormals(geo) {
@@ -16105,11 +16347,11 @@ function repairZeroNormals(geo) {
if (broken.size === 0)
return;
const acc = new Float32Array(normal.count * 3);
- const a = new THREE24.Vector3;
- const b = new THREE24.Vector3;
- const c = new THREE24.Vector3;
- const face = new THREE24.Vector3;
- const edge = new THREE24.Vector3;
+ const a = new THREE25.Vector3;
+ const b = new THREE25.Vector3;
+ const c = new THREE25.Vector3;
+ const face = new THREE25.Vector3;
+ const edge = new THREE25.Vector3;
for (let t = 0;t + 2 < index.count; t += 3) {
const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];
if (!tri.some((i) => broken.has(i)))
@@ -16143,7 +16385,7 @@ var _xatlasReady = null;
var init_uv = () => {};
// src/uv-shapes.ts
-import * as THREE25 from "three";
+import * as THREE26 from "three";
function boxUnwrap(geo) {
const cloned = geo.clone();
if (!cloned.getAttribute("uv")) {
@@ -16200,7 +16442,7 @@ function cylindricalProjectToUVs(geo) {
uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;
uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;
}
- geo.setAttribute("uv", new THREE25.BufferAttribute(uv, 2));
+ geo.setAttribute("uv", new THREE26.BufferAttribute(uv, 2));
}
function planeUnwrap(geo) {
const cloned = geo.clone();
@@ -16223,7 +16465,7 @@ function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {
function planarProjectToUVs(geo) {
geo.computeBoundingBox();
const bb = geo.boundingBox;
- const size = new THREE25.Vector3;
+ const size = new THREE26.Vector3;
bb.getSize(size);
const w = size.x || 1;
const h = size.y || 1;
@@ -16233,12 +16475,12 @@ function planarProjectToUVs(geo) {
uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;
uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;
}
- geo.setAttribute("uv", new THREE25.BufferAttribute(uvs, 2));
+ geo.setAttribute("uv", new THREE26.BufferAttribute(uvs, 2));
}
var init_uv_shapes = () => {};
// src/material-recipe-runtime.ts
-import * as THREE26 from "three";
+import * as THREE27 from "three";
async function applyMaterialRecipeV1(request, options = {}) {
const resolved = resolveMaterialRecipeV1(request);
const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;
@@ -16261,9 +16503,9 @@ async function applyMaterialRecipeV1(request, options = {}) {
};
const material = pbrMaterial(materialOptions);
material.name = options.name ?? request.id;
- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE26.LinearSRGBColorSpace);
+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE27.LinearSRGBColorSpace);
material.opacity = resolved.baseColorFactor[3];
- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE26.LinearSRGBColorSpace);
+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE27.LinearSRGBColorSpace);
const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));
const provenance = {
schemaVersion: 1,
@@ -16314,17 +16556,17 @@ var init_material_recipe_runtime = __esm(() => {
});
// src/primitives.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
function vectorToTuple(v) {
return [v.x, v.y, v.z];
}
function createRoot(name) {
- const root = new THREE27.Object3D;
+ const root = new THREE28.Object3D;
root.name = name;
return root;
}
function createPivot(name, position = [0, 0, 0], parent) {
- const pivot = new THREE27.Object3D;
+ const pivot = new THREE28.Object3D;
pivot.name = `Joint_${name}`;
pivot.position.set(...position);
if (parent)
@@ -16356,16 +16598,16 @@ function assertPartArgs(name, geometry2, material) {
}
function createPart(name, geometry2, material, options = {}) {
assertPartArgs(name, geometry2, material);
- const mesh = new THREE27.Mesh(geometry2, material);
+ const mesh = new THREE28.Mesh(geometry2, material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE27.MathUtils.degToRad(options.rotation[0]), THREE27.MathUtils.degToRad(options.rotation[1]), THREE27.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE28.MathUtils.degToRad(options.rotation[0]), THREE28.MathUtils.degToRad(options.rotation[1]), THREE28.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.pivot) {
- const pivot = new THREE27.Object3D;
+ const pivot = new THREE28.Object3D;
pivot.name = `Joint_${name}`;
pivot.add(mesh);
mesh.position.set(0, 0, 0);
@@ -16384,7 +16626,7 @@ function createPart(name, geometry2, material, options = {}) {
return mesh;
}
function capsuleGeo(radius, height, segments = 6) {
- return new THREE27.CapsuleGeometry(radius, height, 2, segments);
+ return new THREE28.CapsuleGeometry(radius, height, 2, segments);
}
function capsuleXGeo(radius, length, segments = 6) {
const geo = capsuleGeo(radius, length, segments);
@@ -16397,7 +16639,7 @@ function capsuleZGeo(radius, length, segments = 6) {
return geo;
}
function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {
- return new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ return new THREE28.CylinderGeometry(radiusTop, radiusBottom, height, segments);
}
function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
@@ -16410,13 +16652,13 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {
return geo;
}
function boxGeo(width, height, depth) {
- return new THREE27.BoxGeometry(width, height, depth);
+ return new THREE28.BoxGeometry(width, height, depth);
}
function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {
- return new THREE27.SphereGeometry(radius, widthSegments, heightSegments);
+ return new THREE28.SphereGeometry(radius, widthSegments, heightSegments);
}
function coneGeo(radius, height, segments = 8) {
- return new THREE27.ConeGeometry(radius, height, segments);
+ return new THREE28.ConeGeometry(radius, height, segments);
}
function coneXGeo(radius, length, segments = 8) {
const geo = coneGeo(radius, length, segments);
@@ -16431,20 +16673,20 @@ function coneZGeo(radius, length, segments = 8) {
function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {
const radiusTop = options.radiusTop ?? radiusBottom;
const segments = options.segments ?? 8;
- const geo = new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);
- const n = new THREE27.Vector3(normal[0], normal[1], normal[2]);
+ const geo = new THREE28.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const n = new THREE28.Vector3(normal[0], normal[1], normal[2]);
const len = n.length();
if (len < 0.000001) {
throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);
}
n.divideScalar(len);
- const q = new THREE27.Quaternion().setFromUnitVectors(new THREE27.Vector3(0, 1, 0), n);
+ const q = new THREE28.Quaternion().setFromUnitVectors(new THREE28.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
geo.translate(center[0], center[1], center[2]);
return geo;
}
function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {
- const geo = new THREE27.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const geo = new THREE28.CylinderGeometry(radiusTop, radiusBottom, height, segments);
if (axis === "x")
geo.rotateZ(-Math.PI / 2);
else if (axis === "z")
@@ -16452,20 +16694,20 @@ function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8)
return geo;
}
function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {
- return new THREE27.TorusGeometry(radius, tube, radialSegments, tubularSegments);
+ return new THREE28.TorusGeometry(radius, tube, radialSegments, tubularSegments);
}
function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {
- return new THREE27.PlaneGeometry(width, height, widthSegments, heightSegments);
+ return new THREE28.PlaneGeometry(width, height, widthSegments, heightSegments);
}
function decalBox(width, height, depth = 0.01) {
const d = Math.max(depth, 0.002);
- return new THREE27.BoxGeometry(width, height, d);
+ return new THREE28.BoxGeometry(width, height, d);
}
function foliageCardGeo(opts = {}) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE27.PlaneGeometry(w, h);
+ const geom = new THREE28.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
geom.userData["kilnGeometryRole"] = "foliageCard";
return geom;
@@ -16478,12 +16720,12 @@ function crossedQuadsGeo(opts = {}) {
const geometries = [];
for (let i = 0;i < planes; i++) {
const angle = i / planes * Math.PI;
- const quad = new THREE27.PlaneGeometry(w, h);
+ const quad = new THREE28.PlaneGeometry(w, h);
quad.translate(0, h * (0.5 - yPivot), 0);
quad.rotateY(angle);
geometries.push(quad);
}
- const out = new THREE27.BufferGeometry;
+ const out = new THREE28.BufferGeometry;
const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);
const positions = new Float32Array(posCount * 3);
const normals = new Float32Array(posCount * 3);
@@ -16510,9 +16752,9 @@ function crossedQuadsGeo(opts = {}) {
}
vOffset += p.count;
}
- out.setAttribute("position", new THREE27.BufferAttribute(positions, 3));
- out.setAttribute("normal", new THREE27.BufferAttribute(normals, 3));
- out.setAttribute("uv", new THREE27.BufferAttribute(uvs, 2));
+ out.setAttribute("position", new THREE28.BufferAttribute(positions, 3));
+ out.setAttribute("normal", new THREE28.BufferAttribute(normals, 3));
+ out.setAttribute("uv", new THREE28.BufferAttribute(uvs, 2));
out.setIndex(indices);
out.userData["kilnGeometryRole"] = "foliageCard";
return out;
@@ -16521,7 +16763,7 @@ function octaGridPlane(opts) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE27.PlaneGeometry(w, h);
+ const geom = new THREE28.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
const uv = geom.attributes.uv;
const du = 1 / opts.tilesX;
@@ -16609,8 +16851,8 @@ function wingGeo(options = {}) {
7,
6
];
- const geo = new THREE27.BufferGeometry;
- geo.setAttribute("position", new THREE27.BufferAttribute(vertices, 3));
+ const geo = new THREE28.BufferGeometry;
+ geo.setAttribute("position", new THREE28.BufferAttribute(vertices, 3));
geo.setIndex(indices);
geo.computeVertexNormals();
return geo;
@@ -16633,17 +16875,17 @@ function createWingPair(name, material, options) {
};
}
function beamBetween(name, start, end, radius, material, options = {}) {
- const a = new THREE27.Vector3(...start);
- const b = new THREE27.Vector3(...end);
+ const a = new THREE28.Vector3(...start);
+ const b = new THREE28.Vector3(...end);
const direction = b.clone().sub(a);
const length = direction.length();
if (length <= 0.0001) {
throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);
}
- const mesh = new THREE27.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
+ const mesh = new THREE28.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
mesh.name = `Mesh_${name}`;
mesh.position.copy(a.add(b).multiplyScalar(0.5));
- mesh.quaternion.setFromUnitVectors(new THREE27.Vector3(0, 1, 0), direction.normalize());
+ mesh.quaternion.setFromUnitVectors(new THREE28.Vector3(0, 1, 0), direction.normalize());
if (options.parent)
options.parent.add(mesh);
return mesh;
@@ -16652,11 +16894,11 @@ function snapTo(part, host, options = {}) {
const overlap = options.overlap ?? 0.02;
part.updateMatrixWorld(true);
host.updateMatrixWorld(true);
- const a = new THREE27.Box3().setFromObject(part);
- const b = new THREE27.Box3().setFromObject(host);
+ const a = new THREE28.Box3().setFromObject(part);
+ const b = new THREE28.Box3().setFromObject(host);
if (a.isEmpty() || b.isEmpty())
return part;
- const delta = new THREE27.Vector3;
+ const delta = new THREE28.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
delta[axis] = b.max[axis] - a.min[axis];
@@ -16672,7 +16914,7 @@ function snapTo(part, host, options = {}) {
delta[dominant] = -overlap;
const parent = part.parent;
if (parent) {
- const p0 = new THREE27.Vector3;
+ const p0 = new THREE28.Vector3;
part.getWorldPosition(p0);
const p1 = p0.clone().add(delta);
const l0 = parent.worldToLocal(p0.clone());
@@ -16697,9 +16939,9 @@ function createLadder(name, options) {
widthAxis = "x",
parent
} = options;
- const bottomVec = new THREE27.Vector3(...bottom);
- const topVec = new THREE27.Vector3(...top);
- const offset = widthAxis === "x" ? new THREE27.Vector3(width / 2, 0, 0) : new THREE27.Vector3(0, 0, width / 2);
+ const bottomVec = new THREE28.Vector3(...bottom);
+ const topVec = new THREE28.Vector3(...top);
+ const offset = widthAxis === "x" ? new THREE28.Vector3(width / 2, 0, 0) : new THREE28.Vector3(0, 0, width / 2);
const leftBottom = bottomVec.clone().sub(offset);
const leftTop = topVec.clone().sub(offset);
const rightBottom = bottomVec.clone().add(offset);
@@ -16716,7 +16958,7 @@ function createLadder(name, options) {
}
function wallWithOpening(name, material, options) {
const { length, height, thickness, axis = "z", opening, parent } = options;
- const group = new THREE27.Object3D;
+ const group = new THREE28.Object3D;
group.name = name;
const overlap = 0.02;
const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {
@@ -16761,7 +17003,7 @@ function room(name, material, options = {}) {
parent
} = options;
const openings = options.openings ?? [{ wall: "front", kind: "door" }];
- const root = new THREE27.Object3D;
+ const root = new THREE28.Object3D;
root.name = name;
const openingFor = (wall) => {
const found = openings.find((op) => op.wall === wall);
@@ -16805,7 +17047,7 @@ function createRoofPlanes2(name, material, options) {
result.slopes[0].name = `Mesh_${name}A`;
result.slopes[1].name = `Mesh_${name}B`;
for (let index = 0;index < result.slopes.length; index++) {
- const normal = new THREE27.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
+ const normal = new THREE28.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);
}
if ((options.ridgeAxis ?? "x") === "x") {
@@ -16832,7 +17074,7 @@ function createStairs(name, material, options) {
if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {
throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);
}
- const root = new THREE27.Object3D;
+ const root = new THREE28.Object3D;
root.name = name;
const stepRise = totalRise / steps;
const stepRun = totalRun / steps;
@@ -16862,7 +17104,7 @@ function requireColor(color, fn) {
}
function gameMaterial(color, options = {}) {
requireColor(color, "gameMaterial");
- return new THREE27.MeshStandardMaterial({
+ return new THREE28.MeshStandardMaterial({
color,
metalness: options.metalness ?? 0,
roughness: options.roughness ?? 0.8,
@@ -16873,7 +17115,7 @@ function gameMaterial(color, options = {}) {
}
function basicMaterial(color, options = {}) {
requireColor(color, "basicMaterial");
- return new THREE27.MeshBasicMaterial({
+ return new THREE28.MeshBasicMaterial({
color,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
@@ -16881,38 +17123,38 @@ function basicMaterial(color, options = {}) {
}
function glassMaterial(color, options = {}) {
requireColor(color, "glassMaterial");
- return new THREE27.MeshStandardMaterial({
+ return new THREE28.MeshStandardMaterial({
color,
transparent: true,
opacity: options.opacity ?? 0.35,
roughness: options.roughness ?? 0.1,
metalness: options.metalness ?? 0,
- side: THREE27.DoubleSide
+ side: THREE28.DoubleSide
});
}
function lambertMaterial(color, options = {}) {
requireColor(color, "lambertMaterial");
- return new THREE27.MeshLambertMaterial({
+ return new THREE28.MeshLambertMaterial({
color,
flatShading: options.flatShading ?? true,
emissive: options.emissive ?? 0
});
}
function threeInterpolation(mode) {
- return mode === "STEP" ? THREE27.InterpolateDiscrete : THREE27.InterpolateLinear;
+ return mode === "STEP" ? THREE28.InterpolateDiscrete : THREE28.InterpolateLinear;
}
function rotationTrack(jointName, keyframes, interpolation) {
const times = [];
const values = [];
- const euler = new THREE27.Euler;
- const quat = new THREE27.Quaternion;
+ const euler = new THREE28.Euler;
+ const quat = new THREE28.Quaternion;
for (const kf of keyframes) {
times.push(kf.time);
- euler.set(THREE27.MathUtils.degToRad(kf.rotation[0]), THREE27.MathUtils.degToRad(kf.rotation[1]), THREE27.MathUtils.degToRad(kf.rotation[2]));
+ euler.set(THREE28.MathUtils.degToRad(kf.rotation[0]), THREE28.MathUtils.degToRad(kf.rotation[1]), THREE28.MathUtils.degToRad(kf.rotation[2]));
quat.setFromEuler(euler);
values.push(quat.x, quat.y, quat.z, quat.w);
}
- return new THREE27.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
+ return new THREE28.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
}
function positionTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -16921,7 +17163,7 @@ function positionTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.position);
}
- return new THREE27.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
+ return new THREE28.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
}
function scaleTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -16930,10 +17172,10 @@ function scaleTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.scale);
}
- return new THREE27.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
+ return new THREE28.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
}
function createClip(name, duration, tracks) {
- return new THREE27.AnimationClip(name, duration, tracks);
+ return new THREE28.AnimationClip(name, duration, tracks);
}
function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {
const y = 0;
@@ -16983,12 +17225,12 @@ function createInstance(name, source, options = {}) {
if (!sourceMesh) {
throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);
}
- const mesh = new THREE27.Mesh(sourceMesh.geometry, sourceMesh.material);
+ const mesh = new THREE28.Mesh(sourceMesh.geometry, sourceMesh.material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE27.MathUtils.degToRad(options.rotation[0]), THREE27.MathUtils.degToRad(options.rotation[1]), THREE27.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE28.MathUtils.degToRad(options.rotation[0]), THREE28.MathUtils.degToRad(options.rotation[1]), THREE28.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.parent)
@@ -17232,7 +17474,7 @@ function buildSandboxGlobals(usage, options = {}) {
countMaterials: wrap("countMaterials", countMaterials),
getJointNames: wrap("getJointNames", getJointNames),
validateAsset: wrap("validateAsset", validateAsset),
- THREE: THREE27,
+ THREE: THREE28,
Math,
console
};
@@ -17407,9 +17649,7 @@ async function validateFinalGlbBytes(bytes, uri = "model.glb") {
var init_gltf = () => {};
// src/qa/breadth-final.ts
-import { WebIO } from "@gltf-transform/core";
-import { EXTMeshGPUInstancing } from "@gltf-transform/extensions";
-import * as THREE28 from "three";
+import * as THREE29 from "three";
function bytesContainAscii(bytes, value) {
const needle = new TextEncoder().encode(value);
outer:
@@ -17468,7 +17708,7 @@ function finalEffectAxis(nodes, mode) {
if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {
continue;
}
- const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());
+ const matrix = new THREE29.Matrix4().fromArray(node.getWorldMatrix());
const scale = node.getWorldScale();
const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
@@ -17478,9 +17718,9 @@ function finalEffectAxis(nodes, mode) {
const min = position.getMin([]);
const max = position.getMax([]);
const axes = [
- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },
- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },
- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }
+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE29.Vector3(1, 0, 0) },
+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE29.Vector3(0, 1, 0) },
+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE29.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const candidate = {
@@ -17495,7 +17735,7 @@ function finalEffectAxis(nodes, mode) {
return best ? signedAxis2(best.direction) : undefined;
}
async function analyzeFinalVfxGlbBytesV1(bytes) {
- const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+ const io = createGltfIO();
const document = await io.readBinary(bytes);
const root = document.getRoot();
const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);
@@ -17731,6 +17971,7 @@ async function appendFinalVfxGlbQa(intent, report, bytes) {
}
var stable8 = (value) => Math.round(value * 1e6) / 1e6;
var init_breadth_final = __esm(() => {
+ init_gltf_io();
init_contracts();
init_types();
});
@@ -19780,7 +20021,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash3 } from "node:crypto";
-import * as THREE29 from "three";
+import * as THREE30 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -19872,7 +20113,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE30.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -19953,10 +20194,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE29.Vector3;
- const t = new THREE29.Vector3;
- const tmp = new THREE29.Vector3;
- const tmp2 = new THREE29.Vector3;
+ const n = new THREE30.Vector3;
+ const t = new THREE30.Vector3;
+ const tmp = new THREE30.Vector3;
+ const tmp2 = new THREE30.Vector3;
for (let v = 0;v < vertexCount; v++) {
n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
@@ -19976,7 +20217,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE30.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -20022,7 +20263,7 @@ var init_texture_bake = __esm(() => {
});
// src/views/character.ts
-import * as THREE30 from "three";
+import * as THREE31 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -20064,9 +20305,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE30.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE31.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE31.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE31.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -22547,24 +22788,18 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive,
- WebIO as WebIO2
+ Primitive
} from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
- KHRMaterialsVariants as KHRMaterialsVariants2,
- KHRTextureBasisu as KHRTextureBasisu2
-} from "@gltf-transform/extensions";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry14,
- Group,
+ Group as Group2,
Matrix4 as Matrix47,
- Mesh as Mesh10,
+ Mesh as Mesh11,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
SRGBColorSpace as SRGBColorSpace5,
- Texture,
+ Texture as Texture2,
AnimationClip as AnimationClip3,
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
@@ -22682,7 +22917,7 @@ function preserveTexture(source, usage, cache) {
const existing = byUsage.get(usage);
if (existing)
return existing;
- const texture = new Texture;
+ const texture = new Texture2;
texture.name = source.getName();
texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;
texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };
@@ -22849,7 +23084,7 @@ async function loadGlbReviewScene(bytes) {
if (!sourceScene)
throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
const reasons = new Set;
- const root = new Group;
+ const root = new Group2;
root.name = sourceScene.getName() || "Scene";
const nodeMap = new Map;
const textureCache = new Map;
@@ -22859,7 +23094,7 @@ async function loadGlbReviewScene(bytes) {
const existing = nodeMap.get(source);
if (existing)
return existing;
- const target = new Group;
+ const target = new Group2;
target.name = source.getName();
target.position.fromArray(source.getTranslation());
target.quaternion.fromArray(source.getRotation());
@@ -22924,7 +23159,7 @@ async function loadGlbReviewScene(bytes) {
threeMaterial.aoMapIntensity = material.getOcclusionStrength();
}
for (const [index, matrix] of matrices.entries()) {
- const mesh = new Mesh10(geometry, threeMaterial);
+ const mesh = new Mesh11(geometry, threeMaterial);
const baseName = source.getName() || sourceMesh.getName() || "Mesh";
mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;
mesh.matrixAutoUpdate = false;
@@ -22964,8 +23199,9 @@ async function loadGlbReviewScene(bytes) {
instanceCount
};
}
-var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO = () => new WebIO2().registerExtensions([EXTMeshGPUInstancing2, KHRMaterialsVariants2, KHRTextureBasisu2]);
+var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO;
var init_glb = __esm(() => {
+ init_gltf_io();
GLB_GEOMETRY_FLAT_REASON = {
TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
@@ -22994,6 +23230,7 @@ var init_glb = __esm(() => {
this.name = "GlbGeometryFlatError";
}
};
+ glbIO = createGltfIO;
});
// src/evaluator/handler.ts
@@ -23262,7 +23499,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE31 from "three";
+import * as THREE32 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -23273,18 +23510,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE32 from "three";
+import * as THREE33 from "three";
function hasRole2(node, prefix) {
return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
}
function chassisBounds(root, inverse) {
- const bounds = new THREE32.Box3;
+ const bounds = new THREE33.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
+ if (!(part instanceof THREE33.Mesh) || !(part.geometry instanceof THREE33.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -23294,7 +23531,7 @@ function chassisBounds(root, inverse) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE33.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -23362,33 +23599,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE32.Vector3(...start);
- const to = new THREE32.Vector3(...end);
+ const from = new THREE33.Vector3(...start);
+ const to = new THREE33.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);
- const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE33.CylinderGeometry(radius, radius, length, 8) : new THREE33.SphereGeometry(radius, 8, 6);
+ const result = new THREE33.Mesh(geometry, new THREE33.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE32.Group;
+ const overlay = new THREE33.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE32.Group;
+ const arrow = new THREE33.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE33.Mesh(new THREE33.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE33.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), new THREE33.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -23396,18 +23633,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE33.Mesh(new THREE33.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE33.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE32.Vector3(...wheel.axle);
+ const axle = new THREE33.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE32.Group;
+ const chassis = new THREE33.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -23441,7 +23678,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE32.Group;
+ const plane = new THREE33.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -23993,7 +24230,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE33 from "three";
+import * as THREE34 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -24030,22 +24267,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE33.Box3().setFromObject(root);
+ const bounds = new THREE34.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE33.Vector3);
- const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
- const upHint = new THREE33.Vector3(0, 1, 0);
- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE34.Vector3(-0.5, 0, -0.5), new THREE34.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE34.Vector3);
+ const camera = cameraId === "front" ? new THREE34.Vector3(1, 0, 0) : new THREE34.Vector3(0, 0, 1);
+ const upHint = new THREE34.Vector3(0, 1, 0);
+ const xAxis = new THREE34.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE34.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
+ const point = new THREE34.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE34.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -24168,14 +24405,74 @@ var init_character_capture = __esm(() => {
init_pose();
});
+// src/exporter-node.ts
+var exports_exporter_node = {};
+__export(exports_exporter_node, {
+ nodeExportPlatform: () => nodeExportPlatform
+});
+async function prepareNodeExport(hasTextures) {
+ const host = globalThis;
+ if (!host["FileReader"])
+ host["FileReader"] = ExportFileReader;
+ if (!hasTextures || host["OffscreenCanvas"] || host["document"])
+ return;
+ const { Canvas, ImageData } = await import("@napi-rs/canvas");
+
+ class ExportCanvas extends Canvas {
+ async convertToBlob(options = {}) {
+ const type = options.type ?? options.mime ?? "image/png";
+ if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")
+ throw new Error(`Unsupported export image type: ${type}`);
+ const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);
+ return new Blob([new Uint8Array(bytes)], { type });
+ }
+ }
+ host["OffscreenCanvas"] = ExportCanvas;
+ if (!host["ImageData"])
+ host["ImageData"] = ImageData;
+}
+
+class ExportFileReader {
+ result = null;
+ error = null;
+ onloadend = null;
+ onerror = null;
+ readAsArrayBuffer(blob) {
+ this.read(blob, false);
+ }
+ readAsDataURL(blob) {
+ this.read(blob, true);
+ }
+ read(blob, dataUrl) {
+ blob.arrayBuffer().then((bytes) => {
+ this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;
+ this.onloadend?.();
+ }, (error) => {
+ this.error = error;
+ this.onerror?.();
+ this.onloadend?.();
+ });
+ }
+}
+var nodeExportPlatform;
+var init_exporter_node = __esm(() => {
+ nodeExportPlatform = {
+ prepare: prepareNodeExport,
+ async decode(bytes) {
+ const { default: sharp } = await import("sharp");
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return {
+ data: new Uint8Array(decoded.data),
+ width: decoded.info.width,
+ height: decoded.info.height
+ };
+ }
+ };
+});
+
// src/render.ts
-import * as THREE34 from "three";
-import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
- KHRMaterialsVariants as KHRMaterialsVariants3,
- KHRTextureBasisu as KHRTextureBasisu3
-} from "@gltf-transform/extensions";
+import * as THREE35 from "three";
+import { Document, getBounds } from "@gltf-transform/core";
import {
dedup,
instance,
@@ -24309,7 +24606,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE34.DoubleSide) {
+ if (stdMat.side === THREE35.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -24378,7 +24675,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE34.DoubleSide)
+ if (threeMat.side === THREE35.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -24431,22 +24728,15 @@ function bridgeGeometry(doc, buf, geometry, material, meshName) {
if (!Array.isArray(material))
return mesh.addPrimitive(prim);
const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
- const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
+ const groups = validateMaterialGroups(geometry, material.length, meshName);
for (const group of groups) {
- if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
- throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
- }
const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
for (const semantic of prim.listSemantics())
part.setAttribute(semantic, prim.getAttribute(semantic));
const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
part.setIndices(doc.createAccessor(`${meshName}_group_indices`).setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
mesh.addPrimitive(part);
- covered += group.count;
}
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
prim.dispose();
return mesh;
}
@@ -24513,7 +24803,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE34.PlaneGeometry(1, 1);
+ const geometry = new THREE35.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -24665,7 +24955,8 @@ async function renderSceneToGLB(root, opts = {}) {
const clips = opts.clips ?? [];
if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
const tris = countTriangles(root);
const intent = opts.intent ?? createAssetIntentV1({
category: isAssetCategory(opts.category) ? opts.category : "prop"
@@ -24699,19 +24990,28 @@ async function renderSceneToGLB(root, opts = {}) {
throw blocked;
warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
}
- const doc = new Document;
+ const doc = exporter === "three" ? await communitySceneDocument(root, clips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform) : new Document;
doc.getRoot().getAsset().generator = "Kiln";
- const buf = doc.createBuffer();
- const matCache = new Map;
- const meshCache = new Map;
- const texCache = new Map;
- const nodeMap = new Map;
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ if (exporter === "legacy") {
+ const buf = doc.createBuffer();
+ const matCache = new Map;
+ const meshCache = new Map;
+ const texCache = new Map;
+ const nodeMap = new Map;
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ } else {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ throw new Error("Community exporter produced no scene.");
+ scene.setName(opts.sceneName ?? "Scene");
+ if (clips.length > 0)
+ scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
}
if (opts.dedup !== false) {
try {
@@ -24831,6 +25131,7 @@ async function renderGLBInProcess(code, opts = {}) {
});
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
+ gltfExporter: opts.gltfExporter,
sceneName: meta.name || "Scene",
geometryPolicy: opts.geometryPolicy,
clips,
@@ -24917,12 +25218,12 @@ function collectMeshStats(root) {
return;
const idx = geo.getIndex();
const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
- const box = new THREE34.Box3().setFromObject(obj);
+ const box = new THREE35.Box3().setFromObject(obj);
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE34.Vector3;
- const size = new THREE34.Vector3;
+ const center = new THREE35.Vector3;
+ const size = new THREE35.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -24937,7 +25238,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE34.Vector3;
+ const v = new THREE35.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -24955,10 +25256,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE34.Box3;
+ const all = new THREE35.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE34.Vector3;
+ const size = new THREE35.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -25019,9 +25320,11 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
var init_render = __esm(() => {
init_authoring_diagnostic();
+ init_gltf_io();
+ init_community_exporter();
init_geometry_export();
init_primitives();
init_contracts();
@@ -25038,6 +25341,7 @@ var init_render = __esm(() => {
init_texture_bake();
init_character_capture();
init_vehicle3();
+ engineIO = createGltfIO;
REVIEW_CLIP_LIMITS2 = {
clips: 32,
tracks: 256,
@@ -26074,6 +26378,7 @@ function createLocalToolContext(base = {}, env = process.env) {
const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";
const instance = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";
const maxGlbBytes = 16 * 1024 * 1024;
+ const gltfExporter = resolveGltfExporter(env.KILN_GLTF_EXPORTER ?? "legacy");
const maxResponseBytes = 32 * 1024 * 1024;
const evaluatorPort = {
async render(code, options = {}, controls = {}) {
@@ -26084,6 +26389,7 @@ function createLocalToolContext(base = {}, env = process.env) {
if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
const resolved = {
+ ...gltfExporter === "three" ? { gltfExporter } : {},
optimize,
instance,
...options,
@@ -26178,7 +26484,8 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
instance: env.KILN_BAKE_INSTANCE ?? "auto",
qa: env.KILN_QA_MODE ?? "enforce",
geometryPolicy: context.geometryPolicy,
- timezone: env.TZ
+ timezone: env.TZ,
+ ...env.KILN_GLTF_EXPORTER === "three" ? { gltfExporter: "three" } : {}
})}`;
context.localExecution = {
...context.localExecution,
@@ -26195,6 +26502,7 @@ var init_local_runtime = __esm(() => {
init_render();
init_program_store_node();
init_build_cache();
+ init_community_exporter();
init_build_cache_node();
init_runtime_identity();
});
@@ -27305,7 +27613,7 @@ var init_asset_widget = __esm(() => {
// src/tools/registry.ts
import { z as z4 } from "zod";
-import * as THREE35 from "three";
+import * as THREE36 from "three";
function proceduralTextureMaterialContract(rendered, context) {
const required = [...new Set(context.requiredProceduralTextureUsages ?? [])];
if (required.length === 0)
@@ -27378,7 +27686,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE35.DoubleSide;
+ copy.side = THREE36.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -27578,16 +27886,16 @@ function collectSceneMetrics(root) {
} else if (mat) {
materialSet.add(mat);
}
- const mb = new THREE35.Box3().setFromObject(node);
+ const mb = new THREE36.Box3().setFromObject(node);
if (!mb.isEmpty() && (!lowestPart || mb.min.y < lowestPart.y)) {
lowestPart = { name: node.name || "(unnamed mesh)", y: mb.min.y };
}
}
});
- const box = new THREE35.Box3().setFromObject(root);
+ const box = new THREE36.Box3().setFromObject(root);
let bbox;
if (!box.isEmpty()) {
- const size = new THREE35.Vector3;
+ const size = new THREE36.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -28162,7 +28470,8 @@ function withBuildCache(context) {
declared ?? scope,
env["KILN_QA_MODE"],
env["KILN_BAKE_OPTIMIZE"],
- env["KILN_BAKE_INSTANCE"]
+ env["KILN_BAKE_INSTANCE"],
+ ...env["KILN_GLTF_EXPORTER"] === "three" ? ["three"] : []
]);
}
})
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index 7cfa68b8..a512cbe5 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -1,3 +1,17 @@
+var __defProp = Object.defineProperty;
+var __returnValue = (v) => v;
+function __exportSetter(name, newValue) {
+ this[name] = __returnValue.bind(null, newValue);
+}
+var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, {
+ get: all[name],
+ enumerable: true,
+ configurable: true,
+ set: __exportSetter.bind(all, name)
+ });
+};
var __esm = (fn, res, err) => () => {
if (fn)
try {
@@ -40,87 +54,14 @@ var init_authoring_diagnostic = __esm(() => {
};
});
-// src/geometry-export.ts
-function geometryAttributeValues(attribute) {
- const values = new Float32Array(attribute.count * attribute.itemSize);
- for (let vertex = 0;vertex < attribute.count; vertex++) {
- for (let component = 0;component < attribute.itemSize; component++) {
- values[vertex * attribute.itemSize + component] = attribute.getComponent(vertex, component);
- }
- }
- return values;
-}
-function inspectGeometryExport(root, policy = "warn") {
- const warnings = [];
- root.traverse((node) => {
- const mesh = node;
- if (!mesh.isMesh)
- return;
- const geometry = mesh.geometry;
- const name = mesh.name || "<unnamed mesh>";
- const unsupported = (feature) => {
- const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
- if (policy === "strict")
- throw new TypeError(message);
- warnings.push(message);
- };
- const position = geometry.getAttribute("position");
- if (position?.itemSize !== 3)
- throw new TypeError(`${name}: position requires xyz vertices.`);
- for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];
- if (expected === undefined) {
- unsupported(key);
- continue;
- }
- if (attribute.itemSize !== expected || attribute.count !== position.count) {
- throw new TypeError(`${name}: ${key} requires ${position.count} vertices with ${expected} components each.`);
- }
- for (let vertex = 0;vertex < attribute.count; vertex++) {
- for (let component = 0;component < attribute.itemSize; component++) {
- if (!Number.isFinite(attribute.getComponent(vertex, component))) {
- throw new TypeError(`${name}: ${key} contains a non-finite value at vertex ${vertex}.`);
- }
- }
- }
- }
- const index = geometry.getIndex();
- if ((index?.count ?? position.count) % 3 !== 0)
- throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
- if (index) {
- for (let i = 0;i < index.count; i++) {
- const value = index.getX(i);
- if (!Number.isInteger(value) || value < 0 || value >= position.count)
- throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
- }
- }
- for (const key of Object.keys(geometry.morphAttributes))
- unsupported(`morph ${key}`);
- if (mesh.isSkinnedMesh)
- unsupported("skinning");
- for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {
- const notes = geometry.userData[key];
- if (!Array.isArray(notes))
- continue;
- for (const note of notes) {
- if (typeof note === "string")
- warnings.push(`${name}: ${note}`);
- else if (note && typeof note === "object" && "code" in note)
- warnings.push(`${name}: ${String(note.code)}${"message" in note ? ` ${String(note.message)}` : ""}`);
- }
- }
- });
- return warnings;
+// src/gltf-io.ts
+import { WebIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+function createGltfIO() {
+ return new WebIO().registerExtensions(ALL_EXTENSIONS);
}
-var EXPORTED_GEOMETRY_ATTRIBUTES;
-var init_geometry_export = __esm(() => {
- EXPORTED_GEOMETRY_ATTRIBUTES = {
- position: 3,
- normal: 3,
- uv: 2,
- tangent: 4
- };
-});
+var init_gltf_io = () => {};
+
// src/contracts/breadth.ts
function cloneVfxIntentV1(value) {
return {
@@ -2344,8 +2285,323 @@ var init_contracts = __esm(() => {
init_semantic();
});
-// src/character.ts
+// src/community-exporter.ts
import * as THREE from "three";
+import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
+function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
+ if (value === undefined || value === "legacy")
+ return "legacy";
+ if (value === "three")
+ return "three";
+ throw new Error(`Invalid KILN_GLTF_EXPORTER ${JSON.stringify(value)}; use legacy or three.`);
+}
+function cleanClone(source) {
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ return shadow.clone();
+}
+async function communitySceneDocument(root, clips, platform = browserPlatform) {
+ const materials = new Map;
+ const textures = new Map;
+ const nodes = new Map;
+ const encoded = [];
+ function texture(source) {
+ const found = textures.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ normalizeTextureTransform(copy);
+ copy.source = new THREE.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData["encoded"];
+ if (bytes?.bytes) {
+ encoded.push((async () => {
+ copy.image = await platform.decode(bytes.bytes);
+ Object.defineProperty(copy, "isDataTexture", { value: true });
+ copy.format = THREE.RGBAFormat;
+ copy.type = THREE.UnsignedByteType;
+ })());
+ }
+ return copy;
+ }
+ function material(source) {
+ const found = materials.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ const physical = copy;
+ if (physical.isMeshPhysicalMaterial && physical.sheen > 0) {
+ physical.sheenColor.multiplyScalar(physical.sheen);
+ physical.sheen = 1;
+ }
+ for (const [key, value] of Object.entries(copy)) {
+ if (value instanceof THREE.Texture)
+ copy[key] = texture(value);
+ }
+ materials.set(source, copy);
+ return copy;
+ }
+ function node(source) {
+ if (source.isLine || source.isPoints)
+ throw new Error("Experimental glTF exporter supports triangle meshes and sprites, not lines or points.");
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ let copy = shadow.clone(false);
+ if (source.isScene) {
+ copy = new THREE.Group;
+ copy.copy(shadow, false);
+ }
+ if (source.isSprite) {
+ const sprite = source;
+ const geometry = new THREE.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE.MeshBasicMaterial({
+ name: sprite.material.name,
+ color: sprite.material.color,
+ opacity: sprite.material.opacity,
+ transparent: sprite.material.transparent,
+ alphaTest: sprite.material.alphaTest,
+ side: sprite.material.side,
+ map: sprite.material.map ? texture(sprite.material.map) : null
+ });
+ copy = new THREE.Mesh(geometry, spriteMaterial);
+ THREE.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ if (semantic !== undefined) {
+ const checked = validateSemanticMetadataV1(semantic);
+ if (!checked.valid || !checked.value)
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on ${source.name}`);
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(checked.value);
+ }
+ if (source.isSprite) {
+ const metadata = copy.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = createSemanticMetadataV1({
+ ...metadata,
+ roles: [
+ ...(metadata?.roles ?? []).filter((role) => !role.startsWith("vfx.facing.")),
+ "vfx.facing.camera-spherical",
+ ...metadata?.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
+ ]
+ });
+ }
+ if (source.isMesh) {
+ const original = source;
+ const mesh = copy;
+ mesh.geometry = cleanClone(original.geometry);
+ mesh.material = Array.isArray(original.material) ? original.material.map(material) : material(original.material);
+ }
+ nodes.set(source, copy);
+ for (const child of source.children)
+ copy.add(node(child));
+ return copy;
+ }
+ const copy = node(root);
+ for (const [source, target] of nodes) {
+ if (!source.isSkinnedMesh)
+ continue;
+ const original = source;
+ const mesh = target;
+ mesh.skeleton = original.skeleton.clone();
+ mesh.skeleton.bones = original.skeleton.bones.map((bone) => {
+ const mapped = nodes.get(bone);
+ if (!mapped)
+ throw new Error(`Skin bone ${bone.name} is outside the exported hierarchy.`);
+ return mapped;
+ });
+ mesh.bind(mesh.skeleton, original.bindMatrix);
+ }
+ await Promise.all(encoded);
+ await platform.prepare(textures.size > 0);
+ const exportClips = clips.map((clip) => {
+ const cloned = cleanClone(clip);
+ for (const track of cloned.tracks) {
+ for (const [source, target] of nodes) {
+ if (track.name.startsWith(`${source.uuid}.`))
+ track.name = target.uuid + track.name.slice(source.uuid.length);
+ }
+ }
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ } catch {
+ return false;
+ }
+ });
+ return cloned;
+ });
+ const bytes = await new GLTFExporter().parseAsync(copy, {
+ binary: true,
+ trs: true,
+ onlyVisible: false,
+ animations: exportClips.filter((clip) => clip.tracks.length > 0)
+ });
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(new Uint8Array(bytes));
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name)
+ continue;
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name)
+ image.name = binding.name;
+ }
+ return io.readJSON(json);
+}
+function normalizeTextureTransform(texture) {
+ if (texture.matrixAutoUpdate)
+ texture.updateMatrix();
+ const e = texture.matrix.elements;
+ const sx = Math.hypot(e[0], e[1]);
+ const rotation = sx > 0 ? Math.atan2(-e[1], e[0]) : Math.atan2(e[3], e[4]);
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ const sy = e[3] * s + e[4] * c;
+ const reconstructed = [sx * c, -sx * s, 0, sy * s, sy * c, 0, e[6], e[7], 1];
+ const tolerance = 0.0000001 * Math.max(1, ...e.map(Math.abs));
+ if (e.some((value, i) => !Number.isFinite(value) || Math.abs(value - reconstructed[i]) > tolerance)) {
+ throw new Error(`Texture ${texture.name || "<unnamed>"}: UV matrix contains shear or perspective that KHR_texture_transform cannot represent; lossless UV baking is not yet qualified.`);
+ }
+ texture.offset.set(e[6], e[7]);
+ texture.repeat.set(sx, sy);
+ texture.rotation = rotation;
+ texture.center.set(0, 0);
+ texture.matrixAutoUpdate = false;
+}
+var browserPlatform;
+var init_community_exporter = __esm(() => {
+ init_gltf_io();
+ init_contracts();
+ browserPlatform = {
+ async prepare() {},
+ async decode(bytes) {
+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]), {
+ colorSpaceConversion: "none"
+ });
+ try {
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("A 2D canvas is required to decode export textures.");
+ context.drawImage(bitmap, 0, 0);
+ const image = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ return { data: new Uint8Array(image.data), width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ }
+ };
+});
+
+// src/geometry-export.ts
+function validateMaterialGroups(geometry, materialCount, name) {
+ const length = geometry.getIndex()?.count ?? geometry.getAttribute("position").count;
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ const materialIndex = group.materialIndex ?? 0;
+ if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > length || !Number.isInteger(materialIndex) || materialIndex < 0 || materialIndex >= materialCount)
+ throw new TypeError(`${name}: material groups must cover every triangle exactly once with valid material indices.`);
+ covered = group.start + group.count;
+ }
+ if (covered !== length)
+ throw new TypeError(`${name}: material groups do not cover every triangle.`);
+ return groups;
+}
+function geometryAttributeValues(attribute) {
+ const values = new Float32Array(attribute.count * attribute.itemSize);
+ for (let vertex = 0;vertex < attribute.count; vertex++) {
+ for (let component = 0;component < attribute.itemSize; component++) {
+ values[vertex * attribute.itemSize + component] = attribute.getComponent(vertex, component);
+ }
+ }
+ return values;
+}
+function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
+ const warnings = [];
+ root.traverse((node) => {
+ const mesh = node;
+ if (!mesh.isMesh)
+ return;
+ const geometry = mesh.geometry;
+ const name = mesh.name || "<unnamed mesh>";
+ const unsupported = (feature) => {
+ const message = `EXPORT_ATTRIBUTE_UNSUPPORTED ${name}: ${feature} is not preserved by the GLB bridge.`;
+ if (policy === "strict")
+ throw new TypeError(message);
+ warnings.push(message);
+ };
+ const position = geometry.getAttribute("position");
+ if (position?.itemSize !== 3)
+ throw new TypeError(`${name}: position requires xyz vertices.`);
+ for (const [key, attribute] of Object.entries(geometry.attributes)) {
+ const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key] ?? (exporter === "three" ? {
+ color: attribute.itemSize === 4 ? 4 : 3,
+ uv1: 2,
+ uv2: 2,
+ uv3: 2,
+ skinIndex: 4,
+ skinWeight: 4
+ }[key] : undefined);
+ if (expected === undefined) {
+ unsupported(key);
+ continue;
+ }
+ if (attribute.itemSize !== expected || attribute.count !== position.count) {
+ throw new TypeError(`${name}: ${key} requires ${position.count} vertices with ${expected} components each.`);
+ }
+ for (let vertex = 0;vertex < attribute.count; vertex++) {
+ for (let component = 0;component < attribute.itemSize; component++) {
+ if (!Number.isFinite(attribute.getComponent(vertex, component))) {
+ throw new TypeError(`${name}: ${key} contains a non-finite value at vertex ${vertex}.`);
+ }
+ }
+ }
+ }
+ const index = geometry.getIndex();
+ if ((index?.count ?? position.count) % 3 !== 0)
+ throw new TypeError(`${name}: triangle indices/vertices must be a multiple of three.`);
+ if (index) {
+ for (let i = 0;i < index.count; i++) {
+ const value = index.getX(i);
+ if (!Number.isInteger(value) || value < 0 || value >= position.count)
+ throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
+ }
+ }
+ if (exporter === "three" && Array.isArray(mesh.material))
+ validateMaterialGroups(geometry, mesh.material.length, name);
+ if (exporter === "legacy") {
+ for (const key of Object.keys(geometry.morphAttributes))
+ unsupported(`morph ${key}`);
+ if (mesh.isSkinnedMesh)
+ unsupported("skinning");
+ }
+ for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {
+ const notes = geometry.userData[key];
+ if (!Array.isArray(notes))
+ continue;
+ for (const note of notes) {
+ if (typeof note === "string")
+ warnings.push(`${name}: ${note}`);
+ else if (note && typeof note === "object" && "code" in note)
+ warnings.push(`${name}: ${String(note.code)}${"message" in note ? ` ${String(note.message)}` : ""}`);
+ }
+ }
+ });
+ return warnings;
+}
+var EXPORTED_GEOMETRY_ATTRIBUTES;
+var init_geometry_export = __esm(() => {
+ EXPORTED_GEOMETRY_ATTRIBUTES = {
+ position: 3,
+ normal: 3,
+ uv: 2,
+ tangent: 4
+ };
+});
+// src/character.ts
+import * as THREE2 from "three";
function validRole(value) {
return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);
}
@@ -2626,7 +2882,7 @@ function readCharacterRigGraphV1(target) {
return result.valid ? result.value : undefined;
}
function axisQuaternion(from, to) {
- const value = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(...from), new THREE.Vector3(...to));
+ const value = new THREE2.Quaternion().setFromUnitVectors(new THREE2.Vector3(...from), new THREE2.Vector3(...to));
return [value.x, value.y, value.z, value.w];
}
function stampCharacterJointDescriptorV1(target, input) {
@@ -2731,7 +2987,7 @@ function createJointChain(chainName, segments, options = {}) {
endEffector: segment.endEffector,
contact: segment.contact
});
- const node = new THREE.Object3D;
+ const node = new THREE2.Object3D;
node.name = characterJointNodeName(chainName, segment.role);
node.position.fromArray(descriptor.rest.translation);
node.quaternion.fromArray(descriptor.rest.rotation);
@@ -2873,7 +3129,7 @@ var init_character = __esm(() => {
});
// src/architecture.ts
-import * as THREE2 from "three";
+import * as THREE3 from "three";
function positive(value, name) {
if (!Number.isFinite(value) || value <= 0)
throw new RangeError(`${name} must be finite and > 0`);
@@ -2938,17 +3194,17 @@ function buildFace(roofRoot, profile, sideSign) {
const verticalRun = profile.ridgeY - profile.eaveY;
const downhillLength = Math.hypot(horizontalRun, verticalRun);
const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;
- const downhill = profile.ridgeAxis === "x" ? new THREE2.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE2.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
- const tangent = profile.ridgeAxis === "x" ? new THREE2.Vector3(sideSign, 0, 0) : new THREE2.Vector3(0, 0, -sideSign);
+ const downhill = profile.ridgeAxis === "x" ? new THREE3.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE3.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
+ const tangent = profile.ridgeAxis === "x" ? new THREE3.Vector3(sideSign, 0, 0) : new THREE3.Vector3(0, 0, -sideSign);
const normal = downhill.clone().cross(tangent).normalize();
- const localToRoof = new THREE2.Matrix4().makeBasis(tangent, normal, downhill);
+ const localToRoof = new THREE3.Matrix4().makeBasis(tangent, normal, downhill);
localToRoof.setPosition(0, profile.ridgeY, 0);
const world = () => {
roofRoot.updateWorldMatrix(true, false);
return roofRoot.matrixWorld.clone().multiply(localToRoof);
};
const direction = (axis) => axis.clone().transformDirection(world());
- const point = (x, z) => new THREE2.Vector3(x, 0, z).applyMatrix4(world());
+ const point = (x, z) => new THREE3.Vector3(x, 0, z).applyMatrix4(world());
return {
side,
ridgeAxis: profile.ridgeAxis,
@@ -2958,13 +3214,13 @@ function buildFace(roofRoot, profile, sideSign) {
return world();
},
get ridgeTangent() {
- return direction(new THREE2.Vector3(1, 0, 0));
+ return direction(new THREE3.Vector3(1, 0, 0));
},
get downhillDirection() {
- return direction(new THREE2.Vector3(0, 0, 1));
+ return direction(new THREE3.Vector3(0, 0, 1));
},
get outwardNormal() {
- return direction(new THREE2.Vector3(0, 1, 0));
+ return direction(new THREE3.Vector3(0, 1, 0));
},
get ridgeStart() {
return point(-alongRidge / 2, 0);
@@ -2982,17 +3238,17 @@ function buildFace(roofRoot, profile, sideSign) {
};
}
function buildRoof(name, material, profile, parent) {
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
if (parent)
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));
const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];
const buildSlope = (face) => {
- const geometry = new THREE2.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
- const mesh = new THREE2.Mesh(geometry, material);
+ const geometry = new THREE3.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
+ const mesh = new THREE3.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${face.side}`;
- const center = new THREE2.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
+ const center = new THREE3.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
setTransform(mesh, face.localToRoof.clone().multiply(center));
const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";
stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [
@@ -3062,7 +3318,7 @@ function createGableEndPanel(name, material, options) {
const ridgeAxis = options.ridgeAxis ?? "x";
const side = options.side ?? "positive";
const half = span / 2;
- const shape = new THREE2.Shape;
+ const shape = new THREE3.Shape;
shape.moveTo(-half, 0);
shape.lineTo(half, 0);
shape.lineTo(0, rise);
@@ -3081,7 +3337,7 @@ function createGableEndPanel(name, material, options) {
const right = opening.offset + opening.width / 2;
const bottom = opening.bottom;
const top = bottom + opening.height;
- const hole = new THREE2.Path;
+ const hole = new THREE3.Path;
hole.moveTo(left, bottom);
hole.lineTo(left, top);
hole.lineTo(right, top);
@@ -3089,7 +3345,7 @@ function createGableEndPanel(name, material, options) {
hole.closePath();
shape.holes.push(hole);
}
- const geometry = new THREE2.ExtrudeGeometry(shape, {
+ const geometry = new THREE3.ExtrudeGeometry(shape, {
depth: thickness,
bevelEnabled: false,
steps: 1
@@ -3098,7 +3354,7 @@ function createGableEndPanel(name, material, options) {
if (ridgeAxis === "x")
geometry.rotateY(-Math.PI / 2);
geometry.computeVertexNormals();
- const root = new THREE2.Mesh(geometry, material);
+ const root = new THREE3.Mesh(geometry, material);
root.name = `Mesh_${name}`;
stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [
relationship("adjacent-to", "roof.slope.positive"),
@@ -3114,7 +3370,7 @@ function createGableEndPanel(name, material, options) {
}
]));
const markers = normalized.map((opening, index) => {
- const marker = new THREE2.Object3D;
+ const marker = new THREE3.Object3D;
marker.name = `Opening_${name}_${opening.id ?? index + 1}`;
marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);
marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);
@@ -3134,7 +3390,7 @@ function wallNeighbors(wall) {
}
function createShellWall(name, wall, material, length, height, thickness, openings) {
const axis = wallRunAxis(wall);
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = `${name}_Wall_${wall}`;
const neighbors = wallNeighbors(wall);
stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [
@@ -3157,8 +3413,8 @@ function createShellWall(name, wall, material, length, height, thickness, openin
const panel = (suffix, lo, hi, y0, y1) => {
if (hi - lo <= EPSILON || y1 - y0 <= EPSILON)
return;
- const geometry = axis === "x" ? new THREE2.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE2.BoxGeometry(thickness, y1 - y0, hi - lo);
- const mesh = new THREE2.Mesh(geometry, material);
+ const geometry = axis === "x" ? new THREE3.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE3.BoxGeometry(thickness, y1 - y0, hi - lo);
+ const mesh = new THREE3.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${wall}_${suffix}`;
mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);
root.add(mesh);
@@ -3178,7 +3434,7 @@ function createShellWall(name, wall, material, length, height, thickness, openin
panel("lintel", left, right, top, height);
if (opening.sill > 0)
panel("sill", left, right, 0, opening.sill);
- const marker = new THREE2.Object3D;
+ const marker = new THREE3.Object3D;
marker.name = `Opening_${wall}_${opening.id}`;
marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);
marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);
@@ -3201,7 +3457,7 @@ function createGableShell(name, materials, options) {
const closedEnds = options.closedEnds ?? true;
const enterable = options.enterable ?? true;
const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
if (options.parent)
options.parent.add(root);
@@ -3221,7 +3477,7 @@ function createGableShell(name, materials, options) {
walls[wall] = built.root;
openingMarkers.push(...built.openings);
}
- const floor = new THREE2.Mesh(new THREE2.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
+ const floor = new THREE3.Mesh(new THREE3.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
floor.name = `Mesh_${name}_Floor`;
floor.position.y = -floorThickness / 2;
stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));
@@ -3267,7 +3523,7 @@ function createGableShell(name, materials, options) {
}
function createRoofSurfaceLayout(name, material, options) {
const parent = options.parent ?? options.face.roofRoot;
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));
@@ -3319,9 +3575,9 @@ function createRoofSurfaceLayout(name, material, options) {
});
}
const items = specs.map((spec, index) => {
- const mesh = new THREE2.Mesh(new THREE2.BoxGeometry(spec.width, thickness, spec.length), material);
+ const mesh = new THREE3.Mesh(new THREE3.BoxGeometry(spec.width, thickness, spec.length), material);
mesh.name = `Mesh_${name}_${index + 1}`;
- const local = new THREE2.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
+ const local = new THREE3.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
setTransform(mesh, faceToRoot.clone().multiply(local));
root.add(mesh);
return mesh;
@@ -3335,7 +3591,7 @@ var init_architecture = __esm(() => {
});
// src/gears.ts
-import * as THREE3 from "three";
+import * as THREE4 from "three";
function gearGeo(opts = {}) {
const {
teeth = 12,
@@ -3429,8 +3685,8 @@ function gearGeo(opts = {}) {
indices.push(tA, bA, bB);
indices.push(tA, bB, tB);
}
- const geo = new THREE3.BufferGeometry;
- geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));
+ const geo = new THREE4.BufferGeometry;
+ geo.setAttribute("position", new THREE4.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -3518,8 +3774,8 @@ function bladeGeo(opts = {}) {
}
}
}
- const geo = new THREE3.BufferGeometry;
- geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));
+ const geo = new THREE4.BufferGeometry;
+ geo.setAttribute("position", new THREE4.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -3530,7 +3786,7 @@ var init_gears = __esm(() => {
});
// src/ops.ts
-import * as THREE4 from "three";
+import * as THREE5 from "three";
import { LoopSubdivision } from "three-subdivide/build/index.module.js";
import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";
function arrayLinear(namePrefix, source, count, offset, parent) {
@@ -3550,19 +3806,19 @@ function arrayLinear(namePrefix, source, count, offset, parent) {
}
function degreesOf(euler) {
return [
- THREE4.MathUtils.radToDeg(euler.x),
- THREE4.MathUtils.radToDeg(euler.y),
- THREE4.MathUtils.radToDeg(euler.z)
+ THREE5.MathUtils.radToDeg(euler.x),
+ THREE5.MathUtils.radToDeg(euler.y),
+ THREE5.MathUtils.radToDeg(euler.z)
];
}
function arrayRadial(namePrefix, source, count, axis = "y", parent, center) {
const out = [];
- const pivot = center ? new THREE4.Vector3(...center) : new THREE4.Vector3;
+ const pivot = center ? new THREE5.Vector3(...center) : new THREE5.Vector3;
const basePos = source.position.clone().sub(pivot);
- const axisVec = axis === "x" ? new THREE4.Vector3(1, 0, 0) : axis === "z" ? new THREE4.Vector3(0, 0, 1) : new THREE4.Vector3(0, 1, 0);
+ const axisVec = axis === "x" ? new THREE5.Vector3(1, 0, 0) : axis === "z" ? new THREE5.Vector3(0, 0, 1) : new THREE5.Vector3(0, 1, 0);
for (let i = 1;i < count; i++) {
const angle = i / count * Math.PI * 2;
- const m = new THREE4.Matrix4().makeRotationAxis(axisVec, angle);
+ const m = new THREE5.Matrix4().makeRotationAxis(axisVec, angle);
const rotated = basePos.clone().applyMatrix4(m).add(pivot);
const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];
out.push(createInstance(`${namePrefix}${i}`, source, {
@@ -3591,25 +3847,25 @@ function mergeVertices(geometry, opts = {}) {
const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;
if (!positionOnly)
return threeMergeVertices(geometry, tolerance);
- const stripped = new THREE4.BufferGeometry;
+ const stripped = new THREE5.BufferGeometry;
const pos = geometry.getAttribute("position");
if (!pos)
return geometry;
- stripped.setAttribute("position", new THREE4.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
+ stripped.setAttribute("position", new THREE5.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
if (geometry.index) {
- stripped.setIndex(new THREE4.BufferAttribute(new Uint32Array(geometry.index.array), 1));
+ stripped.setIndex(new THREE5.BufferAttribute(new Uint32Array(geometry.index.array), 1));
}
return threeMergeVertices(stripped, tolerance);
}
function subdivide(geometry, iterations = 1, opts = {}) {
const { weld = true, preserveUV = false, ...subOpts } = opts;
const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();
- const center = new THREE4.Vector3;
+ const center = new THREE5.Vector3;
let normalizationScale = 1;
if (preserveUV) {
subOpts.uvSmooth = false;
input.computeBoundingBox();
- const extent = input.boundingBox.getSize(new THREE4.Vector3);
+ const extent = input.boundingBox.getSize(new THREE5.Vector3);
input.boundingBox.getCenter(center);
const size = Math.max(extent.x, extent.y, extent.z);
normalizationScale = size > 0 ? 1e4 / size : 1;
@@ -3643,9 +3899,9 @@ function subdivide(geometry, iterations = 1, opts = {}) {
return output;
}
function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {
- const vectors = points.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
- const curve = new THREE4.CatmullRomCurve3(vectors, closed);
- return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = points.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE5.CatmullRomCurve3(vectors, closed);
+ return new THREE5.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function normalizeSurfaceNormals(geo) {
const normal = geo.getAttribute("normal");
@@ -3672,20 +3928,20 @@ function normalizeSurfaceNormals(geo) {
return geo;
}
function lathe(profile, segments = 12) {
- const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));
- return normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments));
+ const points2d = profile.map((p) => new THREE5.Vector2(p[0], p[1]));
+ return normalizeSurfaceNormals(new THREE5.LatheGeometry(points2d, segments));
}
function revolveGeo(profile, options = {}) {
const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
- const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));
- const geo = normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments, 0, angle));
- const n = new THREE4.Vector3(axis[0], axis[1], axis[2]);
+ const points2d = profile.map((p) => new THREE5.Vector2(p[0], p[1]));
+ const geo = normalizeSurfaceNormals(new THREE5.LatheGeometry(points2d, segments, 0, angle));
+ const n = new THREE5.Vector3(axis[0], axis[1], axis[2]);
if (n.lengthSq() < 0.000000000001) {
throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);
}
n.normalize();
if (n.x !== 0 || n.y !== 1 || n.z !== 0) {
- const q = new THREE4.Quaternion().setFromUnitVectors(new THREE4.Vector3(0, 1, 0), n);
+ const q = new THREE5.Quaternion().setFromUnitVectors(new THREE5.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
}
return geo;
@@ -3700,9 +3956,9 @@ function pipeAlongPath(points, radius, options = {}) {
const smoothed = [];
smoothed.push(points[0]);
for (let i = 1;i < points.length - 1; i++) {
- const prev = new THREE4.Vector3(...points[i - 1]);
- const cur = new THREE4.Vector3(...points[i]);
- const next = new THREE4.Vector3(...points[i + 1]);
+ const prev = new THREE5.Vector3(...points[i - 1]);
+ const cur = new THREE5.Vector3(...points[i]);
+ const next = new THREE5.Vector3(...points[i + 1]);
const inDir = cur.clone().sub(prev);
const outDir = next.clone().sub(cur);
const inLen = inDir.length();
@@ -3717,17 +3973,17 @@ function pipeAlongPath(points, radius, options = {}) {
smoothed.push(points[points.length - 1]);
pathPoints = smoothed;
}
- const vectors = pathPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
- const curve = new THREE4.CatmullRomCurve3(vectors, closed);
- return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = pathPoints.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE5.CatmullRomCurve3(vectors, closed);
+ return new THREE5.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function bezierCurve(controlPoints, samples = 32) {
- const vecs = controlPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
+ const vecs = controlPoints.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
let curve;
if (vecs.length === 3) {
- curve = new THREE4.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
+ curve = new THREE5.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
} else if (vecs.length === 4) {
- curve = new THREE4.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
+ curve = new THREE5.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
} else {
throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);
}
@@ -3738,7 +3994,7 @@ var init_ops = __esm(() => {
});
// src/geometry.ts
-import * as THREE5 from "three";
+import * as THREE6 from "three";
function finiteArray(values, label, length) {
const result = Array.from(values);
if (length !== undefined && result.length !== length)
@@ -3752,8 +4008,8 @@ function meshGeo(data) {
if (positions.length < 9 || positions.length % 3)
throw new Error("meshGeo positions: need at least three xyz vertices");
const count = positions.length / 3;
- const geometry = new THREE5.BufferGeometry;
- geometry.setAttribute("position", new THREE5.Float32BufferAttribute(positions, 3));
+ const geometry = new THREE6.BufferGeometry;
+ geometry.setAttribute("position", new THREE6.Float32BufferAttribute(positions, 3));
if (data.indices) {
const indices = Array.from(data.indices);
if (!indices.length || indices.length % 3)
@@ -3765,7 +4021,7 @@ function meshGeo(data) {
throw new Error("meshGeo: non-indexed positions must form complete triangles");
if (data.normals) {
const normals = finiteArray(data.normals, "meshGeo normals", count * 3);
- geometry.setAttribute("normal", new THREE5.Float32BufferAttribute(normals, 3));
+ geometry.setAttribute("normal", new THREE6.Float32BufferAttribute(normals, 3));
for (let i = 0;i < count; i++)
if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)
throw new Error("meshGeo normals: zero-length normal");
@@ -3773,14 +4029,14 @@ function meshGeo(data) {
} else
geometry.computeVertexNormals();
if (data.uvs)
- geometry.setAttribute("uv", new THREE5.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
+ geometry.setAttribute("uv", new THREE6.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
if (data.tangents) {
const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);
for (let i = 0;i < count; i++) {
if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)
throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");
}
- geometry.setAttribute("tangent", new THREE5.Float32BufferAttribute(tangents, 4));
+ geometry.setAttribute("tangent", new THREE6.Float32BufferAttribute(tangents, 4));
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
@@ -3815,7 +4071,7 @@ function geometryDiagnostics(geometry, tolerance = 0.000001) {
}
const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);
const edges = new Map;
- const a = new THREE5.Vector3, b = new THREE5.Vector3, c = new THREE5.Vector3;
+ const a = new THREE6.Vector3, b = new THREE6.Vector3, c = new THREE6.Vector3;
for (let i = 0;i < indices.length; i += 3) {
result.triangles++;
const triangle = indices.slice(i, i + 3);
@@ -3919,8 +4175,8 @@ function parametricSurface(sample, options = {}) {
const sums = new Map;
for (let i = 0;i < normal.count; i++) {
const id = find(i);
- const sum = sums.get(id) ?? new THREE5.Vector3;
- sum.add(new THREE5.Vector3().fromBufferAttribute(normal, i));
+ const sum = sums.get(id) ?? new THREE6.Vector3;
+ sum.add(new THREE6.Vector3().fromBufferAttribute(normal, i));
sums.set(id, sum);
}
for (let i = 0;i < normal.count; i++) {
@@ -3939,7 +4195,7 @@ function creaseNormals(geometry, options = {}) {
if (position?.itemSize !== 3 || position.count % 3 !== 0)
throw new Error("creaseNormals requires complete xyz triangles");
out.computeBoundingBox();
- const diagonal = out.boundingBox.getSize(new THREE5.Vector3).length();
+ const diagonal = out.boundingBox.getSize(new THREE6.Vector3).length();
const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);
if (!Number.isFinite(tolerance) || tolerance <= 0)
throw new Error("creaseNormals tolerance must be positive and finite");
@@ -3947,13 +4203,13 @@ function creaseNormals(geometry, options = {}) {
const keys = [];
const faces = [];
for (let i = 0;i < position.count; i += 3) {
- const a = new THREE5.Vector3().fromBufferAttribute(position, i);
- const b = new THREE5.Vector3().fromBufferAttribute(position, i + 1);
- const c = new THREE5.Vector3().fromBufferAttribute(position, i + 2);
+ const a = new THREE6.Vector3().fromBufferAttribute(position, i);
+ const b = new THREE6.Vector3().fromBufferAttribute(position, i + 1);
+ const c = new THREE6.Vector3().fromBufferAttribute(position, i + 2);
const face = b.sub(a).cross(c.sub(a)).normalize();
faces.push(face);
for (let j = i;j < i + 3; j++) {
- const point = new THREE5.Vector3().fromBufferAttribute(position, j);
+ const point = new THREE6.Vector3().fromBufferAttribute(position, j);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("creaseNormals positions must be finite");
const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");
@@ -3964,15 +4220,15 @@ function creaseNormals(geometry, options = {}) {
}
}
const normals = new Float32Array(position.count * 3);
- const threshold = Math.cos(THREE5.MathUtils.degToRad(angle));
+ const threshold = Math.cos(THREE6.MathUtils.degToRad(angle));
for (let i = 0;i < position.count; i++) {
- const face = faces[Math.floor(i / 3)], sum = new THREE5.Vector3;
+ const face = faces[Math.floor(i / 3)], sum = new THREE6.Vector3;
for (const other of adjacent.get(keys[i]))
if (face.dot(faces[other]) >= threshold - 0.000000000001)
sum.add(faces[other]);
sum.normalize().toArray(normals, i * 3);
}
- out.setAttribute("normal", new THREE5.BufferAttribute(normals, 3));
+ out.setAttribute("normal", new THREE6.BufferAttribute(normals, 3));
out.deleteAttribute("tangent");
out.computeBoundingSphere();
return out;
@@ -3982,19 +4238,19 @@ var init_geometry = __esm(() => {
});
// src/deform.ts
-import * as THREE6 from "three";
+import * as THREE7 from "three";
function geometryFrameMatrix(frame = {}) {
const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];
if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))
throw new Error("geometry frame requires finite xyz origin and rotation");
- return new THREE6.Matrix4().compose(new THREE6.Vector3(...origin), new THREE6.Quaternion().setFromEuler(new THREE6.Euler(...rotation.map(THREE6.MathUtils.degToRad), "XYZ")), new THREE6.Vector3(1, 1, 1));
+ return new THREE7.Matrix4().compose(new THREE7.Vector3(...origin), new THREE7.Quaternion().setFromEuler(new THREE7.Euler(...rotation.map(THREE7.MathUtils.degToRad), "XYZ")), new THREE7.Vector3(1, 1, 1));
}
function deform(geometry, options, map) {
const source = geometry.getAttribute("position");
if (source?.itemSize !== 3 || source.count === 0)
throw new Error("deformation requires nonempty xyz positions");
const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();
- const points = Array.from({ length: source.count }, (_, i) => new THREE6.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
+ const points = Array.from({ length: source.count }, (_, i) => new THREE7.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))
throw new Error("deformation positions must be finite");
let low = Infinity, high = -Infinity;
@@ -4015,7 +4271,7 @@ function deform(geometry, options, map) {
const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;
if (point.y < low - epsilon || point.y > high + epsilon)
continue;
- const t = length > epsilon ? THREE6.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
+ const t = length > epsilon ? THREE7.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
const weight = options.falloff?.(t) ?? 1;
if (!Number.isFinite(weight) || weight < 0 || weight > 1)
throw new Error("deformation falloff must return a finite weight between 0 and 1");
@@ -4037,41 +4293,41 @@ function deform(geometry, options, map) {
function twist(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("twist angle must be finite degrees");
- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE6.Vector3(0, 1, 0), THREE6.MathUtils.degToRad(options.angle) * t));
+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE7.Vector3(0, 1, 0), THREE7.MathUtils.degToRad(options.angle) * t));
}
function bend(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("bend angle must be finite degrees");
- const angle = THREE6.MathUtils.degToRad(options.angle);
+ const angle = THREE7.MathUtils.degToRad(options.angle);
return deform(geometry, options, (p, t, low, length) => {
if (Math.abs(angle) < 0.0000000001 || length === 0)
return p;
const radius = length / angle, theta = angle * t;
- return new THREE6.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
+ return new THREE7.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
});
}
function taper(geometry, options) {
const start = options.startScale ?? [1, 1], end = options.endScale;
if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))
throw new Error("taper scales must be two finite positive values");
- return deform(geometry, options, (p, t) => p.set(p.x * THREE6.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE6.MathUtils.lerp(start[1], end[1], t)));
+ return deform(geometry, options, (p, t) => p.set(p.x * THREE7.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE7.MathUtils.lerp(start[1], end[1], t)));
}
function displace(geometry, offset, options = {}) {
return deform(geometry, options, (p, t) => {
const delta = offset([p.x, p.y, p.z], t);
if (delta.length !== 3 || !delta.every(Number.isFinite))
throw new Error("displace callback must return three finite offsets");
- return p.add(new THREE6.Vector3(...delta));
+ return p.add(new THREE7.Vector3(...delta));
});
}
var init_deform = () => {};
// src/sweep.ts
-import * as THREE7 from "three";
+import * as THREE8 from "three";
function profilePoints(profile) {
if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
throw new Error("profile requires at least three finite xy points");
- const points = profile.map((p) => new THREE7.Vector2(...p));
+ const points = profile.map((p) => new THREE8.Vector2(...p));
if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)
points.pop();
if (points.length < 3)
@@ -4089,7 +4345,7 @@ function profilePoints(profile) {
throw new Error("profile self-intersects or touches itself");
}
}
- const area = THREE7.ShapeUtils.area(points);
+ const area = THREE8.ShapeUtils.area(points);
if (Math.abs(area) < 0.000000000001)
throw new Error("profile area must be nonzero");
if (area < 0)
@@ -4098,7 +4354,7 @@ function profilePoints(profile) {
}
function buildLoft(rings, profiles, closed, cap) {
const n = rings[0].length, positions = [], uvs = [], indices = [];
- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE7.Vector3).multiplyScalar(1 / n));
+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE8.Vector3).multiplyScalar(1 / n));
const lengths = [0];
for (let i = 1;i < centers.length; i++)
lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));
@@ -4123,13 +4379,13 @@ function buildLoft(rings, profiles, closed, cap) {
for (const station of [0, rings.length - 1]) {
const ring = rings[station], profile = profiles[station];
const start = positions.length / 3;
- const bounds = new THREE7.Box2().setFromPoints(profile);
- const size = bounds.getSize(new THREE7.Vector2);
+ const bounds = new THREE8.Box2().setFromPoints(profile);
+ const size = bounds.getSize(new THREE8.Vector2);
for (let j = 0;j < n; j++) {
positions.push(...ring[j].toArray());
uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));
}
- for (const tri of THREE7.ShapeUtils.triangulateShape(profile, [])) {
+ for (const tri of THREE8.ShapeUtils.triangulateShape(profile, [])) {
if (station === 0)
indices.push(...tri.map((j) => start + j));
else
@@ -4140,14 +4396,14 @@ function buildLoft(rings, profiles, closed, cap) {
const normal = out.getAttribute("normal");
for (let i = 0;i < rings.length; i++) {
const a = i * (n + 1), b = a + n;
- const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE8.Vector3().fromBufferAttribute(normal, a).add(new THREE8.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
if (closed)
for (let j = 0;j <= n; j++) {
const a = j, b = (rings.length - 1) * (n + 1) + j;
- const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE8.Vector3().fromBufferAttribute(normal, a).add(new THREE8.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
@@ -4161,7 +4417,7 @@ function loftProfiles(sections, options = {}) {
throw new Error("loftProfiles sections must have the same point count and correspondence");
const rings = sections.map((section, i) => {
const frame = geometryFrameMatrix(section.frame);
- return profiles[i].map((p) => new THREE7.Vector3(p.x, 0, p.y).applyMatrix4(frame));
+ return profiles[i].map((p) => new THREE8.Vector3(p.x, 0, p.y).applyMatrix4(frame));
});
const out = buildLoft(rings, profiles, false, options.cap ?? true);
out.userData.kilnGeometryWarnings = [
@@ -4180,7 +4436,7 @@ function sweepProfile(profile, path, options = {}) {
throw new Error("closed sweep twist must be a multiple of 360 degrees");
if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))
throw new Error("sweepProfile requires finite path points (two open or three closed)");
- const stations = path.map((p) => new THREE7.Vector3(...p));
+ const stations = path.map((p) => new THREE8.Vector3(...p));
if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)
throw new Error("closed sweep path should omit its repeated endpoint");
const segments = [];
@@ -4217,7 +4473,7 @@ function sweepProfile(profile, path, options = {}) {
});
if (Array.isArray(options.scale) && options.scale.length !== stations.length)
throw new Error("sweepProfile scale needs one pair per path station");
- const up = options.up ? new THREE7.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE7.Vector3(0, 0, 1) : new THREE7.Vector3(1, 0, 0);
+ const up = options.up ? new THREE8.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE8.Vector3(0, 0, 1) : new THREE8.Vector3(1, 0, 0);
if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)
throw new Error("sweepProfile up must be a finite nonzero vector");
let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));
@@ -4232,7 +4488,7 @@ function sweepProfile(profile, path, options = {}) {
}
const distances = [0];
for (let i = 1;i < stations.length; i++) {
- z = z.clone().applyQuaternion(new THREE7.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
+ z = z.clone().applyQuaternion(new THREE8.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
normals.push(z);
distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));
}
@@ -4242,7 +4498,7 @@ function sweepProfile(profile, path, options = {}) {
correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));
const rings = stations.map((station, i) => {
const tangent = tangents[i], t = distances[i] / total;
- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE7.MathUtils.degToRad(twist)) * t);
+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE8.MathUtils.degToRad(twist)) * t);
const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];
return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));
});
@@ -4262,7 +4518,7 @@ var init_sweep = __esm(() => {
});
// src/solids.ts
-import * as THREE8 from "three";
+import * as THREE9 from "three";
async function getManifoldModule() {
if (_module)
return _module;
@@ -4322,7 +4578,7 @@ function threeToManifold(src, mod, label, context) {
else
context.missingUV.add(mesh.name || label);
}
- const point = new THREE8.Vector3;
+ const point = new THREE9.Vector3;
for (let i = 0;i < position.count; i++) {
point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))
@@ -4391,11 +4647,11 @@ function manifoldToGeometry(m, opts = {}) {
if (uvs)
uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);
}
- const geometry = new THREE8.BufferGeometry;
- geometry.setAttribute("position", new THREE8.BufferAttribute(positions, 3));
- geometry.setIndex(new THREE8.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
+ const geometry = new THREE9.BufferGeometry;
+ geometry.setAttribute("position", new THREE9.BufferAttribute(positions, 3));
+ geometry.setIndex(new THREE9.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
if (uvs)
- geometry.setAttribute("uv", new THREE8.BufferAttribute(uvs, 2));
+ geometry.setAttribute("uv", new THREE9.BufferAttribute(uvs, 2));
const out = opts.smooth ? geometry : geometry.toNonIndexed();
out.computeVertexNormals();
if (opts.smooth && uvs) {
@@ -4416,7 +4672,7 @@ function firstMaterial(src) {
if (!material && mesh.isMesh)
material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
});
- return material ?? new THREE8.MeshStandardMaterial;
+ return material ?? new THREE9.MeshStandardMaterial;
}
function outputMesh(result, name, parts, opts, context, isHull) {
const geometry = manifoldToGeometry(result, {
@@ -4471,7 +4727,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {
message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."
});
geometry.userData.kilnAttributeWarnings = warnings;
- const output = new THREE8.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
+ const output = new THREE9.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
output.name = `Mesh_${name}`;
return output;
}
@@ -4820,7 +5076,7 @@ var init_profile = __esm(() => {
});
// src/textures.ts
-import * as THREE9 from "three";
+import * as THREE10 from "three";
async function loadTexture(source, opts = {}) {
let bytes;
if (typeof source === "string") {
@@ -4841,7 +5097,7 @@ async function loadTexture(source, opts = {}) {
if (!meta.width || !meta.height) {
throw new Error("loadTexture: could not read image dimensions");
}
- const tex = new THREE9.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE9.RGBAFormat, THREE9.UnsignedByteType);
+ const tex = new THREE10.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE10.RGBAFormat, THREE10.UnsignedByteType);
const usage = opts.usage ?? "albedo";
const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";
let hasAlpha = false;
@@ -4851,14 +5107,14 @@ async function loadTexture(source, opts = {}) {
break;
}
}
- tex.colorSpace = colorSpace === "srgb" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;
+ tex.colorSpace = colorSpace === "srgb" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
if (opts.name)
tex.name = opts.name;
tex.needsUpdate = true;
- tex.wrapS = THREE9.RepeatWrapping;
- tex.wrapT = THREE9.RepeatWrapping;
- tex.minFilter = THREE9.LinearMipmapLinearFilter;
- tex.magFilter = THREE9.LinearFilter;
+ tex.wrapS = THREE10.RepeatWrapping;
+ tex.wrapT = THREE10.RepeatWrapping;
+ tex.minFilter = THREE10.LinearMipmapLinearFilter;
+ tex.magFilter = THREE10.LinearFilter;
tex.generateMipmaps = true;
tex.userData["encoded"] = {
mime,
@@ -4893,17 +5149,17 @@ function requireTextureUsage(texture, usage) {
if (meta && meta.usage !== usage) {
throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);
}
- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;
+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
}
function pbrMaterial(opts = {}) {
- const mat = new THREE9.MeshStandardMaterial;
+ const mat = new THREE10.MeshStandardMaterial;
const isTex = (v) => !!v?.isTexture;
if (isTex(opts.albedo)) {
requireTextureUsage(opts.albedo, "albedo");
mat.map = opts.albedo;
- mat.color = new THREE9.Color(16777215);
+ mat.color = new THREE10.Color(16777215);
} else if (opts.albedo !== undefined) {
- mat.color = new THREE9.Color(opts.albedo);
+ mat.color = new THREE10.Color(opts.albedo);
}
if (opts.normal) {
requireTextureUsage(opts.normal, "normal");
@@ -4941,9 +5197,9 @@ function pbrMaterial(opts = {}) {
if (isTex(opts.emissive)) {
requireTextureUsage(opts.emissive, "emissive");
mat.emissiveMap = opts.emissive;
- mat.emissive = new THREE9.Color(16777215);
+ mat.emissive = new THREE10.Color(16777215);
} else if (opts.emissive !== undefined) {
- mat.emissive = new THREE9.Color(opts.emissive);
+ mat.emissive = new THREE10.Color(opts.emissive);
}
if (opts.emissiveIntensity !== undefined) {
mat.emissiveIntensity = opts.emissiveIntensity;
@@ -4975,7 +5231,7 @@ function pbrMaterial(opts = {}) {
mat.transparent = true;
}
if (opts.doubleSided)
- mat.side = THREE9.DoubleSide;
+ mat.side = THREE10.DoubleSide;
mat.userData["kilnMaterial"] = {
alphaMode,
...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},
@@ -5477,7 +5733,7 @@ var init_procedural_material_v2 = __esm(() => {
});
// src/procedural-texture.ts
-import * as THREE10 from "three";
+import * as THREE11 from "three";
function hash2(x, y, seed) {
let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;
h = h ^ h >>> 13;
@@ -5618,14 +5874,14 @@ function compileProceduralTextureSpecV2(input) {
function proceduralTexture(spec) {
const compiled = compileProceduralTextureSpecV2(spec);
const { size, usage, name, layers } = compiled.spec;
- const tex = new THREE10.DataTexture(compiled.pixels, size, size, THREE10.RGBAFormat, THREE10.UnsignedByteType);
+ const tex = new THREE11.DataTexture(compiled.pixels, size, size, THREE11.RGBAFormat, THREE11.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
- tex.wrapS = THREE10.RepeatWrapping;
- tex.wrapT = THREE10.RepeatWrapping;
- tex.minFilter = THREE10.LinearMipmapLinearFilter;
- tex.magFilter = THREE10.LinearFilter;
+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE11.SRGBColorSpace : THREE11.NoColorSpace;
+ tex.wrapS = THREE11.RepeatWrapping;
+ tex.wrapT = THREE11.RepeatWrapping;
+ tex.minFilter = THREE11.LinearMipmapLinearFilter;
+ tex.magFilter = THREE11.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -5679,13 +5935,13 @@ function normalMapFromHeight(source, opts = {}) {
out[o + 3] = 255;
}
}
- const tex = new THREE10.DataTexture(out, width, height, THREE10.RGBAFormat, THREE10.UnsignedByteType);
+ const tex = new THREE11.DataTexture(out, width, height, THREE11.RGBAFormat, THREE11.UnsignedByteType);
tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");
- tex.colorSpace = THREE10.NoColorSpace;
- tex.wrapS = THREE10.RepeatWrapping;
- tex.wrapT = THREE10.RepeatWrapping;
- tex.minFilter = THREE10.LinearMipmapLinearFilter;
- tex.magFilter = THREE10.LinearFilter;
+ tex.colorSpace = THREE11.NoColorSpace;
+ tex.wrapS = THREE11.RepeatWrapping;
+ tex.wrapT = THREE11.RepeatWrapping;
+ tex.minFilter = THREE11.LinearMipmapLinearFilter;
+ tex.magFilter = THREE11.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
return tex;
@@ -7852,7 +8108,7 @@ var init_portable_material_runtime = __esm(() => {
});
// src/vehicle.ts
-import * as THREE11 from "three";
+import * as THREE12 from "three";
function assertId(value, name) {
if (!ID_PATTERN.test(value))
throw new TypeError(`${name} must be a stable identifier`);
@@ -7888,7 +8144,7 @@ function createTypedSocket(kind, input, parent) {
if (!input.position.every(Number.isFinite))
throw new TypeError(`${kind}.${id} position must be finite`);
const rotation = normalizedQuaternion(input.rotation);
- const node = new THREE11.Object3D;
+ const node = new THREE12.Object3D;
node.name = `Socket_${kind}_${id}`;
node.position.set(...input.position);
node.quaternion.set(...rotation);
@@ -7909,7 +8165,7 @@ function createTypedSocket(kind, input, parent) {
return node;
}
function createVehicleFrame(name, options = {}) {
- const root = new THREE11.Object3D;
+ const root = new THREE12.Object3D;
root.name = name;
stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {
frames: [
@@ -7934,7 +8190,7 @@ function createVehicleFrame(name, options = {}) {
};
}
function cylinderZ(radius, width, segments = 16) {
- const geometry = new THREE11.CylinderGeometry(radius, radius, width, segments);
+ const geometry = new THREE12.CylinderGeometry(radius, radius, width, segments);
geometry.rotateX(Math.PI / 2);
return geometry;
}
@@ -7945,7 +8201,7 @@ function createWheelGeometrySet(radius, width) {
throw new RangeError("wheel width must be less than its diameter");
const tube = width / 2;
return {
- tire: new THREE11.TorusGeometry(radius - tube, tube, 8, 20),
+ tire: new THREE12.TorusGeometry(radius - tube, tube, 8, 20),
rim: cylinderZ(radius * 0.68, width * 0.8),
hub: cylinderZ(radius * 0.34, width * 0.94)
};
@@ -7964,11 +8220,11 @@ function createWheelAssembly(name, materials, options) {
const index = assertId(String(options.index), "wheel index");
const key = `${options.side}.${index}`;
const parent = options.parent;
- const root = new THREE11.Object3D;
+ const root = new THREE12.Object3D;
root.name = `${name}_Assembly_${options.side}_${index}`;
let steeringPivot;
if (options.steering) {
- steeringPivot = new THREE11.Object3D;
+ steeringPivot = new THREE12.Object3D;
steeringPivot.name = `SteeringPivot_${options.side}_${index}`;
steeringPivot.position.set(...options.position ?? [0, 0, 0]);
stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {
@@ -7979,7 +8235,7 @@ function createWheelAssembly(name, materials, options) {
}));
root.add(steeringPivot);
}
- const spinPivot = new THREE11.Object3D;
+ const spinPivot = new THREE12.Object3D;
spinPivot.name = `WheelPivot_${options.side}_${index}`;
if (!steeringPivot)
spinPivot.position.set(...options.position ?? [0, 0, 0]);
@@ -8001,9 +8257,9 @@ function createWheelAssembly(name, materials, options) {
}));
(steeringPivot ?? root).add(spinPivot);
const defaults = createWheelGeometrySet(radius, width);
- const tire = new THREE11.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);
- const rim = new THREE11.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);
- const hub = new THREE11.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);
+ const tire = new THREE12.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);
+ const rim = new THREE12.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);
+ const hub = new THREE12.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);
tire.name = `Tire_${options.side}_${index}`;
rim.name = `Rim_${options.side}_${index}`;
hub.name = `Hub_${options.side}_${index}`;
@@ -8023,7 +8279,7 @@ function createWheelAssembly(name, materials, options) {
]
}));
spinPivot.add(tire, rim, hub);
- const contact = new THREE11.Object3D;
+ const contact = new THREE12.Object3D;
contact.name = `Contact_${options.side}_${index}`;
contact.position.y = -radius;
stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {
@@ -8080,10 +8336,10 @@ function objectBoundsInFrame(object, frame) {
object.updateWorldMatrix(true, true);
frame.updateWorldMatrix(true, false);
const worldToFrame = frame.matrixWorld.clone().invert();
- const bounds = new THREE11.Box3;
+ const bounds = new THREE12.Box3;
let found = false;
object.traverse((node) => {
- if (!(node instanceof THREE11.Mesh) || !(node.geometry instanceof THREE11.BufferGeometry))
+ if (!(node instanceof THREE12.Mesh) || !(node.geometry instanceof THREE12.BufferGeometry))
return;
node.geometry.computeBoundingBox();
const local = node.geometry.boundingBox;
@@ -8093,7 +8349,7 @@ function objectBoundsInFrame(object, frame) {
for (const x of [local.min.x, local.max.x])
for (const y of [local.min.y, local.max.y])
for (const z of [local.min.z, local.max.z]) {
- bounds.expandByPoint(new THREE11.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE12.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -8105,9 +8361,9 @@ function dimensions(object, frame) {
const bounds = objectBoundsInFrame(object, frame);
if (!bounds)
return;
- const size = bounds.getSize(new THREE11.Vector3);
+ const size = bounds.getSize(new THREE12.Vector3);
return {
- center: bounds.getCenter(new THREE11.Vector3),
+ center: bounds.getCenter(new THREE12.Vector3),
radius: Math.max(size.x, size.y) / 2,
width: size.z
};
@@ -8117,7 +8373,7 @@ function resolved(source, id, root, pivot, parts) {
const tire = dimensions(parts.tire, pivot);
const rim = dimensions(parts.rim, pivot);
const hub = dimensions(parts.hub, pivot);
- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE11.Vector3;
+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE12.Vector3;
const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);
return {
id,
@@ -8132,11 +8388,11 @@ function resolved(source, id, root, pivot, parts) {
...parts.hub ? { hub: parts.hub } : {},
...parts.contact ? { contact: parts.contact } : {},
centerWorld: toWorld(centerLocal),
- pivotCenterWorld: new THREE11.Vector3().setFromMatrixPosition(pivot.matrixWorld),
+ pivotCenterWorld: new THREE12.Vector3().setFromMatrixPosition(pivot.matrixWorld),
...tire ? { tireCenterWorld: toWorld(tire.center) } : {},
...rim ? { rimCenterWorld: toWorld(rim.center) } : {},
...hub ? { hubCenterWorld: toWorld(hub.center) } : {},
- spinAxisWorld: new THREE11.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),
+ spinAxisWorld: new THREE12.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),
...tire ? { radius: tire.radius, width: tire.width } : {},
...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},
...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},
@@ -8235,7 +8491,7 @@ var init_vehicle = __esm(() => {
});
// src/uv.ts
-import * as THREE12 from "three";
+import * as THREE13 from "three";
async function getXatlas() {
if (!_xatlasReady) {
_xatlasReady = (async () => {
@@ -8281,16 +8537,16 @@ async function autoUnwrap(geometry, opts = {}) {
xa.destroyAtlas();
throw new Error("autoUnwrap: xatlas returned no meshes");
}
- const out = new THREE12.BufferGeometry;
- out.setAttribute("position", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
+ const out = new THREE13.BufferGeometry;
+ out.setAttribute("position", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
if (mesh.vertex.normals) {
- out.setAttribute("normal", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
+ out.setAttribute("normal", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
}
if (mesh.vertex.coords1) {
- out.setAttribute("uv", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
+ out.setAttribute("uv", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
}
if (mesh.index) {
- out.setIndex(new THREE12.BufferAttribute(new Uint32Array(mesh.index), 1));
+ out.setIndex(new THREE13.BufferAttribute(new Uint32Array(mesh.index), 1));
}
out.userData["atlas"] = {
width: result.width,
@@ -8313,7 +8569,7 @@ function toIndexed(geo) {
for (let i = 0;i < posAttr.count; i++)
indices[i] = i;
const out = geo.clone();
- out.setIndex(new THREE12.BufferAttribute(indices, 1));
+ out.setIndex(new THREE13.BufferAttribute(indices, 1));
return out;
}
function repairZeroNormals(geo) {
@@ -8333,11 +8589,11 @@ function repairZeroNormals(geo) {
if (broken.size === 0)
return;
const acc = new Float32Array(normal.count * 3);
- const a = new THREE12.Vector3;
- const b = new THREE12.Vector3;
- const c = new THREE12.Vector3;
- const face = new THREE12.Vector3;
- const edge = new THREE12.Vector3;
+ const a = new THREE13.Vector3;
+ const b = new THREE13.Vector3;
+ const c = new THREE13.Vector3;
+ const face = new THREE13.Vector3;
+ const edge = new THREE13.Vector3;
for (let t = 0;t + 2 < index.count; t += 3) {
const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];
if (!tri.some((i) => broken.has(i)))
@@ -8371,7 +8627,7 @@ var _xatlasReady = null;
var init_uv = () => {};
// src/uv-shapes.ts
-import * as THREE13 from "three";
+import * as THREE14 from "three";
function boxUnwrap(geo) {
const cloned = geo.clone();
if (!cloned.getAttribute("uv")) {
@@ -8428,7 +8684,7 @@ function cylindricalProjectToUVs(geo) {
uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;
uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uv, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uv, 2));
}
function planeUnwrap(geo) {
const cloned = geo.clone();
@@ -8451,7 +8707,7 @@ function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {
function planarProjectToUVs(geo) {
geo.computeBoundingBox();
const bb = geo.boundingBox;
- const size = new THREE13.Vector3;
+ const size = new THREE14.Vector3;
bb.getSize(size);
const w = size.x || 1;
const h = size.y || 1;
@@ -8461,12 +8717,12 @@ function planarProjectToUVs(geo) {
uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;
uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uvs, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uvs, 2));
}
var init_uv_shapes = () => {};
// src/material-recipe-runtime.ts
-import * as THREE14 from "three";
+import * as THREE15 from "three";
async function applyMaterialRecipeV1(request, options = {}) {
const resolved = resolveMaterialRecipeV1(request);
const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;
@@ -8489,9 +8745,9 @@ async function applyMaterialRecipeV1(request, options = {}) {
};
const material = pbrMaterial(materialOptions);
material.name = options.name ?? request.id;
- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);
+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE15.LinearSRGBColorSpace);
material.opacity = resolved.baseColorFactor[3];
- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);
+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE15.LinearSRGBColorSpace);
const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));
const provenance = {
schemaVersion: 1,
@@ -8542,17 +8798,17 @@ var init_material_recipe_runtime = __esm(() => {
});
// src/primitives.ts
-import * as THREE15 from "three";
+import * as THREE16 from "three";
function vectorToTuple(v) {
return [v.x, v.y, v.z];
}
function createRoot(name) {
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
return root;
}
function createPivot(name, position = [0, 0, 0], parent) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.position.set(...position);
if (parent)
@@ -8584,16 +8840,16 @@ function assertPartArgs(name, geometry2, material) {
}
function createPart(name, geometry2, material, options = {}) {
assertPartArgs(name, geometry2, material);
- const mesh = new THREE15.Mesh(geometry2, material);
+ const mesh = new THREE16.Mesh(geometry2, material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.pivot) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.add(mesh);
mesh.position.set(0, 0, 0);
@@ -8612,7 +8868,7 @@ function createPart(name, geometry2, material, options = {}) {
return mesh;
}
function capsuleGeo(radius, height, segments = 6) {
- return new THREE15.CapsuleGeometry(radius, height, 2, segments);
+ return new THREE16.CapsuleGeometry(radius, height, 2, segments);
}
function capsuleXGeo(radius, length, segments = 6) {
const geo = capsuleGeo(radius, length, segments);
@@ -8625,7 +8881,7 @@ function capsuleZGeo(radius, length, segments = 6) {
return geo;
}
function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {
- return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ return new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
}
function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
@@ -8638,13 +8894,13 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {
return geo;
}
function boxGeo(width, height, depth) {
- return new THREE15.BoxGeometry(width, height, depth);
+ return new THREE16.BoxGeometry(width, height, depth);
}
function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {
- return new THREE15.SphereGeometry(radius, widthSegments, heightSegments);
+ return new THREE16.SphereGeometry(radius, widthSegments, heightSegments);
}
function coneGeo(radius, height, segments = 8) {
- return new THREE15.ConeGeometry(radius, height, segments);
+ return new THREE16.ConeGeometry(radius, height, segments);
}
function coneXGeo(radius, length, segments = 8) {
const geo = coneGeo(radius, length, segments);
@@ -8659,20 +8915,20 @@ function coneZGeo(radius, length, segments = 8) {
function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {
const radiusTop = options.radiusTop ?? radiusBottom;
const segments = options.segments ?? 8;
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
- const n = new THREE15.Vector3(normal[0], normal[1], normal[2]);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const n = new THREE16.Vector3(normal[0], normal[1], normal[2]);
const len = n.length();
if (len < 0.000001) {
throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);
}
n.divideScalar(len);
- const q = new THREE15.Quaternion().setFromUnitVectors(new THREE15.Vector3(0, 1, 0), n);
+ const q = new THREE16.Quaternion().setFromUnitVectors(new THREE16.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
geo.translate(center[0], center[1], center[2]);
return geo;
}
function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
if (axis === "x")
geo.rotateZ(-Math.PI / 2);
else if (axis === "z")
@@ -8680,20 +8936,20 @@ function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8)
return geo;
}
function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {
- return new THREE15.TorusGeometry(radius, tube, radialSegments, tubularSegments);
+ return new THREE16.TorusGeometry(radius, tube, radialSegments, tubularSegments);
}
function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {
- return new THREE15.PlaneGeometry(width, height, widthSegments, heightSegments);
+ return new THREE16.PlaneGeometry(width, height, widthSegments, heightSegments);
}
function decalBox(width, height, depth = 0.01) {
const d = Math.max(depth, 0.002);
- return new THREE15.BoxGeometry(width, height, d);
+ return new THREE16.BoxGeometry(width, height, d);
}
function foliageCardGeo(opts = {}) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
geom.userData["kilnGeometryRole"] = "foliageCard";
return geom;
@@ -8706,12 +8962,12 @@ function crossedQuadsGeo(opts = {}) {
const geometries = [];
for (let i = 0;i < planes; i++) {
const angle = i / planes * Math.PI;
- const quad = new THREE15.PlaneGeometry(w, h);
+ const quad = new THREE16.PlaneGeometry(w, h);
quad.translate(0, h * (0.5 - yPivot), 0);
quad.rotateY(angle);
geometries.push(quad);
}
- const out = new THREE15.BufferGeometry;
+ const out = new THREE16.BufferGeometry;
const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);
const positions = new Float32Array(posCount * 3);
const normals = new Float32Array(posCount * 3);
@@ -8738,9 +8994,9 @@ function crossedQuadsGeo(opts = {}) {
}
vOffset += p.count;
}
- out.setAttribute("position", new THREE15.BufferAttribute(positions, 3));
- out.setAttribute("normal", new THREE15.BufferAttribute(normals, 3));
- out.setAttribute("uv", new THREE15.BufferAttribute(uvs, 2));
+ out.setAttribute("position", new THREE16.BufferAttribute(positions, 3));
+ out.setAttribute("normal", new THREE16.BufferAttribute(normals, 3));
+ out.setAttribute("uv", new THREE16.BufferAttribute(uvs, 2));
out.setIndex(indices);
out.userData["kilnGeometryRole"] = "foliageCard";
return out;
@@ -8749,7 +9005,7 @@ function octaGridPlane(opts) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
const uv = geom.attributes.uv;
const du = 1 / opts.tilesX;
@@ -8837,8 +9093,8 @@ function wingGeo(options = {}) {
7,
6
];
- const geo = new THREE15.BufferGeometry;
- geo.setAttribute("position", new THREE15.BufferAttribute(vertices, 3));
+ const geo = new THREE16.BufferGeometry;
+ geo.setAttribute("position", new THREE16.BufferAttribute(vertices, 3));
geo.setIndex(indices);
geo.computeVertexNormals();
return geo;
@@ -8861,17 +9117,17 @@ function createWingPair(name, material, options) {
};
}
function beamBetween(name, start, end, radius, material, options = {}) {
- const a = new THREE15.Vector3(...start);
- const b = new THREE15.Vector3(...end);
+ const a = new THREE16.Vector3(...start);
+ const b = new THREE16.Vector3(...end);
const direction = b.clone().sub(a);
const length = direction.length();
if (length <= 0.0001) {
throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);
}
- const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
+ const mesh = new THREE16.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
mesh.name = `Mesh_${name}`;
mesh.position.copy(a.add(b).multiplyScalar(0.5));
- mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());
+ mesh.quaternion.setFromUnitVectors(new THREE16.Vector3(0, 1, 0), direction.normalize());
if (options.parent)
options.parent.add(mesh);
return mesh;
@@ -8880,11 +9136,11 @@ function snapTo(part, host, options = {}) {
const overlap = options.overlap ?? 0.02;
part.updateMatrixWorld(true);
host.updateMatrixWorld(true);
- const a = new THREE15.Box3().setFromObject(part);
- const b = new THREE15.Box3().setFromObject(host);
+ const a = new THREE16.Box3().setFromObject(part);
+ const b = new THREE16.Box3().setFromObject(host);
if (a.isEmpty() || b.isEmpty())
return part;
- const delta = new THREE15.Vector3;
+ const delta = new THREE16.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
delta[axis] = b.max[axis] - a.min[axis];
@@ -8900,7 +9156,7 @@ function snapTo(part, host, options = {}) {
delta[dominant] = -overlap;
const parent = part.parent;
if (parent) {
- const p0 = new THREE15.Vector3;
+ const p0 = new THREE16.Vector3;
part.getWorldPosition(p0);
const p1 = p0.clone().add(delta);
const l0 = parent.worldToLocal(p0.clone());
@@ -8925,9 +9181,9 @@ function createLadder(name, options) {
widthAxis = "x",
parent
} = options;
- const bottomVec = new THREE15.Vector3(...bottom);
- const topVec = new THREE15.Vector3(...top);
- const offset = widthAxis === "x" ? new THREE15.Vector3(width / 2, 0, 0) : new THREE15.Vector3(0, 0, width / 2);
+ const bottomVec = new THREE16.Vector3(...bottom);
+ const topVec = new THREE16.Vector3(...top);
+ const offset = widthAxis === "x" ? new THREE16.Vector3(width / 2, 0, 0) : new THREE16.Vector3(0, 0, width / 2);
const leftBottom = bottomVec.clone().sub(offset);
const leftTop = topVec.clone().sub(offset);
const rightBottom = bottomVec.clone().add(offset);
@@ -8944,7 +9200,7 @@ function createLadder(name, options) {
}
function wallWithOpening(name, material, options) {
const { length, height, thickness, axis = "z", opening, parent } = options;
- const group = new THREE15.Object3D;
+ const group = new THREE16.Object3D;
group.name = name;
const overlap = 0.02;
const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {
@@ -8989,7 +9245,7 @@ function room(name, material, options = {}) {
parent
} = options;
const openings = options.openings ?? [{ wall: "front", kind: "door" }];
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const openingFor = (wall) => {
const found = openings.find((op) => op.wall === wall);
@@ -9033,7 +9289,7 @@ function createRoofPlanes2(name, material, options) {
result.slopes[0].name = `Mesh_${name}A`;
result.slopes[1].name = `Mesh_${name}B`;
for (let index = 0;index < result.slopes.length; index++) {
- const normal = new THREE15.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
+ const normal = new THREE16.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);
}
if ((options.ridgeAxis ?? "x") === "x") {
@@ -9060,7 +9316,7 @@ function createStairs(name, material, options) {
if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {
throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);
}
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const stepRise = totalRise / steps;
const stepRun = totalRun / steps;
@@ -9090,7 +9346,7 @@ function requireColor(color, fn) {
}
function gameMaterial(color, options = {}) {
requireColor(color, "gameMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
metalness: options.metalness ?? 0,
roughness: options.roughness ?? 0.8,
@@ -9101,7 +9357,7 @@ function gameMaterial(color, options = {}) {
}
function basicMaterial(color, options = {}) {
requireColor(color, "basicMaterial");
- return new THREE15.MeshBasicMaterial({
+ return new THREE16.MeshBasicMaterial({
color,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
@@ -9109,38 +9365,38 @@ function basicMaterial(color, options = {}) {
}
function glassMaterial(color, options = {}) {
requireColor(color, "glassMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
transparent: true,
opacity: options.opacity ?? 0.35,
roughness: options.roughness ?? 0.1,
metalness: options.metalness ?? 0,
- side: THREE15.DoubleSide
+ side: THREE16.DoubleSide
});
}
function lambertMaterial(color, options = {}) {
requireColor(color, "lambertMaterial");
- return new THREE15.MeshLambertMaterial({
+ return new THREE16.MeshLambertMaterial({
color,
flatShading: options.flatShading ?? true,
emissive: options.emissive ?? 0
});
}
function threeInterpolation(mode) {
- return mode === "STEP" ? THREE15.InterpolateDiscrete : THREE15.InterpolateLinear;
+ return mode === "STEP" ? THREE16.InterpolateDiscrete : THREE16.InterpolateLinear;
}
function rotationTrack(jointName, keyframes, interpolation) {
const times = [];
const values = [];
- const euler = new THREE15.Euler;
- const quat = new THREE15.Quaternion;
+ const euler = new THREE16.Euler;
+ const quat = new THREE16.Quaternion;
for (const kf of keyframes) {
times.push(kf.time);
- euler.set(THREE15.MathUtils.degToRad(kf.rotation[0]), THREE15.MathUtils.degToRad(kf.rotation[1]), THREE15.MathUtils.degToRad(kf.rotation[2]));
+ euler.set(THREE16.MathUtils.degToRad(kf.rotation[0]), THREE16.MathUtils.degToRad(kf.rotation[1]), THREE16.MathUtils.degToRad(kf.rotation[2]));
quat.setFromEuler(euler);
values.push(quat.x, quat.y, quat.z, quat.w);
}
- return new THREE15.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
+ return new THREE16.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
}
function positionTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -9149,7 +9405,7 @@ function positionTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.position);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
}
function scaleTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -9158,10 +9414,10 @@ function scaleTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.scale);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
}
function createClip(name, duration, tracks) {
- return new THREE15.AnimationClip(name, duration, tracks);
+ return new THREE16.AnimationClip(name, duration, tracks);
}
function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {
const y = 0;
@@ -9211,12 +9467,12 @@ function createInstance(name, source, options = {}) {
if (!sourceMesh) {
throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);
}
- const mesh = new THREE15.Mesh(sourceMesh.geometry, sourceMesh.material);
+ const mesh = new THREE16.Mesh(sourceMesh.geometry, sourceMesh.material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.parent)
@@ -9460,7 +9716,7 @@ function buildSandboxGlobals(usage, options = {}) {
countMaterials: wrap("countMaterials", countMaterials),
getJointNames: wrap("getJointNames", getJointNames),
validateAsset: wrap("validateAsset", validateAsset),
- THREE: THREE15,
+ THREE: THREE16,
Math,
console
};
@@ -9988,7 +10244,7 @@ var init_registry = __esm(() => {
});
// src/qa/material.ts
-import * as THREE16 from "three";
+import * as THREE17 from "three";
function textureMeta(texture) {
return texture.userData["kilnTexture"];
}
@@ -10036,7 +10292,7 @@ function validateTextureSlot(findings, mesh, material, texture, slot, expected)
if (!texture)
return;
const meta = textureMeta(texture);
- const actual = texture.colorSpace === THREE16.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE16.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
+ const actual = texture.colorSpace === THREE17.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE17.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
if (!meta || !encodedTextureIsExportable(texture)) {
findings.push({
code: "MAT_TEXTURE_DECODE_FAILED",
@@ -10137,7 +10393,7 @@ function validateMaterial2(mesh, material, requiresPrecomputedTangents) {
}
if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {
const validMask = standard.alphaTest > 0 && !standard.transparent;
- if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE16.DoubleSide || !mesh.geometry.getAttribute("uv")) {
+ if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE17.DoubleSide || !mesh.geometry.getAttribute("uv")) {
findings.push({
code: "MAT_FOLIAGE_CARD_CONTRACT",
disposition: "block",
@@ -10251,14 +10507,14 @@ var init_architecture_repairs = __esm(() => {
});
// src/qa/architecture.ts
-import * as THREE17 from "three";
+import * as THREE18 from "three";
function semanticMetadata(node) {
return readSemanticMetadataV1FromExtras(node.userData);
}
function markerBounds(matrix) {
const bounds = emptyBounds();
for (let corner = 0;corner < 8; corner++) {
- expandBounds(bounds, new THREE17.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
+ expandBounds(bounds, new THREE18.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
}
return bounds;
}
@@ -10267,7 +10523,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const local = geometry.boundingBox;
if (!local)
return;
- const size = local.getSize(new THREE17.Vector3);
+ const size = local.getSize(new THREE18.Vector3);
const dimensions = [
["x", size.x],
["y", size.y],
@@ -10277,7 +10533,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const axis = dimensions[0]?.[0];
if (!axis)
return;
- const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
+ const normal = new THREE18.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
if (normal.y < 0)
normal.multiplyScalar(-1);
return normal.normalize();
@@ -10289,7 +10545,7 @@ function geometryEvidence(geometry, relativeMatrix) {
if (position?.itemSize !== 3)
return { bounds, vertices, triangles: [] };
for (let index = 0;index < position.count; index++) {
- const point = new THREE17.Vector3(position.getX(index), position.getY(index), position.getZ(index));
+ const point = new THREE18.Vector3(position.getX(index), position.getY(index), position.getZ(index));
point.applyMatrix4(relativeMatrix);
vertices.push(point);
expandBounds(bounds, point);
@@ -10316,7 +10572,7 @@ function geometryEvidence(geometry, relativeMatrix) {
return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };
}
function collectArchitectureEvidence(scene) {
- if (!(scene instanceof THREE17.Object3D))
+ if (!(scene instanceof THREE18.Object3D))
return;
scene.updateMatrixWorld(true);
const rootInverse = scene.matrixWorld.clone().invert();
@@ -10334,7 +10590,7 @@ function collectArchitectureEvidence(scene) {
const nodePath = parentPath ? `${parentPath}/${segment}` : segment;
const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);
const mesh = node;
- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE17.BufferGeometry;
+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE18.BufferGeometry;
const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {
bounds: markerBounds(relativeMatrix),
vertices: [],
@@ -10393,7 +10649,7 @@ function architectureFinding(context, value) {
function averageNormal(normals) {
if (normals.length === 0)
return;
- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE17.Vector3);
+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE18.Vector3);
return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;
}
function intervalCoverage(min, max, expectedMin, expectedMax) {
@@ -11102,8 +11358,8 @@ function evaluateArchitectureQa(context) {
];
}
var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({
- min: new THREE17.Vector3(Infinity, Infinity, Infinity),
- max: new THREE17.Vector3(-Infinity, -Infinity, -Infinity)
+ min: new THREE18.Vector3(Infinity, Infinity, Infinity),
+ max: new THREE18.Vector3(-Infinity, -Infinity, -Infinity)
}), expandBounds = (bounds, point) => {
bounds.min.min(point);
bounds.max.max(point);
@@ -11193,7 +11449,7 @@ var init_character_repairs = __esm(() => {
});
// src/qa/character.ts
-import * as THREE18 from "three";
+import * as THREE19 from "three";
function isClipLike(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -11431,7 +11687,7 @@ function contactFindings(intent, root) {
const tolerance = Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0 ? trusted.contactTolerance : CONTACT_TOLERANCE;
const findings = [];
for (const contact of contacts) {
- const point = contact.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(rootInverse);
+ const point = contact.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(rootInverse);
if (point.y > tolerance) {
findings.push(block(intent, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`, {
dimension: "categoryReadiness",
@@ -11692,13 +11948,13 @@ function declaredHeldItem(nodes) {
function characterJointScale(root) {
root.updateMatrixWorld(true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE18.Box3;
+ const bounds = new THREE19.Box3;
for (const joint of collectCharacterJointNodes(root)) {
- bounds.expandByPoint(joint.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse));
+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse));
}
if (bounds.isEmpty())
return 1;
- const size = bounds.getSize(new THREE18.Vector3);
+ const size = bounds.getSize(new THREE19.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function heldItemMotionFindings(intent, root, clips) {
@@ -11734,8 +11990,8 @@ function heldItemMotionFindings(intent, root, clips) {
if (!cloneItem || !cloneAttachment)
continue;
const inverse = clone.matrixWorld.clone().invert();
- const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
- const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
+ const itemPoint = cloneItem.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
+ const gripPoint = cloneAttachment.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
const distance = itemPoint.distanceTo(gripPoint);
baseline ??= distance;
const drift = Math.abs(distance - baseline);
@@ -11768,7 +12024,7 @@ function heldItemMotionFindings(intent, root, clips) {
function evaluateCharacterQa(context) {
if (context.intent.category !== "character")
return [];
- const root = context.scene instanceof THREE18.Object3D ? context.scene : undefined;
+ const root = context.scene instanceof THREE19.Object3D ? context.scene : undefined;
const clips = (context.clips ?? []).filter(isClipLike);
const findings = [];
if (root) {
@@ -11807,7 +12063,7 @@ var init_character2 = __esm(() => {
});
// src/qa/character-advisory.ts
-import * as THREE19 from "three";
+import * as THREE20 from "three";
function isClipLike2(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -11833,16 +12089,16 @@ function jointPoints(root) {
const inverse = rootInverse(root);
return collectCharacterJointNodes(root).map((evidence) => ({
evidence,
- local: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse)
+ local: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse)
}));
}
function characterScale(points) {
if (points.length === 0)
return 1;
- const bounds = new THREE19.Box3;
+ const bounds = new THREE20.Box3;
for (const point of points)
bounds.expandByPoint(point.local);
- const size = bounds.getSize(new THREE19.Vector3);
+ const size = bounds.getSize(new THREE20.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function pairKey(descriptor) {
@@ -11941,12 +12197,12 @@ function restChainFindings(context, root) {
}
function forwardMarkerFindings(context, root) {
root.updateMatrixWorld(true);
- const expected = new THREE19.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
+ const expected = new THREE20.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));
return markers.flatMap((marker) => {
- const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);
- const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
- const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));
+ const quaternion = marker.node.getWorldQuaternion(new THREE20.Quaternion);
+ const actual = new THREE20.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
+ const angle = THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(actual.dot(expected), -1, 1)));
if (angle <= FORWARD_ANGLE_DEGREES)
return [];
return [
@@ -12000,7 +12256,7 @@ function sampleClip(root, clip) {
byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [
evidence.descriptor.role,
{
- point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),
+ point: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse),
evidence
}
]))
@@ -12112,12 +12368,12 @@ function phaseOppositionFindings(context, root, clips) {
return findings;
}
function signedBendDegrees(descriptor, quaternion) {
- const rest = new THREE19.Quaternion(...descriptor.rest.rotation);
+ const rest = new THREE20.Quaternion(...descriptor.rest.rotation);
const delta = rest.invert().multiply(quaternion).normalize();
- const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);
- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));
+ const axis = new THREE20.Vector3(delta.x, delta.y, delta.z);
+ const signedMagnitude = axis.dot(new THREE20.Vector3(...descriptor.localBendAxis));
const angle = 2 * Math.atan2(signedMagnitude, delta.w);
- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
+ return THREE20.MathUtils.radToDeg(THREE20.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
}
function bendDirectionFindings(context, root, clips) {
const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));
@@ -12131,7 +12387,7 @@ function bendDirectionFindings(context, root, clips) {
let maximumFraction = 0;
for (const fraction of SAMPLE_FRACTIONS) {
const value = track.createInterpolant().evaluate(fraction * clip.duration);
- const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());
+ const bend = signedBendDegrees(joint.descriptor, new THREE20.Quaternion().fromArray(value).normalize());
if (Math.abs(bend) > Math.abs(maximum)) {
maximum = bend;
maximumFraction = fraction;
@@ -12214,7 +12470,7 @@ function footSlideFindings(context, root, clips) {
return findings;
}
function evaluateCharacterAdvisoryQa(context) {
- if (context.intent.category !== "character" || !(context.scene instanceof THREE19.Object3D)) {
+ if (context.intent.category !== "character" || !(context.scene instanceof THREE20.Object3D)) {
return [];
}
const root = context.scene;
@@ -12497,7 +12753,7 @@ var EPSILON3 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value
];
// src/qa/vehicle-advisory.ts
-import * as THREE20 from "three";
+import * as THREE21 from "three";
function advisory2(context, value) {
return {
...value,
@@ -12571,7 +12827,7 @@ function isFender(node) {
return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);
}
function isChassisMesh(node) {
- if (!(node instanceof THREE20.Mesh) || isFender(node))
+ if (!(node instanceof THREE21.Mesh) || isFender(node))
return false;
return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);
}
@@ -12579,10 +12835,10 @@ function objectBoundsInFrame2(object, frame) {
object.updateWorldMatrix(true, true);
frame.updateWorldMatrix(true, false);
const worldToFrame = frame.matrixWorld.clone().invert();
- const bounds = new THREE20.Box3;
+ const bounds = new THREE21.Box3;
let found = false;
object.traverse((part) => {
- if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))
+ if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -12592,7 +12848,7 @@ function objectBoundsInFrame2(object, frame) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -12603,15 +12859,15 @@ function tuple(value) {
}
function probeBox(id, root, bounds) {
root.updateWorldMatrix(true, false);
- const center = bounds.getCenter(new THREE20.Vector3).applyMatrix4(root.matrixWorld);
- const size = bounds.getSize(new THREE20.Vector3);
- const position = new THREE20.Vector3;
- const quaternion = new THREE20.Quaternion;
- const scale = new THREE20.Vector3;
+ const center = bounds.getCenter(new THREE21.Vector3).applyMatrix4(root.matrixWorld);
+ const size = bounds.getSize(new THREE21.Vector3);
+ const position = new THREE21.Vector3;
+ const quaternion = new THREE21.Quaternion;
+ const scale = new THREE21.Vector3;
root.matrixWorld.decompose(position, quaternion, scale);
- const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
- const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
- const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
+ const xAxis = new THREE21.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
+ const yAxis = new THREE21.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
+ const zAxis = new THREE21.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
return createOrientedProbeBox3({
id,
frame: createProbeLocalFrame3({
@@ -12680,7 +12936,7 @@ function orientationFindings(context, root, intent) {
const bounds = wholeAssetBounds(root);
if (!bounds)
return [];
- const size = bounds.getSize(new THREE20.Vector3);
+ const size = bounds.getSize(new THREE21.Vector3);
const ratio = size.z / Math.max(size.x, 0.000000001);
if (ratio <= ORIENTATION_RATIO)
return [];
@@ -12724,13 +12980,13 @@ function weldedBoundaryEdges(root, loop) {
let triangleCount = 0;
const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");
loop.traverse((node) => {
- if (!(node instanceof THREE20.Mesh) || !(node.geometry instanceof THREE20.BufferGeometry))
+ if (!(node instanceof THREE21.Mesh) || !(node.geometry instanceof THREE21.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (!positions)
return;
const matrix = inverse.clone().multiply(node.matrixWorld);
- const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE21.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
const index = node.geometry.getIndex();
const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);
for (let offset = 0;offset + 2 < indices.length; offset += 3) {
@@ -12800,7 +13056,7 @@ function trackProfileFindings(context, root, intent) {
const wheelBounds = objectBoundsInFrame2(roadWheel, root);
if (!wheelBounds)
continue;
- const center = wheelBounds.getCenter(new THREE20.Vector3);
+ const center = wheelBounds.getCenter(new THREE21.Vector3);
if (expanded.containsPoint(center))
continue;
const clamped = center.clone().clamp(expanded.min, expanded.max);
@@ -12826,7 +13082,7 @@ function trackProfileFindings(context, root, intent) {
return findings;
}
function evaluateVehicleAdvisoryQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE20.Object3D)) {
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D)) {
return [];
}
const intent = context.intent.vehicle;
@@ -12864,7 +13120,7 @@ var init_vehicle_advisory = __esm(() => {
});
// src/qa/vehicle.ts
-import * as THREE21 from "three";
+import * as THREE22 from "three";
function finding(context, value) {
return {
...value,
@@ -12881,7 +13137,7 @@ function rootAxis(root, axis) {
return axis.clone().transformDirection(root.matrixWorld);
}
function angleDegrees(a, b) {
- return THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
+ return THREE22.MathUtils.radToDeg(Math.acos(THREE22.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
}
function isDescendant(node, ancestor) {
let current = node;
@@ -12929,7 +13185,7 @@ function wheelCountFindings(context, intent, wheels) {
}
function wheelGeometryFindings(context, root, wheels) {
const findings = [];
- const expectedAxle = rootAxis(root, new THREE21.Vector3(0, 0, 1));
+ const expectedAxle = rootAxis(root, new THREE22.Vector3(0, 0, 1));
for (const wheel of wheels) {
const disposition = componentDisposition(wheel);
const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);
@@ -13118,7 +13374,7 @@ function contactFindings2(context, root, intent, wheels) {
function renderableMinYInRoot(rootInverse, node) {
let minimum = Infinity;
node.traverse((part) => {
- if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
+ if (!(part instanceof THREE22.Mesh) || !(part.geometry instanceof THREE22.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const bounds = part.geometry.boundingBox;
@@ -13128,7 +13384,7 @@ function renderableMinYInRoot(rootInverse, node) {
for (const x of [bounds.min.x, bounds.max.x]) {
for (const y of [bounds.min.y, bounds.max.y]) {
for (const z of [bounds.min.z, bounds.max.z]) {
- minimum = Math.min(minimum, new THREE21.Vector3(x, y, z).applyMatrix4(matrix).y);
+ minimum = Math.min(minimum, new THREE22.Vector3(x, y, z).applyMatrix4(matrix).y);
}
}
}
@@ -13148,7 +13404,7 @@ function supportContactFindings(context, root, intent) {
if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {
explicitContacts.push({
node,
- contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
+ contactY: localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
source: "contact"
});
}
@@ -13228,7 +13484,7 @@ function steeringFindings(context, root, intent, wheels) {
return [];
root.updateWorldMatrix(true, false);
const inverse = root.matrixWorld.clone().invert();
- const expectedAxis = rootAxis(root, new THREE21.Vector3(0, 1, 0));
+ const expectedAxis = rootAxis(root, new THREE22.Vector3(0, 1, 0));
const localCenters = wheels.map((wheel) => ({
wheel,
center: localPoint2(inverse, wheel.centerWorld)
@@ -13238,8 +13494,8 @@ function steeringFindings(context, root, intent, wheels) {
const findings = [];
for (const { wheel } of targets) {
const steering = wheel.steeringPivot;
- const centerDelta = steering ? localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
- const axisAngle = steering ? angleDegrees(new THREE21.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
+ const centerDelta = steering ? localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
+ const axisAngle = steering ? angleDegrees(new THREE22.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {
const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;
findings.push(finding(context, {
@@ -13294,14 +13550,14 @@ function propulsionFindings(context, root, intent) {
}
for (const component of candidates) {
const pivot = pivots.get(component.id);
- const box = new THREE21.Box3().setFromObject(component.node);
- const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);
- const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
+ const box = new THREE22.Box3().setFromObject(component.node);
+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE22.Vector3);
+ const pivotCenter = pivot ? new THREE22.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;
const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";
const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);
- const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);
- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE21.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
+ const canonicalAxis = kind === "rotor" ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(1, 0, 0);
+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE22.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {
findings.push(finding(context, {
code: "VEH_ROTOR_PIVOT",
@@ -13323,7 +13579,7 @@ function propulsionFindings(context, root, intent) {
return findings;
}
function evaluateVehicleQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D))
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE22.Object3D))
return [];
const intent = context.intent.vehicle;
if (!intent)
@@ -13387,7 +13643,7 @@ var init_vehicle2 = __esm(() => {
});
// src/qa/vegetation.ts
-import * as THREE22 from "three";
+import * as THREE23 from "three";
function rolesOf(node) {
return readSemanticMetadataV1(node)?.roles ?? [];
}
@@ -13403,21 +13659,21 @@ function pathOf(node, root) {
return names.reverse().join("/");
}
function localPoint3(rootInverse, node) {
- return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);
+ return node.getWorldPosition(new THREE23.Vector3).applyMatrix4(rootInverse);
}
function meshLocalBox(mesh, rootInverse) {
- if (!(mesh.geometry instanceof THREE22.BufferGeometry))
+ if (!(mesh.geometry instanceof THREE23.BufferGeometry))
return;
mesh.geometry.computeBoundingBox();
const source = mesh.geometry.boundingBox;
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(mesh.matrixWorld);
- const result = new THREE22.Box3;
+ const result = new THREE23.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -13428,7 +13684,7 @@ function collectRenderableBounds(root) {
const inverse = root.matrixWorld.clone().invert();
const values = [];
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (!box)
@@ -13446,7 +13702,7 @@ function vegetationIntent(intent) {
}
function evaluateVegetationContactQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.grounded || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.grounded || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
root.updateWorldMatrix(true, true);
@@ -13483,7 +13739,7 @@ function evaluateVegetationContactQa(context) {
}
const findings = [];
for (const contact of contacts) {
- const contactPoint = contact.frameTranslation ? new THREE22.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
+ const contactPoint = contact.frameTranslation ? new THREE23.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
const y = contactPoint.y;
if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS)
continue;
@@ -13511,7 +13767,7 @@ function evaluateVegetationContactQa(context) {
for (const support of semanticSupports) {
let minimumY = Infinity;
support.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (box)
@@ -13539,25 +13795,25 @@ function evaluateVegetationContactQa(context) {
return findings;
}
function materialNames(node) {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return [];
const materials = Array.isArray(node.material) ? node.material : [node.material];
return materials.filter(Boolean).map((material) => material.name ?? "");
}
function evaluateVegetationScopeQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.standalone || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.standalone || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
const renderables = collectRenderableBounds(root);
if (renderables.length === 0)
return [];
- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const overallSize = overall.getSize(new THREE22.Vector3);
+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const overallSize = overall.getSize(new THREE23.Vector3);
const findings = [];
for (const value of renderables) {
- const size = value.box.getSize(new THREE22.Vector3);
- const center = value.box.getCenter(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
+ const center = value.box.getCenter(new THREE23.Vector3);
const names = [value.node.name, ...value.roles];
const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));
const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));
@@ -13594,8 +13850,8 @@ function evaluateVegetationScopeQa(context) {
function unionVolume(boxes) {
if (boxes.length === 0)
return 0;
- const union = boxes.reduce((result, box) => result.union(box), new THREE22.Box3);
- const size = union.getSize(new THREE22.Vector3);
+ const union = boxes.reduce((result, box) => result.union(box), new THREE23.Box3);
+ const size = union.getSize(new THREE23.Vector3);
return size.x * size.y * size.z;
}
function projectedOccupancy(boxes, axes) {
@@ -13665,7 +13921,7 @@ function boxDistanceToPoint(box, point) {
function endpointRadius(position, axis, axisValue, tolerance, scale) {
const radialAxes = [0, 1, 2].filter((value) => value !== axis);
const points = [];
- const point = new THREE22.Vector3;
+ const point = new THREE23.Vector3;
for (let index = 0;index < position.count; index++) {
point.fromBufferAttribute(position, index);
if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)
@@ -13673,7 +13929,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
}
if (points.length === 0)
return;
- const center = new THREE22.Vector3;
+ const center = new THREE23.Vector3;
center.setComponent(axis, axisValue);
for (const radialAxis of radialAxes) {
center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);
@@ -13687,7 +13943,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
return { center, radius };
}
function growthNodeMeasurement(root, candidate, allCandidates, band) {
- if (!(candidate.node instanceof THREE22.Mesh))
+ if (!(candidate.node instanceof THREE23.Mesh))
return;
const geometry = candidate.node.geometry;
const position = geometry.getAttribute("position");
@@ -13699,9 +13955,9 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {
return;
root.updateWorldMatrix(true, true);
const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);
- const relativeScale = new THREE22.Vector3;
- relative.decompose(new THREE22.Vector3, new THREE22.Quaternion, relativeScale);
- const size = geometryBox.getSize(new THREE22.Vector3);
+ const relativeScale = new THREE23.Vector3;
+ relative.decompose(new THREE23.Vector3, new THREE23.Quaternion, relativeScale);
+ const size = geometryBox.getSize(new THREE23.Vector3);
const scaledSizes = [
Math.abs(size.x * relativeScale.x),
Math.abs(size.y * relativeScale.y),
@@ -13768,7 +14024,7 @@ function measureVegetationGrowth(intent, root) {
};
}
function evaluateVegetationGrowthQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationGrowth(context.intent, context.scene);
const findings = [];
@@ -13819,7 +14075,7 @@ function measureVegetationFoliageAttachment(root) {
const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));
const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));
const clusters = foliage.map((value) => {
- const size = value.box.getSize(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));
const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];
const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";
@@ -13842,7 +14098,7 @@ function measureVegetationFoliageAttachment(root) {
};
}
function evaluateVegetationFoliageAttachmentQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {
code: "VEG_FOLIAGE_DETACHED",
@@ -13862,9 +14118,9 @@ function evaluateVegetationFoliageAttachmentQa(context) {
}
function relativeTransformSignature(root, node) {
const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
- const scale = new THREE22.Vector3;
- const quaternion = new THREE22.Quaternion;
- matrix.decompose(new THREE22.Vector3, quaternion, scale);
+ const scale = new THREE23.Vector3;
+ const quaternion = new THREE23.Quaternion;
+ matrix.decompose(new THREE23.Vector3, quaternion, scale);
if (quaternion.w < 0)
quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);
const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));
@@ -13885,9 +14141,9 @@ function measureVegetationRepetition(intent, root) {
nodes: values.map((value) => value.node.name || "foliage-cluster").sort()
})).sort((a, b) => a.signature.localeCompare(b.signature));
const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));
- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const centers = foliage.map((value) => value.box.getCenter(new THREE22.Vector3));
- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE22.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE22.Vector3);
+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const centers = foliage.map((value) => value.box.getCenter(new THREE23.Vector3));
+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE23.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE23.Vector3);
const radial = centers.map((value) => ({
angle: Math.atan2(value.z - center.z, value.x - center.x),
radius: Math.hypot(value.x - center.x, value.z - center.z)
@@ -13922,7 +14178,7 @@ function measureVegetationRepetition(intent, root) {
};
}
function evaluateVegetationRepetitionQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationRepetition(context.intent, context.scene);
if (measured.suppressedForTopiary)
@@ -13981,7 +14237,7 @@ function measureVegetationCanopy(intent, root) {
}
function evaluateVegetationCanopyQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted || !(context.scene instanceof THREE23.Object3D))
return [];
const measurements = measureVegetationCanopy(context.intent, context.scene);
const bands = PROFILE_BANDS[measurements.profile];
@@ -14042,7 +14298,7 @@ function evaluateVegetationCanopyQa(context) {
return findings;
}
function materialValue(material) {
- if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {
+ if (!(material instanceof THREE23.MeshStandardMaterial) && !(material instanceof THREE23.MeshBasicMaterial)) {
return;
}
const color = material.color;
@@ -14052,11 +14308,11 @@ function measureVegetationFoliageMaterials(intent, root) {
const values = [];
let foliageNodeCount = 0;
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const bounds = {
node,
- box: new THREE22.Box3,
+ box: new THREE23.Box3,
roles: rolesOf(node),
source: rolesOf(node).length > 0 ? "semantic" : "fallback"
};
@@ -14083,7 +14339,7 @@ function measureVegetationFoliageMaterials(intent, root) {
};
}
function evaluateVegetationMaterialQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationFoliageMaterials(context.intent, context.scene);
if (measured.foliageNodeCount === 0 || measured.coherent)
@@ -14219,7 +14475,7 @@ var init_vegetation = __esm(() => {
});
// src/qa/prop.ts
-import * as THREE23 from "three";
+import * as THREE24 from "three";
function finding3(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE3 };
}
@@ -14238,11 +14494,11 @@ function nodePath2(root, node) {
return names.reverse().join("/");
}
function transformedBox(source, transform) {
- const result = new THREE23.Box3;
+ const result = new THREE24.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE24.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -14254,15 +14510,15 @@ function collectParts(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf2(node);
- const renderable = node instanceof THREE23.Mesh;
+ const renderable = node instanceof THREE24.Mesh;
let box;
- if (renderable && node.geometry instanceof THREE23.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE24.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));
}
} else if (roles.length > 0) {
- box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
+ box = transformedBox(new THREE24.Box3(new THREE24.Vector3(-0.5, -0.5, -0.5), new THREE24.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
}
if (box?.isEmpty())
box = undefined;
@@ -14352,14 +14608,14 @@ function legacyArticulationEvidence(context, root) {
});
if (joints.length === 0)
return false;
- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE23.AnimationClip);
+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE24.AnimationClip);
if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)
return true;
const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));
return joints.some((joint) => targets.has(joint));
}
function evaluatePropArticulationQa(context) {
- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE23.Object3D)) {
+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE24.Object3D)) {
return [];
}
const root = context.scene;
@@ -14473,11 +14729,11 @@ function rolePart(parts, expression) {
return parts.find((part) => part.roles.some((role) => expression.test(role)));
}
function interiorUsable(box) {
- const size = box.getSize(new THREE23.Vector3);
+ const size = box.getSize(new THREE24.Vector3);
return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;
}
function evaluatePropContainerQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const explicitlyOpen = context.intent.capabilities.includes("openable");
const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");
@@ -14527,7 +14783,7 @@ function evaluatePropContainerQa(context) {
repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."
}));
} else if (!interiorUsable(interior.box)) {
- const size = interior.box.getSize(new THREE23.Vector3);
+ const size = interior.box.getSize(new THREE24.Vector3);
findings.push(finding3(context, {
code: "PROP_CONTAINER_INTERIOR_UNUSABLE",
disposition: "block",
@@ -14585,21 +14841,21 @@ function evaluatePropContainerQa(context) {
return findings;
}
function horizontalDirection(part, root) {
- if (!(part.node instanceof THREE23.Mesh) || !(part.node.geometry instanceof THREE23.BufferGeometry)) {
+ if (!(part.node instanceof THREE24.Mesh) || !(part.node.geometry instanceof THREE24.BufferGeometry)) {
return;
}
part.node.geometry.computeBoundingBox();
const box = part.node.geometry.boundingBox;
if (!box)
return;
- const size = box.getSize(new THREE23.Vector3);
- const axis = size.x >= size.z ? new THREE23.Vector3(1, 0, 0) : new THREE23.Vector3(0, 0, 1);
+ const size = box.getSize(new THREE24.Vector3);
+ const axis = size.x >= size.z ? new THREE24.Vector3(1, 0, 0) : new THREE24.Vector3(0, 0, 1);
root.updateWorldMatrix(true, true);
- const rootQuaternion = root.getWorldQuaternion(new THREE23.Quaternion).invert();
- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE23.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
+ const rootQuaternion = root.getWorldQuaternion(new THREE24.Quaternion).invert();
+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE24.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
}
function evaluatePropCircularAssemblyQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
@@ -14610,8 +14866,8 @@ function evaluatePropCircularAssemblyQa(context) {
const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));
if (memberParts.length < 3)
return [];
- const centers = memberParts.map((part) => part.box.getCenter(new THREE23.Vector3));
- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE23.Vector3).multiplyScalar(1 / centers.length);
+ const centers = memberParts.map((part) => part.box.getCenter(new THREE24.Vector3));
+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE24.Vector3).multiplyScalar(1 / centers.length);
const members = memberParts.map((part, index) => {
const center = centers[index];
return {
@@ -14650,7 +14906,7 @@ function evaluatePropCircularAssemblyQa(context) {
if (!member.horizontalDirection)
return false;
const radial = member.center.clone().sub(ringCenter).setY(0).normalize();
- const tangent = new THREE23.Vector3(-radial.z, 0, radial.x);
+ const tangent = new THREE24.Vector3(-radial.z, 0, radial.x);
const radialScore = Math.abs(member.horizontalDirection.dot(radial));
const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));
return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;
@@ -14677,15 +14933,15 @@ function evaluatePropCircularAssemblyQa(context) {
return findings;
}
function evaluatePropScalePivotQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
const renderable = parts.filter((part) => part.renderable && part.box);
if (renderable.length === 0)
return [];
- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE23.Box3);
- const size = bounds.getSize(new THREE23.Vector3);
+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE24.Box3);
+ const size = bounds.getSize(new THREE24.Vector3);
const findings = [];
for (const axis of ["x", "y", "z"]) {
const expected = context.intent.bounds?.[axis];
@@ -14732,7 +14988,7 @@ function evaluatePropScalePivotQa(context) {
}
const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));
if (placement) {
- const point = placement.node.getWorldPosition(new THREE23.Vector3);
+ const point = placement.node.getWorldPosition(new THREE24.Vector3);
point.applyMatrix4(root.matrixWorld.clone().invert());
const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;
const verticalDelta = Math.abs(point.y - bounds.min.y);
@@ -14795,7 +15051,7 @@ var init_prop = __esm(() => {
});
// src/qa/part-connectivity.ts
-import * as THREE24 from "three";
+import * as THREE25 from "three";
function collectParts2(root, exempt) {
const parts = [];
root.updateWorldMatrix(true, true);
@@ -14808,7 +15064,7 @@ function collectParts2(root, exempt) {
exempt.push(name);
return;
}
- const box = new THREE24.Box3().setFromObject(mesh);
+ const box = new THREE25.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, box });
@@ -14903,7 +15159,7 @@ var init_part_connectivity = __esm(() => {
owner: KILN_ENGINE_QA_OWNER,
defaultMode: "observe",
evaluate(context) {
- if (!(context.scene instanceof THREE24.Object3D))
+ if (!(context.scene instanceof THREE25.Object3D))
return [];
const report = analyzePartConnectivity(context.scene);
if (report.groups.length === 0)
@@ -14993,7 +15249,7 @@ var init_reference_comparison = __esm(() => {
});
// src/qa/self-intersection.ts
-import * as THREE25 from "three";
+import * as THREE26 from "three";
function triangleCount(geometry) {
const index = geometry.getIndex();
const position = geometry.getAttribute("position");
@@ -15019,7 +15275,7 @@ function collectParts3(root, skipped) {
});
return;
}
- const box = new THREE25.Box3().setFromObject(mesh);
+ const box = new THREE26.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, mesh, box, triangles });
@@ -15032,7 +15288,7 @@ function meshToArrays(mesh) {
if (!position)
return null;
const matrix = mesh.matrixWorld;
- const v = new THREE25.Vector3;
+ const v = new THREE26.Vector3;
const verts = new Float32Array(position.count * 3);
for (let i = 0;i < position.count; i++) {
v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);
@@ -15195,7 +15451,7 @@ var init_self_intersection = __esm(() => {
});
// src/qa/environment.ts
-import * as THREE26 from "three";
+import * as THREE27 from "three";
function finding4(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE4 };
}
@@ -15214,11 +15470,11 @@ function nodePath3(root, node) {
return names.reverse().join("/");
}
function transformedBox2(source, transform) {
- const result = new THREE26.Box3;
+ const result = new THREE27.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -15228,16 +15484,16 @@ function orientedBoxFromLocalBounds(root, node, source) {
const relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
if (!relative.elements.every(Number.isFinite))
return;
- const position = new THREE26.Vector3;
- const rotation = new THREE26.Quaternion;
- const scale = new THREE26.Vector3;
+ const position = new THREE27.Vector3;
+ const rotation = new THREE27.Quaternion;
+ const scale = new THREE27.Vector3;
relative.decompose(position, rotation, scale);
- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);
+ const recomposed = new THREE27.Matrix4().compose(position, rotation, scale);
const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));
if (residual > 0.00001)
return;
- const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);
- const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);
+ const center = source.getCenter(new THREE27.Vector3).applyMatrix4(relative);
+ const sourceHalf = source.getSize(new THREE27.Vector3).multiplyScalar(0.5);
const halfExtents = [
Math.abs(sourceHalf.x * scale.x),
Math.abs(sourceHalf.y * scale.y),
@@ -15258,17 +15514,17 @@ function collectParts4(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf3(node);
- const renderable = node instanceof THREE26.Mesh;
+ const renderable = node instanceof THREE27.Mesh;
let box;
let orientedBox;
let source;
- if (renderable && node.geometry instanceof THREE26.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE27.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
source = node.geometry.boundingBox;
}
} else if (roles.length > 0) {
- source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));
+ source = new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.5), new THREE27.Vector3(0.5, 0.5, 0.5));
}
if (source) {
box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));
@@ -15296,9 +15552,9 @@ function resolveSocket(root, node, socket) {
return;
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();
- const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
+ const point = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rotation = node.getWorldQuaternion(new THREE27.Quaternion).multiply(new THREE27.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
return {
id: socket.id,
type: socket.type,
@@ -15327,7 +15583,7 @@ function socketByType(sockets, type) {
return sockets.find((socket) => socket.type === type);
}
function evaluateEnvironmentSocketQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -15391,7 +15647,7 @@ function materialSignature(material) {
function boundarySamples(root, axis, side, bins = 12) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE26.Box3().setFromObject(root);
+ const bounds = new THREE27.Box3().setFromObject(root);
const localBounds = transformedBox2(bounds, root.matrixWorld.clone().invert());
const edge = side === "negative" ? localBounds.min[axis] : localBounds.max[axis];
const axisExtent = localBounds.max[axis] - localBounds.min[axis];
@@ -15401,22 +15657,22 @@ function boundarySamples(root, axis, side, bins = 12) {
const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);
const byBin = new Map;
root.traverse((node) => {
- if (!(node instanceof THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))
+ if (!(node instanceof THREE27.Mesh) || !(node.geometry instanceof THREE27.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (positions?.itemSize !== 3)
return;
const normals = node.geometry.getAttribute("normal");
const transform = inverse.clone().multiply(node.matrixWorld);
- const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);
+ const normalMatrix = new THREE27.Matrix3().getNormalMatrix(transform);
const material = materialSignature(node.material);
for (let index = 0;index < positions.count; index++) {
- const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
+ const point = new THREE27.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
if (Math.abs(point[axis] - edge) > band)
continue;
- const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
+ const t = THREE27.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
const bin = Math.min(bins - 1, Math.floor(t * bins));
- const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);
+ const normal = normals ? new THREE27.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE27.Vector3(0, 1, 0);
const current = byBin.get(bin);
if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {
byBin.set(bin, { bin, height: point.y, normal, material });
@@ -15438,7 +15694,7 @@ function edgePairMeasurements(root, axis, sockets) {
...positive.map((sample) => sample.bin)
]);
const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;
- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE27.MathUtils.radToDeg(Math.acos(THREE27.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);
const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);
const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);
@@ -15455,7 +15711,7 @@ function edgePairMeasurements(root, axis, sockets) {
};
}
function evaluateEnvironmentTileEdgeQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -15538,7 +15794,7 @@ function isCorridor(part) {
return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));
}
function evaluateEnvironmentNavigabilityQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -15652,7 +15908,7 @@ function functionalLayer(part) {
return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));
}
function evaluateEnvironmentGroundQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -15699,7 +15955,7 @@ function evaluateEnvironmentGroundQa(context) {
}));
}
}
- const size = box.getSize(new THREE26.Vector3);
+ const size = box.getSize(new THREE27.Vector3);
if (box.min.y < -0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {
findings.push(finding4(context, {
code: "ENV_GROUND_UNDECLARED_SKIRT",
@@ -16226,7 +16482,7 @@ var init_breadth2 = __esm(() => {
});
// src/qa/breadth-evidence.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
function record3(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -16248,7 +16504,7 @@ function isAnimationClip(value) {
function localRenderableBox(rootInverse, node) {
if (isSpriteNode(node)) {
const transform = rootInverse.clone().multiply(node.matrixWorld);
- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
+ return new THREE28.Box3(new THREE28.Vector3(-0.5, -0.5, -0.0005), new THREE28.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
}
if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)
return;
@@ -16257,11 +16513,11 @@ function localRenderableBox(rootInverse, node) {
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(node.matrixWorld);
- const result = new THREE27.Box3;
+ const result = new THREE28.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE28.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -16349,10 +16605,10 @@ function isEffectSurface(nodes) {
function coverageRatio(boxes, overall) {
if (boxes.length === 0 || overall.isEmpty())
return 0;
- const overallSize = overall.getSize(new THREE27.Vector3);
+ const overallSize = overall.getSize(new THREE28.Vector3);
const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);
const area = boxes.reduce((sum, box) => {
- const size = box.getSize(new THREE27.Vector3);
+ const size = box.getSize(new THREE28.Vector3);
return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);
}, 0);
return stable7(Math.min(1, area / denominator));
@@ -16361,7 +16617,7 @@ function collectMaterialEvidence(root, intent) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
const byMaterial = new Map;
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (!box || !isMeshNode(node) && !isSpriteNode(node))
@@ -16386,7 +16642,7 @@ function collectMaterialEvidence(root, intent) {
effectSurface: isEffectSurface(value.nodes),
alphaMode: mode,
alphaData: alphaData(material),
- doubleSided: material.side === THREE27.DoubleSide,
+ doubleSided: material.side === THREE28.DoubleSide,
...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},
screenAreaRatio: coverageRatio(value.boxes, overall),
transparentLayers: mode === "blend" ? value.nodes.length : 0,
@@ -16414,23 +16670,23 @@ function dominantGeometryAxis(root, mode) {
const bounds = node.geometry.boundingBox;
if (!bounds || bounds.isEmpty())
return;
- const size = bounds.getSize(new THREE27.Vector3);
+ const size = bounds.getSize(new THREE28.Vector3);
const axes = [
- { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },
- { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },
- { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }
+ { score: size.x, direction: new THREE28.Vector3(1, 0, 0) },
+ { score: size.y, direction: new THREE28.Vector3(0, 1, 0) },
+ { score: size.z, direction: new THREE28.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const relative = inverse.clone().multiply(node.matrixWorld);
const direction = selected.direction.transformDirection(relative);
- const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();
+ const score = selected.score * node.getWorldScale(new THREE28.Vector3).length();
if (!best || (mode === "length" ? score > best.score : score < best.score)) {
best = { score, direction };
}
});
if (best)
return signedAxis(best.direction);
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (box)
@@ -16438,8 +16694,8 @@ function dominantGeometryAxis(root, mode) {
});
if (overall.isEmpty())
return "+X";
- const size = overall.getSize(new THREE27.Vector3);
- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);
+ const size = overall.getSize(new THREE28.Vector3);
+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE28.Vector3(1, 0, 0) : size.y >= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE28.Vector3(1, 0, 0) : size.y <= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1);
return signedAxis(vector);
}
function analyzedFacing(root, intent) {
@@ -16561,21 +16817,21 @@ function pathOf2(root, node) {
function analyzeSockets(root) {
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rootWorldRotation = root.getWorldQuaternion(new THREE28.Quaternion).invert();
const values = [];
root.traverse((node) => {
const metadata = readSemanticMetadataV1(node);
if (!metadata)
return;
- const nodeWorldRotation = node.getWorldQuaternion(new THREE27.Quaternion);
+ const nodeWorldRotation = node.getWorldQuaternion(new THREE28.Quaternion);
for (const socket of metadata.sockets) {
const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);
if (!frame)
continue;
- const frameRotation = new THREE27.Quaternion(...frame.rotation);
+ const frameRotation = new THREE28.Quaternion(...frame.rotation);
const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);
- const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
+ const position = new THREE28.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const normal = new THREE28.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
values.push({
contract: {
id: socket.id,
@@ -16608,8 +16864,8 @@ function analyzeModularEvidenceV1(root, trustedGrid) {
if (!pair)
return { kit };
const relative = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);
- const euler = new THREE27.Euler().setFromQuaternion(relative, "YXZ");
- const rotation = THREE27.MathUtils.euclideanModulo(THREE27.MathUtils.radToDeg(euler.y), 360);
+ const euler = new THREE28.Euler().setFromQuaternion(relative, "YXZ");
+ const rotation = THREE28.MathUtils.euclideanModulo(THREE28.MathUtils.radToDeg(euler.y), 360);
return {
kit,
join: {
@@ -17207,9 +17463,7 @@ var init_run = __esm(() => {
});
// src/qa/breadth-final.ts
-import { WebIO } from "@gltf-transform/core";
-import { EXTMeshGPUInstancing } from "@gltf-transform/extensions";
-import * as THREE28 from "three";
+import * as THREE29 from "three";
function bytesContainAscii(bytes, value) {
const needle = new TextEncoder().encode(value);
outer:
@@ -17268,7 +17522,7 @@ function finalEffectAxis(nodes, mode) {
if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {
continue;
}
- const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());
+ const matrix = new THREE29.Matrix4().fromArray(node.getWorldMatrix());
const scale = node.getWorldScale();
const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
@@ -17278,9 +17532,9 @@ function finalEffectAxis(nodes, mode) {
const min = position.getMin([]);
const max = position.getMax([]);
const axes = [
- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },
- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },
- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }
+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE29.Vector3(1, 0, 0) },
+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE29.Vector3(0, 1, 0) },
+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE29.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const candidate = {
@@ -17295,7 +17549,7 @@ function finalEffectAxis(nodes, mode) {
return best ? signedAxis2(best.direction) : undefined;
}
async function analyzeFinalVfxGlbBytesV1(bytes) {
- const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+ const io = createGltfIO();
const document = await io.readBinary(bytes);
const root = document.getRoot();
const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);
@@ -17531,6 +17785,7 @@ async function appendFinalVfxGlbQa(intent, report, bytes) {
}
var stable8 = (value) => Math.round(value * 1e6) / 1e6;
var init_breadth_final = __esm(() => {
+ init_gltf_io();
init_contracts();
init_types();
});
@@ -19060,7 +19315,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash3 } from "node:crypto";
-import * as THREE29 from "three";
+import * as THREE30 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -19152,7 +19407,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE30.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -19233,10 +19488,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE29.Vector3;
- const t = new THREE29.Vector3;
- const tmp = new THREE29.Vector3;
- const tmp2 = new THREE29.Vector3;
+ const n = new THREE30.Vector3;
+ const t = new THREE30.Vector3;
+ const tmp = new THREE30.Vector3;
+ const tmp2 = new THREE30.Vector3;
for (let v = 0;v < vertexCount; v++) {
n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
@@ -19256,7 +19511,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE30.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -19302,7 +19557,7 @@ var init_texture_bake = __esm(() => {
});
// src/views/character.ts
-import * as THREE30 from "three";
+import * as THREE31 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -19344,9 +19599,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE30.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE31.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE31.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE31.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -21109,24 +21364,18 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive,
- WebIO as WebIO2
+ Primitive
} from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
- KHRMaterialsVariants as KHRMaterialsVariants2,
- KHRTextureBasisu as KHRTextureBasisu2
-} from "@gltf-transform/extensions";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry14,
- Group,
+ Group as Group2,
Matrix4 as Matrix47,
- Mesh as Mesh10,
+ Mesh as Mesh11,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
SRGBColorSpace as SRGBColorSpace5,
- Texture,
+ Texture as Texture2,
AnimationClip as AnimationClip3,
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
@@ -21135,6 +21384,7 @@ import {
} from "three";
var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER;
var init_glb = __esm(() => {
+ init_gltf_io();
GLB_GEOMETRY_FLAT_REASON = {
TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
@@ -21171,10 +21421,22 @@ function validInteger(value, min, max) {
return Number.isInteger(value) && Number(value) >= min && Number(value) <= max;
}
function parseOptions(value) {
- if (!isRecord5(value) || !hasExactKeys(value, ["optimize", "instance", "intent", "category", "geometryPolicy"])) {
+ if (!isRecord5(value) || !hasExactKeys(value, [
+ "optimize",
+ "instance",
+ "intent",
+ "category",
+ "geometryPolicy",
+ "gltfExporter"
+ ])) {
return fail("request");
}
const options = {};
+ if (value.gltfExporter !== undefined) {
+ if (value.gltfExporter !== "legacy" && value.gltfExporter !== "three")
+ fail("request");
+ options.gltfExporter = value.gltfExporter;
+ }
if (value.geometryPolicy !== undefined) {
if (!["warn", "strict"].includes(String(value.geometryPolicy)))
fail("request");
@@ -21323,7 +21585,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE31 from "three";
+import * as THREE32 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -21334,18 +21596,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE32 from "three";
+import * as THREE33 from "three";
function hasRole2(node, prefix) {
return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
}
function chassisBounds(root, inverse) {
- const bounds = new THREE32.Box3;
+ const bounds = new THREE33.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
+ if (!(part instanceof THREE33.Mesh) || !(part.geometry instanceof THREE33.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -21355,7 +21617,7 @@ function chassisBounds(root, inverse) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE33.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -21423,33 +21685,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE32.Vector3(...start);
- const to = new THREE32.Vector3(...end);
+ const from = new THREE33.Vector3(...start);
+ const to = new THREE33.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);
- const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE33.CylinderGeometry(radius, radius, length, 8) : new THREE33.SphereGeometry(radius, 8, 6);
+ const result = new THREE33.Mesh(geometry, new THREE33.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE32.Group;
+ const overlay = new THREE33.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE32.Group;
+ const arrow = new THREE33.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE33.Mesh(new THREE33.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE33.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), new THREE33.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -21457,18 +21719,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE33.Mesh(new THREE33.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE33.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE32.Vector3(...wheel.axle);
+ const axle = new THREE33.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE32.Group;
+ const chassis = new THREE33.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -21502,7 +21764,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE32.Group;
+ const plane = new THREE33.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -21781,7 +22043,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE33 from "three";
+import * as THREE34 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -21818,22 +22080,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE33.Box3().setFromObject(root);
+ const bounds = new THREE34.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE33.Vector3);
- const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
- const upHint = new THREE33.Vector3(0, 1, 0);
- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE34.Vector3(-0.5, 0, -0.5), new THREE34.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE34.Vector3);
+ const camera = cameraId === "front" ? new THREE34.Vector3(1, 0, 0) : new THREE34.Vector3(0, 0, 1);
+ const upHint = new THREE34.Vector3(0, 1, 0);
+ const xAxis = new THREE34.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE34.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
+ const point = new THREE34.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE34.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -21956,14 +22218,74 @@ var init_character_capture = __esm(() => {
init_pose();
});
+// src/exporter-node.ts
+var exports_exporter_node = {};
+__export(exports_exporter_node, {
+ nodeExportPlatform: () => nodeExportPlatform
+});
+async function prepareNodeExport(hasTextures) {
+ const host = globalThis;
+ if (!host["FileReader"])
+ host["FileReader"] = ExportFileReader;
+ if (!hasTextures || host["OffscreenCanvas"] || host["document"])
+ return;
+ const { Canvas, ImageData } = await import("@napi-rs/canvas");
+
+ class ExportCanvas extends Canvas {
+ async convertToBlob(options = {}) {
+ const type = options.type ?? options.mime ?? "image/png";
+ if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")
+ throw new Error(`Unsupported export image type: ${type}`);
+ const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);
+ return new Blob([new Uint8Array(bytes)], { type });
+ }
+ }
+ host["OffscreenCanvas"] = ExportCanvas;
+ if (!host["ImageData"])
+ host["ImageData"] = ImageData;
+}
+
+class ExportFileReader {
+ result = null;
+ error = null;
+ onloadend = null;
+ onerror = null;
+ readAsArrayBuffer(blob) {
+ this.read(blob, false);
+ }
+ readAsDataURL(blob) {
+ this.read(blob, true);
+ }
+ read(blob, dataUrl) {
+ blob.arrayBuffer().then((bytes) => {
+ this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;
+ this.onloadend?.();
+ }, (error) => {
+ this.error = error;
+ this.onerror?.();
+ this.onloadend?.();
+ });
+ }
+}
+var nodeExportPlatform;
+var init_exporter_node = __esm(() => {
+ nodeExportPlatform = {
+ prepare: prepareNodeExport,
+ async decode(bytes) {
+ const { default: sharp } = await import("sharp");
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return {
+ data: new Uint8Array(decoded.data),
+ width: decoded.info.width,
+ height: decoded.info.height
+ };
+ }
+ };
+});
+
// src/render.ts
-import * as THREE34 from "three";
-import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
- KHRMaterialsVariants as KHRMaterialsVariants3,
- KHRTextureBasisu as KHRTextureBasisu3
-} from "@gltf-transform/extensions";
+import * as THREE35 from "three";
+import { Document, getBounds } from "@gltf-transform/core";
import {
dedup,
instance,
@@ -22097,7 +22419,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE34.DoubleSide) {
+ if (stdMat.side === THREE35.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -22166,7 +22488,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE34.DoubleSide)
+ if (threeMat.side === THREE35.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -22219,22 +22541,15 @@ function bridgeGeometry(doc, buf, geometry, material, meshName) {
if (!Array.isArray(material))
return mesh.addPrimitive(prim);
const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
- const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
+ const groups = validateMaterialGroups(geometry, material.length, meshName);
for (const group of groups) {
- if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
- throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
- }
const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
for (const semantic of prim.listSemantics())
part.setAttribute(semantic, prim.getAttribute(semantic));
const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
part.setIndices(doc.createAccessor(`${meshName}_group_indices`).setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
mesh.addPrimitive(part);
- covered += group.count;
}
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
prim.dispose();
return mesh;
}
@@ -22301,7 +22616,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE34.PlaneGeometry(1, 1);
+ const geometry = new THREE35.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -22453,7 +22768,8 @@ async function renderSceneToGLB(root, opts = {}) {
const clips = opts.clips ?? [];
if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
const tris = countTriangles(root);
const intent = opts.intent ?? createAssetIntentV1({
category: isAssetCategory(opts.category) ? opts.category : "prop"
@@ -22487,19 +22803,28 @@ async function renderSceneToGLB(root, opts = {}) {
throw blocked;
warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
}
- const doc = new Document;
+ const doc = exporter === "three" ? await communitySceneDocument(root, clips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform) : new Document;
doc.getRoot().getAsset().generator = "Kiln";
- const buf = doc.createBuffer();
- const matCache = new Map;
- const meshCache = new Map;
- const texCache = new Map;
- const nodeMap = new Map;
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ if (exporter === "legacy") {
+ const buf = doc.createBuffer();
+ const matCache = new Map;
+ const meshCache = new Map;
+ const texCache = new Map;
+ const nodeMap = new Map;
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ } else {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ throw new Error("Community exporter produced no scene.");
+ scene.setName(opts.sceneName ?? "Scene");
+ if (clips.length > 0)
+ scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
}
if (opts.dedup !== false) {
try {
@@ -22619,6 +22944,7 @@ async function renderGLBInProcess(code, opts = {}) {
});
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
+ gltfExporter: opts.gltfExporter,
sceneName: meta.name || "Scene",
geometryPolicy: opts.geometryPolicy,
clips,
@@ -22695,12 +23021,12 @@ function collectMeshStats(root) {
return;
const idx = geo.getIndex();
const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
- const box = new THREE34.Box3().setFromObject(obj);
+ const box = new THREE35.Box3().setFromObject(obj);
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE34.Vector3;
- const size = new THREE34.Vector3;
+ const center = new THREE35.Vector3;
+ const size = new THREE35.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -22715,7 +23041,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE34.Vector3;
+ const v = new THREE35.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -22733,10 +23059,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE34.Box3;
+ const all = new THREE35.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE34.Vector3;
+ const size = new THREE35.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -22797,9 +23123,11 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, PALETTE_MIN = 4, INSTANCE_MIN = 5;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, PALETTE_MIN = 4, INSTANCE_MIN = 5;
var init_render = __esm(() => {
init_authoring_diagnostic();
+ init_gltf_io();
+ init_community_exporter();
init_geometry_export();
init_primitives();
init_contracts();
@@ -22816,6 +23144,7 @@ var init_render = __esm(() => {
init_texture_bake();
init_character_capture();
init_vehicle3();
+ engineIO = createGltfIO;
REVIEW_CLIP_LIMITS = {
clips: 32,
tracks: 256,
diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjs
index e894837d..17cedcf6 100644
--- a/dist/mcp-server.mjs
+++ b/dist/mcp-server.mjs
@@ -4890,7 +4890,238 @@ var init_types = __esm(() => {
];
});
+// src/gltf-io.ts
+import { WebIO } from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+function createGltfIO() {
+ return new WebIO().registerExtensions(ALL_EXTENSIONS);
+}
+var init_gltf_io = () => {};
+
+// src/community-exporter.ts
+import * as THREE from "three";
+import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
+function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
+ if (value === undefined || value === "legacy")
+ return "legacy";
+ if (value === "three")
+ return "three";
+ throw new Error(`Invalid KILN_GLTF_EXPORTER ${JSON.stringify(value)}; use legacy or three.`);
+}
+function cleanClone(source) {
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ return shadow.clone();
+}
+async function communitySceneDocument(root, clips, platform = browserPlatform) {
+ const materials = new Map;
+ const textures = new Map;
+ const nodes = new Map;
+ const encoded = [];
+ function texture(source) {
+ const found = textures.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ normalizeTextureTransform(copy);
+ copy.source = new THREE.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData["encoded"];
+ if (bytes?.bytes) {
+ encoded.push((async () => {
+ copy.image = await platform.decode(bytes.bytes);
+ Object.defineProperty(copy, "isDataTexture", { value: true });
+ copy.format = THREE.RGBAFormat;
+ copy.type = THREE.UnsignedByteType;
+ })());
+ }
+ return copy;
+ }
+ function material(source) {
+ const found = materials.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ const physical = copy;
+ if (physical.isMeshPhysicalMaterial && physical.sheen > 0) {
+ physical.sheenColor.multiplyScalar(physical.sheen);
+ physical.sheen = 1;
+ }
+ for (const [key, value] of Object.entries(copy)) {
+ if (value instanceof THREE.Texture)
+ copy[key] = texture(value);
+ }
+ materials.set(source, copy);
+ return copy;
+ }
+ function node(source) {
+ if (source.isLine || source.isPoints)
+ throw new Error("Experimental glTF exporter supports triangle meshes and sprites, not lines or points.");
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ let copy = shadow.clone(false);
+ if (source.isScene) {
+ copy = new THREE.Group;
+ copy.copy(shadow, false);
+ }
+ if (source.isSprite) {
+ const sprite = source;
+ const geometry = new THREE.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE.MeshBasicMaterial({
+ name: sprite.material.name,
+ color: sprite.material.color,
+ opacity: sprite.material.opacity,
+ transparent: sprite.material.transparent,
+ alphaTest: sprite.material.alphaTest,
+ side: sprite.material.side,
+ map: sprite.material.map ? texture(sprite.material.map) : null
+ });
+ copy = new THREE.Mesh(geometry, spriteMaterial);
+ THREE.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ if (semantic !== undefined) {
+ const checked = validateSemanticMetadataV1(semantic);
+ if (!checked.valid || !checked.value)
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on ${source.name}`);
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(checked.value);
+ }
+ if (source.isSprite) {
+ const metadata = copy.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = createSemanticMetadataV1({
+ ...metadata,
+ roles: [
+ ...(metadata?.roles ?? []).filter((role) => !role.startsWith("vfx.facing.")),
+ "vfx.facing.camera-spherical",
+ ...metadata?.roles.some((role) => role.startsWith("vfx.effect.surface")) ? [] : ["vfx.effect.surface.card"]
+ ]
+ });
+ }
+ if (source.isMesh) {
+ const original = source;
+ const mesh = copy;
+ mesh.geometry = cleanClone(original.geometry);
+ mesh.material = Array.isArray(original.material) ? original.material.map(material) : material(original.material);
+ }
+ nodes.set(source, copy);
+ for (const child of source.children)
+ copy.add(node(child));
+ return copy;
+ }
+ const copy = node(root);
+ for (const [source, target] of nodes) {
+ if (!source.isSkinnedMesh)
+ continue;
+ const original = source;
+ const mesh = target;
+ mesh.skeleton = original.skeleton.clone();
+ mesh.skeleton.bones = original.skeleton.bones.map((bone) => {
+ const mapped = nodes.get(bone);
+ if (!mapped)
+ throw new Error(`Skin bone ${bone.name} is outside the exported hierarchy.`);
+ return mapped;
+ });
+ mesh.bind(mesh.skeleton, original.bindMatrix);
+ }
+ await Promise.all(encoded);
+ await platform.prepare(textures.size > 0);
+ const exportClips = clips.map((clip) => {
+ const cloned = cleanClone(clip);
+ for (const track of cloned.tracks) {
+ for (const [source, target] of nodes) {
+ if (track.name.startsWith(`${source.uuid}.`))
+ track.name = target.uuid + track.name.slice(source.uuid.length);
+ }
+ }
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ } catch {
+ return false;
+ }
+ });
+ return cloned;
+ });
+ const bytes = await new GLTFExporter().parseAsync(copy, {
+ binary: true,
+ trs: true,
+ onlyVisible: false,
+ animations: exportClips.filter((clip) => clip.tracks.length > 0)
+ });
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(new Uint8Array(bytes));
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name)
+ continue;
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name)
+ image.name = binding.name;
+ }
+ return io.readJSON(json);
+}
+function normalizeTextureTransform(texture) {
+ if (texture.matrixAutoUpdate)
+ texture.updateMatrix();
+ const e = texture.matrix.elements;
+ const sx = Math.hypot(e[0], e[1]);
+ const rotation = sx > 0 ? Math.atan2(-e[1], e[0]) : Math.atan2(e[3], e[4]);
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ const sy = e[3] * s + e[4] * c;
+ const reconstructed = [sx * c, -sx * s, 0, sy * s, sy * c, 0, e[6], e[7], 1];
+ const tolerance = 0.0000001 * Math.max(1, ...e.map(Math.abs));
+ if (e.some((value, i) => !Number.isFinite(value) || Math.abs(value - reconstructed[i]) > tolerance)) {
+ throw new Error(`Texture ${texture.name || "<unnamed>"}: UV matrix contains shear or perspective that KHR_texture_transform cannot represent; lossless UV baking is not yet qualified.`);
+ }
+ texture.offset.set(e[6], e[7]);
+ texture.repeat.set(sx, sy);
+ texture.rotation = rotation;
+ texture.center.set(0, 0);
+ texture.matrixAutoUpdate = false;
+}
+var browserPlatform;
+var init_community_exporter = __esm(() => {
+ init_gltf_io();
+ init_contracts();
+ browserPlatform = {
+ async prepare() {},
+ async decode(bytes) {
+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]), {
+ colorSpaceConversion: "none"
+ });
+ try {
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("A 2D canvas is required to decode export textures.");
+ context.drawImage(bitmap, 0, 0);
+ const image = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ return { data: new Uint8Array(image.data), width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ }
+ };
+});
+
// src/geometry-export.ts
+function validateMaterialGroups(geometry, materialCount, name) {
+ const length = geometry.getIndex()?.count ?? geometry.getAttribute("position").count;
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ const materialIndex = group.materialIndex ?? 0;
+ if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > length || !Number.isInteger(materialIndex) || materialIndex < 0 || materialIndex >= materialCount)
+ throw new TypeError(`${name}: material groups must cover every triangle exactly once with valid material indices.`);
+ covered = group.start + group.count;
+ }
+ if (covered !== length)
+ throw new TypeError(`${name}: material groups do not cover every triangle.`);
+ return groups;
+}
function geometryAttributeValues(attribute) {
const values = new Float32Array(attribute.count * attribute.itemSize);
for (let vertex = 0;vertex < attribute.count; vertex++) {
@@ -4900,7 +5131,7 @@ function geometryAttributeValues(attribute) {
}
return values;
}
-function inspectGeometryExport(root, policy = "warn") {
+function inspectGeometryExport(root, policy = "warn", exporter = "legacy") {
const warnings = [];
root.traverse((node) => {
const mesh = node;
@@ -4918,7 +5149,14 @@ function inspectGeometryExport(root, policy = "warn") {
if (position?.itemSize !== 3)
throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];
+ const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key] ?? (exporter === "three" ? {
+ color: attribute.itemSize === 4 ? 4 : 3,
+ uv1: 2,
+ uv2: 2,
+ uv3: 2,
+ skinIndex: 4,
+ skinWeight: 4
+ }[key] : undefined);
if (expected === undefined) {
unsupported(key);
continue;
@@ -4944,10 +5182,14 @@ function inspectGeometryExport(root, policy = "warn") {
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
- for (const key of Object.keys(geometry.morphAttributes))
- unsupported(`morph ${key}`);
- if (mesh.isSkinnedMesh)
- unsupported("skinning");
+ if (exporter === "three" && Array.isArray(mesh.material))
+ validateMaterialGroups(geometry, mesh.material.length, name);
+ if (exporter === "legacy") {
+ for (const key of Object.keys(geometry.morphAttributes))
+ unsupported(`morph ${key}`);
+ if (mesh.isSkinnedMesh)
+ unsupported("skinning");
+ }
for (const key of ["kilnAttributeWarnings", "kilnGeometryWarnings"]) {
const notes = geometry.userData[key];
if (!Array.isArray(notes))
@@ -5081,7 +5323,7 @@ var dE2 = (a, b) => {
}, chroma = (lab) => Math.hypot(lab[1], lab[2]), REL_CHROMA_GATE = 0.04, relChroma = (lab) => chroma(lab) / Math.max(lab[0], 0.25);
// src/character.ts
-import * as THREE from "three";
+import * as THREE2 from "three";
function validRole(value) {
return typeof value === "string" && /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(value);
}
@@ -5362,7 +5604,7 @@ function readCharacterRigGraphV1(target) {
return result.valid ? result.value : undefined;
}
function axisQuaternion(from, to) {
- const value = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(...from), new THREE.Vector3(...to));
+ const value = new THREE2.Quaternion().setFromUnitVectors(new THREE2.Vector3(...from), new THREE2.Vector3(...to));
return [value.x, value.y, value.z, value.w];
}
function stampCharacterJointDescriptorV1(target, input) {
@@ -5467,7 +5709,7 @@ function createJointChain(chainName, segments, options = {}) {
endEffector: segment.endEffector,
contact: segment.contact
});
- const node = new THREE.Object3D;
+ const node = new THREE2.Object3D;
node.name = characterJointNodeName(chainName, segment.role);
node.position.fromArray(descriptor.rest.translation);
node.quaternion.fromArray(descriptor.rest.rotation);
@@ -5609,7 +5851,7 @@ var init_character = __esm(() => {
});
// src/architecture.ts
-import * as THREE2 from "three";
+import * as THREE3 from "three";
function positive(value, name) {
if (!Number.isFinite(value) || value <= 0)
throw new RangeError(`${name} must be finite and > 0`);
@@ -5674,17 +5916,17 @@ function buildFace(roofRoot, profile, sideSign) {
const verticalRun = profile.ridgeY - profile.eaveY;
const downhillLength = Math.hypot(horizontalRun, verticalRun);
const alongRidge = (profile.ridgeAxis === "x" ? profile.spanX : profile.spanZ) + profile.overhang * 2;
- const downhill = profile.ridgeAxis === "x" ? new THREE2.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE2.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
- const tangent = profile.ridgeAxis === "x" ? new THREE2.Vector3(sideSign, 0, 0) : new THREE2.Vector3(0, 0, -sideSign);
+ const downhill = profile.ridgeAxis === "x" ? new THREE3.Vector3(0, -verticalRun, sideSign * horizontalRun).normalize() : new THREE3.Vector3(sideSign * horizontalRun, -verticalRun, 0).normalize();
+ const tangent = profile.ridgeAxis === "x" ? new THREE3.Vector3(sideSign, 0, 0) : new THREE3.Vector3(0, 0, -sideSign);
const normal = downhill.clone().cross(tangent).normalize();
- const localToRoof = new THREE2.Matrix4().makeBasis(tangent, normal, downhill);
+ const localToRoof = new THREE3.Matrix4().makeBasis(tangent, normal, downhill);
localToRoof.setPosition(0, profile.ridgeY, 0);
const world = () => {
roofRoot.updateWorldMatrix(true, false);
return roofRoot.matrixWorld.clone().multiply(localToRoof);
};
const direction = (axis) => axis.clone().transformDirection(world());
- const point = (x, z) => new THREE2.Vector3(x, 0, z).applyMatrix4(world());
+ const point = (x, z) => new THREE3.Vector3(x, 0, z).applyMatrix4(world());
return {
side,
ridgeAxis: profile.ridgeAxis,
@@ -5694,13 +5936,13 @@ function buildFace(roofRoot, profile, sideSign) {
return world();
},
get ridgeTangent() {
- return direction(new THREE2.Vector3(1, 0, 0));
+ return direction(new THREE3.Vector3(1, 0, 0));
},
get downhillDirection() {
- return direction(new THREE2.Vector3(0, 0, 1));
+ return direction(new THREE3.Vector3(0, 0, 1));
},
get outwardNormal() {
- return direction(new THREE2.Vector3(0, 1, 0));
+ return direction(new THREE3.Vector3(0, 1, 0));
},
get ridgeStart() {
return point(-alongRidge / 2, 0);
@@ -5718,17 +5960,17 @@ function buildFace(roofRoot, profile, sideSign) {
};
}
function buildRoof(name, material, profile, parent) {
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
if (parent)
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "assembly")], [relationship("separable-from", "architecture.shell.gable")]));
const faces = [buildFace(root, profile, 1), buildFace(root, profile, -1)];
const buildSlope = (face) => {
- const geometry = new THREE2.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
- const mesh = new THREE2.Mesh(geometry, material);
+ const geometry = new THREE3.BoxGeometry(face.dimensions.alongRidge, profile.thickness, face.dimensions.downhill);
+ const mesh = new THREE3.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${face.side}`;
- const center = new THREE2.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
+ const center = new THREE3.Matrix4().makeTranslation(0, -profile.thickness / 2, face.dimensions.downhill / 2);
setTransform(mesh, face.localToRoof.clone().multiply(center));
const coveredWall = profile.ridgeAxis === "x" ? face.side === "positive" ? "wall.right" : "wall.left" : face.side === "positive" ? "wall.front" : "wall.back";
stampSemanticMetadataV1(mesh, roleMetadata([semanticRole(KILN_SEMANTIC_ROLES.roof, "slope", face.side)], [
@@ -5798,7 +6040,7 @@ function createGableEndPanel(name, material, options) {
const ridgeAxis = options.ridgeAxis ?? "x";
const side = options.side ?? "positive";
const half = span / 2;
- const shape = new THREE2.Shape;
+ const shape = new THREE3.Shape;
shape.moveTo(-half, 0);
shape.lineTo(half, 0);
shape.lineTo(0, rise);
@@ -5817,7 +6059,7 @@ function createGableEndPanel(name, material, options) {
const right = opening.offset + opening.width / 2;
const bottom = opening.bottom;
const top = bottom + opening.height;
- const hole = new THREE2.Path;
+ const hole = new THREE3.Path;
hole.moveTo(left, bottom);
hole.lineTo(left, top);
hole.lineTo(right, top);
@@ -5825,7 +6067,7 @@ function createGableEndPanel(name, material, options) {
hole.closePath();
shape.holes.push(hole);
}
- const geometry = new THREE2.ExtrudeGeometry(shape, {
+ const geometry = new THREE3.ExtrudeGeometry(shape, {
depth: thickness,
bevelEnabled: false,
steps: 1
@@ -5834,7 +6076,7 @@ function createGableEndPanel(name, material, options) {
if (ridgeAxis === "x")
geometry.rotateY(-Math.PI / 2);
geometry.computeVertexNormals();
- const root = new THREE2.Mesh(geometry, material);
+ const root = new THREE3.Mesh(geometry, material);
root.name = `Mesh_${name}`;
stampSemanticMetadataV1(root, roleMetadata([`roof.gable.${side}`], [
relationship("adjacent-to", "roof.slope.positive"),
@@ -5850,7 +6092,7 @@ function createGableEndPanel(name, material, options) {
}
]));
const markers = normalized.map((opening, index) => {
- const marker = new THREE2.Object3D;
+ const marker = new THREE3.Object3D;
marker.name = `Opening_${name}_${opening.id ?? index + 1}`;
marker.position.set(ridgeAxis === "z" ? opening.offset : 0, opening.bottom + opening.height / 2, ridgeAxis === "x" ? opening.offset : 0);
marker.scale.set(ridgeAxis === "x" ? thickness : opening.width, opening.height, ridgeAxis === "x" ? opening.width : thickness);
@@ -5870,7 +6112,7 @@ function wallNeighbors(wall) {
}
function createShellWall(name, wall, material, length, height, thickness, openings) {
const axis = wallRunAxis(wall);
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = `${name}_Wall_${wall}`;
const neighbors = wallNeighbors(wall);
stampSemanticMetadataV1(root, roleMetadata([`wall.${wall}`], [
@@ -5893,8 +6135,8 @@ function createShellWall(name, wall, material, length, height, thickness, openin
const panel = (suffix, lo, hi, y0, y1) => {
if (hi - lo <= EPSILON || y1 - y0 <= EPSILON)
return;
- const geometry = axis === "x" ? new THREE2.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE2.BoxGeometry(thickness, y1 - y0, hi - lo);
- const mesh = new THREE2.Mesh(geometry, material);
+ const geometry = axis === "x" ? new THREE3.BoxGeometry(hi - lo, y1 - y0, thickness) : new THREE3.BoxGeometry(thickness, y1 - y0, hi - lo);
+ const mesh = new THREE3.Mesh(geometry, material);
mesh.name = `Mesh_${name}_${wall}_${suffix}`;
mesh.position.set(axis === "x" ? (lo + hi) / 2 : 0, (y0 + y1) / 2, axis === "z" ? (lo + hi) / 2 : 0);
root.add(mesh);
@@ -5914,7 +6156,7 @@ function createShellWall(name, wall, material, length, height, thickness, openin
panel("lintel", left, right, top, height);
if (opening.sill > 0)
panel("sill", left, right, 0, opening.sill);
- const marker = new THREE2.Object3D;
+ const marker = new THREE3.Object3D;
marker.name = `Opening_${wall}_${opening.id}`;
marker.position.set(axis === "x" ? opening.offset : 0, opening.sill + opening.height / 2, axis === "z" ? opening.offset : 0);
marker.scale.set(axis === "x" ? opening.width : opening.depth, opening.height, axis === "z" ? opening.width : opening.depth);
@@ -5937,7 +6179,7 @@ function createGableShell(name, materials, options) {
const closedEnds = options.closedEnds ?? true;
const enterable = options.enterable ?? true;
const shellOpenings = options.openings ?? (enterable ? [{ wall: "front", kind: "door" }] : []);
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
if (options.parent)
options.parent.add(root);
@@ -5957,7 +6199,7 @@ function createGableShell(name, materials, options) {
walls[wall] = built.root;
openingMarkers.push(...built.openings);
}
- const floor = new THREE2.Mesh(new THREE2.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
+ const floor = new THREE3.Mesh(new THREE3.BoxGeometry(spanX, floorThickness, spanZ), materials.floor ?? materials.wall);
floor.name = `Mesh_${name}_Floor`;
floor.position.y = -floorThickness / 2;
stampSemanticMetadataV1(floor, roleMetadata(["floor"], ["front", "back", "left", "right"].map((wall) => relationship("adjacent-to", `wall.${wall}`))));
@@ -6003,7 +6245,7 @@ function createGableShell(name, materials, options) {
}
function createRoofSurfaceLayout(name, material, options) {
const parent = options.parent ?? options.face.roofRoot;
- const root = new THREE2.Object3D;
+ const root = new THREE3.Object3D;
root.name = name;
parent.add(root);
stampSemanticMetadataV1(root, roleMetadata([`roof.surface.${options.kind}`], [relationship("coverage-of", `roof.slope.${options.face.side}`)]));
@@ -6055,9 +6297,9 @@ function createRoofSurfaceLayout(name, material, options) {
});
}
const items = specs.map((spec, index) => {
- const mesh = new THREE2.Mesh(new THREE2.BoxGeometry(spec.width, thickness, spec.length), material);
+ const mesh = new THREE3.Mesh(new THREE3.BoxGeometry(spec.width, thickness, spec.length), material);
mesh.name = `Mesh_${name}_${index + 1}`;
- const local = new THREE2.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
+ const local = new THREE3.Matrix4().makeTranslation(spec.x, thickness / 2 + 0.002, spec.z);
setTransform(mesh, faceToRoot.clone().multiply(local));
root.add(mesh);
return mesh;
@@ -6071,7 +6313,7 @@ var init_architecture = __esm(() => {
});
// src/gears.ts
-import * as THREE3 from "three";
+import * as THREE4 from "three";
function gearGeo(opts = {}) {
const {
teeth = 12,
@@ -6165,8 +6407,8 @@ function gearGeo(opts = {}) {
indices.push(tA, bA, bB);
indices.push(tA, bB, tB);
}
- const geo = new THREE3.BufferGeometry;
- geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));
+ const geo = new THREE4.BufferGeometry;
+ geo.setAttribute("position", new THREE4.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -6254,8 +6496,8 @@ function bladeGeo(opts = {}) {
}
}
}
- const geo = new THREE3.BufferGeometry;
- geo.setAttribute("position", new THREE3.Float32BufferAttribute(positions, 3));
+ const geo = new THREE4.BufferGeometry;
+ geo.setAttribute("position", new THREE4.Float32BufferAttribute(positions, 3));
geo.setIndex(indices);
const nonIndexed = geo.toNonIndexed();
nonIndexed.computeVertexNormals();
@@ -6266,7 +6508,7 @@ var init_gears = __esm(() => {
});
// src/ops.ts
-import * as THREE4 from "three";
+import * as THREE5 from "three";
import { LoopSubdivision } from "three-subdivide/build/index.module.js";
import { mergeVertices as threeMergeVertices } from "three/examples/jsm/utils/BufferGeometryUtils.js";
function arrayLinear(namePrefix, source, count, offset, parent) {
@@ -6286,19 +6528,19 @@ function arrayLinear(namePrefix, source, count, offset, parent) {
}
function degreesOf(euler) {
return [
- THREE4.MathUtils.radToDeg(euler.x),
- THREE4.MathUtils.radToDeg(euler.y),
- THREE4.MathUtils.radToDeg(euler.z)
+ THREE5.MathUtils.radToDeg(euler.x),
+ THREE5.MathUtils.radToDeg(euler.y),
+ THREE5.MathUtils.radToDeg(euler.z)
];
}
function arrayRadial(namePrefix, source, count, axis = "y", parent, center) {
const out = [];
- const pivot = center ? new THREE4.Vector3(...center) : new THREE4.Vector3;
+ const pivot = center ? new THREE5.Vector3(...center) : new THREE5.Vector3;
const basePos = source.position.clone().sub(pivot);
- const axisVec = axis === "x" ? new THREE4.Vector3(1, 0, 0) : axis === "z" ? new THREE4.Vector3(0, 0, 1) : new THREE4.Vector3(0, 1, 0);
+ const axisVec = axis === "x" ? new THREE5.Vector3(1, 0, 0) : axis === "z" ? new THREE5.Vector3(0, 0, 1) : new THREE5.Vector3(0, 1, 0);
for (let i = 1;i < count; i++) {
const angle = i / count * Math.PI * 2;
- const m = new THREE4.Matrix4().makeRotationAxis(axisVec, angle);
+ const m = new THREE5.Matrix4().makeRotationAxis(axisVec, angle);
const rotated = basePos.clone().applyMatrix4(m).add(pivot);
const eulerDeg = axis === "y" ? [0, angle * 180 / Math.PI, 0] : axis === "x" ? [angle * 180 / Math.PI, 0, 0] : [0, 0, angle * 180 / Math.PI];
out.push(createInstance(`${namePrefix}${i}`, source, {
@@ -6327,25 +6569,25 @@ function mergeVertices(geometry, opts = {}) {
const { tolerance = 0.0001, positionOnly = false } = typeof opts === "number" ? { tolerance: opts } : opts;
if (!positionOnly)
return threeMergeVertices(geometry, tolerance);
- const stripped = new THREE4.BufferGeometry;
+ const stripped = new THREE5.BufferGeometry;
const pos = geometry.getAttribute("position");
if (!pos)
return geometry;
- stripped.setAttribute("position", new THREE4.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
+ stripped.setAttribute("position", new THREE5.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized));
if (geometry.index) {
- stripped.setIndex(new THREE4.BufferAttribute(new Uint32Array(geometry.index.array), 1));
+ stripped.setIndex(new THREE5.BufferAttribute(new Uint32Array(geometry.index.array), 1));
}
return threeMergeVertices(stripped, tolerance);
}
function subdivide(geometry, iterations = 1, opts = {}) {
const { weld = true, preserveUV = false, ...subOpts } = opts;
const input = weld && !preserveUV ? mergeVertices(geometry, { positionOnly: true }) : geometry.clone();
- const center = new THREE4.Vector3;
+ const center = new THREE5.Vector3;
let normalizationScale = 1;
if (preserveUV) {
subOpts.uvSmooth = false;
input.computeBoundingBox();
- const extent = input.boundingBox.getSize(new THREE4.Vector3);
+ const extent = input.boundingBox.getSize(new THREE5.Vector3);
input.boundingBox.getCenter(center);
const size = Math.max(extent.x, extent.y, extent.z);
normalizationScale = size > 0 ? 1e4 / size : 1;
@@ -6379,9 +6621,9 @@ function subdivide(geometry, iterations = 1, opts = {}) {
return output;
}
function curveToMesh(points, radius, tubularSegments = 32, radialSegments = 8, closed = false) {
- const vectors = points.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
- const curve = new THREE4.CatmullRomCurve3(vectors, closed);
- return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = points.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE5.CatmullRomCurve3(vectors, closed);
+ return new THREE5.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function normalizeSurfaceNormals(geo) {
const normal = geo.getAttribute("normal");
@@ -6408,20 +6650,20 @@ function normalizeSurfaceNormals(geo) {
return geo;
}
function lathe(profile, segments = 12) {
- const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));
- return normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments));
+ const points2d = profile.map((p) => new THREE5.Vector2(p[0], p[1]));
+ return normalizeSurfaceNormals(new THREE5.LatheGeometry(points2d, segments));
}
function revolveGeo(profile, options = {}) {
const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
- const points2d = profile.map((p) => new THREE4.Vector2(p[0], p[1]));
- const geo = normalizeSurfaceNormals(new THREE4.LatheGeometry(points2d, segments, 0, angle));
- const n = new THREE4.Vector3(axis[0], axis[1], axis[2]);
+ const points2d = profile.map((p) => new THREE5.Vector2(p[0], p[1]));
+ const geo = normalizeSurfaceNormals(new THREE5.LatheGeometry(points2d, segments, 0, angle));
+ const n = new THREE5.Vector3(axis[0], axis[1], axis[2]);
if (n.lengthSq() < 0.000000000001) {
throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(",")}]).`);
}
n.normalize();
if (n.x !== 0 || n.y !== 1 || n.z !== 0) {
- const q = new THREE4.Quaternion().setFromUnitVectors(new THREE4.Vector3(0, 1, 0), n);
+ const q = new THREE5.Quaternion().setFromUnitVectors(new THREE5.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
}
return geo;
@@ -6436,9 +6678,9 @@ function pipeAlongPath(points, radius, options = {}) {
const smoothed = [];
smoothed.push(points[0]);
for (let i = 1;i < points.length - 1; i++) {
- const prev = new THREE4.Vector3(...points[i - 1]);
- const cur = new THREE4.Vector3(...points[i]);
- const next = new THREE4.Vector3(...points[i + 1]);
+ const prev = new THREE5.Vector3(...points[i - 1]);
+ const cur = new THREE5.Vector3(...points[i]);
+ const next = new THREE5.Vector3(...points[i + 1]);
const inDir = cur.clone().sub(prev);
const outDir = next.clone().sub(cur);
const inLen = inDir.length();
@@ -6453,17 +6695,17 @@ function pipeAlongPath(points, radius, options = {}) {
smoothed.push(points[points.length - 1]);
pathPoints = smoothed;
}
- const vectors = pathPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
- const curve = new THREE4.CatmullRomCurve3(vectors, closed);
- return new THREE4.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+ const vectors = pathPoints.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE5.CatmullRomCurve3(vectors, closed);
+ return new THREE5.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
}
function bezierCurve(controlPoints, samples = 32) {
- const vecs = controlPoints.map((p) => new THREE4.Vector3(p[0], p[1], p[2]));
+ const vecs = controlPoints.map((p) => new THREE5.Vector3(p[0], p[1], p[2]));
let curve;
if (vecs.length === 3) {
- curve = new THREE4.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
+ curve = new THREE5.QuadraticBezierCurve3(vecs[0], vecs[1], vecs[2]);
} else if (vecs.length === 4) {
- curve = new THREE4.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
+ curve = new THREE5.CubicBezierCurve3(vecs[0], vecs[1], vecs[2], vecs[3]);
} else {
throw new Error(`bezierCurve: need 3 or 4 control points, got ${vecs.length}`);
}
@@ -6474,7 +6716,7 @@ var init_ops = __esm(() => {
});
// src/geometry.ts
-import * as THREE5 from "three";
+import * as THREE6 from "three";
function finiteArray(values, label, length) {
const result = Array.from(values);
if (length !== undefined && result.length !== length)
@@ -6488,8 +6730,8 @@ function meshGeo(data) {
if (positions.length < 9 || positions.length % 3)
throw new Error("meshGeo positions: need at least three xyz vertices");
const count = positions.length / 3;
- const geometry = new THREE5.BufferGeometry;
- geometry.setAttribute("position", new THREE5.Float32BufferAttribute(positions, 3));
+ const geometry = new THREE6.BufferGeometry;
+ geometry.setAttribute("position", new THREE6.Float32BufferAttribute(positions, 3));
if (data.indices) {
const indices = Array.from(data.indices);
if (!indices.length || indices.length % 3)
@@ -6501,7 +6743,7 @@ function meshGeo(data) {
throw new Error("meshGeo: non-indexed positions must form complete triangles");
if (data.normals) {
const normals = finiteArray(data.normals, "meshGeo normals", count * 3);
- geometry.setAttribute("normal", new THREE5.Float32BufferAttribute(normals, 3));
+ geometry.setAttribute("normal", new THREE6.Float32BufferAttribute(normals, 3));
for (let i = 0;i < count; i++)
if (Math.hypot(normals[i * 3], normals[i * 3 + 1], normals[i * 3 + 2]) === 0)
throw new Error("meshGeo normals: zero-length normal");
@@ -6509,14 +6751,14 @@ function meshGeo(data) {
} else
geometry.computeVertexNormals();
if (data.uvs)
- geometry.setAttribute("uv", new THREE5.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
+ geometry.setAttribute("uv", new THREE6.Float32BufferAttribute(finiteArray(data.uvs, "meshGeo uvs", count * 2), 2));
if (data.tangents) {
const tangents = finiteArray(data.tangents, "meshGeo tangents", count * 4);
for (let i = 0;i < count; i++) {
if (Math.abs(Math.hypot(tangents[i * 4], tangents[i * 4 + 1], tangents[i * 4 + 2]) - 1) > 0.0001 || Math.abs(tangents[i * 4 + 3]) !== 1)
throw new Error("meshGeo tangents: expected unit xyz and handedness +1 or -1");
}
- geometry.setAttribute("tangent", new THREE5.Float32BufferAttribute(tangents, 4));
+ geometry.setAttribute("tangent", new THREE6.Float32BufferAttribute(tangents, 4));
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
@@ -6551,7 +6793,7 @@ function geometryDiagnostics(geometry, tolerance = 0.000001) {
}
const indices = geometry.index ? Array.from(geometry.index.array) : Array.from({ length: p.count }, (_, i) => i);
const edges = new Map;
- const a = new THREE5.Vector3, b = new THREE5.Vector3, c = new THREE5.Vector3;
+ const a = new THREE6.Vector3, b = new THREE6.Vector3, c = new THREE6.Vector3;
for (let i = 0;i < indices.length; i += 3) {
result.triangles++;
const triangle = indices.slice(i, i + 3);
@@ -6655,8 +6897,8 @@ function parametricSurface(sample, options = {}) {
const sums = new Map;
for (let i = 0;i < normal.count; i++) {
const id = find(i);
- const sum = sums.get(id) ?? new THREE5.Vector3;
- sum.add(new THREE5.Vector3().fromBufferAttribute(normal, i));
+ const sum = sums.get(id) ?? new THREE6.Vector3;
+ sum.add(new THREE6.Vector3().fromBufferAttribute(normal, i));
sums.set(id, sum);
}
for (let i = 0;i < normal.count; i++) {
@@ -6675,7 +6917,7 @@ function creaseNormals(geometry, options = {}) {
if (position?.itemSize !== 3 || position.count % 3 !== 0)
throw new Error("creaseNormals requires complete xyz triangles");
out.computeBoundingBox();
- const diagonal = out.boundingBox.getSize(new THREE5.Vector3).length();
+ const diagonal = out.boundingBox.getSize(new THREE6.Vector3).length();
const tolerance = options.tolerance ?? Math.max(diagonal * 0.00000001, 0.000000000001);
if (!Number.isFinite(tolerance) || tolerance <= 0)
throw new Error("creaseNormals tolerance must be positive and finite");
@@ -6683,13 +6925,13 @@ function creaseNormals(geometry, options = {}) {
const keys = [];
const faces = [];
for (let i = 0;i < position.count; i += 3) {
- const a = new THREE5.Vector3().fromBufferAttribute(position, i);
- const b = new THREE5.Vector3().fromBufferAttribute(position, i + 1);
- const c = new THREE5.Vector3().fromBufferAttribute(position, i + 2);
+ const a = new THREE6.Vector3().fromBufferAttribute(position, i);
+ const b = new THREE6.Vector3().fromBufferAttribute(position, i + 1);
+ const c = new THREE6.Vector3().fromBufferAttribute(position, i + 2);
const face = b.sub(a).cross(c.sub(a)).normalize();
faces.push(face);
for (let j = i;j < i + 3; j++) {
- const point = new THREE5.Vector3().fromBufferAttribute(position, j);
+ const point = new THREE6.Vector3().fromBufferAttribute(position, j);
if (![point.x, point.y, point.z].every(Number.isFinite))
throw new Error("creaseNormals positions must be finite");
const key = point.toArray().map((n) => Math.round(n / tolerance)).join(",");
@@ -6700,15 +6942,15 @@ function creaseNormals(geometry, options = {}) {
}
}
const normals = new Float32Array(position.count * 3);
- const threshold = Math.cos(THREE5.MathUtils.degToRad(angle));
+ const threshold = Math.cos(THREE6.MathUtils.degToRad(angle));
for (let i = 0;i < position.count; i++) {
- const face = faces[Math.floor(i / 3)], sum = new THREE5.Vector3;
+ const face = faces[Math.floor(i / 3)], sum = new THREE6.Vector3;
for (const other of adjacent.get(keys[i]))
if (face.dot(faces[other]) >= threshold - 0.000000000001)
sum.add(faces[other]);
sum.normalize().toArray(normals, i * 3);
}
- out.setAttribute("normal", new THREE5.BufferAttribute(normals, 3));
+ out.setAttribute("normal", new THREE6.BufferAttribute(normals, 3));
out.deleteAttribute("tangent");
out.computeBoundingSphere();
return out;
@@ -6718,19 +6960,19 @@ var init_geometry = __esm(() => {
});
// src/deform.ts
-import * as THREE6 from "three";
+import * as THREE7 from "three";
function geometryFrameMatrix(frame = {}) {
const origin = frame.origin ?? [0, 0, 0], rotation = frame.rotation ?? [0, 0, 0];
if (origin.length !== 3 || rotation.length !== 3 || ![...origin, ...rotation].every(Number.isFinite))
throw new Error("geometry frame requires finite xyz origin and rotation");
- return new THREE6.Matrix4().compose(new THREE6.Vector3(...origin), new THREE6.Quaternion().setFromEuler(new THREE6.Euler(...rotation.map(THREE6.MathUtils.degToRad), "XYZ")), new THREE6.Vector3(1, 1, 1));
+ return new THREE7.Matrix4().compose(new THREE7.Vector3(...origin), new THREE7.Quaternion().setFromEuler(new THREE7.Euler(...rotation.map(THREE7.MathUtils.degToRad), "XYZ")), new THREE7.Vector3(1, 1, 1));
}
function deform(geometry, options, map) {
const source = geometry.getAttribute("position");
if (source?.itemSize !== 3 || source.count === 0)
throw new Error("deformation requires nonempty xyz positions");
const matrix = geometryFrameMatrix(options.frame), inverse = matrix.clone().invert();
- const points = Array.from({ length: source.count }, (_, i) => new THREE6.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
+ const points = Array.from({ length: source.count }, (_, i) => new THREE7.Vector3().fromBufferAttribute(source, i).applyMatrix4(inverse));
if (points.some((p) => ![p.x, p.y, p.z].every(Number.isFinite)))
throw new Error("deformation positions must be finite");
let low = Infinity, high = -Infinity;
@@ -6751,7 +6993,7 @@ function deform(geometry, options, map) {
const epsilon = Math.max(1, Math.abs(low), Math.abs(high)) * 0.0000001;
if (point.y < low - epsilon || point.y > high + epsilon)
continue;
- const t = length > epsilon ? THREE6.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
+ const t = length > epsilon ? THREE7.MathUtils.clamp((point.y - low) / length, 0, 1) : 0;
const weight = options.falloff?.(t) ?? 1;
if (!Number.isFinite(weight) || weight < 0 || weight > 1)
throw new Error("deformation falloff must return a finite weight between 0 and 1");
@@ -6773,41 +7015,41 @@ function deform(geometry, options, map) {
function twist(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("twist angle must be finite degrees");
- return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE6.Vector3(0, 1, 0), THREE6.MathUtils.degToRad(options.angle) * t));
+ return deform(geometry, options, (p, t) => p.applyAxisAngle(new THREE7.Vector3(0, 1, 0), THREE7.MathUtils.degToRad(options.angle) * t));
}
function bend(geometry, options) {
if (!Number.isFinite(options.angle))
throw new Error("bend angle must be finite degrees");
- const angle = THREE6.MathUtils.degToRad(options.angle);
+ const angle = THREE7.MathUtils.degToRad(options.angle);
return deform(geometry, options, (p, t, low, length) => {
if (Math.abs(angle) < 0.0000000001 || length === 0)
return p;
const radius = length / angle, theta = angle * t;
- return new THREE6.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
+ return new THREE7.Vector3(radius - (radius - p.x) * Math.cos(theta), low + (radius - p.x) * Math.sin(theta), p.z);
});
}
function taper(geometry, options) {
const start = options.startScale ?? [1, 1], end = options.endScale;
if (start.length !== 2 || end.length !== 2 || ![...start, ...end].every((n) => Number.isFinite(n) && n > 0))
throw new Error("taper scales must be two finite positive values");
- return deform(geometry, options, (p, t) => p.set(p.x * THREE6.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE6.MathUtils.lerp(start[1], end[1], t)));
+ return deform(geometry, options, (p, t) => p.set(p.x * THREE7.MathUtils.lerp(start[0], end[0], t), p.y, p.z * THREE7.MathUtils.lerp(start[1], end[1], t)));
}
function displace(geometry, offset, options = {}) {
return deform(geometry, options, (p, t) => {
const delta = offset([p.x, p.y, p.z], t);
if (delta.length !== 3 || !delta.every(Number.isFinite))
throw new Error("displace callback must return three finite offsets");
- return p.add(new THREE6.Vector3(...delta));
+ return p.add(new THREE7.Vector3(...delta));
});
}
var init_deform = () => {};
// src/sweep.ts
-import * as THREE7 from "three";
+import * as THREE8 from "three";
function profilePoints(profile) {
if (profile.length < 3 || profile.some((p) => p.length !== 2 || !p.every(Number.isFinite)))
throw new Error("profile requires at least three finite xy points");
- const points = profile.map((p) => new THREE7.Vector2(...p));
+ const points = profile.map((p) => new THREE8.Vector2(...p));
if (points[0].distanceTo(points[points.length - 1]) < 0.0000000001)
points.pop();
if (points.length < 3)
@@ -6825,7 +7067,7 @@ function profilePoints(profile) {
throw new Error("profile self-intersects or touches itself");
}
}
- const area = THREE7.ShapeUtils.area(points);
+ const area = THREE8.ShapeUtils.area(points);
if (Math.abs(area) < 0.000000000001)
throw new Error("profile area must be nonzero");
if (area < 0)
@@ -6834,7 +7076,7 @@ function profilePoints(profile) {
}
function buildLoft(rings, profiles, closed, cap) {
const n = rings[0].length, positions = [], uvs = [], indices = [];
- const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE7.Vector3).multiplyScalar(1 / n));
+ const centers = rings.map((r) => r.reduce((sum, p) => sum.add(p), new THREE8.Vector3).multiplyScalar(1 / n));
const lengths = [0];
for (let i = 1;i < centers.length; i++)
lengths.push(lengths[i - 1] + centers[i].distanceTo(centers[i - 1]));
@@ -6859,13 +7101,13 @@ function buildLoft(rings, profiles, closed, cap) {
for (const station of [0, rings.length - 1]) {
const ring = rings[station], profile = profiles[station];
const start = positions.length / 3;
- const bounds = new THREE7.Box2().setFromPoints(profile);
- const size = bounds.getSize(new THREE7.Vector2);
+ const bounds = new THREE8.Box2().setFromPoints(profile);
+ const size = bounds.getSize(new THREE8.Vector2);
for (let j = 0;j < n; j++) {
positions.push(...ring[j].toArray());
uvs.push((profile[j].x - bounds.min.x) / (size.x || 1), (profile[j].y - bounds.min.y) / (size.y || 1));
}
- for (const tri of THREE7.ShapeUtils.triangulateShape(profile, [])) {
+ for (const tri of THREE8.ShapeUtils.triangulateShape(profile, [])) {
if (station === 0)
indices.push(...tri.map((j) => start + j));
else
@@ -6876,14 +7118,14 @@ function buildLoft(rings, profiles, closed, cap) {
const normal = out.getAttribute("normal");
for (let i = 0;i < rings.length; i++) {
const a = i * (n + 1), b = a + n;
- const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE8.Vector3().fromBufferAttribute(normal, a).add(new THREE8.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
if (closed)
for (let j = 0;j <= n; j++) {
const a = j, b = (rings.length - 1) * (n + 1) + j;
- const sum = new THREE7.Vector3().fromBufferAttribute(normal, a).add(new THREE7.Vector3().fromBufferAttribute(normal, b)).normalize();
+ const sum = new THREE8.Vector3().fromBufferAttribute(normal, a).add(new THREE8.Vector3().fromBufferAttribute(normal, b)).normalize();
normal.setXYZ(a, sum.x, sum.y, sum.z);
normal.setXYZ(b, sum.x, sum.y, sum.z);
}
@@ -6897,7 +7139,7 @@ function loftProfiles(sections, options = {}) {
throw new Error("loftProfiles sections must have the same point count and correspondence");
const rings = sections.map((section, i) => {
const frame = geometryFrameMatrix(section.frame);
- return profiles[i].map((p) => new THREE7.Vector3(p.x, 0, p.y).applyMatrix4(frame));
+ return profiles[i].map((p) => new THREE8.Vector3(p.x, 0, p.y).applyMatrix4(frame));
});
const out = buildLoft(rings, profiles, false, options.cap ?? true);
out.userData.kilnGeometryWarnings = [
@@ -6916,7 +7158,7 @@ function sweepProfile(profile, path, options = {}) {
throw new Error("closed sweep twist must be a multiple of 360 degrees");
if (path.length < (closed ? 3 : 2) || path.some((p) => p.length !== 3 || !p.every(Number.isFinite)))
throw new Error("sweepProfile requires finite path points (two open or three closed)");
- const stations = path.map((p) => new THREE7.Vector3(...p));
+ const stations = path.map((p) => new THREE8.Vector3(...p));
if (closed && stations[0].distanceTo(stations[stations.length - 1]) < 0.0000000001)
throw new Error("closed sweep path should omit its repeated endpoint");
const segments = [];
@@ -6953,7 +7195,7 @@ function sweepProfile(profile, path, options = {}) {
});
if (Array.isArray(options.scale) && options.scale.length !== stations.length)
throw new Error("sweepProfile scale needs one pair per path station");
- const up = options.up ? new THREE7.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE7.Vector3(0, 0, 1) : new THREE7.Vector3(1, 0, 0);
+ const up = options.up ? new THREE8.Vector3(...options.up) : Math.abs(tangents[0].z) < 0.9 ? new THREE8.Vector3(0, 0, 1) : new THREE8.Vector3(1, 0, 0);
if (![up.x, up.y, up.z].every(Number.isFinite) || up.lengthSq() < 0.00000000000000000001)
throw new Error("sweepProfile up must be a finite nonzero vector");
let z = up.clone().addScaledVector(tangents[0], -up.dot(tangents[0]));
@@ -6968,7 +7210,7 @@ function sweepProfile(profile, path, options = {}) {
}
const distances = [0];
for (let i = 1;i < stations.length; i++) {
- z = z.clone().applyQuaternion(new THREE7.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
+ z = z.clone().applyQuaternion(new THREE8.Quaternion().setFromUnitVectors(tangents[i - 1], tangents[i]));
normals.push(z);
distances.push(distances[i - 1] + stations[i].distanceTo(stations[i - 1]));
}
@@ -6978,7 +7220,7 @@ function sweepProfile(profile, path, options = {}) {
correction = Math.atan2(tangents[0].dot(normals[normals.length - 1].clone().cross(normals[0])), normals[normals.length - 1].dot(normals[0]));
const rings = stations.map((station, i) => {
const tangent = tangents[i], t = distances[i] / total;
- const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE7.MathUtils.degToRad(twist)) * t);
+ const axisZ = normals[i].clone().applyAxisAngle(tangent, (correction + THREE8.MathUtils.degToRad(twist)) * t);
const axisX = tangent.clone().cross(axisZ).normalize(), scale = scales[i];
return points.map((p) => station.clone().addScaledVector(axisX, p.x * scale[0]).addScaledVector(axisZ, p.y * scale[1]));
});
@@ -6998,7 +7240,7 @@ var init_sweep = __esm(() => {
});
// src/solids.ts
-import * as THREE8 from "three";
+import * as THREE9 from "three";
async function getManifoldModule() {
if (_module)
return _module;
@@ -7058,7 +7300,7 @@ function threeToManifold(src, mod, label, context) {
else
context.missingUV.add(mesh.name || label);
}
- const point = new THREE8.Vector3;
+ const point = new THREE9.Vector3;
for (let i = 0;i < position.count; i++) {
point.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
if (![point.x, point.y, point.z].every((n) => Number.isFinite(Math.fround(n))))
@@ -7127,11 +7369,11 @@ function manifoldToGeometry(m, opts = {}) {
if (uvs)
uvs.set(mesh.vertProperties.subarray(i + 3, i + 5), v * 2);
}
- const geometry = new THREE8.BufferGeometry;
- geometry.setAttribute("position", new THREE8.BufferAttribute(positions, 3));
- geometry.setIndex(new THREE8.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
+ const geometry = new THREE9.BufferGeometry;
+ geometry.setAttribute("position", new THREE9.BufferAttribute(positions, 3));
+ geometry.setIndex(new THREE9.BufferAttribute(new Uint32Array(mesh.triVerts), 1));
if (uvs)
- geometry.setAttribute("uv", new THREE8.BufferAttribute(uvs, 2));
+ geometry.setAttribute("uv", new THREE9.BufferAttribute(uvs, 2));
const out = opts.smooth ? geometry : geometry.toNonIndexed();
out.computeVertexNormals();
if (opts.smooth && uvs) {
@@ -7152,7 +7394,7 @@ function firstMaterial(src) {
if (!material && mesh.isMesh)
material = Array.isArray(mesh.material) ? mesh.material[0] : mesh.material;
});
- return material ?? new THREE8.MeshStandardMaterial;
+ return material ?? new THREE9.MeshStandardMaterial;
}
function outputMesh(result, name, parts, opts, context, isHull) {
const geometry = manifoldToGeometry(result, {
@@ -7207,7 +7449,7 @@ function outputMesh(result, name, parts, opts, context, isHull) {
message: "A convex hull creates new faces. Source UVs and material boundaries cannot be assigned faithfully; output uses the first material and no UVs."
});
geometry.userData.kilnAttributeWarnings = warnings;
- const output = new THREE8.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
+ const output = new THREE9.Mesh(geometry, context.preserve && !isHull && materials.length ? materials : firstMaterial(parts[0]));
output.name = `Mesh_${name}`;
return output;
}
@@ -7556,7 +7798,7 @@ var init_profile = __esm(() => {
});
// src/textures.ts
-import * as THREE9 from "three";
+import * as THREE10 from "three";
async function loadTexture(source, opts = {}) {
let bytes;
if (typeof source === "string") {
@@ -7577,7 +7819,7 @@ async function loadTexture(source, opts = {}) {
if (!meta.width || !meta.height) {
throw new Error("loadTexture: could not read image dimensions");
}
- const tex = new THREE9.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE9.RGBAFormat, THREE9.UnsignedByteType);
+ const tex = new THREE10.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE10.RGBAFormat, THREE10.UnsignedByteType);
const usage = opts.usage ?? "albedo";
const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";
let hasAlpha = false;
@@ -7587,14 +7829,14 @@ async function loadTexture(source, opts = {}) {
break;
}
}
- tex.colorSpace = colorSpace === "srgb" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;
+ tex.colorSpace = colorSpace === "srgb" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
if (opts.name)
tex.name = opts.name;
tex.needsUpdate = true;
- tex.wrapS = THREE9.RepeatWrapping;
- tex.wrapT = THREE9.RepeatWrapping;
- tex.minFilter = THREE9.LinearMipmapLinearFilter;
- tex.magFilter = THREE9.LinearFilter;
+ tex.wrapS = THREE10.RepeatWrapping;
+ tex.wrapT = THREE10.RepeatWrapping;
+ tex.minFilter = THREE10.LinearMipmapLinearFilter;
+ tex.magFilter = THREE10.LinearFilter;
tex.generateMipmaps = true;
tex.userData["encoded"] = {
mime,
@@ -7629,17 +7871,17 @@ function requireTextureUsage(texture, usage) {
if (meta && meta.usage !== usage) {
throw new TypeError(`Texture ${JSON.stringify(texture.name || "(unnamed)")} was loaded for ${meta.usage}, not ${usage}.`);
}
- texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE9.SRGBColorSpace : THREE9.NoColorSpace;
+ texture.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
}
function pbrMaterial(opts = {}) {
- const mat = new THREE9.MeshStandardMaterial;
+ const mat = new THREE10.MeshStandardMaterial;
const isTex = (v) => !!v?.isTexture;
if (isTex(opts.albedo)) {
requireTextureUsage(opts.albedo, "albedo");
mat.map = opts.albedo;
- mat.color = new THREE9.Color(16777215);
+ mat.color = new THREE10.Color(16777215);
} else if (opts.albedo !== undefined) {
- mat.color = new THREE9.Color(opts.albedo);
+ mat.color = new THREE10.Color(opts.albedo);
}
if (opts.normal) {
requireTextureUsage(opts.normal, "normal");
@@ -7677,9 +7919,9 @@ function pbrMaterial(opts = {}) {
if (isTex(opts.emissive)) {
requireTextureUsage(opts.emissive, "emissive");
mat.emissiveMap = opts.emissive;
- mat.emissive = new THREE9.Color(16777215);
+ mat.emissive = new THREE10.Color(16777215);
} else if (opts.emissive !== undefined) {
- mat.emissive = new THREE9.Color(opts.emissive);
+ mat.emissive = new THREE10.Color(opts.emissive);
}
if (opts.emissiveIntensity !== undefined) {
mat.emissiveIntensity = opts.emissiveIntensity;
@@ -7711,7 +7953,7 @@ function pbrMaterial(opts = {}) {
mat.transparent = true;
}
if (opts.doubleSided)
- mat.side = THREE9.DoubleSide;
+ mat.side = THREE10.DoubleSide;
mat.userData["kilnMaterial"] = {
alphaMode,
...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},
@@ -8213,7 +8455,7 @@ var init_procedural_material_v2 = __esm(() => {
});
// src/procedural-texture.ts
-import * as THREE10 from "three";
+import * as THREE11 from "three";
function hash2(x, y, seed) {
let h = Math.imul(x, 374761393) + Math.imul(y, 668265263) + Math.imul(seed, 1274126177) | 0;
h = h ^ h >>> 13;
@@ -8354,14 +8596,14 @@ function compileProceduralTextureSpecV2(input) {
function proceduralTexture(spec) {
const compiled = compileProceduralTextureSpecV2(spec);
const { size, usage, name, layers } = compiled.spec;
- const tex = new THREE10.DataTexture(compiled.pixels, size, size, THREE10.RGBAFormat, THREE10.UnsignedByteType);
+ const tex = new THREE11.DataTexture(compiled.pixels, size, size, THREE11.RGBAFormat, THREE11.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE10.SRGBColorSpace : THREE10.NoColorSpace;
- tex.wrapS = THREE10.RepeatWrapping;
- tex.wrapT = THREE10.RepeatWrapping;
- tex.minFilter = THREE10.LinearMipmapLinearFilter;
- tex.magFilter = THREE10.LinearFilter;
+ tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE11.SRGBColorSpace : THREE11.NoColorSpace;
+ tex.wrapS = THREE11.RepeatWrapping;
+ tex.wrapT = THREE11.RepeatWrapping;
+ tex.minFilter = THREE11.LinearMipmapLinearFilter;
+ tex.magFilter = THREE11.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -8415,13 +8657,13 @@ function normalMapFromHeight(source, opts = {}) {
out[o + 3] = 255;
}
}
- const tex = new THREE10.DataTexture(out, width, height, THREE10.RGBAFormat, THREE10.UnsignedByteType);
+ const tex = new THREE11.DataTexture(out, width, height, THREE11.RGBAFormat, THREE11.UnsignedByteType);
tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");
- tex.colorSpace = THREE10.NoColorSpace;
- tex.wrapS = THREE10.RepeatWrapping;
- tex.wrapT = THREE10.RepeatWrapping;
- tex.minFilter = THREE10.LinearMipmapLinearFilter;
- tex.magFilter = THREE10.LinearFilter;
+ tex.colorSpace = THREE11.NoColorSpace;
+ tex.wrapS = THREE11.RepeatWrapping;
+ tex.wrapT = THREE11.RepeatWrapping;
+ tex.minFilter = THREE11.LinearMipmapLinearFilter;
+ tex.magFilter = THREE11.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
return tex;
@@ -10609,7 +10851,7 @@ var init_portable_material_runtime = __esm(() => {
});
// src/vehicle.ts
-import * as THREE11 from "three";
+import * as THREE12 from "three";
function assertId(value, name) {
if (!ID_PATTERN.test(value))
throw new TypeError(`${name} must be a stable identifier`);
@@ -10645,7 +10887,7 @@ function createTypedSocket(kind, input, parent) {
if (!input.position.every(Number.isFinite))
throw new TypeError(`${kind}.${id} position must be finite`);
const rotation = normalizedQuaternion(input.rotation);
- const node = new THREE11.Object3D;
+ const node = new THREE12.Object3D;
node.name = `Socket_${kind}_${id}`;
node.position.set(...input.position);
node.quaternion.set(...rotation);
@@ -10666,7 +10908,7 @@ function createTypedSocket(kind, input, parent) {
return node;
}
function createVehicleFrame(name, options = {}) {
- const root = new THREE11.Object3D;
+ const root = new THREE12.Object3D;
root.name = name;
stampSemanticMetadataV1(root, semantic2([KILN_SEMANTIC_ROLES.vehicleFrame, KILN_SEMANTIC_ROLES.vehicleForward], {
frames: [
@@ -10691,7 +10933,7 @@ function createVehicleFrame(name, options = {}) {
};
}
function cylinderZ(radius, width, segments = 16) {
- const geometry = new THREE11.CylinderGeometry(radius, radius, width, segments);
+ const geometry = new THREE12.CylinderGeometry(radius, radius, width, segments);
geometry.rotateX(Math.PI / 2);
return geometry;
}
@@ -10702,7 +10944,7 @@ function createWheelGeometrySet(radius, width) {
throw new RangeError("wheel width must be less than its diameter");
const tube = width / 2;
return {
- tire: new THREE11.TorusGeometry(radius - tube, tube, 8, 20),
+ tire: new THREE12.TorusGeometry(radius - tube, tube, 8, 20),
rim: cylinderZ(radius * 0.68, width * 0.8),
hub: cylinderZ(radius * 0.34, width * 0.94)
};
@@ -10721,11 +10963,11 @@ function createWheelAssembly(name, materials, options) {
const index = assertId(String(options.index), "wheel index");
const key = `${options.side}.${index}`;
const parent = options.parent;
- const root = new THREE11.Object3D;
+ const root = new THREE12.Object3D;
root.name = `${name}_Assembly_${options.side}_${index}`;
let steeringPivot;
if (options.steering) {
- steeringPivot = new THREE11.Object3D;
+ steeringPivot = new THREE12.Object3D;
steeringPivot.name = `SteeringPivot_${options.side}_${index}`;
steeringPivot.position.set(...options.position ?? [0, 0, 0]);
stampSemanticMetadataV1(steeringPivot, semantic2([semanticRole(ROLE.steeringPivot, key)], {
@@ -10736,7 +10978,7 @@ function createWheelAssembly(name, materials, options) {
}));
root.add(steeringPivot);
}
- const spinPivot = new THREE11.Object3D;
+ const spinPivot = new THREE12.Object3D;
spinPivot.name = `WheelPivot_${options.side}_${index}`;
if (!steeringPivot)
spinPivot.position.set(...options.position ?? [0, 0, 0]);
@@ -10758,9 +11000,9 @@ function createWheelAssembly(name, materials, options) {
}));
(steeringPivot ?? root).add(spinPivot);
const defaults = createWheelGeometrySet(radius, width);
- const tire = new THREE11.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);
- const rim = new THREE11.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);
- const hub = new THREE11.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);
+ const tire = new THREE12.Mesh(options.geometries?.tire ?? defaults.tire, materials.tire);
+ const rim = new THREE12.Mesh(options.geometries?.rim ?? cylinderZ(rimRadius, rimWidth), materials.rim);
+ const hub = new THREE12.Mesh(options.geometries?.hub ?? cylinderZ(hubRadius, hubWidth), materials.hub ?? materials.rim);
tire.name = `Tire_${options.side}_${index}`;
rim.name = `Rim_${options.side}_${index}`;
hub.name = `Hub_${options.side}_${index}`;
@@ -10780,7 +11022,7 @@ function createWheelAssembly(name, materials, options) {
]
}));
spinPivot.add(tire, rim, hub);
- const contact = new THREE11.Object3D;
+ const contact = new THREE12.Object3D;
contact.name = `Contact_${options.side}_${index}`;
contact.position.y = -radius;
stampSemanticMetadataV1(contact, semantic2([semanticRole(ROLE.wheelContact, key), semanticRole(ROLE.contact, key)], {
@@ -10837,10 +11079,10 @@ function objectBoundsInFrame(object, frame) {
object.updateWorldMatrix(true, true);
frame.updateWorldMatrix(true, false);
const worldToFrame = frame.matrixWorld.clone().invert();
- const bounds = new THREE11.Box3;
+ const bounds = new THREE12.Box3;
let found = false;
object.traverse((node) => {
- if (!(node instanceof THREE11.Mesh) || !(node.geometry instanceof THREE11.BufferGeometry))
+ if (!(node instanceof THREE12.Mesh) || !(node.geometry instanceof THREE12.BufferGeometry))
return;
node.geometry.computeBoundingBox();
const local = node.geometry.boundingBox;
@@ -10850,7 +11092,7 @@ function objectBoundsInFrame(object, frame) {
for (const x of [local.min.x, local.max.x])
for (const y of [local.min.y, local.max.y])
for (const z of [local.min.z, local.max.z]) {
- bounds.expandByPoint(new THREE11.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE12.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -10862,9 +11104,9 @@ function dimensions(object, frame) {
const bounds = objectBoundsInFrame(object, frame);
if (!bounds)
return;
- const size = bounds.getSize(new THREE11.Vector3);
+ const size = bounds.getSize(new THREE12.Vector3);
return {
- center: bounds.getCenter(new THREE11.Vector3),
+ center: bounds.getCenter(new THREE12.Vector3),
radius: Math.max(size.x, size.y) / 2,
width: size.z
};
@@ -10874,7 +11116,7 @@ function resolved(source, id, root, pivot, parts) {
const tire = dimensions(parts.tire, pivot);
const rim = dimensions(parts.rim, pivot);
const hub = dimensions(parts.hub, pivot);
- const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE11.Vector3;
+ const centerLocal = tire?.center ?? rim?.center ?? hub?.center ?? new THREE12.Vector3;
const toWorld = (value) => value.clone().applyMatrix4(pivot.matrixWorld);
return {
id,
@@ -10889,11 +11131,11 @@ function resolved(source, id, root, pivot, parts) {
...parts.hub ? { hub: parts.hub } : {},
...parts.contact ? { contact: parts.contact } : {},
centerWorld: toWorld(centerLocal),
- pivotCenterWorld: new THREE11.Vector3().setFromMatrixPosition(pivot.matrixWorld),
+ pivotCenterWorld: new THREE12.Vector3().setFromMatrixPosition(pivot.matrixWorld),
...tire ? { tireCenterWorld: toWorld(tire.center) } : {},
...rim ? { rimCenterWorld: toWorld(rim.center) } : {},
...hub ? { hubCenterWorld: toWorld(hub.center) } : {},
- spinAxisWorld: new THREE11.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),
+ spinAxisWorld: new THREE12.Vector3(0, 0, 1).transformDirection(pivot.matrixWorld),
...tire ? { radius: tire.radius, width: tire.width } : {},
...rim ? { rimRadius: rim.radius, rimWidth: rim.width } : {},
...hub ? { hubRadius: hub.radius, hubWidth: hub.width } : {},
@@ -10992,7 +11234,7 @@ var init_vehicle = __esm(() => {
});
// src/uv.ts
-import * as THREE12 from "three";
+import * as THREE13 from "three";
async function getXatlas() {
if (!_xatlasReady) {
_xatlasReady = (async () => {
@@ -11038,16 +11280,16 @@ async function autoUnwrap(geometry, opts = {}) {
xa.destroyAtlas();
throw new Error("autoUnwrap: xatlas returned no meshes");
}
- const out = new THREE12.BufferGeometry;
- out.setAttribute("position", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
+ const out = new THREE13.BufferGeometry;
+ out.setAttribute("position", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.vertices), 3));
if (mesh.vertex.normals) {
- out.setAttribute("normal", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
+ out.setAttribute("normal", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.normals), 3));
}
if (mesh.vertex.coords1) {
- out.setAttribute("uv", new THREE12.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
+ out.setAttribute("uv", new THREE13.BufferAttribute(new Float32Array(mesh.vertex.coords1), 2));
}
if (mesh.index) {
- out.setIndex(new THREE12.BufferAttribute(new Uint32Array(mesh.index), 1));
+ out.setIndex(new THREE13.BufferAttribute(new Uint32Array(mesh.index), 1));
}
out.userData["atlas"] = {
width: result.width,
@@ -11070,7 +11312,7 @@ function toIndexed(geo) {
for (let i = 0;i < posAttr.count; i++)
indices[i] = i;
const out = geo.clone();
- out.setIndex(new THREE12.BufferAttribute(indices, 1));
+ out.setIndex(new THREE13.BufferAttribute(indices, 1));
return out;
}
function repairZeroNormals(geo) {
@@ -11090,11 +11332,11 @@ function repairZeroNormals(geo) {
if (broken.size === 0)
return;
const acc = new Float32Array(normal.count * 3);
- const a = new THREE12.Vector3;
- const b = new THREE12.Vector3;
- const c = new THREE12.Vector3;
- const face = new THREE12.Vector3;
- const edge = new THREE12.Vector3;
+ const a = new THREE13.Vector3;
+ const b = new THREE13.Vector3;
+ const c = new THREE13.Vector3;
+ const face = new THREE13.Vector3;
+ const edge = new THREE13.Vector3;
for (let t = 0;t + 2 < index.count; t += 3) {
const tri = [index.getX(t), index.getX(t + 1), index.getX(t + 2)];
if (!tri.some((i) => broken.has(i)))
@@ -11128,7 +11370,7 @@ var _xatlasReady = null;
var init_uv = () => {};
// src/uv-shapes.ts
-import * as THREE13 from "three";
+import * as THREE14 from "three";
function boxUnwrap(geo) {
const cloned = geo.clone();
if (!cloned.getAttribute("uv")) {
@@ -11185,7 +11427,7 @@ function cylindricalProjectToUVs(geo) {
uv[i * 2] = span > 0.000001 ? (a - minA) / span : 0.5;
uv[i * 2 + 1] = height > 0.000001 ? (y - minY) / height : Math.hypot(x, z) / maxR;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uv, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uv, 2));
}
function planeUnwrap(geo) {
const cloned = geo.clone();
@@ -11208,7 +11450,7 @@ function panelRemapV(geo, vScale = 0.3, vOffset = 0, uScale = 1, uOffset = 0) {
function planarProjectToUVs(geo) {
geo.computeBoundingBox();
const bb = geo.boundingBox;
- const size = new THREE13.Vector3;
+ const size = new THREE14.Vector3;
bb.getSize(size);
const w = size.x || 1;
const h = size.y || 1;
@@ -11218,12 +11460,12 @@ function planarProjectToUVs(geo) {
uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;
uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;
}
- geo.setAttribute("uv", new THREE13.BufferAttribute(uvs, 2));
+ geo.setAttribute("uv", new THREE14.BufferAttribute(uvs, 2));
}
var init_uv_shapes = () => {};
// src/material-recipe-runtime.ts
-import * as THREE14 from "three";
+import * as THREE15 from "three";
async function applyMaterialRecipeV1(request, options = {}) {
const resolved = resolveMaterialRecipeV1(request);
const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;
@@ -11246,9 +11488,9 @@ async function applyMaterialRecipeV1(request, options = {}) {
};
const material = pbrMaterial(materialOptions);
material.name = options.name ?? request.id;
- material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE14.LinearSRGBColorSpace);
+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE15.LinearSRGBColorSpace);
material.opacity = resolved.baseColorFactor[3];
- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE14.LinearSRGBColorSpace);
+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE15.LinearSRGBColorSpace);
const resources = [...loaded.values()].map((entry) => entry.provenance).sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));
const provenance = {
schemaVersion: 1,
@@ -11299,17 +11541,17 @@ var init_material_recipe_runtime = __esm(() => {
});
// src/primitives.ts
-import * as THREE15 from "three";
+import * as THREE16 from "three";
function vectorToTuple(v) {
return [v.x, v.y, v.z];
}
function createRoot(name) {
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
return root;
}
function createPivot(name, position = [0, 0, 0], parent) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.position.set(...position);
if (parent)
@@ -11341,16 +11583,16 @@ function assertPartArgs(name, geometry2, material) {
}
function createPart(name, geometry2, material, options = {}) {
assertPartArgs(name, geometry2, material);
- const mesh = new THREE15.Mesh(geometry2, material);
+ const mesh = new THREE16.Mesh(geometry2, material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.pivot) {
- const pivot = new THREE15.Object3D;
+ const pivot = new THREE16.Object3D;
pivot.name = `Joint_${name}`;
pivot.add(mesh);
mesh.position.set(0, 0, 0);
@@ -11369,7 +11611,7 @@ function createPart(name, geometry2, material, options = {}) {
return mesh;
}
function capsuleGeo(radius, height, segments = 6) {
- return new THREE15.CapsuleGeometry(radius, height, 2, segments);
+ return new THREE16.CapsuleGeometry(radius, height, 2, segments);
}
function capsuleXGeo(radius, length, segments = 6) {
const geo = capsuleGeo(radius, length, segments);
@@ -11382,7 +11624,7 @@ function capsuleZGeo(radius, length, segments = 6) {
return geo;
}
function cylinderGeo(radiusTop, radiusBottom, height, segments = 8) {
- return new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ return new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
}
function cylinderXGeo(radiusTop, radiusBottom, length, segments = 8) {
const geo = cylinderGeo(radiusTop, radiusBottom, length, segments);
@@ -11395,13 +11637,13 @@ function cylinderZGeo(radiusTop, radiusBottom, length, segments = 8) {
return geo;
}
function boxGeo(width, height, depth) {
- return new THREE15.BoxGeometry(width, height, depth);
+ return new THREE16.BoxGeometry(width, height, depth);
}
function sphereGeo(radius, widthSegments = 8, heightSegments = 6) {
- return new THREE15.SphereGeometry(radius, widthSegments, heightSegments);
+ return new THREE16.SphereGeometry(radius, widthSegments, heightSegments);
}
function coneGeo(radius, height, segments = 8) {
- return new THREE15.ConeGeometry(radius, height, segments);
+ return new THREE16.ConeGeometry(radius, height, segments);
}
function coneXGeo(radius, length, segments = 8) {
const geo = coneGeo(radius, length, segments);
@@ -11416,20 +11658,20 @@ function coneZGeo(radius, length, segments = 8) {
function cylinderOnAxis(center, normal, radiusBottom, height, options = {}) {
const radiusTop = options.radiusTop ?? radiusBottom;
const segments = options.segments ?? 8;
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
- const n = new THREE15.Vector3(normal[0], normal[1], normal[2]);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const n = new THREE16.Vector3(normal[0], normal[1], normal[2]);
const len = n.length();
if (len < 0.000001) {
throw new Error(`cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(",")}]).`);
}
n.divideScalar(len);
- const q = new THREE15.Quaternion().setFromUnitVectors(new THREE15.Vector3(0, 1, 0), n);
+ const q = new THREE16.Quaternion().setFromUnitVectors(new THREE16.Vector3(0, 1, 0), n);
geo.applyQuaternion(q);
geo.translate(center[0], center[1], center[2]);
return geo;
}
function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8) {
- const geo = new THREE15.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ const geo = new THREE16.CylinderGeometry(radiusTop, radiusBottom, height, segments);
if (axis === "x")
geo.rotateZ(-Math.PI / 2);
else if (axis === "z")
@@ -11437,20 +11679,20 @@ function taperConeGeo(radiusBottom, radiusTop, height, axis = "y", segments = 8)
return geo;
}
function torusGeo(radius, tube, radialSegments = 8, tubularSegments = 12) {
- return new THREE15.TorusGeometry(radius, tube, radialSegments, tubularSegments);
+ return new THREE16.TorusGeometry(radius, tube, radialSegments, tubularSegments);
}
function planeGeo(width, height, widthSegments = 1, heightSegments = 1) {
- return new THREE15.PlaneGeometry(width, height, widthSegments, heightSegments);
+ return new THREE16.PlaneGeometry(width, height, widthSegments, heightSegments);
}
function decalBox(width, height, depth = 0.01) {
const d = Math.max(depth, 0.002);
- return new THREE15.BoxGeometry(width, height, d);
+ return new THREE16.BoxGeometry(width, height, d);
}
function foliageCardGeo(opts = {}) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
geom.userData["kilnGeometryRole"] = "foliageCard";
return geom;
@@ -11463,12 +11705,12 @@ function crossedQuadsGeo(opts = {}) {
const geometries = [];
for (let i = 0;i < planes; i++) {
const angle = i / planes * Math.PI;
- const quad = new THREE15.PlaneGeometry(w, h);
+ const quad = new THREE16.PlaneGeometry(w, h);
quad.translate(0, h * (0.5 - yPivot), 0);
quad.rotateY(angle);
geometries.push(quad);
}
- const out = new THREE15.BufferGeometry;
+ const out = new THREE16.BufferGeometry;
const posCount = geometries.reduce((sum, g) => sum + (g.attributes.position?.count ?? 0), 0);
const positions = new Float32Array(posCount * 3);
const normals = new Float32Array(posCount * 3);
@@ -11495,9 +11737,9 @@ function crossedQuadsGeo(opts = {}) {
}
vOffset += p.count;
}
- out.setAttribute("position", new THREE15.BufferAttribute(positions, 3));
- out.setAttribute("normal", new THREE15.BufferAttribute(normals, 3));
- out.setAttribute("uv", new THREE15.BufferAttribute(uvs, 2));
+ out.setAttribute("position", new THREE16.BufferAttribute(positions, 3));
+ out.setAttribute("normal", new THREE16.BufferAttribute(normals, 3));
+ out.setAttribute("uv", new THREE16.BufferAttribute(uvs, 2));
out.setIndex(indices);
out.userData["kilnGeometryRole"] = "foliageCard";
return out;
@@ -11506,7 +11748,7 @@ function octaGridPlane(opts) {
const w = opts.width ?? 1;
const h = opts.height ?? 1;
const yPivot = opts.yPivot ?? 0;
- const geom = new THREE15.PlaneGeometry(w, h);
+ const geom = new THREE16.PlaneGeometry(w, h);
geom.translate(0, h * (0.5 - yPivot), 0);
const uv = geom.attributes.uv;
const du = 1 / opts.tilesX;
@@ -11594,8 +11836,8 @@ function wingGeo(options = {}) {
7,
6
];
- const geo = new THREE15.BufferGeometry;
- geo.setAttribute("position", new THREE15.BufferAttribute(vertices, 3));
+ const geo = new THREE16.BufferGeometry;
+ geo.setAttribute("position", new THREE16.BufferAttribute(vertices, 3));
geo.setIndex(indices);
geo.computeVertexNormals();
return geo;
@@ -11618,17 +11860,17 @@ function createWingPair(name, material, options) {
};
}
function beamBetween(name, start, end, radius, material, options = {}) {
- const a = new THREE15.Vector3(...start);
- const b = new THREE15.Vector3(...end);
+ const a = new THREE16.Vector3(...start);
+ const b = new THREE16.Vector3(...end);
const direction = b.clone().sub(a);
const length = direction.length();
if (length <= 0.0001) {
throw new Error(`beamBetween("${name}"): start and end must be different points (got start=[${start.join(",")}], end=[${end.join(",")}], delta=${length.toExponential(2)}). Pick two distinct endpoints or switch to cylinderGeo with an explicit length + position.`);
}
- const mesh = new THREE15.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
+ const mesh = new THREE16.Mesh(cylinderGeo(radius, radius, length, options.segments ?? 8), material);
mesh.name = `Mesh_${name}`;
mesh.position.copy(a.add(b).multiplyScalar(0.5));
- mesh.quaternion.setFromUnitVectors(new THREE15.Vector3(0, 1, 0), direction.normalize());
+ mesh.quaternion.setFromUnitVectors(new THREE16.Vector3(0, 1, 0), direction.normalize());
if (options.parent)
options.parent.add(mesh);
return mesh;
@@ -11637,11 +11879,11 @@ function snapTo(part, host, options = {}) {
const overlap = options.overlap ?? 0.02;
part.updateMatrixWorld(true);
host.updateMatrixWorld(true);
- const a = new THREE15.Box3().setFromObject(part);
- const b = new THREE15.Box3().setFromObject(host);
+ const a = new THREE16.Box3().setFromObject(part);
+ const b = new THREE16.Box3().setFromObject(host);
if (a.isEmpty() || b.isEmpty())
return part;
- const delta = new THREE15.Vector3;
+ const delta = new THREE16.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
delta[axis] = b.max[axis] - a.min[axis];
@@ -11657,7 +11899,7 @@ function snapTo(part, host, options = {}) {
delta[dominant] = -overlap;
const parent = part.parent;
if (parent) {
- const p0 = new THREE15.Vector3;
+ const p0 = new THREE16.Vector3;
part.getWorldPosition(p0);
const p1 = p0.clone().add(delta);
const l0 = parent.worldToLocal(p0.clone());
@@ -11682,9 +11924,9 @@ function createLadder(name, options) {
widthAxis = "x",
parent
} = options;
- const bottomVec = new THREE15.Vector3(...bottom);
- const topVec = new THREE15.Vector3(...top);
- const offset = widthAxis === "x" ? new THREE15.Vector3(width / 2, 0, 0) : new THREE15.Vector3(0, 0, width / 2);
+ const bottomVec = new THREE16.Vector3(...bottom);
+ const topVec = new THREE16.Vector3(...top);
+ const offset = widthAxis === "x" ? new THREE16.Vector3(width / 2, 0, 0) : new THREE16.Vector3(0, 0, width / 2);
const leftBottom = bottomVec.clone().sub(offset);
const leftTop = topVec.clone().sub(offset);
const rightBottom = bottomVec.clone().add(offset);
@@ -11701,7 +11943,7 @@ function createLadder(name, options) {
}
function wallWithOpening(name, material, options) {
const { length, height, thickness, axis = "z", opening, parent } = options;
- const group = new THREE15.Object3D;
+ const group = new THREE16.Object3D;
group.name = name;
const overlap = 0.02;
const panel = (suffix, lenStart, lenEnd, yLo, yHi) => {
@@ -11746,7 +11988,7 @@ function room(name, material, options = {}) {
parent
} = options;
const openings = options.openings ?? [{ wall: "front", kind: "door" }];
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const openingFor = (wall) => {
const found = openings.find((op) => op.wall === wall);
@@ -11790,7 +12032,7 @@ function createRoofPlanes2(name, material, options) {
result.slopes[0].name = `Mesh_${name}A`;
result.slopes[1].name = `Mesh_${name}B`;
for (let index = 0;index < result.slopes.length; index++) {
- const normal = new THREE15.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
+ const normal = new THREE16.Vector3().setFromMatrixColumn(result.faces[index].localToRoof, 1);
result.slopes[index].position.addScaledVector(normal, (options.thickness ?? 0.08) / 2);
}
if ((options.ridgeAxis ?? "x") === "x") {
@@ -11817,7 +12059,7 @@ function createStairs(name, material, options) {
if (Math.abs(totalRise) < 0.0001 || Math.abs(totalRun) < 0.0001) {
throw new Error(`createStairs("${name}"): totalRise and totalRun must be non-zero (got rise=${totalRise}, run=${totalRun}).`);
}
- const root = new THREE15.Object3D;
+ const root = new THREE16.Object3D;
root.name = name;
const stepRise = totalRise / steps;
const stepRun = totalRun / steps;
@@ -11847,7 +12089,7 @@ function requireColor(color, fn) {
}
function gameMaterial(color, options = {}) {
requireColor(color, "gameMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
metalness: options.metalness ?? 0,
roughness: options.roughness ?? 0.8,
@@ -11858,7 +12100,7 @@ function gameMaterial(color, options = {}) {
}
function basicMaterial(color, options = {}) {
requireColor(color, "basicMaterial");
- return new THREE15.MeshBasicMaterial({
+ return new THREE16.MeshBasicMaterial({
color,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
@@ -11866,38 +12108,38 @@ function basicMaterial(color, options = {}) {
}
function glassMaterial(color, options = {}) {
requireColor(color, "glassMaterial");
- return new THREE15.MeshStandardMaterial({
+ return new THREE16.MeshStandardMaterial({
color,
transparent: true,
opacity: options.opacity ?? 0.35,
roughness: options.roughness ?? 0.1,
metalness: options.metalness ?? 0,
- side: THREE15.DoubleSide
+ side: THREE16.DoubleSide
});
}
function lambertMaterial(color, options = {}) {
requireColor(color, "lambertMaterial");
- return new THREE15.MeshLambertMaterial({
+ return new THREE16.MeshLambertMaterial({
color,
flatShading: options.flatShading ?? true,
emissive: options.emissive ?? 0
});
}
function threeInterpolation(mode) {
- return mode === "STEP" ? THREE15.InterpolateDiscrete : THREE15.InterpolateLinear;
+ return mode === "STEP" ? THREE16.InterpolateDiscrete : THREE16.InterpolateLinear;
}
function rotationTrack(jointName, keyframes, interpolation) {
const times = [];
const values = [];
- const euler = new THREE15.Euler;
- const quat = new THREE15.Quaternion;
+ const euler = new THREE16.Euler;
+ const quat = new THREE16.Quaternion;
for (const kf of keyframes) {
times.push(kf.time);
- euler.set(THREE15.MathUtils.degToRad(kf.rotation[0]), THREE15.MathUtils.degToRad(kf.rotation[1]), THREE15.MathUtils.degToRad(kf.rotation[2]));
+ euler.set(THREE16.MathUtils.degToRad(kf.rotation[0]), THREE16.MathUtils.degToRad(kf.rotation[1]), THREE16.MathUtils.degToRad(kf.rotation[2]));
quat.setFromEuler(euler);
values.push(quat.x, quat.y, quat.z, quat.w);
}
- return new THREE15.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
+ return new THREE16.QuaternionKeyframeTrack(`${jointName}.quaternion`, times, values, threeInterpolation(interpolation));
}
function positionTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -11906,7 +12148,7 @@ function positionTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.position);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.position`, times, values, threeInterpolation(interpolation));
}
function scaleTrack(jointName, keyframes, interpolation) {
const times = [];
@@ -11915,10 +12157,10 @@ function scaleTrack(jointName, keyframes, interpolation) {
times.push(kf.time);
values.push(...kf.scale);
}
- return new THREE15.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
+ return new THREE16.VectorKeyframeTrack(`${jointName}.scale`, times, values, threeInterpolation(interpolation));
}
function createClip(name, duration, tracks) {
- return new THREE15.AnimationClip(name, duration, tracks);
+ return new THREE16.AnimationClip(name, duration, tracks);
}
function idleBreathing(bodyJoint, duration = 2, amount = 0.02) {
const y = 0;
@@ -11968,12 +12210,12 @@ function createInstance(name, source, options = {}) {
if (!sourceMesh) {
throw new Error(`createInstance("${name}"): source "${source.name}" has no Mesh to clone from`);
}
- const mesh = new THREE15.Mesh(sourceMesh.geometry, sourceMesh.material);
+ const mesh = new THREE16.Mesh(sourceMesh.geometry, sourceMesh.material);
mesh.name = `Mesh_${name}`;
if (options.position)
mesh.position.set(...options.position);
if (options.rotation)
- mesh.rotation.set(THREE15.MathUtils.degToRad(options.rotation[0]), THREE15.MathUtils.degToRad(options.rotation[1]), THREE15.MathUtils.degToRad(options.rotation[2]));
+ mesh.rotation.set(THREE16.MathUtils.degToRad(options.rotation[0]), THREE16.MathUtils.degToRad(options.rotation[1]), THREE16.MathUtils.degToRad(options.rotation[2]));
if (options.scale)
mesh.scale.set(...options.scale);
if (options.parent)
@@ -12217,7 +12459,7 @@ function buildSandboxGlobals(usage, options = {}) {
countMaterials: wrap("countMaterials", countMaterials),
getJointNames: wrap("getJointNames", getJointNames),
validateAsset: wrap("validateAsset", validateAsset),
- THREE: THREE15,
+ THREE: THREE16,
Math,
console
};
@@ -12745,7 +12987,7 @@ var init_registry = __esm(() => {
});
// src/qa/material.ts
-import * as THREE16 from "three";
+import * as THREE17 from "three";
function textureMeta(texture) {
return texture.userData["kilnTexture"];
}
@@ -12793,7 +13035,7 @@ function validateTextureSlot(findings, mesh, material, texture, slot, expected)
if (!texture)
return;
const meta = textureMeta(texture);
- const actual = texture.colorSpace === THREE16.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE16.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
+ const actual = texture.colorSpace === THREE17.SRGBColorSpace ? "srgb" : texture.colorSpace === THREE17.NoColorSpace ? "linear" : meta?.colorSpace ?? "linear";
if (!meta || !encodedTextureIsExportable(texture)) {
findings.push({
code: "MAT_TEXTURE_DECODE_FAILED",
@@ -12894,7 +13136,7 @@ function validateMaterial2(mesh, material, requiresPrecomputedTangents) {
}
if (mesh.geometry.userData["kilnGeometryRole"] === "foliageCard") {
const validMask = standard.alphaTest > 0 && !standard.transparent;
- if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE16.DoubleSide || !mesh.geometry.getAttribute("uv")) {
+ if (!standard.map || !textureHasAlpha(standard.map) || !validMask || standard.side !== THREE17.DoubleSide || !mesh.geometry.getAttribute("uv")) {
findings.push({
code: "MAT_FOLIAGE_CARD_CONTRACT",
disposition: "block",
@@ -13008,14 +13250,14 @@ var init_architecture_repairs = __esm(() => {
});
// src/qa/architecture.ts
-import * as THREE17 from "three";
+import * as THREE18 from "three";
function semanticMetadata(node) {
return readSemanticMetadataV1FromExtras(node.userData);
}
function markerBounds(matrix) {
const bounds = emptyBounds();
for (let corner = 0;corner < 8; corner++) {
- expandBounds(bounds, new THREE17.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
+ expandBounds(bounds, new THREE18.Vector3(corner & 1 ? 0.5 : -0.5, corner & 2 ? 0.5 : -0.5, corner & 4 ? 0.5 : -0.5).applyMatrix4(matrix));
}
return bounds;
}
@@ -13024,7 +13266,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const local = geometry.boundingBox;
if (!local)
return;
- const size = local.getSize(new THREE17.Vector3);
+ const size = local.getSize(new THREE18.Vector3);
const dimensions = [
["x", size.x],
["y", size.y],
@@ -13034,7 +13276,7 @@ function geometryPlaneNormal(geometry, relativeMatrix) {
const axis = dimensions[0]?.[0];
if (!axis)
return;
- const normal = new THREE17.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
+ const normal = new THREE18.Vector3(axis === "x" ? 1 : 0, axis === "y" ? 1 : 0, axis === "z" ? 1 : 0).transformDirection(relativeMatrix);
if (normal.y < 0)
normal.multiplyScalar(-1);
return normal.normalize();
@@ -13046,7 +13288,7 @@ function geometryEvidence(geometry, relativeMatrix) {
if (position?.itemSize !== 3)
return { bounds, vertices, triangles: [] };
for (let index = 0;index < position.count; index++) {
- const point = new THREE17.Vector3(position.getX(index), position.getY(index), position.getZ(index));
+ const point = new THREE18.Vector3(position.getX(index), position.getY(index), position.getZ(index));
point.applyMatrix4(relativeMatrix);
vertices.push(point);
expandBounds(bounds, point);
@@ -13073,7 +13315,7 @@ function geometryEvidence(geometry, relativeMatrix) {
return { bounds, vertices, triangles, ...planeNormal ? { planeNormal } : {} };
}
function collectArchitectureEvidence(scene) {
- if (!(scene instanceof THREE17.Object3D))
+ if (!(scene instanceof THREE18.Object3D))
return;
scene.updateMatrixWorld(true);
const rootInverse = scene.matrixWorld.clone().invert();
@@ -13091,7 +13333,7 @@ function collectArchitectureEvidence(scene) {
const nodePath = parentPath ? `${parentPath}/${segment}` : segment;
const relativeMatrix = rootInverse.clone().multiply(node.matrixWorld);
const mesh = node;
- const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE17.BufferGeometry;
+ const isMesh = mesh.isMesh === true && mesh.geometry instanceof THREE18.BufferGeometry;
const evidence = isMesh ? geometryEvidence(mesh.geometry, relativeMatrix) : {
bounds: markerBounds(relativeMatrix),
vertices: [],
@@ -13150,7 +13392,7 @@ function architectureFinding(context, value) {
function averageNormal(normals) {
if (normals.length === 0)
return;
- const result = normals.reduce((sum, normal) => sum.add(normal), new THREE17.Vector3);
+ const result = normals.reduce((sum, normal) => sum.add(normal), new THREE18.Vector3);
return result.lengthSq() > EPSILON2 ? result.normalize() : undefined;
}
function intervalCoverage(min, max, expectedMin, expectedMax) {
@@ -13859,8 +14101,8 @@ function evaluateArchitectureQa(context) {
];
}
var PROFILE_RULE_ID = "ARCHITECTURE_PROFILE", EPSILON2 = 0.000001, ARCHITECTURE_REALISTIC_SCALE_BANDS, emptyBounds = () => ({
- min: new THREE17.Vector3(Infinity, Infinity, Infinity),
- max: new THREE17.Vector3(-Infinity, -Infinity, -Infinity)
+ min: new THREE18.Vector3(Infinity, Infinity, Infinity),
+ max: new THREE18.Vector3(-Infinity, -Infinity, -Infinity)
}), expandBounds = (bounds, point) => {
bounds.min.min(point);
bounds.max.max(point);
@@ -13950,7 +14192,7 @@ var init_character_repairs = __esm(() => {
});
// src/qa/character.ts
-import * as THREE18 from "three";
+import * as THREE19 from "three";
function isClipLike(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -14188,7 +14430,7 @@ function contactFindings(intent, root) {
const tolerance = Number.isFinite(trusted.contactTolerance) && (trusted.contactTolerance ?? 0) >= 0 ? trusted.contactTolerance : CONTACT_TOLERANCE;
const findings = [];
for (const contact of contacts) {
- const point = contact.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(rootInverse);
+ const point = contact.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(rootInverse);
if (point.y > tolerance) {
findings.push(block(intent, "CHAR_CONTACT_FLOATING", `Ground contact ${contact.descriptor.role} is ${point.y.toFixed(6)} m above asset-local ground.`, {
dimension: "categoryReadiness",
@@ -14449,13 +14691,13 @@ function declaredHeldItem(nodes) {
function characterJointScale(root) {
root.updateMatrixWorld(true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE18.Box3;
+ const bounds = new THREE19.Box3;
for (const joint of collectCharacterJointNodes(root)) {
- bounds.expandByPoint(joint.node.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse));
+ bounds.expandByPoint(joint.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse));
}
if (bounds.isEmpty())
return 1;
- const size = bounds.getSize(new THREE18.Vector3);
+ const size = bounds.getSize(new THREE19.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function heldItemMotionFindings(intent, root, clips) {
@@ -14491,8 +14733,8 @@ function heldItemMotionFindings(intent, root, clips) {
if (!cloneItem || !cloneAttachment)
continue;
const inverse = clone.matrixWorld.clone().invert();
- const itemPoint = cloneItem.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
- const gripPoint = cloneAttachment.getWorldPosition(new THREE18.Vector3).applyMatrix4(inverse);
+ const itemPoint = cloneItem.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
+ const gripPoint = cloneAttachment.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse);
const distance = itemPoint.distanceTo(gripPoint);
baseline ??= distance;
const drift = Math.abs(distance - baseline);
@@ -14525,7 +14767,7 @@ function heldItemMotionFindings(intent, root, clips) {
function evaluateCharacterQa(context) {
if (context.intent.category !== "character")
return [];
- const root = context.scene instanceof THREE18.Object3D ? context.scene : undefined;
+ const root = context.scene instanceof THREE19.Object3D ? context.scene : undefined;
const clips = (context.clips ?? []).filter(isClipLike);
const findings = [];
if (root) {
@@ -14564,7 +14806,7 @@ var init_character2 = __esm(() => {
});
// src/qa/character-advisory.ts
-import * as THREE19 from "three";
+import * as THREE20 from "three";
function isClipLike2(value) {
if (typeof value !== "object" || value === null)
return false;
@@ -14590,16 +14832,16 @@ function jointPoints(root) {
const inverse = rootInverse(root);
return collectCharacterJointNodes(root).map((evidence) => ({
evidence,
- local: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse)
+ local: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse)
}));
}
function characterScale(points) {
if (points.length === 0)
return 1;
- const bounds = new THREE19.Box3;
+ const bounds = new THREE20.Box3;
for (const point of points)
bounds.expandByPoint(point.local);
- const size = bounds.getSize(new THREE19.Vector3);
+ const size = bounds.getSize(new THREE20.Vector3);
return Math.max(size.x, size.y, size.z, 1);
}
function pairKey(descriptor) {
@@ -14698,12 +14940,12 @@ function restChainFindings(context, root) {
}
function forwardMarkerFindings(context, root) {
root.updateMatrixWorld(true);
- const expected = new THREE19.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
+ const expected = new THREE20.Vector3(1, 0, 0).transformDirection(root.matrixWorld);
const markers = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:toe|muzzle|head)(?:$|[._-])/i.test(joint.descriptor.role));
return markers.flatMap((marker) => {
- const quaternion = marker.node.getWorldQuaternion(new THREE19.Quaternion);
- const actual = new THREE19.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
- const angle = THREE19.MathUtils.radToDeg(Math.acos(THREE19.MathUtils.clamp(actual.dot(expected), -1, 1)));
+ const quaternion = marker.node.getWorldQuaternion(new THREE20.Quaternion);
+ const actual = new THREE20.Vector3(...marker.descriptor.localForwardAxis).applyQuaternion(quaternion).normalize();
+ const angle = THREE20.MathUtils.radToDeg(Math.acos(THREE20.MathUtils.clamp(actual.dot(expected), -1, 1)));
if (angle <= FORWARD_ANGLE_DEGREES)
return [];
return [
@@ -14757,7 +14999,7 @@ function sampleClip(root, clip) {
byRole: new Map(collectCharacterJointNodes(clone).map((evidence) => [
evidence.descriptor.role,
{
- point: evidence.node.getWorldPosition(new THREE19.Vector3).applyMatrix4(inverse),
+ point: evidence.node.getWorldPosition(new THREE20.Vector3).applyMatrix4(inverse),
evidence
}
]))
@@ -14869,12 +15111,12 @@ function phaseOppositionFindings(context, root, clips) {
return findings;
}
function signedBendDegrees(descriptor, quaternion) {
- const rest = new THREE19.Quaternion(...descriptor.rest.rotation);
+ const rest = new THREE20.Quaternion(...descriptor.rest.rotation);
const delta = rest.invert().multiply(quaternion).normalize();
- const axis = new THREE19.Vector3(delta.x, delta.y, delta.z);
- const signedMagnitude = axis.dot(new THREE19.Vector3(...descriptor.localBendAxis));
+ const axis = new THREE20.Vector3(delta.x, delta.y, delta.z);
+ const signedMagnitude = axis.dot(new THREE20.Vector3(...descriptor.localBendAxis));
const angle = 2 * Math.atan2(signedMagnitude, delta.w);
- return THREE19.MathUtils.radToDeg(THREE19.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
+ return THREE20.MathUtils.radToDeg(THREE20.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI);
}
function bendDirectionFindings(context, root, clips) {
const joints = collectCharacterJointNodes(root).filter((joint) => /(?:^|[._-])(?:knee|elbow)(?:$|[._-])/i.test(joint.descriptor.role));
@@ -14888,7 +15130,7 @@ function bendDirectionFindings(context, root, clips) {
let maximumFraction = 0;
for (const fraction of SAMPLE_FRACTIONS) {
const value = track.createInterpolant().evaluate(fraction * clip.duration);
- const bend = signedBendDegrees(joint.descriptor, new THREE19.Quaternion().fromArray(value).normalize());
+ const bend = signedBendDegrees(joint.descriptor, new THREE20.Quaternion().fromArray(value).normalize());
if (Math.abs(bend) > Math.abs(maximum)) {
maximum = bend;
maximumFraction = fraction;
@@ -14971,7 +15213,7 @@ function footSlideFindings(context, root, clips) {
return findings;
}
function evaluateCharacterAdvisoryQa(context) {
- if (context.intent.category !== "character" || !(context.scene instanceof THREE19.Object3D)) {
+ if (context.intent.category !== "character" || !(context.scene instanceof THREE20.Object3D)) {
return [];
}
const root = context.scene;
@@ -15254,7 +15496,7 @@ var EPSILON3 = 0.0000000001, DEFAULT_TOLERANCE = 0.000001, finiteVector = (value
];
// src/qa/vehicle-advisory.ts
-import * as THREE20 from "three";
+import * as THREE21 from "three";
function advisory2(context, value) {
return {
...value,
@@ -15328,7 +15570,7 @@ function isFender(node) {
return semanticRoles(node).some((role) => /(?:^|\.)(?:fender|wheel-arch)(?:\.|$)/i.test(role)) || /fender|wheel[ _.-]?arch/i.test(node.name);
}
function isChassisMesh(node) {
- if (!(node instanceof THREE20.Mesh) || isFender(node))
+ if (!(node instanceof THREE21.Mesh) || isFender(node))
return false;
return semanticRoles(node).some((role) => /^(?:vehicle\.)?(?:chassis|body|hull)(?:\.|$)/i.test(role)) || /chassis|vehicle[ _.-]?body|fuselage|hull/i.test(node.name);
}
@@ -15336,10 +15578,10 @@ function objectBoundsInFrame2(object, frame) {
object.updateWorldMatrix(true, true);
frame.updateWorldMatrix(true, false);
const worldToFrame = frame.matrixWorld.clone().invert();
- const bounds = new THREE20.Box3;
+ const bounds = new THREE21.Box3;
let found = false;
object.traverse((part) => {
- if (!(part instanceof THREE20.Mesh) || !(part.geometry instanceof THREE20.BufferGeometry))
+ if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -15349,7 +15591,7 @@ function objectBoundsInFrame2(object, frame) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE20.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE21.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -15360,15 +15602,15 @@ function tuple2(value) {
}
function probeBox(id, root, bounds) {
root.updateWorldMatrix(true, false);
- const center = bounds.getCenter(new THREE20.Vector3).applyMatrix4(root.matrixWorld);
- const size = bounds.getSize(new THREE20.Vector3);
- const position = new THREE20.Vector3;
- const quaternion = new THREE20.Quaternion;
- const scale = new THREE20.Vector3;
+ const center = bounds.getCenter(new THREE21.Vector3).applyMatrix4(root.matrixWorld);
+ const size = bounds.getSize(new THREE21.Vector3);
+ const position = new THREE21.Vector3;
+ const quaternion = new THREE21.Quaternion;
+ const scale = new THREE21.Vector3;
root.matrixWorld.decompose(position, quaternion, scale);
- const xAxis = new THREE20.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
- const yAxis = new THREE20.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
- const zAxis = new THREE20.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
+ const xAxis = new THREE21.Vector3(1, 0, 0).applyQuaternion(quaternion).normalize();
+ const yAxis = new THREE21.Vector3(0, 1, 0).applyQuaternion(quaternion).normalize();
+ const zAxis = new THREE21.Vector3(0, 0, 1).applyQuaternion(quaternion).normalize();
return createOrientedProbeBox3({
id,
frame: createProbeLocalFrame3({
@@ -15437,7 +15679,7 @@ function orientationFindings(context, root, intent) {
const bounds = wholeAssetBounds(root);
if (!bounds)
return [];
- const size = bounds.getSize(new THREE20.Vector3);
+ const size = bounds.getSize(new THREE21.Vector3);
const ratio = size.z / Math.max(size.x, 0.000000001);
if (ratio <= ORIENTATION_RATIO)
return [];
@@ -15481,13 +15723,13 @@ function weldedBoundaryEdges(root, loop) {
let triangleCount = 0;
const vertexKey = (point) => [point.x, point.y, point.z].map((value) => Math.round(value * 1e6)).join(",");
loop.traverse((node) => {
- if (!(node instanceof THREE20.Mesh) || !(node.geometry instanceof THREE20.BufferGeometry))
+ if (!(node instanceof THREE21.Mesh) || !(node.geometry instanceof THREE21.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (!positions)
return;
const matrix = inverse.clone().multiply(node.matrixWorld);
- const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE20.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
+ const keys = Array.from({ length: positions.count }, (_, index) => vertexKey(new THREE21.Vector3().fromBufferAttribute(positions, index).applyMatrix4(matrix)));
const index = node.geometry.getIndex();
const indices = index ? Array.from(index.array, Number) : Array.from({ length: positions.count }, (_, value) => value);
for (let offset = 0;offset + 2 < indices.length; offset += 3) {
@@ -15557,7 +15799,7 @@ function trackProfileFindings(context, root, intent) {
const wheelBounds = objectBoundsInFrame2(roadWheel, root);
if (!wheelBounds)
continue;
- const center = wheelBounds.getCenter(new THREE20.Vector3);
+ const center = wheelBounds.getCenter(new THREE21.Vector3);
if (expanded.containsPoint(center))
continue;
const clamped = center.clone().clamp(expanded.min, expanded.max);
@@ -15583,7 +15825,7 @@ function trackProfileFindings(context, root, intent) {
return findings;
}
function evaluateVehicleAdvisoryQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE20.Object3D)) {
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D)) {
return [];
}
const intent = context.intent.vehicle;
@@ -15621,7 +15863,7 @@ var init_vehicle_advisory = __esm(() => {
});
// src/qa/vehicle.ts
-import * as THREE21 from "three";
+import * as THREE22 from "three";
function finding(context, value) {
return {
...value,
@@ -15638,7 +15880,7 @@ function rootAxis(root, axis) {
return axis.clone().transformDirection(root.matrixWorld);
}
function angleDegrees(a, b) {
- return THREE21.MathUtils.radToDeg(Math.acos(THREE21.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
+ return THREE22.MathUtils.radToDeg(Math.acos(THREE22.MathUtils.clamp(a.clone().normalize().dot(b.clone().normalize()), -1, 1)));
}
function isDescendant(node, ancestor) {
let current = node;
@@ -15686,7 +15928,7 @@ function wheelCountFindings(context, intent, wheels) {
}
function wheelGeometryFindings(context, root, wheels) {
const findings = [];
- const expectedAxle = rootAxis(root, new THREE21.Vector3(0, 0, 1));
+ const expectedAxle = rootAxis(root, new THREE22.Vector3(0, 0, 1));
for (const wheel of wheels) {
const disposition = componentDisposition(wheel);
const centerTolerance = Math.max(CENTER_MINIMUM, (wheel.radius ?? 0) * CENTER_RATIO);
@@ -15875,7 +16117,7 @@ function contactFindings2(context, root, intent, wheels) {
function renderableMinYInRoot(rootInverse, node) {
let minimum = Infinity;
node.traverse((part) => {
- if (!(part instanceof THREE21.Mesh) || !(part.geometry instanceof THREE21.BufferGeometry))
+ if (!(part instanceof THREE22.Mesh) || !(part.geometry instanceof THREE22.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const bounds = part.geometry.boundingBox;
@@ -15885,7 +16127,7 @@ function renderableMinYInRoot(rootInverse, node) {
for (const x of [bounds.min.x, bounds.max.x]) {
for (const y of [bounds.min.y, bounds.max.y]) {
for (const z of [bounds.min.z, bounds.max.z]) {
- minimum = Math.min(minimum, new THREE21.Vector3(x, y, z).applyMatrix4(matrix).y);
+ minimum = Math.min(minimum, new THREE22.Vector3(x, y, z).applyMatrix4(matrix).y);
}
}
}
@@ -15905,7 +16147,7 @@ function supportContactFindings(context, root, intent) {
if (!isWheelContact && roles.some((role) => role.startsWith("contact."))) {
explicitContacts.push({
node,
- contactY: localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
+ contactY: localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(node.matrixWorld)).y,
source: "contact"
});
}
@@ -15985,7 +16227,7 @@ function steeringFindings(context, root, intent, wheels) {
return [];
root.updateWorldMatrix(true, false);
const inverse = root.matrixWorld.clone().invert();
- const expectedAxis = rootAxis(root, new THREE21.Vector3(0, 1, 0));
+ const expectedAxis = rootAxis(root, new THREE22.Vector3(0, 1, 0));
const localCenters = wheels.map((wheel) => ({
wheel,
center: localPoint2(inverse, wheel.centerWorld)
@@ -15995,8 +16237,8 @@ function steeringFindings(context, root, intent, wheels) {
const findings = [];
for (const { wheel } of targets) {
const steering = wheel.steeringPivot;
- const centerDelta = steering ? localPoint2(inverse, new THREE21.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
- const axisAngle = steering ? angleDegrees(new THREE21.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
+ const centerDelta = steering ? localPoint2(inverse, new THREE22.Vector3().setFromMatrixPosition(steering.matrixWorld)).distanceTo(localPoint2(inverse, wheel.centerWorld)) : Infinity;
+ const axisAngle = steering ? angleDegrees(new THREE22.Vector3(0, 1, 0).transformDirection(steering.matrixWorld), expectedAxis) : Infinity;
if (!steering || !isDescendant(wheel.pivot, steering) || centerDelta > CENTER_MINIMUM || axisAngle > AXIS_TOLERANCE_DEGREES) {
const axisInvalid = axisAngle > AXIS_TOLERANCE_DEGREES;
findings.push(finding(context, {
@@ -16051,14 +16293,14 @@ function propulsionFindings(context, root, intent) {
}
for (const component of candidates) {
const pivot = pivots.get(component.id);
- const box = new THREE21.Box3().setFromObject(component.node);
- const center = box.isEmpty() ? undefined : box.getCenter(new THREE21.Vector3);
- const pivotCenter = pivot ? new THREE21.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
+ const box = new THREE22.Box3().setFromObject(component.node);
+ const center = box.isEmpty() ? undefined : box.getCenter(new THREE22.Vector3);
+ const pivotCenter = pivot ? new THREE22.Vector3().setFromMatrixPosition(pivot.matrixWorld) : undefined;
const delta = center && pivotCenter ? localPoint2(rootInverse, center).distanceTo(localPoint2(rootInverse, pivotCenter)) : Infinity;
const frameId = kind === "rotor" ? "propulsion-axis.+y" : "propulsion-axis.+x";
const axisFrame = readSemanticMetadataV1(pivot ?? component.node)?.frames.find((frame) => frame.id === frameId);
- const canonicalAxis = kind === "rotor" ? new THREE21.Vector3(0, 1, 0) : new THREE21.Vector3(1, 0, 0);
- const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE21.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
+ const canonicalAxis = kind === "rotor" ? new THREE22.Vector3(0, 1, 0) : new THREE22.Vector3(1, 0, 0);
+ const axisAngle = pivot && axisFrame ? angleDegrees(canonicalAxis.clone().applyQuaternion(new THREE22.Quaternion(...axisFrame.rotation)).transformDirection(pivot.matrixWorld), rootAxis(root, canonicalAxis)) : Infinity;
if (!pivot || !isDescendant(component.node, pivot) || delta > CENTER_MINIMUM || !axisFrame || axisAngle > AXIS_TOLERANCE_DEGREES) {
findings.push(finding(context, {
code: "VEH_ROTOR_PIVOT",
@@ -16080,7 +16322,7 @@ function propulsionFindings(context, root, intent) {
return findings;
}
function evaluateVehicleQa(context) {
- if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE21.Object3D))
+ if (context.intent.category !== "vehicle" || !(context.scene instanceof THREE22.Object3D))
return [];
const intent = context.intent.vehicle;
if (!intent)
@@ -16144,7 +16386,7 @@ var init_vehicle2 = __esm(() => {
});
// src/qa/vegetation.ts
-import * as THREE22 from "three";
+import * as THREE23 from "three";
function rolesOf(node) {
return readSemanticMetadataV1(node)?.roles ?? [];
}
@@ -16160,21 +16402,21 @@ function pathOf(node, root) {
return names.reverse().join("/");
}
function localPoint3(rootInverse, node) {
- return node.getWorldPosition(new THREE22.Vector3).applyMatrix4(rootInverse);
+ return node.getWorldPosition(new THREE23.Vector3).applyMatrix4(rootInverse);
}
function meshLocalBox(mesh, rootInverse) {
- if (!(mesh.geometry instanceof THREE22.BufferGeometry))
+ if (!(mesh.geometry instanceof THREE23.BufferGeometry))
return;
mesh.geometry.computeBoundingBox();
const source = mesh.geometry.boundingBox;
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(mesh.matrixWorld);
- const result = new THREE22.Box3;
+ const result = new THREE23.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE22.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -16185,7 +16427,7 @@ function collectRenderableBounds(root) {
const inverse = root.matrixWorld.clone().invert();
const values = [];
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (!box)
@@ -16203,7 +16445,7 @@ function vegetationIntent(intent) {
}
function evaluateVegetationContactQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.grounded || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.grounded || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
root.updateWorldMatrix(true, true);
@@ -16240,7 +16482,7 @@ function evaluateVegetationContactQa(context) {
}
const findings = [];
for (const contact of contacts) {
- const contactPoint = contact.frameTranslation ? new THREE22.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
+ const contactPoint = contact.frameTranslation ? new THREE23.Vector3(...contact.frameTranslation).applyMatrix4(contact.node.matrixWorld).applyMatrix4(inverse) : localPoint3(inverse, contact.node);
const y = contactPoint.y;
if (Math.abs(y) <= VEGETATION_CONTACT_TOLERANCE_METERS)
continue;
@@ -16268,7 +16510,7 @@ function evaluateVegetationContactQa(context) {
for (const support of semanticSupports) {
let minimumY = Infinity;
support.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const box = meshLocalBox(node, inverse);
if (box)
@@ -16296,25 +16538,25 @@ function evaluateVegetationContactQa(context) {
return findings;
}
function materialNames(node) {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return [];
const materials = Array.isArray(node.material) ? node.material : [node.material];
return materials.filter(Boolean).map((material) => material.name ?? "");
}
function evaluateVegetationScopeQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted?.standalone || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted?.standalone || !(context.scene instanceof THREE23.Object3D))
return [];
const root = context.scene;
const renderables = collectRenderableBounds(root);
if (renderables.length === 0)
return [];
- const overall = renderables.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const overallSize = overall.getSize(new THREE22.Vector3);
+ const overall = renderables.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const overallSize = overall.getSize(new THREE23.Vector3);
const findings = [];
for (const value of renderables) {
- const size = value.box.getSize(new THREE22.Vector3);
- const center = value.box.getCenter(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
+ const center = value.box.getCenter(new THREE23.Vector3);
const names = [value.node.name, ...value.roles];
const nameEvidence = names.some((name) => CLUTTER_NAME.test(name));
const roleEvidence = value.roles.some((role) => /(?:terrain|soil|rock|pot|planter|base)/i.test(role));
@@ -16351,8 +16593,8 @@ function evaluateVegetationScopeQa(context) {
function unionVolume(boxes) {
if (boxes.length === 0)
return 0;
- const union = boxes.reduce((result, box) => result.union(box), new THREE22.Box3);
- const size = union.getSize(new THREE22.Vector3);
+ const union = boxes.reduce((result, box) => result.union(box), new THREE23.Box3);
+ const size = union.getSize(new THREE23.Vector3);
return size.x * size.y * size.z;
}
function projectedOccupancy(boxes, axes) {
@@ -16422,7 +16664,7 @@ function boxDistanceToPoint(box, point) {
function endpointRadius(position, axis, axisValue, tolerance, scale) {
const radialAxes = [0, 1, 2].filter((value) => value !== axis);
const points = [];
- const point = new THREE22.Vector3;
+ const point = new THREE23.Vector3;
for (let index = 0;index < position.count; index++) {
point.fromBufferAttribute(position, index);
if (Math.abs(point.getComponent(axis) - axisValue) <= tolerance)
@@ -16430,7 +16672,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
}
if (points.length === 0)
return;
- const center = new THREE22.Vector3;
+ const center = new THREE23.Vector3;
center.setComponent(axis, axisValue);
for (const radialAxis of radialAxes) {
center.setComponent(radialAxis, points.reduce((sum, value) => sum + value.getComponent(radialAxis), 0) / points.length);
@@ -16444,7 +16686,7 @@ function endpointRadius(position, axis, axisValue, tolerance, scale) {
return { center, radius };
}
function growthNodeMeasurement(root, candidate, allCandidates, band) {
- if (!(candidate.node instanceof THREE22.Mesh))
+ if (!(candidate.node instanceof THREE23.Mesh))
return;
const geometry = candidate.node.geometry;
const position = geometry.getAttribute("position");
@@ -16456,9 +16698,9 @@ function growthNodeMeasurement(root, candidate, allCandidates, band) {
return;
root.updateWorldMatrix(true, true);
const relative = root.matrixWorld.clone().invert().multiply(candidate.node.matrixWorld);
- const relativeScale = new THREE22.Vector3;
- relative.decompose(new THREE22.Vector3, new THREE22.Quaternion, relativeScale);
- const size = geometryBox.getSize(new THREE22.Vector3);
+ const relativeScale = new THREE23.Vector3;
+ relative.decompose(new THREE23.Vector3, new THREE23.Quaternion, relativeScale);
+ const size = geometryBox.getSize(new THREE23.Vector3);
const scaledSizes = [
Math.abs(size.x * relativeScale.x),
Math.abs(size.y * relativeScale.y),
@@ -16525,7 +16767,7 @@ function measureVegetationGrowth(intent, root) {
};
}
function evaluateVegetationGrowthQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationGrowth(context.intent, context.scene);
const findings = [];
@@ -16576,7 +16818,7 @@ function measureVegetationFoliageAttachment(root) {
const support = renderables.filter((value) => roleOrNameSource(value, TRUNK_PATTERNS) || roleOrNameSource(value, BRANCH_PATTERNS));
const foliage = renderables.filter((value) => roleOrNameSource(value, CANOPY_PATTERNS));
const clusters = foliage.map((value) => {
- const size = value.box.getSize(new THREE22.Vector3);
+ const size = value.box.getSize(new THREE23.Vector3);
const threshold = stable3(Math.max(0.03, Math.min(0.18, size.length() * 0.12)));
const nearest = support.map((candidate) => ({ candidate, gap: distanceBetweenBoxes(value.box, candidate.box) })).sort((a, b) => a.gap - b.gap || (a.candidate.node.name || "").localeCompare(b.candidate.node.name || ""))[0];
const source = roleOrNameSource(value, CANOPY_PATTERNS) ?? "fallback";
@@ -16599,7 +16841,7 @@ function measureVegetationFoliageAttachment(root) {
};
}
function evaluateVegetationFoliageAttachmentQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
return measureVegetationFoliageAttachment(context.scene).clusters.filter((cluster) => cluster.detached).map((cluster) => finding2(context, {
code: "VEG_FOLIAGE_DETACHED",
@@ -16619,9 +16861,9 @@ function evaluateVegetationFoliageAttachmentQa(context) {
}
function relativeTransformSignature(root, node) {
const matrix = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
- const scale = new THREE22.Vector3;
- const quaternion = new THREE22.Quaternion;
- matrix.decompose(new THREE22.Vector3, quaternion, scale);
+ const scale = new THREE23.Vector3;
+ const quaternion = new THREE23.Quaternion;
+ matrix.decompose(new THREE23.Vector3, quaternion, scale);
if (quaternion.w < 0)
quaternion.set(-quaternion.x, -quaternion.y, -quaternion.z, -quaternion.w);
const values = [...scale.toArray(), ...quaternion.toArray()].map((value) => stable3(value));
@@ -16642,9 +16884,9 @@ function measureVegetationRepetition(intent, root) {
nodes: values.map((value) => value.node.name || "foliage-cluster").sort()
})).sort((a, b) => a.signature.localeCompare(b.signature));
const supports = collectRenderableBounds(root).filter((value) => roleOrNameSource(value, TRUNK_PATTERNS));
- const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE22.Box3);
- const centers = foliage.map((value) => value.box.getCenter(new THREE22.Vector3));
- const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE22.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE22.Vector3);
+ const centerBox = supports.reduce((box, value) => box.union(value.box), new THREE23.Box3);
+ const centers = foliage.map((value) => value.box.getCenter(new THREE23.Vector3));
+ const center = centerBox.isEmpty() ? centers.reduce((result, value) => result.add(value), new THREE23.Vector3).multiplyScalar(centers.length > 0 ? 1 / centers.length : 0) : centerBox.getCenter(new THREE23.Vector3);
const radial = centers.map((value) => ({
angle: Math.atan2(value.z - center.z, value.x - center.x),
radius: Math.hypot(value.x - center.x, value.z - center.z)
@@ -16679,7 +16921,7 @@ function measureVegetationRepetition(intent, root) {
};
}
function evaluateVegetationRepetitionQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationRepetition(context.intent, context.scene);
if (measured.suppressedForTopiary)
@@ -16738,7 +16980,7 @@ function measureVegetationCanopy(intent, root) {
}
function evaluateVegetationCanopyQa(context) {
const trusted = vegetationIntent(context.intent);
- if (!trusted || !(context.scene instanceof THREE22.Object3D))
+ if (!trusted || !(context.scene instanceof THREE23.Object3D))
return [];
const measurements = measureVegetationCanopy(context.intent, context.scene);
const bands = PROFILE_BANDS[measurements.profile];
@@ -16799,7 +17041,7 @@ function evaluateVegetationCanopyQa(context) {
return findings;
}
function materialValue(material) {
- if (!(material instanceof THREE22.MeshStandardMaterial) && !(material instanceof THREE22.MeshBasicMaterial)) {
+ if (!(material instanceof THREE23.MeshStandardMaterial) && !(material instanceof THREE23.MeshBasicMaterial)) {
return;
}
const color = material.color;
@@ -16809,11 +17051,11 @@ function measureVegetationFoliageMaterials(intent, root) {
const values = [];
let foliageNodeCount = 0;
root.traverse((node) => {
- if (!(node instanceof THREE22.Mesh))
+ if (!(node instanceof THREE23.Mesh))
return;
const bounds = {
node,
- box: new THREE22.Box3,
+ box: new THREE23.Box3,
roles: rolesOf(node),
source: rolesOf(node).length > 0 ? "semantic" : "fallback"
};
@@ -16840,7 +17082,7 @@ function measureVegetationFoliageMaterials(intent, root) {
};
}
function evaluateVegetationMaterialQa(context) {
- if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE22.Object3D))
+ if (context.intent.category !== "vegetation" || !(context.scene instanceof THREE23.Object3D))
return [];
const measured = measureVegetationFoliageMaterials(context.intent, context.scene);
if (measured.foliageNodeCount === 0 || measured.coherent)
@@ -16976,7 +17218,7 @@ var init_vegetation = __esm(() => {
});
// src/qa/prop.ts
-import * as THREE23 from "three";
+import * as THREE24 from "three";
function finding3(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE3 };
}
@@ -16995,11 +17237,11 @@ function nodePath2(root, node) {
return names.reverse().join("/");
}
function transformedBox(source, transform) {
- const result = new THREE23.Box3;
+ const result = new THREE24.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE23.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE24.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -17011,15 +17253,15 @@ function collectParts(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf2(node);
- const renderable = node instanceof THREE23.Mesh;
+ const renderable = node instanceof THREE24.Mesh;
let box;
- if (renderable && node.geometry instanceof THREE23.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE24.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
box = transformedBox(node.geometry.boundingBox, rootInverse.clone().multiply(node.matrixWorld));
}
} else if (roles.length > 0) {
- box = transformedBox(new THREE23.Box3(new THREE23.Vector3(-0.5, -0.5, -0.5), new THREE23.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
+ box = transformedBox(new THREE24.Box3(new THREE24.Vector3(-0.5, -0.5, -0.5), new THREE24.Vector3(0.5, 0.5, 0.5)), rootInverse.clone().multiply(node.matrixWorld));
}
if (box?.isEmpty())
box = undefined;
@@ -17109,14 +17351,14 @@ function legacyArticulationEvidence(context, root) {
});
if (joints.length === 0)
return false;
- const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE23.AnimationClip);
+ const clips = (context.clips ?? []).filter((clip) => clip instanceof THREE24.AnimationClip);
if ((context.intent.animation?.clips.length ?? 0) === 0 && clips.length === 0)
return true;
const targets = new Set(clips.flatMap((clip) => clip.tracks.map((track) => track.name.split(".")[0] ?? "")));
return joints.some((joint) => targets.has(joint));
}
function evaluatePropArticulationQa(context) {
- if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE23.Object3D)) {
+ if (context.intent.category !== "prop" || !context.intent.capabilities.includes("articulated") || !(context.scene instanceof THREE24.Object3D)) {
return [];
}
const root = context.scene;
@@ -17230,11 +17472,11 @@ function rolePart(parts, expression) {
return parts.find((part) => part.roles.some((role) => expression.test(role)));
}
function interiorUsable(box) {
- const size = box.getSize(new THREE23.Vector3);
+ const size = box.getSize(new THREE24.Vector3);
return size.x >= 0.08 && size.y >= 0.08 && size.z >= 0.08;
}
function evaluatePropContainerQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const explicitlyOpen = context.intent.capabilities.includes("openable");
const explicitContainment = /^(?:open-)?(?:container|chest|case|box)$/i.test(context.intent.subtype ?? "");
@@ -17284,7 +17526,7 @@ function evaluatePropContainerQa(context) {
repairText: "Add a non-rendered scaled prop.container.interior.main marker inside the shell."
}));
} else if (!interiorUsable(interior.box)) {
- const size = interior.box.getSize(new THREE23.Vector3);
+ const size = interior.box.getSize(new THREE24.Vector3);
findings.push(finding3(context, {
code: "PROP_CONTAINER_INTERIOR_UNUSABLE",
disposition: "block",
@@ -17342,21 +17584,21 @@ function evaluatePropContainerQa(context) {
return findings;
}
function horizontalDirection(part, root) {
- if (!(part.node instanceof THREE23.Mesh) || !(part.node.geometry instanceof THREE23.BufferGeometry)) {
+ if (!(part.node instanceof THREE24.Mesh) || !(part.node.geometry instanceof THREE24.BufferGeometry)) {
return;
}
part.node.geometry.computeBoundingBox();
const box = part.node.geometry.boundingBox;
if (!box)
return;
- const size = box.getSize(new THREE23.Vector3);
- const axis = size.x >= size.z ? new THREE23.Vector3(1, 0, 0) : new THREE23.Vector3(0, 0, 1);
+ const size = box.getSize(new THREE24.Vector3);
+ const axis = size.x >= size.z ? new THREE24.Vector3(1, 0, 0) : new THREE24.Vector3(0, 0, 1);
root.updateWorldMatrix(true, true);
- const rootQuaternion = root.getWorldQuaternion(new THREE23.Quaternion).invert();
- return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE23.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
+ const rootQuaternion = root.getWorldQuaternion(new THREE24.Quaternion).invert();
+ return axis.applyQuaternion(part.node.getWorldQuaternion(new THREE24.Quaternion)).applyQuaternion(rootQuaternion).setY(0).normalize();
}
function evaluatePropCircularAssemblyQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
@@ -17367,8 +17609,8 @@ function evaluatePropCircularAssemblyQa(context) {
const memberParts = parts.filter((part) => part.box && (part.roles.some((role) => role.startsWith("prop.circular.member.")) || namedProfile && /(?:stave|ring[_.-]?segment)/i.test(part.node.name)));
if (memberParts.length < 3)
return [];
- const centers = memberParts.map((part) => part.box.getCenter(new THREE23.Vector3));
- const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE23.Vector3).multiplyScalar(1 / centers.length);
+ const centers = memberParts.map((part) => part.box.getCenter(new THREE24.Vector3));
+ const ringCenter = centers.reduce((sum, center) => sum.add(center), new THREE24.Vector3).multiplyScalar(1 / centers.length);
const members = memberParts.map((part, index) => {
const center = centers[index];
return {
@@ -17407,7 +17649,7 @@ function evaluatePropCircularAssemblyQa(context) {
if (!member.horizontalDirection)
return false;
const radial = member.center.clone().sub(ringCenter).setY(0).normalize();
- const tangent = new THREE23.Vector3(-radial.z, 0, radial.x);
+ const tangent = new THREE24.Vector3(-radial.z, 0, radial.x);
const radialScore = Math.abs(member.horizontalDirection.dot(radial));
const tangentScore = Math.abs(member.horizontalDirection.dot(tangent));
return expectedOrientation === "tangent" ? tangentScore + 0.1 < radialScore : radialScore + 0.1 < tangentScore;
@@ -17434,15 +17676,15 @@ function evaluatePropCircularAssemblyQa(context) {
return findings;
}
function evaluatePropScalePivotQa(context) {
- if (context.intent.category !== "prop" || !(context.scene instanceof THREE23.Object3D))
+ if (context.intent.category !== "prop" || !(context.scene instanceof THREE24.Object3D))
return [];
const root = context.scene;
const parts = collectParts(root);
const renderable = parts.filter((part) => part.renderable && part.box);
if (renderable.length === 0)
return [];
- const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE23.Box3);
- const size = bounds.getSize(new THREE23.Vector3);
+ const bounds = renderable.reduce((box, part) => box.union(part.box), new THREE24.Box3);
+ const size = bounds.getSize(new THREE24.Vector3);
const findings = [];
for (const axis of ["x", "y", "z"]) {
const expected = context.intent.bounds?.[axis];
@@ -17489,7 +17731,7 @@ function evaluatePropScalePivotQa(context) {
}
const placement = parts.find((part) => part.roles.includes("prop.pivot.placement"));
if (placement) {
- const point = placement.node.getWorldPosition(new THREE23.Vector3);
+ const point = placement.node.getWorldPosition(new THREE24.Vector3);
point.applyMatrix4(root.matrixWorld.clone().invert());
const horizontalOutside = point.x < bounds.min.x - GROUND_TOLERANCE_METERS || point.x > bounds.max.x + GROUND_TOLERANCE_METERS || point.z < bounds.min.z - GROUND_TOLERANCE_METERS || point.z > bounds.max.z + GROUND_TOLERANCE_METERS;
const verticalDelta = Math.abs(point.y - bounds.min.y);
@@ -17552,7 +17794,7 @@ var init_prop = __esm(() => {
});
// src/qa/part-connectivity.ts
-import * as THREE24 from "three";
+import * as THREE25 from "three";
function collectParts2(root, exempt) {
const parts = [];
root.updateWorldMatrix(true, true);
@@ -17565,7 +17807,7 @@ function collectParts2(root, exempt) {
exempt.push(name);
return;
}
- const box = new THREE24.Box3().setFromObject(mesh);
+ const box = new THREE25.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, box });
@@ -17660,7 +17902,7 @@ var init_part_connectivity = __esm(() => {
owner: KILN_ENGINE_QA_OWNER,
defaultMode: "observe",
evaluate(context) {
- if (!(context.scene instanceof THREE24.Object3D))
+ if (!(context.scene instanceof THREE25.Object3D))
return [];
const report = analyzePartConnectivity(context.scene);
if (report.groups.length === 0)
@@ -17750,7 +17992,7 @@ var init_reference_comparison = __esm(() => {
});
// src/qa/self-intersection.ts
-import * as THREE25 from "three";
+import * as THREE26 from "three";
function triangleCount(geometry) {
const index = geometry.getIndex();
const position = geometry.getAttribute("position");
@@ -17776,7 +18018,7 @@ function collectParts3(root, skipped) {
});
return;
}
- const box = new THREE25.Box3().setFromObject(mesh);
+ const box = new THREE26.Box3().setFromObject(mesh);
if (box.isEmpty())
return;
parts.push({ name, mesh, box, triangles });
@@ -17789,7 +18031,7 @@ function meshToArrays(mesh) {
if (!position)
return null;
const matrix = mesh.matrixWorld;
- const v = new THREE25.Vector3;
+ const v = new THREE26.Vector3;
const verts = new Float32Array(position.count * 3);
for (let i = 0;i < position.count; i++) {
v.set(position.getX(i), position.getY(i), position.getZ(i)).applyMatrix4(matrix);
@@ -17952,7 +18194,7 @@ var init_self_intersection = __esm(() => {
});
// src/qa/environment.ts
-import * as THREE26 from "three";
+import * as THREE27 from "three";
function finding4(context, value) {
return { ...value, profile: context.intent.qaProfile || PROFILE4 };
}
@@ -17971,11 +18213,11 @@ function nodePath3(root, node) {
return names.reverse().join("/");
}
function transformedBox2(source, transform) {
- const result = new THREE26.Box3;
+ const result = new THREE27.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE26.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -17985,16 +18227,16 @@ function orientedBoxFromLocalBounds(root, node, source) {
const relative = root.matrixWorld.clone().invert().multiply(node.matrixWorld);
if (!relative.elements.every(Number.isFinite))
return;
- const position = new THREE26.Vector3;
- const rotation = new THREE26.Quaternion;
- const scale = new THREE26.Vector3;
+ const position = new THREE27.Vector3;
+ const rotation = new THREE27.Quaternion;
+ const scale = new THREE27.Vector3;
relative.decompose(position, rotation, scale);
- const recomposed = new THREE26.Matrix4().compose(position, rotation, scale);
+ const recomposed = new THREE27.Matrix4().compose(position, rotation, scale);
const residual = Math.max(...relative.elements.map((component, index) => Math.abs(component - (recomposed.elements[index] ?? component))));
if (residual > 0.00001)
return;
- const center = source.getCenter(new THREE26.Vector3).applyMatrix4(relative);
- const sourceHalf = source.getSize(new THREE26.Vector3).multiplyScalar(0.5);
+ const center = source.getCenter(new THREE27.Vector3).applyMatrix4(relative);
+ const sourceHalf = source.getSize(new THREE27.Vector3).multiplyScalar(0.5);
const halfExtents = [
Math.abs(sourceHalf.x * scale.x),
Math.abs(sourceHalf.y * scale.y),
@@ -18015,17 +18257,17 @@ function collectParts4(root) {
const result = [];
root.traverse((node) => {
const roles = rolesOf3(node);
- const renderable = node instanceof THREE26.Mesh;
+ const renderable = node instanceof THREE27.Mesh;
let box;
let orientedBox;
let source;
- if (renderable && node.geometry instanceof THREE26.BufferGeometry) {
+ if (renderable && node.geometry instanceof THREE27.BufferGeometry) {
node.geometry.computeBoundingBox();
if (node.geometry.boundingBox) {
source = node.geometry.boundingBox;
}
} else if (roles.length > 0) {
- source = new THREE26.Box3(new THREE26.Vector3(-0.5, -0.5, -0.5), new THREE26.Vector3(0.5, 0.5, 0.5));
+ source = new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.5), new THREE27.Vector3(0.5, 0.5, 0.5));
}
if (source) {
box = transformedBox2(source, rootInverse.clone().multiply(node.matrixWorld));
@@ -18053,9 +18295,9 @@ function resolveSocket(root, node, socket) {
return;
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const point = new THREE26.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const rootInverseQuaternion = root.getWorldQuaternion(new THREE26.Quaternion).invert();
- const rotation = node.getWorldQuaternion(new THREE26.Quaternion).multiply(new THREE26.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
+ const point = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const rootInverseQuaternion = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rotation = node.getWorldQuaternion(new THREE27.Quaternion).multiply(new THREE27.Quaternion(...frame.rotation)).premultiply(rootInverseQuaternion).normalize();
return {
id: socket.id,
type: socket.type,
@@ -18084,7 +18326,7 @@ function socketByType(sockets, type) {
return sockets.find((socket) => socket.type === type);
}
function evaluateEnvironmentSocketQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18148,7 +18390,7 @@ function materialSignature(material) {
function boundarySamples(root, axis, side, bins = 12) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
- const bounds = new THREE26.Box3().setFromObject(root);
+ const bounds = new THREE27.Box3().setFromObject(root);
const localBounds = transformedBox2(bounds, root.matrixWorld.clone().invert());
const edge = side === "negative" ? localBounds.min[axis] : localBounds.max[axis];
const axisExtent = localBounds.max[axis] - localBounds.min[axis];
@@ -18158,22 +18400,22 @@ function boundarySamples(root, axis, side, bins = 12) {
const crossExtent = Math.max(0.000000001, localBounds.max[crossAxis] - crossMin);
const byBin = new Map;
root.traverse((node) => {
- if (!(node instanceof THREE26.Mesh) || !(node.geometry instanceof THREE26.BufferGeometry))
+ if (!(node instanceof THREE27.Mesh) || !(node.geometry instanceof THREE27.BufferGeometry))
return;
const positions = node.geometry.getAttribute("position");
if (positions?.itemSize !== 3)
return;
const normals = node.geometry.getAttribute("normal");
const transform = inverse.clone().multiply(node.matrixWorld);
- const normalMatrix = new THREE26.Matrix3().getNormalMatrix(transform);
+ const normalMatrix = new THREE27.Matrix3().getNormalMatrix(transform);
const material = materialSignature(node.material);
for (let index = 0;index < positions.count; index++) {
- const point = new THREE26.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
+ const point = new THREE27.Vector3(positions.getX(index), positions.getY(index), positions.getZ(index)).applyMatrix4(transform);
if (Math.abs(point[axis] - edge) > band)
continue;
- const t = THREE26.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
+ const t = THREE27.MathUtils.clamp((point[crossAxis] - crossMin) / crossExtent, 0, 1);
const bin = Math.min(bins - 1, Math.floor(t * bins));
- const normal = normals ? new THREE26.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE26.Vector3(0, 1, 0);
+ const normal = normals ? new THREE27.Vector3(normals.getX(index), normals.getY(index), normals.getZ(index)).applyMatrix3(normalMatrix).normalize() : new THREE27.Vector3(0, 1, 0);
const current = byBin.get(bin);
if (!current || point.y > current.height || point.y === current.height && normal.y > current.normal.y) {
byBin.set(bin, { bin, height: point.y, normal, material });
@@ -18195,7 +18437,7 @@ function edgePairMeasurements(root, axis, sockets) {
...positive.map((sample) => sample.bin)
]);
const maximumHeightDelta = pairs.length ? Math.max(...pairs.map(([a, b]) => Math.abs(a.height - b.height))) : Number.POSITIVE_INFINITY;
- const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE26.MathUtils.radToDeg(Math.acos(THREE26.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
+ const maximumNormalDeltaDegrees = pairs.length ? Math.max(...pairs.map(([a, b]) => THREE27.MathUtils.radToDeg(Math.acos(THREE27.MathUtils.clamp(a.normal.dot(b.normal), -1, 1))))) : 180;
const materialMismatch = pairs.some(([a, b]) => a.material !== b.material);
const negativeSocket = socketByType(sockets, `environment.tile.${axis}-negative`);
const positiveSocket = socketByType(sockets, `environment.tile.${axis}-positive`);
@@ -18212,7 +18454,7 @@ function edgePairMeasurements(root, axis, sockets) {
};
}
function evaluateEnvironmentTileEdgeQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("tileable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18295,7 +18537,7 @@ function isCorridor(part) {
return part.roles.some((role) => /^environment\.(?:navigation\.)?corridor(?:\.|$)/.test(role));
}
function evaluateEnvironmentNavigabilityQa(context) {
- if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !context.intent.capabilities.includes("navigable") || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18409,7 +18651,7 @@ function functionalLayer(part) {
return part.roles.some((role) => role.startsWith("environment.functional") || role.startsWith("environment.layer") || role.startsWith("environment.path") || role.startsWith("environment.road") || role.startsWith("environment.bridge") || role.startsWith("environment.gate"));
}
function evaluateEnvironmentGroundQa(context) {
- if (context.intent.category !== "environment" || !(context.scene instanceof THREE26.Object3D)) {
+ if (context.intent.category !== "environment" || !(context.scene instanceof THREE27.Object3D)) {
return [];
}
const root = context.scene;
@@ -18456,7 +18698,7 @@ function evaluateEnvironmentGroundQa(context) {
}));
}
}
- const size = box.getSize(new THREE26.Vector3);
+ const size = box.getSize(new THREE27.Vector3);
if (box.min.y < -0.05 && size.y <= Math.max(0.05, Math.min(size.x, size.z) * 0.03) && Math.max(size.x, size.z) >= 1) {
findings.push(finding4(context, {
code: "ENV_GROUND_UNDECLARED_SKIRT",
@@ -18983,7 +19225,7 @@ var init_breadth2 = __esm(() => {
});
// src/qa/breadth-evidence.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
function record3(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -19005,7 +19247,7 @@ function isAnimationClip(value) {
function localRenderableBox(rootInverse, node) {
if (isSpriteNode(node)) {
const transform = rootInverse.clone().multiply(node.matrixWorld);
- return new THREE27.Box3(new THREE27.Vector3(-0.5, -0.5, -0.0005), new THREE27.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
+ return new THREE28.Box3(new THREE28.Vector3(-0.5, -0.5, -0.0005), new THREE28.Vector3(0.5, 0.5, 0.0005)).applyMatrix4(transform);
}
if (!isMeshNode(node) || !node.geometry?.isBufferGeometry)
return;
@@ -19014,11 +19256,11 @@ function localRenderableBox(rootInverse, node) {
if (!source || source.isEmpty())
return;
const transform = rootInverse.clone().multiply(node.matrixWorld);
- const result = new THREE27.Box3;
+ const result = new THREE28.Box3;
for (const x of [source.min.x, source.max.x]) {
for (const y of [source.min.y, source.max.y]) {
for (const z of [source.min.z, source.max.z]) {
- result.expandByPoint(new THREE27.Vector3(x, y, z).applyMatrix4(transform));
+ result.expandByPoint(new THREE28.Vector3(x, y, z).applyMatrix4(transform));
}
}
}
@@ -19106,10 +19348,10 @@ function isEffectSurface(nodes) {
function coverageRatio(boxes, overall) {
if (boxes.length === 0 || overall.isEmpty())
return 0;
- const overallSize = overall.getSize(new THREE27.Vector3);
+ const overallSize = overall.getSize(new THREE28.Vector3);
const denominator = Math.max(0.000000001, overallSize.x * overallSize.y, overallSize.z * overallSize.y, overallSize.x * overallSize.z);
const area = boxes.reduce((sum, box) => {
- const size = box.getSize(new THREE27.Vector3);
+ const size = box.getSize(new THREE28.Vector3);
return sum + Math.max(size.x * size.y, size.z * size.y, size.x * size.z);
}, 0);
return stable7(Math.min(1, area / denominator));
@@ -19118,7 +19360,7 @@ function collectMaterialEvidence(root, intent) {
root.updateWorldMatrix(true, true);
const inverse = root.matrixWorld.clone().invert();
const byMaterial = new Map;
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (!box || !isMeshNode(node) && !isSpriteNode(node))
@@ -19143,7 +19385,7 @@ function collectMaterialEvidence(root, intent) {
effectSurface: isEffectSurface(value.nodes),
alphaMode: mode,
alphaData: alphaData(material),
- doubleSided: material.side === THREE27.DoubleSide,
+ doubleSided: material.side === THREE28.DoubleSide,
...mode === "mask" ? { alphaCutoff: standard.alphaTest ?? 0 } : {},
screenAreaRatio: coverageRatio(value.boxes, overall),
transparentLayers: mode === "blend" ? value.nodes.length : 0,
@@ -19171,23 +19413,23 @@ function dominantGeometryAxis(root, mode) {
const bounds = node.geometry.boundingBox;
if (!bounds || bounds.isEmpty())
return;
- const size = bounds.getSize(new THREE27.Vector3);
+ const size = bounds.getSize(new THREE28.Vector3);
const axes = [
- { score: size.x, direction: new THREE27.Vector3(1, 0, 0) },
- { score: size.y, direction: new THREE27.Vector3(0, 1, 0) },
- { score: size.z, direction: new THREE27.Vector3(0, 0, 1) }
+ { score: size.x, direction: new THREE28.Vector3(1, 0, 0) },
+ { score: size.y, direction: new THREE28.Vector3(0, 1, 0) },
+ { score: size.z, direction: new THREE28.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const relative = inverse.clone().multiply(node.matrixWorld);
const direction = selected.direction.transformDirection(relative);
- const score = selected.score * node.getWorldScale(new THREE27.Vector3).length();
+ const score = selected.score * node.getWorldScale(new THREE28.Vector3).length();
if (!best || (mode === "length" ? score > best.score : score < best.score)) {
best = { score, direction };
}
});
if (best)
return signedAxis(best.direction);
- const overall = new THREE27.Box3;
+ const overall = new THREE28.Box3;
root.traverse((node) => {
const box = localRenderableBox(inverse, node);
if (box)
@@ -19195,8 +19437,8 @@ function dominantGeometryAxis(root, mode) {
});
if (overall.isEmpty())
return "+X";
- const size = overall.getSize(new THREE27.Vector3);
- const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE27.Vector3(1, 0, 0) : size.y >= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE27.Vector3(1, 0, 0) : size.y <= size.z ? new THREE27.Vector3(0, 1, 0) : new THREE27.Vector3(0, 0, 1);
+ const size = overall.getSize(new THREE28.Vector3);
+ const vector = mode === "length" ? size.x >= size.y && size.x >= size.z ? new THREE28.Vector3(1, 0, 0) : size.y >= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1) : size.x <= size.y && size.x <= size.z ? new THREE28.Vector3(1, 0, 0) : size.y <= size.z ? new THREE28.Vector3(0, 1, 0) : new THREE28.Vector3(0, 0, 1);
return signedAxis(vector);
}
function analyzedFacing(root, intent) {
@@ -19318,21 +19560,21 @@ function pathOf2(root, node) {
function analyzeSockets(root) {
root.updateWorldMatrix(true, true);
const rootInverse = root.matrixWorld.clone().invert();
- const rootWorldRotation = root.getWorldQuaternion(new THREE27.Quaternion).invert();
+ const rootWorldRotation = root.getWorldQuaternion(new THREE28.Quaternion).invert();
const values = [];
root.traverse((node) => {
const metadata = readSemanticMetadataV1(node);
if (!metadata)
return;
- const nodeWorldRotation = node.getWorldQuaternion(new THREE27.Quaternion);
+ const nodeWorldRotation = node.getWorldQuaternion(new THREE28.Quaternion);
for (const socket of metadata.sockets) {
const frame = metadata.frames.find((candidate) => candidate.id === socket.frame);
if (!frame)
continue;
- const frameRotation = new THREE27.Quaternion(...frame.rotation);
+ const frameRotation = new THREE28.Quaternion(...frame.rotation);
const worldRotation = rootWorldRotation.clone().multiply(nodeWorldRotation).multiply(frameRotation);
- const position = new THREE27.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
- const normal = new THREE27.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
+ const position = new THREE28.Vector3(...frame.translation).applyMatrix4(node.matrixWorld).applyMatrix4(rootInverse);
+ const normal = new THREE28.Vector3(1, 0, 0).applyQuaternion(worldRotation).normalize();
values.push({
contract: {
id: socket.id,
@@ -19365,8 +19607,8 @@ function analyzeModularEvidenceV1(root, trustedGrid) {
if (!pair)
return { kit };
const relative = pair[0].worldRotation.clone().invert().multiply(pair[1].worldRotation);
- const euler = new THREE27.Euler().setFromQuaternion(relative, "YXZ");
- const rotation = THREE27.MathUtils.euclideanModulo(THREE27.MathUtils.radToDeg(euler.y), 360);
+ const euler = new THREE28.Euler().setFromQuaternion(relative, "YXZ");
+ const rotation = THREE28.MathUtils.euclideanModulo(THREE28.MathUtils.radToDeg(euler.y), 360);
return {
kit,
join: {
@@ -19922,9 +20164,7 @@ var init_run = __esm(() => {
});
// src/qa/breadth-final.ts
-import { WebIO } from "@gltf-transform/core";
-import { EXTMeshGPUInstancing } from "@gltf-transform/extensions";
-import * as THREE28 from "three";
+import * as THREE29 from "three";
function bytesContainAscii(bytes, value) {
const needle = new TextEncoder().encode(value);
outer:
@@ -19983,7 +20223,7 @@ function finalEffectAxis(nodes, mode) {
if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {
continue;
}
- const matrix = new THREE28.Matrix4().fromArray(node.getWorldMatrix());
+ const matrix = new THREE29.Matrix4().fromArray(node.getWorldMatrix());
const scale = node.getWorldScale();
const scaleMagnitude = Math.hypot(scale[0], scale[1], scale[2]);
for (const primitive of node.getMesh()?.listPrimitives() ?? []) {
@@ -19993,9 +20233,9 @@ function finalEffectAxis(nodes, mode) {
const min = position.getMin([]);
const max = position.getMax([]);
const axes = [
- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE28.Vector3(1, 0, 0) },
- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE28.Vector3(0, 1, 0) },
- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE28.Vector3(0, 0, 1) }
+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE29.Vector3(1, 0, 0) },
+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE29.Vector3(0, 1, 0) },
+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE29.Vector3(0, 0, 1) }
];
const selected = axes.reduce((candidate, value) => mode === "length" ? value.score > candidate.score ? value : candidate : value.score < candidate.score ? value : candidate);
const candidate = {
@@ -20010,7 +20250,7 @@ function finalEffectAxis(nodes, mode) {
return best ? signedAxis2(best.direction) : undefined;
}
async function analyzeFinalVfxGlbBytesV1(bytes) {
- const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+ const io = createGltfIO();
const document = await io.readBinary(bytes);
const root = document.getRoot();
const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);
@@ -20246,6 +20486,7 @@ async function appendFinalVfxGlbQa(intent, report, bytes) {
}
var stable8 = (value) => Math.round(value * 1e6) / 1e6;
var init_breadth_final = __esm(() => {
+ init_gltf_io();
init_contracts();
init_types();
});
@@ -21373,7 +21614,7 @@ var init_kit = __esm(() => {
// src/texture-bake.ts
import { createHash as createHash5 } from "node:crypto";
-import * as THREE29 from "three";
+import * as THREE30 from "three";
function readPixels(texture) {
const image = texture.image;
if (!image)
@@ -21465,7 +21706,7 @@ async function bakeSceneTextures(root, warnings) {
mime: "image/png",
bytes
};
- const colorSpace = entry.texture.colorSpace === THREE29.SRGBColorSpace ? "srgb" : "linear";
+ const colorSpace = entry.texture.colorSpace === THREE30.SRGBColorSpace ? "srgb" : "linear";
const recipe = entry.texture.userData["kilnProcedural"];
const primaryUsage = recipe?.usage ?? (entry.bindings.some(({ slot }) => slot === "roughnessMap") && entry.bindings.some(({ slot }) => slot === "metalnessMap") ? "metallicRoughness" : entry.bindings[0]?.usage ?? "albedo");
entry.texture.userData["kilnTexture"] = {
@@ -21546,10 +21787,10 @@ function computeTangentBasis(geometry) {
}
}
const out = new Float32Array(vertexCount * 4);
- const n = new THREE29.Vector3;
- const t = new THREE29.Vector3;
- const tmp = new THREE29.Vector3;
- const tmp2 = new THREE29.Vector3;
+ const n = new THREE30.Vector3;
+ const t = new THREE30.Vector3;
+ const tmp = new THREE30.Vector3;
+ const tmp2 = new THREE30.Vector3;
for (let v = 0;v < vertexCount; v++) {
n.set(normal.getX(v), normal.getY(v), normal.getZ(v));
t.set(tan1[v * 3], tan1[v * 3 + 1], tan1[v * 3 + 2]);
@@ -21569,7 +21810,7 @@ function computeTangentBasis(geometry) {
out[v * 4 + 2] = tmp.z;
out[v * 4 + 3] = w;
}
- geometry.setAttribute("tangent", new THREE29.BufferAttribute(out, 4));
+ geometry.setAttribute("tangent", new THREE30.BufferAttribute(out, 4));
}
function ensureNormalMapTangents(root, warnings) {
let count = 0;
@@ -21615,7 +21856,7 @@ var init_texture_bake = __esm(() => {
});
// src/views/character.ts
-import * as THREE30 from "three";
+import * as THREE31 from "three";
function rounded(value) {
const result = Math.round(value * 1e9) / 1e9;
return Object.is(result, -0) ? 0 : result;
@@ -21657,9 +21898,9 @@ function buildCharacterDiagnosticDescriptor(root, findings = []) {
const invalidPaths = new Set(invalidFindingNodePaths);
const joints = evidence.map((joint) => {
const relative = rootInverse.clone().multiply(joint.node.matrixWorld);
- const position = new THREE30.Vector3().setFromMatrixPosition(relative);
- const forward = new THREE30.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
- const bend = new THREE30.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const position = new THREE31.Vector3().setFromMatrixPosition(relative);
+ const forward = new THREE31.Vector3(...joint.descriptor.localForwardAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
+ const bend = new THREE31.Vector3(...joint.descriptor.localBendAxis).transformDirection(relative).multiplyScalar(0.2).add(position);
const chainId = chainIdFor(joint.descriptor, descriptorByRole);
return {
role: joint.descriptor.role,
@@ -22589,24 +22830,18 @@ var init_architecture3 = __esm(() => {
// src/views/glb.ts
import {
- Primitive,
- WebIO as WebIO2
+ Primitive
} from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing2,
- KHRMaterialsVariants as KHRMaterialsVariants2,
- KHRTextureBasisu as KHRTextureBasisu2
-} from "@gltf-transform/extensions";
import {
BufferAttribute as BufferAttribute8,
BufferGeometry as BufferGeometry14,
- Group,
+ Group as Group2,
Matrix4 as Matrix47,
- Mesh as Mesh10,
+ Mesh as Mesh11,
MeshStandardMaterial as MeshStandardMaterial5,
NoColorSpace as NoColorSpace4,
SRGBColorSpace as SRGBColorSpace5,
- Texture,
+ Texture as Texture2,
AnimationClip as AnimationClip3,
QuaternionKeyframeTrack as QuaternionKeyframeTrack2,
VectorKeyframeTrack as VectorKeyframeTrack2,
@@ -22724,7 +22959,7 @@ function preserveTexture(source, usage, cache) {
const existing = byUsage.get(usage);
if (existing)
return existing;
- const texture = new Texture;
+ const texture = new Texture2;
texture.name = source.getName();
texture.colorSpace = usage === "color" ? SRGBColorSpace5 : NoColorSpace4;
texture.userData.encoded = { mime, bytes: Uint8Array.from(encoded) };
@@ -22891,7 +23126,7 @@ async function loadGlbReviewScene(bytes) {
if (!sourceScene)
throw new GlbGeometryFlatError("GLB_FLAT_NO_SCENE", "Final GLB has no scene.");
const reasons = new Set;
- const root = new Group;
+ const root = new Group2;
root.name = sourceScene.getName() || "Scene";
const nodeMap = new Map;
const textureCache = new Map;
@@ -22901,7 +23136,7 @@ async function loadGlbReviewScene(bytes) {
const existing = nodeMap.get(source);
if (existing)
return existing;
- const target = new Group;
+ const target = new Group2;
target.name = source.getName();
target.position.fromArray(source.getTranslation());
target.quaternion.fromArray(source.getRotation());
@@ -22966,7 +23201,7 @@ async function loadGlbReviewScene(bytes) {
threeMaterial.aoMapIntensity = material.getOcclusionStrength();
}
for (const [index, matrix] of matrices.entries()) {
- const mesh = new Mesh10(geometry, threeMaterial);
+ const mesh = new Mesh11(geometry, threeMaterial);
const baseName = source.getName() || sourceMesh.getName() || "Mesh";
mesh.name = `${baseName}:primitive-${primitiveIndex}${matrices.length === 1 ? "" : `:instance-${index}`}`;
mesh.matrixAutoUpdate = false;
@@ -23006,8 +23241,9 @@ async function loadGlbReviewScene(bytes) {
instanceCount
};
}
-var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO = () => new WebIO2().registerExtensions([EXTMeshGPUInstancing2, KHRMaterialsVariants2, KHRTextureBasisu2]);
+var GLB_GEOMETRY_FLAT_REASON, REASON_ORDER, REVIEW_CLIPS_EXTRAS_KEY = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS, GlbGeometryFlatError, glbIO;
var init_glb = __esm(() => {
+ init_gltf_io();
GLB_GEOMETRY_FLAT_REASON = {
TEXTURE_SAMPLING_UNSUPPORTED: "GLB_FLAT_TEXTURE_SAMPLING_UNSUPPORTED",
KTX2_SAMPLING_UNSUPPORTED: "GLB_FLAT_KTX2_SAMPLING_UNSUPPORTED",
@@ -23036,6 +23272,7 @@ var init_glb = __esm(() => {
this.name = "GlbGeometryFlatError";
}
};
+ glbIO = createGltfIO;
});
// src/evaluator/handler.ts
@@ -23489,7 +23726,7 @@ var init_renderer_id = __esm(() => {
});
// src/views/scene-raster.ts
-import * as THREE31 from "three";
+import * as THREE32 from "three";
var DEG2;
var init_scene_raster = __esm(() => {
init_evaluator();
@@ -23500,18 +23737,18 @@ var init_scene_raster = __esm(() => {
});
// src/views/vehicle.ts
-import * as THREE32 from "three";
+import * as THREE33 from "three";
function hasRole2(node, prefix) {
return readSemanticMetadataV1(node)?.roles.some((role) => role === prefix || role.startsWith(`${prefix}.`)) ?? false;
}
function chassisBounds(root, inverse) {
- const bounds = new THREE32.Box3;
+ const bounds = new THREE33.Box3;
let found = false;
root.traverse((node) => {
if (!hasRole2(node, "chassis"))
return;
node.traverse((part) => {
- if (!(part instanceof THREE32.Mesh) || !(part.geometry instanceof THREE32.BufferGeometry))
+ if (!(part instanceof THREE33.Mesh) || !(part.geometry instanceof THREE33.BufferGeometry))
return;
part.geometry.computeBoundingBox();
const box = part.geometry.boundingBox;
@@ -23521,7 +23758,7 @@ function chassisBounds(root, inverse) {
for (const x of [box.min.x, box.max.x])
for (const y of [box.min.y, box.max.y])
for (const z of [box.min.z, box.max.z]) {
- bounds.expandByPoint(new THREE32.Vector3(x, y, z).applyMatrix4(matrix));
+ bounds.expandByPoint(new THREE33.Vector3(x, y, z).applyMatrix4(matrix));
found = true;
}
});
@@ -23589,33 +23826,33 @@ function tagDiagnostic(node, role) {
stampSemanticMetadataV1(node, { roles: [role] });
}
function rod(name, start, end, radius, color, role) {
- const from = new THREE32.Vector3(...start);
- const to = new THREE32.Vector3(...end);
+ const from = new THREE33.Vector3(...start);
+ const to = new THREE33.Vector3(...end);
const direction = to.clone().sub(from);
const length = direction.length();
- const geometry = length > 0.000000001 ? new THREE32.CylinderGeometry(radius, radius, length, 8) : new THREE32.SphereGeometry(radius, 8, 6);
- const result = new THREE32.Mesh(geometry, new THREE32.MeshBasicMaterial({ color }));
+ const geometry = length > 0.000000001 ? new THREE33.CylinderGeometry(radius, radius, length, 8) : new THREE33.SphereGeometry(radius, 8, 6);
+ const result = new THREE33.Mesh(geometry, new THREE33.MeshBasicMaterial({ color }));
result.name = name;
result.position.copy(from).add(to).multiplyScalar(0.5);
if (length > 0.000000001) {
- result.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
+ result.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), direction.multiplyScalar(1 / length));
}
tagDiagnostic(result, role);
return result;
}
function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagnostics(root)) {
- const overlay = new THREE32.Group;
+ const overlay = new THREE33.Group;
overlay.name = "VehicleDiagnosticOverlay";
const chassisSpan = descriptor.chassisBox ? Math.max(descriptor.chassisBox.max[0] - descriptor.chassisBox.min[0], descriptor.chassisBox.max[1] - descriptor.chassisBox.min[1], descriptor.chassisBox.max[2] - descriptor.chassisBox.min[2]) : 1;
const thickness = Math.max(0.01, chassisSpan * 0.008);
- const arrow = new THREE32.Group;
+ const arrow = new THREE33.Group;
arrow.name = "Diagnostic_Forward_+X";
tagDiagnostic(arrow, "diagnostic.vehicle.forward");
arrow.add(rod("Diagnostic_Forward_Shaft", descriptor.forwardArrow.start, [descriptor.forwardArrow.end[0] - 0.12, 0, 0], thickness, 16724804, "diagnostic.vehicle.forward"));
- const arrowHead = new THREE32.Mesh(new THREE32.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE32.MeshBasicMaterial({ color: 16724804 }));
+ const arrowHead = new THREE33.Mesh(new THREE33.ConeGeometry(thickness * 3.2, 0.24, 10), new THREE33.MeshBasicMaterial({ color: 16724804 }));
arrowHead.name = "Diagnostic_Forward_Head";
arrowHead.position.set(descriptor.forwardArrow.end[0] - 0.12, 0, 0);
- arrowHead.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 1, 0), new THREE32.Vector3(1, 0, 0));
+ arrowHead.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 1, 0), new THREE33.Vector3(1, 0, 0));
tagDiagnostic(arrowHead, "diagnostic.vehicle.forward");
arrow.add(arrowHead);
overlay.add(arrow);
@@ -23623,18 +23860,18 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(rod(`Diagnostic_Axle_${axle.id}`, axle.start, axle.end, thickness, 3386111, `diagnostic.vehicle.axle.${axle.id}`));
}
for (const wheel of descriptor.wheels) {
- const ring = new THREE32.Mesh(new THREE32.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE32.MeshBasicMaterial({ color: 16763955 }));
+ const ring = new THREE33.Mesh(new THREE33.TorusGeometry(wheel.radius, Math.min(thickness, wheel.radius * 0.15), 6, 32), new THREE33.MeshBasicMaterial({ color: 16763955 }));
ring.name = `Diagnostic_Wheel_${wheel.id}`;
ring.position.set(...wheel.center);
- const axle = new THREE32.Vector3(...wheel.axle);
+ const axle = new THREE33.Vector3(...wheel.axle);
if (axle.lengthSq() > 0.000000000001) {
- ring.quaternion.setFromUnitVectors(new THREE32.Vector3(0, 0, 1), axle.normalize());
+ ring.quaternion.setFromUnitVectors(new THREE33.Vector3(0, 0, 1), axle.normalize());
}
tagDiagnostic(ring, `diagnostic.vehicle.wheel.${wheel.id}`);
overlay.add(ring);
}
if (descriptor.chassisBox) {
- const chassis = new THREE32.Group;
+ const chassis = new THREE33.Group;
chassis.name = "Diagnostic_ChassisBox";
tagDiagnostic(chassis, "diagnostic.vehicle.chassis");
const { min, max } = descriptor.chassisBox;
@@ -23668,7 +23905,7 @@ function createVehicleDiagnosticOverlay(root, descriptor = describeVehicleDiagno
overlay.add(chassis);
}
if (descriptor.supportPlaneY !== undefined) {
- const plane = new THREE32.Group;
+ const plane = new THREE33.Group;
plane.name = "Diagnostic_SupportPlane";
tagDiagnostic(plane, "diagnostic.vehicle.support-plane");
const halfX = Math.max(1, ...descriptor.chassisBox ? [Math.abs(descriptor.chassisBox.min[0]), Math.abs(descriptor.chassisBox.max[0])] : [], ...descriptor.wheels.map((wheel) => Math.abs(wheel.center[0]) + wheel.radius)) + 0.2;
@@ -24220,7 +24457,7 @@ var init_views = __esm(() => {
});
// src/views/character-capture.ts
-import * as THREE33 from "three";
+import * as THREE34 from "three";
function drawLine2(rgb, width, height, from, to, color) {
let x0 = Math.round(from[0]);
let y0 = Math.round(from[1]);
@@ -24257,22 +24494,22 @@ function drawCross(rgb, width, height, point, color, radius = 3) {
}
function projector(root, cameraId, size) {
root.updateMatrixWorld(true);
- const bounds = new THREE33.Box3().setFromObject(root);
+ const bounds = new THREE34.Box3().setFromObject(root);
if (bounds.isEmpty())
- bounds.set(new THREE33.Vector3(-0.5, 0, -0.5), new THREE33.Vector3(0.5, 1, 0.5));
- const center = bounds.getCenter(new THREE33.Vector3);
- const camera = cameraId === "front" ? new THREE33.Vector3(1, 0, 0) : new THREE33.Vector3(0, 0, 1);
- const upHint = new THREE33.Vector3(0, 1, 0);
- const xAxis = new THREE33.Vector3().crossVectors(upHint, camera).normalize();
- const yAxis = new THREE33.Vector3().crossVectors(camera, xAxis).normalize();
+ bounds.set(new THREE34.Vector3(-0.5, 0, -0.5), new THREE34.Vector3(0.5, 1, 0.5));
+ const center = bounds.getCenter(new THREE34.Vector3);
+ const camera = cameraId === "front" ? new THREE34.Vector3(1, 0, 0) : new THREE34.Vector3(0, 0, 1);
+ const upHint = new THREE34.Vector3(0, 1, 0);
+ const xAxis = new THREE34.Vector3().crossVectors(upHint, camera).normalize();
+ const yAxis = new THREE34.Vector3().crossVectors(camera, xAxis).normalize();
let extent = 0.000001;
for (let corner = 0;corner < 8; corner++) {
- const point = new THREE33.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
+ const point = new THREE34.Vector3(corner & 1 ? bounds.max.x : bounds.min.x, corner & 2 ? bounds.max.y : bounds.min.y, corner & 4 ? bounds.max.z : bounds.min.z).sub(center);
extent = Math.max(extent, Math.abs(point.dot(xAxis)), Math.abs(point.dot(yAxis)));
}
const scale = size * 0.45 / extent;
return (assetPoint) => {
- const world = new THREE33.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
+ const world = new THREE34.Vector3(...assetPoint).applyMatrix4(root.matrixWorld).sub(center);
return [size / 2 + world.dot(xAxis) * scale, size / 2 - world.dot(yAxis) * scale];
};
}
@@ -24395,14 +24632,74 @@ var init_character_capture = __esm(() => {
init_pose();
});
+// src/exporter-node.ts
+var exports_exporter_node = {};
+__export(exports_exporter_node, {
+ nodeExportPlatform: () => nodeExportPlatform
+});
+async function prepareNodeExport(hasTextures) {
+ const host = globalThis;
+ if (!host["FileReader"])
+ host["FileReader"] = ExportFileReader;
+ if (!hasTextures || host["OffscreenCanvas"] || host["document"])
+ return;
+ const { Canvas, ImageData } = await import("@napi-rs/canvas");
+
+ class ExportCanvas extends Canvas {
+ async convertToBlob(options = {}) {
+ const type = options.type ?? options.mime ?? "image/png";
+ if (type !== "image/png" && type !== "image/jpeg" && type !== "image/webp")
+ throw new Error(`Unsupported export image type: ${type}`);
+ const bytes = type === "image/png" ? this.toBuffer("image/png") : this.toBuffer(type);
+ return new Blob([new Uint8Array(bytes)], { type });
+ }
+ }
+ host["OffscreenCanvas"] = ExportCanvas;
+ if (!host["ImageData"])
+ host["ImageData"] = ImageData;
+}
+
+class ExportFileReader {
+ result = null;
+ error = null;
+ onloadend = null;
+ onerror = null;
+ readAsArrayBuffer(blob) {
+ this.read(blob, false);
+ }
+ readAsDataURL(blob) {
+ this.read(blob, true);
+ }
+ read(blob, dataUrl) {
+ blob.arrayBuffer().then((bytes) => {
+ this.result = dataUrl ? `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}` : bytes;
+ this.onloadend?.();
+ }, (error) => {
+ this.error = error;
+ this.onerror?.();
+ this.onloadend?.();
+ });
+ }
+}
+var nodeExportPlatform;
+var init_exporter_node = __esm(() => {
+ nodeExportPlatform = {
+ prepare: prepareNodeExport,
+ async decode(bytes) {
+ const { default: sharp } = await import("sharp");
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return {
+ data: new Uint8Array(decoded.data),
+ width: decoded.info.width,
+ height: decoded.info.height
+ };
+ }
+ };
+});
+
// src/render.ts
-import * as THREE34 from "three";
-import { Document, WebIO as WebIO3, getBounds } from "@gltf-transform/core";
-import {
- EXTMeshGPUInstancing as EXTMeshGPUInstancing3,
- KHRMaterialsVariants as KHRMaterialsVariants3,
- KHRTextureBasisu as KHRTextureBasisu3
-} from "@gltf-transform/extensions";
+import * as THREE35 from "three";
+import { Document, getBounds } from "@gltf-transform/core";
import {
dedup,
instance,
@@ -24536,7 +24833,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (stdMat.transparent) {
mat.setAlphaMode("BLEND");
}
- if (stdMat.side === THREE34.DoubleSide) {
+ if (stdMat.side === THREE35.DoubleSide) {
mat.setDoubleSided(true);
}
if (stdMat.map) {
@@ -24605,7 +24902,7 @@ function bridgeMaterial(doc, threeMat, cache, textureCache) {
} else if (common.transparent || (common.opacity ?? 1) < 1) {
mat.setAlphaMode("BLEND");
}
- if (threeMat.side === THREE34.DoubleSide)
+ if (threeMat.side === THREE35.DoubleSide)
mat.setDoubleSided(true);
if (common.map && !mat.getBaseColorTexture()) {
const texture = bridgeTexture(doc, common.map, textureCache);
@@ -24658,22 +24955,15 @@ function bridgeGeometry(doc, buf, geometry, material, meshName) {
if (!Array.isArray(material))
return mesh.addPrimitive(prim);
const indexValues = indexAttr ? Array.from(indexAttr.array) : Array.from({ length: posAttr.count }, (_, i) => i);
- const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
+ const groups = validateMaterialGroups(geometry, material.length, meshName);
for (const group of groups) {
- if (group.start !== covered || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.count <= 0 || group.start % 3 || group.count % 3 || group.start + group.count > indexValues.length || !material[group.materialIndex ?? 0]) {
- throw new TypeError(`${meshName}: material groups must cover every triangle exactly once with valid material indices.`);
- }
const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]);
for (const semantic of prim.listSemantics())
part.setAttribute(semantic, prim.getAttribute(semantic));
const IndexArray = posAttr.count > 65535 ? Uint32Array : Uint16Array;
part.setIndices(doc.createAccessor(`${meshName}_group_indices`).setArray(new IndexArray(indexValues.slice(group.start, group.start + group.count))).setType(TYPE_SCALAR).setBuffer(buf));
mesh.addPrimitive(part);
- covered += group.count;
}
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
prim.dispose();
return mesh;
}
@@ -24740,7 +25030,7 @@ function bridgeNode(doc, buf, threeObj, matCache, nodeMap, meshCache, texCache)
const cacheKey = `kiln-sprite-quad:${centerX}:${centerY}:${rotation}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- const geometry = new THREE34.PlaneGeometry(1, 1);
+ const geometry = new THREE35.PlaneGeometry(1, 1);
if (centerX !== 0.5 || centerY !== 0.5) {
geometry.translate(0.5 - centerX, 0.5 - centerY, 0);
}
@@ -24892,7 +25182,8 @@ async function renderSceneToGLB(root, opts = {}) {
const clips = opts.clips ?? [];
if (opts.geometryPolicy !== undefined && !["warn", "strict"].includes(opts.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
const tris = countTriangles(root);
const intent = opts.intent ?? createAssetIntentV1({
category: isAssetCategory(opts.category) ? opts.category : "prop"
@@ -24926,19 +25217,28 @@ async function renderSceneToGLB(root, opts = {}) {
throw blocked;
warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
}
- const doc = new Document;
+ const doc = exporter === "three" ? await communitySceneDocument(root, clips, (await Promise.resolve().then(() => (init_exporter_node(), exports_exporter_node))).nodeExportPlatform) : new Document;
doc.getRoot().getAsset().generator = "Kiln";
- const buf = doc.createBuffer();
- const matCache = new Map;
- const meshCache = new Map;
- const texCache = new Map;
- const nodeMap = new Map;
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ if (exporter === "legacy") {
+ const buf = doc.createBuffer();
+ const matCache = new Map;
+ const meshCache = new Map;
+ const texCache = new Map;
+ const nodeMap = new Map;
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? "Scene").addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ } else {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ throw new Error("Community exporter produced no scene.");
+ scene.setName(opts.sceneName ?? "Scene");
+ if (clips.length > 0)
+ scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY2]: reviewClipExtras(clips) });
}
if (opts.dedup !== false) {
try {
@@ -25058,6 +25358,7 @@ async function renderGLBInProcess(code, opts = {}) {
});
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
+ gltfExporter: opts.gltfExporter,
sceneName: meta.name || "Scene",
geometryPolicy: opts.geometryPolicy,
clips,
@@ -25144,12 +25445,12 @@ function collectMeshStats(root) {
return;
const idx = geo.getIndex();
const tri = idx ? idx.count / 3 : (geo.getAttribute("position")?.count ?? 0) / 3;
- const box = new THREE34.Box3().setFromObject(obj);
+ const box = new THREE35.Box3().setFromObject(obj);
if (!Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) {
return;
}
- const center = new THREE34.Vector3;
- const size = new THREE34.Vector3;
+ const center = new THREE35.Vector3;
+ const size = new THREE35.Vector3;
box.getCenter(center);
box.getSize(size);
out.push({
@@ -25164,7 +25465,7 @@ function collectMeshStats(root) {
return out;
}
function minimalGapVector(a, b) {
- const v = new THREE34.Vector3;
+ const v = new THREE35.Vector3;
for (const axis of ["x", "y", "z"]) {
if (a.min[axis] > b.max[axis])
v[axis] = b.max[axis] - a.min[axis];
@@ -25182,10 +25483,10 @@ function inspectSceneStructure(root, opts = {}) {
return warnings;
const cat = opts.category?.toLowerCase();
if (cat === "vehicle" || cat === "weapon" || cat === "boat" || cat === "aircraft") {
- const all = new THREE34.Box3;
+ const all = new THREE35.Box3;
for (const m of meshes)
all.union(m.box);
- const size = new THREE34.Vector3;
+ const size = new THREE35.Vector3;
all.getSize(size);
if (cat === "aircraft") {
if (size.y > size.x * 1.2) {
@@ -25246,9 +25547,11 @@ function inspectSceneStructure(root, opts = {}) {
}
return warnings;
}
-var engineIO = () => new WebIO3().registerExtensions([EXTMeshGPUInstancing3, KHRMaterialsVariants3, KHRTextureBasisu3]), TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
+var engineIO, TYPE_SCALAR = "SCALAR", TYPE_VEC2 = "VEC2", TYPE_VEC3 = "VEC3", TYPE_VEC4 = "VEC4", GROUND_CONTACT_TOLERANCE = 0.02, REVIEW_CLIPS_EXTRAS_KEY2 = "kilnReviewClipsV1", REVIEW_CLIP_LIMITS2, PALETTE_MIN = 4, INSTANCE_MIN = 5;
var init_render = __esm(() => {
init_authoring_diagnostic();
+ init_gltf_io();
+ init_community_exporter();
init_geometry_export();
init_primitives();
init_contracts();
@@ -25265,6 +25568,7 @@ var init_render = __esm(() => {
init_texture_bake();
init_character_capture();
init_vehicle3();
+ engineIO = createGltfIO;
REVIEW_CLIP_LIMITS2 = {
clips: 32,
tracks: 256,
@@ -26713,7 +27017,7 @@ init_render();
init_list_primitives();
init_evaluator();
init_material_resources();
-import * as THREE35 from "three";
+import * as THREE36 from "three";
// src/edit-buffer.ts
class KilnDraftBuffer {
@@ -27017,7 +27321,7 @@ async function renderDerivativeCell(input, context) {
return;
const prepare = (material) => {
const copy = material.clone();
- copy.side = THREE35.DoubleSide;
+ copy.side = THREE36.DoubleSide;
return copy;
};
mesh.material = Array.isArray(mesh.material) ? mesh.material.map(prepare) : prepare(mesh.material);
@@ -27316,16 +27620,16 @@ function collectSceneMetrics(root) {
} else if (mat) {
materialSet.add(mat);
}
- const mb = new THREE35.Box3().setFromObject(node);
+ const mb = new THREE36.Box3().setFromObject(node);
if (!mb.isEmpty() && (!lowestPart || mb.min.y < lowestPart.y)) {
lowestPart = { name: node.name || "(unnamed mesh)", y: mb.min.y };
}
}
});
- const box = new THREE35.Box3().setFromObject(root);
+ const box = new THREE36.Box3().setFromObject(root);
let bbox;
if (!box.isEmpty()) {
- const size = new THREE35.Vector3;
+ const size = new THREE36.Vector3;
box.getSize(size);
bbox = {
min: [box.min.x, box.min.y, box.min.z],
@@ -27939,7 +28243,8 @@ function withBuildCache(context) {
declared ?? scope,
env["KILN_QA_MODE"],
env["KILN_BAKE_OPTIMIZE"],
- env["KILN_BAKE_INSTANCE"]
+ env["KILN_BAKE_INSTANCE"],
+ ...env["KILN_GLTF_EXPORTER"] === "three" ? ["three"] : []
]);
}
})
@@ -28800,6 +29105,9 @@ class FileProgramStore2 {
}
}
+// src/local-runtime.ts
+init_community_exporter();
+
// src/build-cache-node.ts
init_protocol();
import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";
@@ -29065,6 +29373,7 @@ function createLocalToolContext(base = {}, env = process.env) {
const optimize = ["auto", "palette", "full"].includes(env.KILN_BAKE_OPTIMIZE ?? "") ? env.KILN_BAKE_OPTIMIZE : "off";
const instance = ["off", "auto", "on"].includes(env.KILN_BAKE_INSTANCE ?? "") ? env.KILN_BAKE_INSTANCE : "auto";
const maxGlbBytes = 16 * 1024 * 1024;
+ const gltfExporter = resolveGltfExporter(env.KILN_GLTF_EXPORTER ?? "legacy");
const maxResponseBytes = 32 * 1024 * 1024;
const evaluatorPort = {
async render(code, options = {}, controls = {}) {
@@ -29075,6 +29384,7 @@ function createLocalToolContext(base = {}, env = process.env) {
if (options.geometryPolicy !== undefined && !["warn", "strict"].includes(options.geometryPolicy))
throw new Error("geometryPolicy must be warn or strict");
const resolved = {
+ ...gltfExporter === "three" ? { gltfExporter } : {},
optimize,
instance,
...options,
@@ -29169,7 +29479,8 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst
instance: env.KILN_BAKE_INSTANCE ?? "auto",
qa: env.KILN_QA_MODE ?? "enforce",
geometryPolicy: context.geometryPolicy,
- timezone: env.TZ
+ timezone: env.TZ,
+ ...env.KILN_GLTF_EXPORTER === "three" ? { gltfExporter: "three" } : {}
})}`;
context.localExecution = {
...context.localExecution,
diff --git a/docs/community-exporter.md b/docs/community-exporter.md
new file mode 100644
index 00000000..8050bf43
--- /dev/null
+++ b/docs/community-exporter.md
@@ -0,0 +1,95 @@
+# Experimental community glTF exporter
+
+Kiln can qualify Three.js `GLTFExporter` as its scene converter while retaining glTF Transform,
+Kiln validation, texture preparation and semantic metadata policy. The established exporter remains
+the default. This is a migration option, not a claim that every renderer supports every glTF feature.
+
+## Normal workflow and experimental testing
+
+Ordinary users and coding agents can continue using the normal CLI/MCP export workflow.
+For Blender or Unity handoff, read the [handoff guide](engine-handoff.md). It explains when
+trying the experimental converter is useful, how to compare outputs, and how to restore the
+default. Choosing Blender or Unity does not automatically require a different exporter.
+The intended end state remains one qualified default exporter.
+
+## Try the experimental converter from a clone
+
+Use the supported toolchain and build matching runtime bundles first:
+
+```sh
+bun install --frozen-lockfile
+bun run build:runtime
+```
+
+In PowerShell:
+
+```powershell
+$env:KILN_GLTF_EXPORTER = 'three'
+node dist/cli.mjs render /path/to/asset.kiln.js --out /path/to/asset.glb
+Remove-Item Env:KILN_GLTF_EXPORTER
+```
+
+The unset value and `legacy` select the established converter. Unknown values fail. CLI/MCP hosts
+carry this choice as a bounded option to their normal subprocess evaluator; worker environment
+sanitization remains intact. Disk cache identities distinguish backends. Library hosts can set
+`gltfExporter: 'three'` explicitly in render options. Public tool schemas are unchanged.
+
+The candidate uses the optional `@napi-rs/canvas` dependency for headless textured exports. If it is
+unavailable, those exports fail; they do not silently switch converter or drop textures. Flat-material
+exports do not load canvas. Native platform packaging must be qualified before changing the default.
+The headless adapter installs missing exporter-required Blob/image APIs in that host process; it
+does not emulate `document` or `window`. Browser scene conversion uses native image/canvas APIs
+through the same host-injected preparation interface.
+
+Texture transforms are normalized from their effective UV matrix. This preserves rotation
+centers and manually assigned glTF-compatible matrices without modifying the source. A Three.js
+texture combining nonuniform scale with rotation can contain shear, which glTF's texture TRS
+cannot represent. The candidate explicitly rejects such a transform. Lossless UV baking for
+these cases remains a blocker to making it the default; automatic texture/geometry changes
+are not introduced as a fallback.
+
+## What is preserved
+
+The candidate covers triangle meshes, material groups, sprites represented as quads with Kiln facing
+metadata, named transforms, animation channels, vertex colours, additional UVs, morph targets, skins,
+and the standard material extensions understood by the community exporter. Invalid material
+partitions are rejected by the shared preflight. Private `userData` is excluded; versioned Kiln
+semantic extras and bounded review clips retain their existing policy. Export copies keep caller
+texture sources and skeleton references intact.
+
+This describes serialization capability. It does not automatically extend all authoring helpers,
+QA rules, preview materials or optimization algorithms. In particular, skin/morph deformation,
+complex texture transforms, material extensions in every review path, and runtime codec support
+still need feature-specific qualification. Lines/points are explicitly rejected by the experimental
+converter rather than bypassing the triangle pipeline's metadata and geometry policy.
+
+## Qualify a consumer
+
+Keep a canonical GLB and name the actual engine, importer, version and render pipeline in results.
+For example, Unity 6 Built-in RP with glTFast is a different target from Unity URP or an FBX workflow.
+Tests should check hierarchy, world-space positions, part names, material assignments, texture pixels,
+animation motion, and GPU appearance. Valid glTF bytes alone do not establish feature preservation.
+
+Unity's glTFast importer can replace a static single-root object's name with the asset filename.
+Its **Scene Object Creation** setting affects the resulting wrapper. Qualify `Always` if preserving
+the authored root below a wrapper matters; prefer explicit part references or paths relative to that
+root. Do not alter canonical geometry to compensate for an importer naming policy.
+
+For an FBX-only consumer, use an explicit conversion recipe and test the result. Blender's experimental
+space-transform baking can corrupt nested offsets; keeping `bake_space_transform=False` preserved
+the diagnostic fixture. That setting is separate from animation baking. Neither recipe nor exporter
+choice guarantees identical materials after conversion.
+
+Reusable tools:
+
+- [Existing-source corpus comparison](evaluation/community-exporter.md)
+- [Blender/Unity importer assertions](../scripts/integration/README.md)
+- `node scripts/exporter-cli-check.mjs`: built CLI, worker and cross-backend disk-cache smoke.
+
+KTX2/runtime optimization is a separate packaging concern. The exporter migration does not change
+compression defaults. Preserve the interchange asset and qualify codec-dependent derivatives for
+their target consumers.
+
+References: [Three.js exporter](https://threejs.org/docs/pages/GLTFExporter.html),
+[glTF Transform](https://gltf-transform.dev/),
+[Unity glTFast features](https://docs.unity3d.com/Packages/[email protected]/manual/features.html).
diff --git a/docs/engine-handoff.md b/docs/engine-handoff.md
new file mode 100644
index 00000000..a661c0c9
--- /dev/null
+++ b/docs/engine-handoff.md
@@ -0,0 +1,131 @@
+# Blender and Unity handoff
+
+Kiln exports GLB files. **The established exporter is still the default.** Use the normal
+CLI/MCP workflow first; choosing Blender or Unity does not require an exporter switch.
+The experimental Three.js exporter is included in builds containing this integration,
+but older installed releases do not gain it by setting an environment variable.
+
+## Choose the import route
+
+| Destination | Start here | Check in the destination |
+| --- | --- | --- |
+| Blender | Import the GLB through Blender's glTF importer. | Hierarchy, named pivots, materials and intermediate animation poses. |
+| Unity | Use the project's glTF importer; glTFast is the tested route. | Importer version, Built-in/URP/HDRP pipeline, shader support, animation and a player build. |
+| FBX-only workflow | Keep the original GLB and make a separate Blender-to-FBX derivative. | Child offsets, axes, animation and material loss after conversion. |
+
+For Unity, follow the installed importer's setup instructions rather than assuming that
+copying a GLB into Assets is sufficient. Our tested combination is Unity 6000.2.3f1,
+Built-in RP and glTFast 6.20.0. Blender checks used 5.2.0 LTS. These are measured profiles,
+not requirements to downgrade another working project or claims about every pipeline.
+
+glTFast supports more than base colour, including double-sided surfaces, but individual
+material extensions have pipeline-specific limits. Preserve glTF-compatible materials
+when importing; replacing them with a different shader can change the result.
+See the [glTFast feature matrix](https://docs.unity3d.com/Packages/[email protected]/manual/features.html).
+
+## When to try the experimental exporter
+
+Try a comparison if the default export reports a feature it cannot preserve, or the task
+requires candidate capabilities such as vertex colours, extra UV sets, skin/morph data or
+additional physical-material extensions. It can also help isolate an exporter defect from
+an importer problem. **It is not an automatic fix for all Blender/Unity issues.**
+
+Keep the source and baseline GLB. Write the candidate to a different filename, import both
+with the same consumer settings, and report what actually changed. Agents should identify
+the candidate as experimental when using it. Do not silently switch a shared host or claim
+an untested importer works. If the default already meets the task, there is no need to switch.
+
+## CLI: compare without changing the machine configuration
+
+In an asset workspace, use its existing `kiln.mjs` launcher. These PowerShell commands scope
+the selection to the current process and restore its previous value even if export fails:
+
+```powershell
+$previousExporter = $env:KILN_GLTF_EXPORTER
+try {
+ $env:KILN_GLTF_EXPORTER = 'legacy'
+ node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Baseline export failed' }
+
+ $env:KILN_GLTF_EXPORTER = 'three'
+ node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Experimental export failed' }
+} finally {
+ if ($null -eq $previousExporter) { Remove-Item Env:KILN_GLTF_EXPORTER -ErrorAction SilentlyContinue }
+ else { $env:KILN_GLTF_EXPORTER = $previousExporter }
+}
+```
+
+`--render gpu` requires a working GPU renderer and fails if unavailable; it does not accept
+a CPU fallback as material evidence. See Kiln's
+[GPU setup](https://github.com/matthew-kissinger/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
+In a repository clone, use `node dist/cli.mjs` instead of `node kiln.mjs`, after
+`bun install --frozen-lockfile` and `bun run build:runtime`. For an installed distribution,
+use the CLI launcher you already use, from a distribution containing this feature.
+
+In a POSIX shell, selection can be scoped to each invocation:
+
+```sh
+KILN_GLTF_EXPORTER=legacy node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+KILN_GLTF_EXPORTER=three node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+```
+
+## MCP: select at host startup
+
+The exporter is **not a `kiln_render` tool argument**. Set `KILN_GLTF_EXPORTER=three` in the
+environment of the existing Kiln MCP server entry, preserving its command, arguments and
+other settings. For hosts using an `env` object, add this field to that object:
+
+```json
+{ "KILN_GLTF_EXPORTER": "three" }
+```
+
+Restart/reconnect that server so it captures the new setting. Continue using the same tools
+and saved `programRef` values; build caches distinguish backends. To restore the established
+exporter, remove that field or set it to `legacy`, then restart/reconnect again. If an agent
+cannot configure the host, it must not claim to have switched it; a separate CLI comparison
+is available when the agent has terminal access.
+
+New workspaces receive this guide through the authoring/QA skills. Existing workspace skills
+are local copies; updating the engine or running workspace repair does not automatically
+replace edited skills. Consult the updated runtime documentation when working in an older workspace.
+
+## Geometry, materials and moving parts
+
+- **Backfaces:** a single-sided sheet disappearing from behind is expected culling. Use a
+ double-sided material for an intentionally thin surface when the importer supports it.
+ Author actual thickness when the object needs thickness, collision or different surfaces;
+ do not automatically extrude every quad to hide an import problem.
+- **Pivots:** give moving groups stable, descriptive names such as `Joint_VaneSwivel`, with
+ visible geometry beneath them, for example `Mesh_Pennant`. This is an authoring convention,
+ not a required engine prefix. Preserve names across revisions and report the actual part paths.
+- **Unity root names:** glTFast can replace a static single-root name with the asset filename.
+ Check its Scene Object Creation setting; test `Always` if an authored root under a wrapper is
+ needed. Resolve parts relative to the imported root instead of assuming one universal path.
+- **Animation:** play the imported clip and inspect intermediate poses. A clip existing in the
+ file is not proof that its target moves. Check skin/morph deformation where applicable.
+- **FBX:** in Blender's FBX export, leave the experimental Apply Transform option
+ (`bake_space_transform`) disabled for the tested nested-part route. This is separate from
+ Bake Animation. Reimport the FBX and check offsets; materials and sidedness can still change.
+ See [Blender's option documentation](https://docs.blender.org/api/main/bpy.ops.export_scene.html).
+
+## Known experimental limits
+
+- Rotated nonuniform Three.js UV scaling and manually sheared/perspective UV matrices are
+ rejected when they cannot be represented losslessly in glTF texture TRS. Do not remove
+ the transform or silently change the asset just to make export succeed.
+- Textured headless candidate exports need the optional native canvas dependency. If it is
+ unavailable, fix the installation or report the limitation; textures are not silently dropped.
+- Lines/points are outside the candidate's qualified triangle/sprite pipeline.
+- Preserved emissive/unlit properties may look different from older exports that dropped them.
+- More extensions in a valid GLB do not guarantee support in every importer or shader. GPU
+ appearance, runtime-loaded shader inclusion, compression codecs and other render pipelines
+ need their own checks. This option does not change KTX2 defaults or fix unsupported Node versions.
+
+## Delivery checklist for users and agents
+
+Record the source revision, chosen exporter, delivered GLB, consumer/importer versions and
+render pipeline. Check scale and orientation alongside a known object; hierarchy and pivots;
+front/back visibility; materials/textures; and animation/deformation. For Unity delivery,
+exercise a player build as well as the editor. Say which checks were not run. Keep the baseline
+and source so a consumer-specific problem can be reproduced without regenerating the asset.
diff --git a/docs/evaluation/community-exporter.md b/docs/evaluation/community-exporter.md
new file mode 100644
index 00000000..56586001
--- /dev/null
+++ b/docs/evaluation/community-exporter.md
@@ -0,0 +1,325 @@
+# Community exporter qualification
+
+The candidate exporter is experimental. The existing production exporter remains the default until
+the exporter and its downstream processing pass structural, visual, packaging, and real-consumer
+checks. Passing glTF validation alone does not prove that authored features survived export.
+
+## Repeatable existing-asset corpus
+
+Run from the repository root with the pinned Bun toolchain:
+
+```powershell
+bun scripts/integration-corpus.mjs --self-test
+bun scripts/integration-corpus.mjs --out tmp/exporter-corpus/baseline
+$env:KILN_GLTF_EXPORTER = 'three'
+bun scripts/integration-corpus.mjs --out tmp/exporter-corpus/candidate --compare tmp/exporter-corpus/baseline
+Remove-Item Env:KILN_GLTF_EXPORTER
+```
+
+The runner exports every `examples/*.kiln.js` source twice with optimization disabled. Use `--input`
+for a separate authoring workspace, `--filter` for a filename substring, or `--limit` for a smoke run.
+It invokes no image renderer and no live model. Corpus geometry export is independent of CPU/GPU
+view rendering; use GPU rendering in the separate visual qualification.
+
+Each output directory contains the retained GLBs, source and output SHA-256 hashes, semantic
+signatures, and an incrementally written `results.json`. A failure, nondeterministic repeat, or
+signature difference causes a nonzero exit status. A missing baseline is an error, not a pass.
+Run the baseline with the default exporter before enabling the candidate. Output hashes establish
+repeatability within a backend; different binary hashes across exporters are expected and are not
+used as the compatibility verdict.
+
+Signatures cover named hierarchy paths, local/world matrices, undeformed world bounds, vertex
+attributes, index topology, morph targets, skin joints and inverse bind matrices, node extras,
+material assignments and core PBR factors, decoded texture pixels, extension names, and animation
+channel targets/keyframes. Numeric arrays are rounded to six decimal places. The built-in self-test
+checks serialization invariance and detects transform corruption, material changes, and vertex
+changes that leave bounding boxes unchanged.
+
+### Interpretation limits
+
+- Differences need classification. Equivalent primitive reordering or deduplication can produce
+ differences, while extension presence alone does not prove every extension parameter survived.
+- This is a static structural comparison. It does not evaluate skin deformation, sampled animation,
+ shader fidelity, texture sampling/UV transforms, material-variant mapping, or GPU instancing.
+- PNG/JPEG texture pixels are decoded. KTX2/Draco/meshopt packaging is outside this uncompressed
+ interchange corpus and needs a codec-aware qualification suite.
+- Every source receives a generic prop intent so that the exporter comparison uses identical
+ settings. These results are not category-specific authoring QA certification.
+- Existing examples supplement focused fixtures and independently authored dogfood. They do not
+ establish support for features absent from the corpus or prove imports in every engine.
+
+## Baseline evidence
+
+The unchanged main checkout completed `bun run test` on 2026-09-15 UTC: **1,943 passed, 4 skipped,
+0 failed**, across 221 files, in 125.10 seconds. Skips were Windows permissions/symlink checks and
+two pre-existing generated-skill checks. Local log:
+`C:/Users/Mattm/X/kiln-oss/tmp/exporter-corpus/baseline-tests.log`.
+
+Candidate evidence must be recorded separately from this unchanged-main baseline. No release
+conclusion follows from the baseline alone.
+
+The initial default-exporter corpus completed all **86 existing example sources**, each exported
+twice: **172 exports, no failures, all byte-repeatable**. Retained evidence is under
+`tmp/exporter-corpus/baseline/` in the migration worktree. This run began before the candidate
+integration was loaded; subsequent candidate runs compare semantic signatures against these files.
+
+## Initial candidate and default-preservation results
+
+On the migration branch, both the explicit `legacy` backend and experimental `three` backend
+completed all 86 sources twice (344 additional exports), with no export failures and byte-identical
+repeats within each backend.
+
+- **Branch legacy:** all 86 semantic signatures and all 86 GLB SHA-256 hashes match the
+ pre-integration baseline exactly. This includes the shared extension-registration change.
+- **Candidate:** 45 signatures match exactly; 41 show material changes. Across the corpus the only
+ reported difference categories are material-extension presence (500 per-material entries and 41
+ document-level extension lists) and eight roughness values for unlit materials in `crawler-crane`.
+ Forty affected assets gain `KHR_materials_emissive_strength`; `crawler-crane` gains
+ `KHR_materials_unlit`.
+ Their legacy fallback roughness was 1; the community export uses 0.9 plus `KHR_materials_unlit`.
+- **No observed structural differences:** named hierarchy, local/world transforms, undeformed bounds,
+ vertex attributes, index topology, animation channels, node extras, and decoded texture data match
+ wherever those features occur in these examples. This does not establish coverage of all features.
+
+These material changes preserve authored features absent from the legacy conversion, but they are
+still appearance changes that need GPU/consumer qualification. They must not be silently relabeled
+as exact parity. Retained results are `tmp/exporter-corpus/candidate/results.json` and
+`tmp/exporter-corpus/branch-default/results.json`. The comparison command intentionally reports a
+nonzero status when these differences exist; manual classification is recorded here separately.
+
+## Browser qualification
+
+The first direct browser bundle attempt exposed native Node dependencies reachable through the
+candidate exporter (sharp and the native canvas library). The candidate now accepts an injected
+host platform, with native browser decoding as its default. After that boundary change, a direct
+browser bundle of `communitySceneDocument` and its fixture built successfully with no Node shims.
+
+An isolated headless Chrome session executed raw RGBA and encoded PNG texture fixtures, each with a
+named pivot and quaternion animation, twice. Both cases preserved exact decoded pixels, the animation
+channel, and private-metadata filtering, and repeated byte-identically. Both final GLBs passed
+Khronos validation with zero errors. An actual WebGL draw reported **ANGLE NVIDIA GeForce RTX 3070,
+Direct3D11**, with software renderers explicitly rejected by the probe.
+
+Local reproduction/evidence: `tmp/browser-export-audit/browser.ts`, `run.cjs`,
+`browser-results.json`, `browser-{raw,encoded}.glb`, `verified.json`, and `browser-gpu.png`.
+Each browser GLB was also reimported with Three.js GLTFLoader. GPU readbacks of the original and
+reimported scenes at animation times 0, 0.5, and 1 second matched byte-for-byte for both texture
+cases (six comparisons, maximum/mean channel differences both zero). This establishes parity for
+the small textured cube/pivot fixtures, not the entire material portfolio or complete browser
+authoring support.
+
+## CLI worker qualification finding
+
+The first Node 22.23.2 bundled CLI comparison found two boundary problems: a cache entry generated by
+the legacy exporter was reused for the candidate request, and disabling the build cache still
+produced legacy bytes because the sanitized worker environment did not carry the experimental
+selection. These runs establish the legacy CLI baseline only. Candidate CLI acceptance requires
+explicit worker configuration and exporter-specific cache identity, followed by a fresh test of the
+rebuilt package. Environment selection in a parent process alone is not evidence of the worker's
+actual exporter.
+
+After those fixes, `scripts/exporter-cli-check.mjs` exercises the actual bundled entry point with
+one textured, emissive, animated fixture in a fresh temporary workspace. Both exporters share one
+disk cache directory. It requires a distinct first-build key and distinct GLB hash for each backend,
+then requires each second run to hit its own key and return identical bytes. Run it with the
+supported Node executable (or pass `--node <absolute-executable>`); it does not install a runtime or
+rebuild the package. It prints and retains a receipt with runtime version and exact CLI bundle hash.
+
+The gate passed on **Node 22.23.2** for CLI SHA-256
+`a689760533a77bca67680512411e63104bf6b18d4c14b03d6d50d3e5fdda9bc5`.
+Separately, the same bundle exported a procedural-texture fixture and the existing `robot-arm`
+asset through both backends, twice each, with distinct backend keys and successful own-cache hits.
+All eight outputs repeated within their backend; the four unique outputs passed Khronos validation
+with zero errors. The robot retained five textures, one animation, and eight animation channels.
+Texture-fixture signatures match; the robot differs only by two preserved emissive-strength
+material extensions. Evidence: `tmp/browser-export-audit/final-verified.json` and
+`reusable-cli-check.log`. These are Windows bundled-entry checks with installed repository
+dependencies, not clean-install tests on other operating systems.
+
+The final source snapshot was also rerun through both complete 86-asset corpora after worker/cache
+changes: **344 exports, all deterministic, no export failures**. Final default signatures and GLB
+hashes still match all 86 baseline assets exactly. Final candidate differences remain the same
+41 material-only cases classified above. Evidence: `tmp/exporter-corpus/final-default/results.json`
+and `tmp/exporter-corpus/final-candidate/results.json`.
+
+### Rebuilt candidate identity
+
+After the unmatched-animation diagnostic regression was fixed, the bundled CLI cache gate was
+rerun on Node 22.23.2. It passed again with build identity
+`5ab4a924cbcac4120e3e00de43416d42d284535e6259d028cb642c9dcb180dfb`
+and verified CLI SHA-256
+`c2119cae8205f047c0afce084a22a0aeb47415ad193715cad2f0c762ea2d384c`.
+Both backend fixture hashes remain unchanged from the previous successful check, and each backend
+created its own disk-cache key and reused it on its second invocation. Receipt:
+`tmp/browser-export-audit/release-candidate-cli-check.log`.
+
+Both complete corpora were rerun after that last fix: `release-candidate-default` and
+`release-candidate-three` each contain 86 successful, deterministic cases (344 exports total).
+Every semantic signature and every GLB hash matches the corresponding prior `final-default` or
+`final-candidate` run. The advisory fix changes none of these valid existing-asset outputs.
+
+## Release decision
+
+### Authored-asset qualification
+
+Four fresh OpenCode Muse Spark 1.3 Contributor Free assets exercised CLI creation, GPU review,
+targeted edits and same-path output replacement: a sailing vane, textured coolant pump,
+transparent compass and folding solar assembly. Initial author sessions used legacy conversion
+because the subprocess did not receive the experimental selection. This was detected, corrected
+with bounded host-option transport and cache separation, and rechecked; the initial sessions are
+workflow evidence, not candidate-conversion evidence.
+
+After that fix, all four sources were exported through both backends with the packaged Node
+22.23.2 subprocess CLI and GPU8017/Dawn D3D12 on RTX3070. Sailing and assembly image comparisons
+were byte-identical. Mean RGB differences were approximately 0.06015/255 for industrial and
+0.01161/255 for instrument; maximum channel differences were 9 and 8. Both instrument views
+show the same overly milky cover, so asset art quality is not represented as fully accepted.
+An additional bounded Muse session made a targeted pennant edit with two actual candidate GPU
+reviews and repeated same-path export. Author source snapshots and tool/renderer receipts were
+retained outside the checkout.
+
+Blender 5.2.0 LTS and Unity 6000.2.3f1 Built-in RP/glTFast 6.20.0 imported the four actual packaged
+candidate GLBs and passed source-derived pivot, material and sampled-motion expectations.
+Unity's static-root filename policy was identified and recorded as an importer-specific mapping.
+A built Windows Unity player ran these assets using Direct3D11 on RTX3070: 189 renderers, zero
+unsupported/error shaders, and three intended joints moving through native Playables.
+
+The separate technical corpus also imported twelve comparison GLBs into both applications,
+covering colours, extra UVs, morphs, skin data, materials and clips. These receipts establish the
+tested features only. They do not establish every shader extension, skin deformation, runtime
+downloaded GLB shader inclusion, other Unity pipelines, or clean installations on every OS.
+
+### Bugs found during qualification
+
+- Explicit exporter selection was missing from worker transport and disk cache identity.
+- Export texture clones shared their image source with the author scene.
+- Community conversion bypassed legacy material-group partition validation.
+- Transformed `THREE.Scene` roots needed a named Group representation.
+- Unresolved advisory tracks could become invalid empty native glTF animations.
+- Browser conversion needed a host-injected decode boundary instead of Node dependencies.
+
+Each behavior correction has targeted coverage or a repeatable integration gate. The adapter
+continues to reject unsupported lines/points explicitly and to filter metadata on export copies.
+
+### Decision
+
+The final local gate passed 1,961 tests with four intentional skips and zero failures.
+Coverage was 95.18% of functions and 92.83% of lines, above the unchanged 94.00% and 92.10%
+thresholds. Toolchain, skill checks, typecheck, lint, and all 45 render-service tests passed.
+The final packaged Node 22.23.2 subprocess CLI reproduced all five reviewed dogfood GLBs
+byte-for-byte. The existing exporter remains the default; this branch does not approve a
+production rollout or a default-backend switch. Hosted CI results are reported on the PR.
+
+Keep the default unchanged if any required qualification is incomplete or an unexplained
+regression remains. Required evidence includes the complete engine gates, supported-platform
+packaging, independently authored CLI dogfood with GPU reviews, actual Three.js/Blender/Unity
+imports, animation and material checks, and a Unity player build. The engine/importer/version/render
+pipeline combination must be named in results rather than claiming universal engine support.
+
+## Expanded qualification and unified migration
+
+The opt-in backend supports explicit experimental comparisons. The normal CLI/MCP schema is
+unchanged; user and agent handoff documentation explains when testing the candidate is useful,
+how to restore the default, and what remains unsupported. The target is one default implementation
+after the migration gates pass, not a permanent two-exporter product.
+
+### Additional executable evidence
+
+- `src/__tests__/exporter-deformation.test.ts` samples combined skin and morph motion before
+ export and after GLTFLoader reload, both before and after the full optimization request.
+ Nonzero deformation must match at four sample times, within 1e-5 world units.
+- Physical-material tests assert actual clearcoat, transmission, volume, IOR, specular, sheen,
+ iridescence and anisotropy factors before/after palette rewriting, not just extension names.
+- Clean npm package checks require a textured candidate export through the real subprocess,
+ decoded checker pixels, named pivot and animation, double-sided material, native canvas,
+ and Khronos validation. Emissive strength proves selection reached the worker. These checks
+ run in the existing Linux, Windows and both macOS architecture package jobs.
+- `scripts/integration/run-browser-export.mjs` exercises real GPU rendering of source versus
+ exported/reimported scenes. `generate-deformation-fixtures.ts` and its expectation manifest
+ provide repeatable evaluated-deformation fixtures for the Blender/Unity adapters.
+
+### Additional gaps found and corrected
+
+The installed Three.js exporter ignores texture centers and manual UV matrices, and serializes
+Three's texture scale/rotation fields despite the differing multiplication order used by glTF.
+GPU comparison exposed the resulting placement error. The adapter now derives glTF-order TRS
+from the effective matrix on an export copy and checks that reconstruction is accurate. It
+rejects matrices with shear or perspective instead of silently changing their appearance.
+Uniform scale with rotated center and representable manual matrices are covered separately.
+The first center-only test was insufficient because it reconstructed Three's matrix order;
+that oracle was corrected and the GPU comparison remains independent.
+
+The exporter also ignores the separate Three.js sheen intensity. The adapter folds that
+intensity into the cloned sheen color, matching Three's actual renderer and glTF's single color
+factor. A focused test first failed on the missing intensity, then passed through export and
+palette rewrite. Sprite conversion now retains authored material names as well.
+
+### Remaining default-switch gate
+
+A diagnostic engine run with `KILN_GLTF_EXPORTER=three` identified tests tied to historical
+serialization and legacy-only attribute limitations, in addition to the real sprite naming
+issue. That run occurred while qualification tests/source were being edited and is not a
+release gate. Before a default switch, run the whole suite on a frozen build, classify each
+remaining difference, and keep historical byte fixtures explicit rather than silently accepting
+new snapshots. Low-level subprocess tests must compare the same explicit backend.
+
+Lossless handling of sheared texture transforms still needs a qualified implementation or an
+upstream solution. UV baking affects texture coordinate channels, shared materials and normal-map
+tangents, so it cannot be treated as an unchecked offset patch. No default switch is approved by
+this revision. Remaining advanced extensions, compression codecs and additional consumer/render
+pipelines require their own feature evidence; this report does not claim universal support.
+
+### Measured expanded results
+
+The expanded browser GPU gate passed eight supported fixtures and 25 pixel-exact source/reimport
+comparisons on Chrome 152 / RTX 3070, with maximum deformed-vertex delta 1.49e-8. Three sheared-UV
+fixtures assert explicit rejection and are not counted as supported exports. The sheen fixture
+also includes a visibly different sheen-disabled control.
+
+Real Blender 5.2 / Unity 6000.2 Built-in RP imports measured 0.538516 m skin displacement and
+0.600000 m morph displacement, matching independent fixture expectations. A separate Windows
+Unity player on RTX 3070 / Direct3D11 measured skin/morph silhouette changes across rendered
+frames with zero shader errors. The double-sided sheet produced 8,742 foreground pixels from
+both sides; its one-sided control produced 8,742 front and zero back. The reusable runner records
+input GLB, helper script and Unity package-lock hashes. Exact end-of-loop samples were avoided,
+and animation samples use separate frames because Unity caches GPU skinning within a frame.
+
+Local coverage after runtime fixes: 1,967 passed, four skipped, zero failed; functions 95.18%,
+lines 92.83%, above unchanged thresholds. The final CLI hash is
+`1ec303580d5452a0b3e2f3f9be6ccab3cd1b6acc21d1a2529b888efd48fc63d8`, runtime identity
+`7c4545f115e22467ba52185f40560683229fcc52bb545cff29856a9cf830f4c9`.
+All five final authored dogfood exports reproduce the prior reviewed GLBs byte-for-byte on this
+build. Hosted clean-package candidate checks and the candidate-selected engine suite are now
+part of the PR gates; their per-revision results are attached to the PR.
+
+The community route for the remaining UV case is an accessor-level UV bake using glTF Transform,
+with copies when shared mesh data requires different mappings. This is described by the maintainer
+in [discussion #1095](https://github.com/donmccurdy/glTF-Transform/discussions/1095).
+A future implementation should reuse those document/accessor APIs and qualify multiple texture
+slots, shared meshes and normal maps with the existing GPU fixtures. It should not fork the
+exporter or alter canonical geometry silently. The normal-map convention boundary also has
+[upstream discussion](https://github.com/mrdoob/three.js/issues/22165); checking installed exporter
+behavior remains necessary even when an upstream issue is marked closed.
+
+### Final frozen revision
+
+After the resource-name fix, the runtime identity is
+`413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8` and CLI SHA-256 is
+`9e7e7fc81233f4bb34584eabfa5a82a82f5c0f636965ec0f3b78872df5c539ed`.
+The final default coverage gate passed 1,967 tests, four skips, zero failures, with functions
+95.18% and lines 92.83%. The final browser gate again passed all 25 pixel comparisons.
+Clean npm installation of the final tarball passed on Node 22.23.2/npm 12.0.2 with the installed
+CLI hash verified. Four dogfood GLBs remain byte-identical; the industrial asset differs only by
+two restored image names (`CastBluePaint`, `CastBlueNormal`), with an identical BIN chunk.
+No geometry, encoded image bytes or shader values changed in that artifact.
+
+Historical architecture experiment hashes are now explicitly pinned to their original legacy
+converter; they were not regenerated to bless candidate differences. Unsupported-attribute
+policy tests use a genuinely unsupported custom attribute instead of newly supported colors/UVs.
+Subprocess parity tests cover both explicit backends. Texture round-trip tests compare decoded
+pixels rather than encoder-dependent PNG lengths, and cache tests use matching host settings.
+These changes preserve each assertion's purpose when the candidate is selected.
+
+The final frozen suite with `KILN_GLTF_EXPORTER=three` also passed **1,967 tests**, four skips and
+zero failures. CI now repeats that suite on Linux in addition to the default coverage gate and
+the explicit-backend packaged worker/cache checks.
diff --git a/package.json b/package.json
index 825dc597..506ff4c1 100644
--- a/package.json
+++ b/package.json
@@ -156,5 +156,8 @@
"ai": "^6.0.282",
"openai": "^6.49.0",
"typescript": "^7.0.2"
+ },
+ "optionalDependencies": {
+ "@napi-rs/canvas": "1.0.9"
}
}
diff --git a/scripts/exporter-cli-check.mjs b/scripts/exporter-cli-check.mjs
new file mode 100644
index 00000000..22619173
--- /dev/null
+++ b/scripts/exporter-cli-check.mjs
@@ -0,0 +1,90 @@
+/** Exercise the built CLI -> sanitized worker -> disk cache, not an in-process substitute. */
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const args = process.argv.slice(2);
+const runtime = args.includes('--node') ? args[args.indexOf('--node') + 1] : process.execPath;
+const directory = await mkdtemp(path.join(os.tmpdir(), 'kiln-exporter-cli-'));
+const sourcePath = path.join(directory, 'fixture.kiln.js');
+await writeFile(
+ sourcePath,
+ `
+const meta = { name: 'ExporterCacheProbe', category: 'prop' };
+function build() {
+ const root = createRoot('ExporterCacheProbe');
+ const albedo = proceduralTexture({schemaVersion:2,size:8,usage:'albedo',layers:[{op:'checker',colorA:0xff0000,colorB:0x0000ff,squares:2}]});
+ const pivot = createPivot('Vane', [0.2, 0.3, 0.1], root);
+ createPart('Painted', boxGeo(0.6,0.2,0.1), pbrMaterial({albedo,roughness:0.4}), {parent:pivot});
+ createPart('Lamp', boxGeo(0.1,0.1,0.1), gameMaterial(0xffaa00,{emissive:0xff8800,emissiveIntensity:0.25}), {position:[0,0.3,0],parent:pivot});
+ return root;
+}
+function animate() {return [createClip('turn',1,[rotationTrack('Joint_Vane',[{time:0,rotation:[0,0,0]},{time:1,rotation:[0,90,0]}])])];}
+`,
+);
+const version = spawnSync(runtime, ['--version'], { encoding: 'utf8', windowsHide: true });
+assert.equal(version.status, 0, version.stderr);
+const records = [];
+for (const backend of ['legacy', 'three']) {
+ let key;
+ let previousBytes;
+ for (const repeat of [1, 2]) {
+ const output = path.join(directory, `${backend}-${repeat}.glb`);
+ const result = spawnSync(
+ runtime,
+ [path.join(root, 'dist/cli.mjs'), 'render', sourcePath, '--out', output],
+ {
+ cwd: directory,
+ encoding: 'utf8',
+ timeout: 120_000,
+ windowsHide: true,
+ env: {
+ ...process.env,
+ KILN_GLTF_EXPORTER: backend,
+ KILN_EVALUATOR_MODE: 'subprocess',
+ KILN_BUILD_CACHE: 'disk',
+ KILN_BUILD_CACHE_DIR: path.join(directory, 'cache'),
+ },
+ },
+ );
+ const log = `${result.stdout ?? ''}${result.stderr ?? ''}`;
+ await writeFile(path.join(directory, `${backend}-${repeat}.log`), log);
+ assert.equal(result.status, 0, `${backend} run ${repeat} failed: ${result.error ?? log}`);
+ const bytes = await readFile(output);
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ if (repeat === 1) {
+ key = log.match(/build created (sha256:[a-f0-9]+)/)?.[1];
+ assert(key, `${backend}: expected its own new disk-cache entry, got ${log}`);
+ previousBytes = bytes;
+ records.push({ backend, key, bytes: bytes.length, sha256: hash });
+ } else {
+ assert(
+ log.includes(`build reused ${key}`),
+ `${backend}: expected its own cache hit, got ${log}`,
+ );
+ assert(bytes.equals(previousBytes), `${backend}: cache hit changed GLB bytes`);
+ }
+ }
+}
+assert.notEqual(records[0].key, records[1].key, 'Exporter backends collided in the disk cache');
+assert.notEqual(
+ records[0].sha256,
+ records[1].sha256,
+ 'Candidate did not change the known emissive fixture; check sanitized worker selection',
+);
+const receipt = {
+ runtime: version.stdout.trim(),
+ cliSha256: createHash('sha256')
+ .update(await readFile(path.join(root, 'dist/cli.mjs')))
+ .digest('hex'),
+ directory,
+ records,
+ ownCacheHits: true,
+};
+await writeFile(path.join(directory, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
+console.log(JSON.stringify(receipt, null, 2));
diff --git a/scripts/integration-corpus.mjs b/scripts/integration-corpus.mjs
new file mode 100644
index 00000000..8761ba14
--- /dev/null
+++ b/scripts/integration-corpus.mjs
@@ -0,0 +1,277 @@
+/** Structural corpus gate. Run with Bun; no image renderer or live provider is invoked. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import sharp from 'sharp';
+
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const rounded = (values) => Array.from(values, (value) => Math.round(value * 1e6) / 1e6);
+
+export async function signature(document) {
+ const root = document.getRoot();
+ const paths = new Map();
+ const nodes = [];
+ const visit = (node, prefix, index) => {
+ const nodePath = `${prefix}/${index}:${node.getName()}`;
+ paths.set(node, nodePath);
+ nodes.push(node);
+ node.listChildren().forEach((child, childIndex) => {
+ visit(child, nodePath, childIndex);
+ });
+ };
+ root.listScenes().forEach((scene, sceneIndex) => {
+ scene.listChildren().forEach((node, index) => {
+ visit(node, `scene:${sceneIndex}`, index);
+ });
+ });
+ const textures = new Map();
+ for (const texture of root.listTextures()) {
+ const bytes = texture.getImage();
+ if (!bytes) continue;
+ // Compare decoded pixels rather than PNG/JPEG container metadata or encoder choices.
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ textures.set(texture, {
+ width: decoded.info.width,
+ height: decoded.info.height,
+ pixels: digest(decoded.data),
+ });
+ }
+ const material = (mat) =>
+ mat && {
+ name: mat.getName(),
+ baseColor: rounded(mat.getBaseColorFactor()),
+ metallic: mat.getMetallicFactor(),
+ roughness: mat.getRoughnessFactor(),
+ emissive: rounded(mat.getEmissiveFactor()),
+ doubleSided: mat.getDoubleSided(),
+ alphaMode: mat.getAlphaMode(),
+ alphaCutoff: mat.getAlphaCutoff(),
+ normalScale: mat.getNormalScale(),
+ occlusionStrength: mat.getOcclusionStrength(),
+ textures: [
+ mat.getBaseColorTexture(),
+ mat.getMetallicRoughnessTexture(),
+ mat.getNormalTexture(),
+ mat.getOcclusionTexture(),
+ mat.getEmissiveTexture(),
+ ].map((texture) => textures.get(texture) ?? null),
+ extensions: mat
+ .listExtensions()
+ .map((extension) => extension.extensionName)
+ .sort(),
+ };
+ return {
+ extensions: root
+ .listExtensionsUsed()
+ .map((extension) => extension.extensionName)
+ .sort(),
+ nodes: nodes.map((node) => {
+ const matrix = node.getWorldMatrix();
+ const primitives =
+ node
+ .getMesh()
+ ?.listPrimitives()
+ .map((primitive) => {
+ const position = primitive.getAttribute('POSITION');
+ const low = [Infinity, Infinity, Infinity];
+ const high = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; position && i < position.getCount(); i++) {
+ const [x, y, z] = position.getElement(i, []);
+ for (let axis = 0; axis < 3; axis++) {
+ const coordinate =
+ matrix[axis] * x +
+ matrix[4 + axis] * y +
+ matrix[8 + axis] * z +
+ matrix[12 + axis];
+ low[axis] = Math.min(low[axis], coordinate);
+ high[axis] = Math.max(high[axis], coordinate);
+ }
+ }
+ return {
+ mode: primitive.getMode(),
+ material: material(primitive.getMaterial()),
+ worldBounds: position ? [rounded(low), rounded(high)] : null,
+ attributes: Object.fromEntries(
+ primitive
+ .listSemantics()
+ .sort()
+ .map((semantic) => {
+ const accessor = primitive.getAttribute(semantic);
+ return [
+ semantic,
+ {
+ count: accessor.getCount(),
+ type: accessor.getType(),
+ normalized: accessor.getNormalized(),
+ values: digest(JSON.stringify(rounded(accessor.getArray()))),
+ },
+ ];
+ }),
+ ),
+ indices: primitive.getIndices()
+ ? digest(JSON.stringify(Array.from(primitive.getIndices().getArray())))
+ : null,
+ morphTargets: primitive.listTargets().map((target) =>
+ Object.fromEntries(
+ target
+ .listSemantics()
+ .sort()
+ .map((semantic) => [
+ semantic,
+ digest(JSON.stringify(rounded(target.getAttribute(semantic).getArray()))),
+ ]),
+ ),
+ ),
+ };
+ }) ?? [];
+ return {
+ path: paths.get(node),
+ matrix: rounded(matrix),
+ localMatrix: rounded(node.getMatrix()),
+ extras: node.getExtras(),
+ weights: node.getWeights(),
+ primitives,
+ skin: node.getSkin()
+ ? {
+ joints: node
+ .getSkin()
+ .listJoints()
+ .map((joint) => paths.get(joint)),
+ inverseBindMatrices: rounded(
+ node.getSkin().getInverseBindMatrices()?.getArray() ?? [],
+ ),
+ }
+ : null,
+ };
+ }),
+ animations: root.listAnimations().map((animation) => ({
+ name: animation.getName(),
+ channels: animation
+ .listChannels()
+ .map((channel) => ({
+ target: paths.get(channel.getTargetNode()),
+ path: channel.getTargetPath(),
+ interpolation: channel.getSampler().getInterpolation(),
+ input: rounded(channel.getSampler().getInput().getArray()),
+ output: rounded(channel.getSampler().getOutput().getArray()),
+ }))
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))),
+ })),
+ };
+}
+
+export function differences(a, b, prefix = '$') {
+ if (JSON.stringify(a) === JSON.stringify(b)) return [];
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return [prefix];
+ return [...new Set([...Object.keys(a), ...Object.keys(b)])]
+ .sort()
+ .flatMap((key) => differences(a[key], b[key], `${prefix}.${key}`));
+}
+
+async function selfTest() {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]))
+ .setBuffer(buffer);
+ const mat = doc.createMaterial().setRoughnessFactor(0.3);
+ const mesh = doc
+ .createMesh()
+ .addPrimitive(doc.createPrimitive().setAttribute('POSITION', positions).setMaterial(mat));
+ const pivot = doc.createNode('Joint_Test').setTranslation([3, 0, 0]);
+ pivot.addChild(doc.createNode('Mesh_Test').setMesh(mesh));
+ doc.createScene().addChild(pivot);
+ const baseline = await signature(doc);
+ assert.deepEqual(baseline.nodes[1].primitives[0].worldBounds, [
+ [3, 0, 0],
+ [4, 1, 0],
+ ]);
+ assert.deepEqual(
+ differences(baseline, await signature(await io.readBinary(await io.writeBinary(doc)))),
+ [],
+ );
+ mat.setRoughnessFactor(0.8);
+ assert(differences(baseline, await signature(doc)).some((item) => item.endsWith('.roughness')));
+ mat.setRoughnessFactor(0.3);
+ pivot.setTranslation([4, 0, 0]);
+ assert(differences(baseline, await signature(doc)).some((item) => item.includes('.worldBounds')));
+ pivot.setTranslation([3, 0, 0]);
+ positions.setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0.5, 1, 0]));
+ assert(
+ differences(baseline, await signature(doc)).some((item) => item.endsWith('.POSITION.values')),
+ );
+ console.log(
+ 'Signature self-test passed: serialization invariant; transform, material, and same-bounds vertex changes detected.',
+ );
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ if (args.includes('--self-test')) return selfTest();
+ const option = (name, fallback) =>
+ args.includes(name) ? args[args.indexOf(name) + 1] : fallback;
+ const input = path.resolve(option('--input', 'examples'));
+ const output = path.resolve(option('--out', 'tmp/exporter-corpus/current'));
+ const compare = option('--compare', null);
+ const filter = option('--filter', '');
+ const limit = Number(option('--limit', '0'));
+ const { renderGLB } = await import('../src/render.ts');
+ const { createAssetIntentV1 } = await import('../src/contracts/index.ts');
+ await mkdir(output, { recursive: true });
+ let files = (await readdir(input))
+ .filter((file) => file.endsWith('.kiln.js') && file.includes(filter))
+ .sort();
+ if (limit) files = files.slice(0, limit);
+ if (!files.length) throw new Error(`No .kiln.js fixtures matched ${input}`);
+ const results = [];
+ for (const file of files) {
+ try {
+ const source = await readFile(path.join(input, file), 'utf8');
+ const opts = { intent: createAssetIntentV1({ category: 'prop' }), optimize: 'off' };
+ const first = await renderGLB(source, opts);
+ const second = await renderGLB(source, opts);
+ const current = await signature(await io.readBinary(first.glb));
+ const name = file.replace('.kiln.js', '');
+ const signatureName = `${name}.signature.json`;
+ await writeFile(path.join(output, `${name}.glb`), first.glb);
+ await writeFile(path.join(output, signatureName), `${JSON.stringify(current, null, 2)}\n`);
+ const changes = compare
+ ? differences(
+ JSON.parse(await readFile(path.join(compare, signatureName), 'utf8')),
+ current,
+ )
+ : [];
+ const deterministic = digest(first.glb) === digest(second.glb);
+ results.push({
+ file,
+ sourceSha256: digest(source),
+ glbSha256: digest(first.glb),
+ bytes: first.glb.length,
+ deterministic,
+ changes,
+ });
+ console.log(
+ `${file}: ${deterministic ? 'repeatable' : 'NONDETERMINISTIC'}, ${changes.length} signature differences`,
+ );
+ } catch (error) {
+ results.push({ file, error: String(error) });
+ console.error(`${file}: ${error}`);
+ }
+ await writeFile(
+ path.join(output, 'results.json'),
+ `${JSON.stringify({ exporter: process.env.KILN_GLTF_EXPORTER ?? 'default', results }, null, 2)}\n`,
+ );
+ }
+ if (results.some((result) => result.error || !result.deterministic || result.changes.length))
+ process.exitCode = 1;
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url))
+ await main();
diff --git a/scripts/integration/KilnDeformationGpuBuild.cs b/scripts/integration/KilnDeformationGpuBuild.cs
new file mode 100644
index 00000000..f903e071
--- /dev/null
+++ b/scripts/integration/KilnDeformationGpuBuild.cs
@@ -0,0 +1,72 @@
+using System;
+using System.IO;
+using System.Linq;
+using UnityEditor;
+using UnityEditor.Build.Reporting;
+using UnityEditor.SceneManagement;
+using UnityEngine;
+
+public static class KilnDeformationGpuBuild
+{
+ public static void Run()
+ {
+ EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
+ var files = Directory.GetFiles("Assets/KilnImportFixtures", "*.glb")
+ .OrderBy(path => path)
+ .ToArray();
+ var expected = new[] { "double-sided", "morph", "single-sided", "skin" };
+ if (!files.Select(Path.GetFileNameWithoutExtension).SequenceEqual(expected))
+ {
+ throw new Exception("Requires exactly the four generated deformation fixtures");
+ }
+
+ var roots = files
+ .Select(path => UnityEngine.Object.Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>(path)))
+ .ToArray();
+ foreach (var root in roots)
+ {
+ foreach (var skin in root.GetComponentsInChildren<SkinnedMeshRenderer>())
+ {
+ skin.updateWhenOffscreen = true;
+ }
+ }
+
+ var camera = new GameObject("Camera").AddComponent<Camera>();
+ camera.tag = "MainCamera";
+ camera.orthographic = true;
+ camera.orthographicSize = 1.1f;
+ camera.clearFlags = CameraClearFlags.SolidColor;
+ camera.backgroundColor = Color.black;
+
+ var smoke = camera.gameObject.AddComponent<KilnDeformationGpuSmoke>();
+ smoke.roots = roots;
+ smoke.names = files.Select(Path.GetFileNameWithoutExtension).ToArray();
+ smoke.clips = files
+ .Select(path => AssetDatabase.LoadAllAssetsAtPath(path).OfType<AnimationClip>().FirstOrDefault())
+ .ToArray();
+
+ var light = new GameObject("Light").AddComponent<Light>();
+ light.type = LightType.Directional;
+ light.intensity = 1;
+ light.transform.rotation = Quaternion.Euler(20, 160, 0);
+ RenderSettings.ambientLight = new Color(.4f, .4f, .4f);
+
+ EditorSceneManager.SaveScene(
+ EditorSceneManager.GetActiveScene(),
+ "Assets/KilnDeformationGpuSmoke.unity"
+ );
+ var args = Environment.GetCommandLineArgs();
+ var output = args[Array.IndexOf(args, "-playerOutput") + 1];
+ var result = BuildPipeline.BuildPlayer(new BuildPlayerOptions
+ {
+ scenes = new[] { "Assets/KilnDeformationGpuSmoke.unity" },
+ locationPathName = output,
+ target = BuildTarget.StandaloneWindows64,
+ options = BuildOptions.Development
+ });
+ if (result.summary.result != BuildResult.Succeeded)
+ {
+ throw new Exception("Build failed");
+ }
+ }
+}
diff --git a/scripts/integration/KilnDeformationGpuSmoke.cs b/scripts/integration/KilnDeformationGpuSmoke.cs
new file mode 100644
index 00000000..d4b0e556
--- /dev/null
+++ b/scripts/integration/KilnDeformationGpuSmoke.cs
@@ -0,0 +1,184 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using UnityEngine;
+using UnityEngine.Animations;
+using UnityEngine.Playables;
+
+public class KilnDeformationGpuSmoke : MonoBehaviour
+{
+ public GameObject[] roots;
+ public AnimationClip[] clips;
+ public string[] names;
+
+ [Serializable]
+ class Asset
+ {
+ public string name;
+ public int frontPixels, backPixels, changedPixels, unsupportedShaders;
+ public float maxVertexDisplacement;
+ }
+
+ [Serializable]
+ class Report
+ {
+ public string unity, device, api;
+ public bool passed;
+ public List<Asset> assets = new();
+ }
+
+ Color32[] Capture(Camera camera, string output)
+ {
+ var target = new RenderTexture(256, 256, 24);
+ camera.targetTexture = target;
+ camera.Render();
+ RenderTexture.active = target;
+
+ var texture = new Texture2D(256, 256, TextureFormat.RGB24, false);
+ texture.ReadPixels(new Rect(0, 0, 256, 256), 0, 0);
+ texture.Apply();
+ var pixels = texture.GetPixels32();
+ File.WriteAllBytes(output, texture.EncodeToPNG());
+
+ camera.targetTexture = null;
+ RenderTexture.active = null;
+ Destroy(target);
+ Destroy(texture);
+ return pixels;
+ }
+
+ int Colored(Color32[] pixels) => pixels.Count(pixel => pixel.r + pixel.g + pixel.b > 30);
+
+ Vector3[] Vertices(GameObject root)
+ {
+ var skin = root.GetComponentInChildren<SkinnedMeshRenderer>();
+ if (!skin)
+ {
+ return Array.Empty<Vector3>();
+ }
+
+ var mesh = new Mesh();
+ skin.BakeMesh(mesh);
+ var vertices = mesh.vertices;
+ Destroy(mesh);
+ return vertices;
+ }
+
+ IEnumerator Start()
+ {
+ yield return null;
+ var args = Environment.GetCommandLineArgs();
+ var output = args[Array.IndexOf(args, "-receiptDirectory") + 1];
+ Directory.CreateDirectory(output);
+ var report = new Report
+ {
+ unity = Application.unityVersion,
+ device = SystemInfo.graphicsDeviceName,
+ api = SystemInfo.graphicsDeviceType.ToString(),
+ passed = SystemInfo.graphicsDeviceType != UnityEngine.Rendering.GraphicsDeviceType.Null
+ };
+ var camera = Camera.main;
+ foreach (var root in roots)
+ {
+ root.SetActive(false);
+ }
+
+ for (int i = 0; i < roots.Length; i++)
+ {
+ var root = roots[i];
+ root.SetActive(true);
+ var asset = new Asset { name = names[i] };
+ report.assets.Add(asset);
+ foreach (var renderer in root.GetComponentsInChildren<Renderer>())
+ {
+ foreach (var material in renderer.sharedMaterials)
+ {
+ if (!material || !material.shader.isSupported || material.shader.name == "Hidden/InternalErrorShader")
+ {
+ asset.unsupportedShaders++;
+ }
+ }
+ }
+
+ var graph = PlayableGraph.Create("Deformation");
+ graph.SetTimeUpdateMode(DirectorUpdateMode.Manual);
+ AnimationClipPlayable playable = default;
+ if (clips[i])
+ {
+ var animator = root.GetComponent<Animator>();
+ if (!animator)
+ {
+ animator = root.AddComponent<Animator>();
+ }
+ animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
+ playable = AnimationClipPlayable.Create(graph, clips[i]);
+ var animationOutput = AnimationPlayableOutput.Create(graph, "Clip", animator);
+ animationOutput.SetSourcePlayable(playable);
+ playable.SetTime(0);
+ graph.Play();
+ graph.Evaluate(0);
+ }
+
+ // Unity caches GPU skinning within a frame, so capture poses on separate frames.
+ yield return null;
+ var start = Vertices(root);
+ camera.transform.position = new Vector3(0, .4f, 3);
+ camera.transform.LookAt(new Vector3(0, .4f, 0));
+ var before = Capture(camera, Path.Combine(output, names[i] + "-start.png"));
+ asset.frontPixels = Colored(before);
+
+ if (clips[i])
+ {
+ // A looping clip wraps at its exact end time; sample just before that point.
+ playable.SetTime(clips[i].length * .999);
+ graph.Evaluate(0);
+ yield return null;
+ var end = Vertices(root);
+ for (int vertex = 0; vertex < start.Length; vertex++)
+ {
+ asset.maxVertexDisplacement = Math.Max(
+ asset.maxVertexDisplacement,
+ Vector3.Distance(start[vertex], end[vertex])
+ );
+ }
+ var after = Capture(camera, Path.Combine(output, names[i] + "-end.png"));
+ asset.changedPixels = before.Where((pixel, index) =>
+ Math.Abs(pixel.r - after[index].r)
+ + Math.Abs(pixel.g - after[index].g)
+ + Math.Abs(pixel.b - after[index].b) > 30
+ ).Count();
+ }
+
+ camera.transform.position = new Vector3(0, .4f, -3);
+ camera.transform.LookAt(new Vector3(0, .4f, 0));
+ asset.backPixels = Colored(Capture(camera, Path.Combine(output, names[i] + "-back.png")));
+ graph.Destroy();
+ root.SetActive(false);
+
+ report.passed &= asset.unsupportedShaders == 0 && asset.frontPixels > 1000;
+ if (names[i] == "skin")
+ {
+ report.passed &= asset.maxVertexDisplacement > .53f && asset.changedPixels > 100;
+ }
+ if (names[i] == "morph")
+ {
+ report.passed &= asset.maxVertexDisplacement > .59f && asset.changedPixels > 100;
+ }
+ if (names[i] == "double-sided")
+ {
+ report.passed &= asset.backPixels > 1000;
+ }
+ if (names[i] == "single-sided")
+ {
+ report.passed &= asset.backPixels == 0;
+ }
+ }
+
+ File.WriteAllText(Path.Combine(output, "player.json"), JsonUtility.ToJson(report, true));
+ Application.Quit(report.passed ? 0 : 1);
+ }
+}
+
+
diff --git a/scripts/integration/KilnImportAudit.cs b/scripts/integration/KilnImportAudit.cs
new file mode 100644
index 00000000..949e6bb5
--- /dev/null
+++ b/scripts/integration/KilnImportAudit.cs
@@ -0,0 +1,132 @@
+// Copy only into a disposable Unity project with its chosen glTF importer installed.
+using UnityEngine;
+using UnityEditor;
+using System;
+using System.IO;
+using System.Linq;
+using System.Collections.Generic;
+
+public static class KilnImportAudit {
+ [Serializable] public class Node {
+ public string name, parent;
+ public float[] localPosition, worldPosition;
+ public float[] materialMetallicFactors, materialRoughnessFactors;
+ public int vertices, colors, uvSets, morphTargets, bones;
+ public float maxVertexDisplacement;
+ public bool deformed;
+ }
+ [Serializable] public class Mat {
+ public string name, shader;
+ public string[] properties, textures;
+ public float metallicFactor, roughnessFactor, cullMode;
+ public bool hasMetallicRoughnessFactors, hasCullMode;
+ }
+ [Serializable] public class Record {
+ public string file, error;
+ public List<Node> nodes = new();
+ public List<Mat> materials = new();
+ public List<string> animations = new();
+ public int animatedNodeCount;
+ public List<string> animatedNodes = new();
+ }
+ [Serializable] public class Report {
+ public string engine = "unity", version = Application.unityVersion, renderPipeline;
+ public string[] packages;
+ public List<Record> files = new();
+ }
+ static float[] Values(Vector3 v) => new[] {v.x, v.y, v.z};
+ static Vector3[] DeformedVertices(SkinnedMeshRenderer renderer) {
+ var baked = new Mesh();
+ try { renderer.BakeMesh(baked); return baked.vertices; }
+ finally { UnityEngine.Object.DestroyImmediate(baked); }
+ }
+ static string Argument(string key) {
+ var args = Environment.GetCommandLineArgs();
+ var index = Array.IndexOf(args, key);
+ if (index < 0 || index + 1 >= args.Length) throw new ArgumentException(key + " is required");
+ return args[index + 1];
+ }
+ public static void Run() {
+ var input = Argument("-kilnInput");
+ var output = Argument("-kilnReceipt");
+ const string folder = "Assets/KilnImportFixtures";
+ if (Directory.Exists(folder)) throw new InvalidOperationException("Use a fresh project: " + folder + " already exists");
+ Directory.CreateDirectory(folder);
+ var pipeline = UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline;
+ var report = new Report {
+ renderPipeline = pipeline ? pipeline.GetType().FullName : "Built-in",
+ packages = UnityEditor.PackageManager.PackageInfo.GetAllRegisteredPackages().Select(p => p.name + "@" + p.version).OrderBy(p => p).ToArray()
+ };
+ foreach (var source in Directory.GetFiles(input, "*.glb").OrderBy(p => p)) {
+ var record = new Record {file = Path.GetFileName(source)};
+ report.files.Add(record);
+ GameObject instance = null;
+ try {
+ var path = folder + "/" + record.file;
+ File.Copy(source, path, false);
+ AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
+ var asset = AssetDatabase.LoadAssetAtPath<GameObject>(path);
+ if (!asset) throw new InvalidOperationException("No imported GameObject");
+ instance = UnityEngine.Object.Instantiate(asset);
+ instance.name = asset.name;
+ foreach (var transform in instance.GetComponentsInChildren<Transform>(true)) {
+ var filter = transform.GetComponent<MeshFilter>();
+ var skin = transform.GetComponent<SkinnedMeshRenderer>();
+ var mesh = skin ? skin.sharedMesh : filter ? filter.sharedMesh : null;
+ var renderer = transform.GetComponent<Renderer>();
+ var materials = renderer ? renderer.sharedMaterials : new Material[0];
+ int uvSets = 0;
+ if (mesh) for (int channel = 0; channel < 8; channel++) {
+ var uv = new List<Vector4>(); mesh.GetUVs(channel, uv); if (uv.Count > 0) uvSets++;
+ }
+ record.nodes.Add(new Node {
+ name = transform.name, parent = transform.parent ? transform.parent.name : null,
+ localPosition = Values(transform.localPosition), worldPosition = Values(transform.position),
+ materialMetallicFactors = materials.Select(m => m && m.HasProperty("metallicFactor") ? m.GetFloat("metallicFactor") : -1).ToArray(),
+ materialRoughnessFactors = materials.Select(m => m && m.HasProperty("roughnessFactor") ? m.GetFloat("roughnessFactor") : -1).ToArray(),
+ vertices = mesh ? mesh.vertexCount : 0, colors = mesh && mesh.colors.Length > 0 ? 1 : 0,
+ uvSets = uvSets, morphTargets = mesh ? mesh.blendShapeCount : 0, bones = skin ? skin.bones.Length : 0
+ });
+ }
+ foreach (var material in instance.GetComponentsInChildren<Renderer>(true).SelectMany(r => r.sharedMaterials).Where(m => m).Distinct()) {
+ record.materials.Add(new Mat {
+ name = material.name, shader = material.shader.name,
+ hasMetallicRoughnessFactors = material.HasProperty("metallicFactor") && material.HasProperty("roughnessFactor"),
+ metallicFactor = material.HasProperty("metallicFactor") ? material.GetFloat("metallicFactor") : 0,
+ roughnessFactor = material.HasProperty("roughnessFactor") ? material.GetFloat("roughnessFactor") : 0,
+ hasCullMode = material.HasProperty("_CullMode"),
+ cullMode = material.HasProperty("_CullMode") ? material.GetFloat("_CullMode") : 0,
+ properties = Enumerable.Range(0, material.shader.GetPropertyCount()).Select(i => material.shader.GetPropertyName(i)).ToArray(),
+ textures = material.GetTexturePropertyNames().Where(p => material.GetTexture(p)).OrderBy(p => p).ToArray()
+ });
+ }
+ var clips = AssetDatabase.LoadAllAssetsAtPath(path).OfType<AnimationClip>().ToArray();
+ record.animations.AddRange(clips.Select(c => c.name).OrderBy(n => n));
+ var moving = new HashSet<string>();
+ foreach (var clip in clips) {
+ clip.SampleAnimation(instance, 0);
+ var transforms = instance.GetComponentsInChildren<Transform>(true);
+ var initialPositions = transforms.Select(t => t.localPosition).ToArray();
+ var initialRotations = transforms.Select(t => t.localRotation).ToArray();
+ var skins = instance.GetComponentsInChildren<SkinnedMeshRenderer>(true);
+ var initialVertices = skins.Select(DeformedVertices).ToArray();
+ foreach (var time in new[] {clip.length * .5f, clip.length}) {
+ clip.SampleAnimation(instance, time);
+ for (int i = 0; i < transforms.Length; i++)
+ if (Vector3.Distance(transforms[i].localPosition, initialPositions[i]) > 1e-5f || Quaternion.Angle(transforms[i].localRotation, initialRotations[i]) > .01f) moving.Add(transforms[i].name);
+ for (int i = 0; i < skins.Length; i++) {
+ var current = DeformedVertices(skins[i]); var original = initialVertices[i];
+ if (current.Length != original.Length) throw new InvalidOperationException("Animation changed vertex count");
+ var node = record.nodes.Single(n => n.name == skins[i].name);
+ for (int j = 0; j < current.Length; j++) node.maxVertexDisplacement = Math.Max(node.maxVertexDisplacement, Vector3.Distance(current[j], original[j]));
+ node.deformed = node.maxVertexDisplacement > 1e-5f;
+ }
+ }
+ }
+ record.animatedNodes = moving.OrderBy(n => n).ToList(); record.animatedNodeCount = moving.Count;
+ } catch (Exception error) { record.error = error.ToString(); }
+ finally { if (instance) UnityEngine.Object.DestroyImmediate(instance); }
+ }
+ File.WriteAllText(output, JsonUtility.ToJson(report, true));
+ }
+}
diff --git a/scripts/integration/README.md b/scripts/integration/README.md
new file mode 100644
index 00000000..d9c565b4
--- /dev/null
+++ b/scripts/integration/README.md
@@ -0,0 +1,122 @@
+# Optional importer qualification
+
+This harness runs real Blender and/or Unity imports and checks explicit expectations.
+It is separate from engine QA and offline CI. It does not render, install applications,
+download packages, or change source GLBs. A successful receipt is structural evidence,
+not visual, animation-playback, or player-build qualification.
+
+```sh
+node scripts/integration/run-imports.mjs \
+ --input /path/to/glbs --output /path/to/new-receipts \
+ --manifest /path/to/expectations.json --blender /path/to/blender
+```
+
+For Unity add `--unity /path/to/Unity --unity-project /path/to/disposable-project`.
+Prepare that project with the chosen importer (for example stable glTFast 6.20.0)
+before running. The harness adds an editor script and copies fixtures into that project;
+it refuses to overwrite an existing audit script or fixture directory. Use a fresh
+project or deliberately remove only those generated files and their Unity `.meta` files
+before rerunning. It records
+the editor version, registered packages and active render pipeline. It uses `-nographics`
+only for structural inspection, not software rendering.
+
+The input is a flat directory of GLBs. Receipts and process logs go to a new output
+directory, with SHA-256 hashes of input assets and the expectation manifest; existing
+receipts are rejected to avoid accepting stale results. Nonzero
+process exits, missing receipts, import errors and failed assertions fail the command.
+
+## Expectations
+
+Write independent, engine-specific expected results, for example:
+
+```json
+{
+ "blender": {
+ "tolerance": 0.00001,
+ "files": {
+ "prop.glb": {
+ "nodes": [{"name": "Mesh_Pennant", "parent": "Joint_Vane", "uvSets": 2}],
+ "materials": [{"name": "Cloth", "metallic": 0.2}],
+ "animationCount": 1,
+ "animatedNodeCount": 1
+ }
+ }
+ }
+}
+```
+
+Add a `unity` section with expectations for its imported representation. Fields omitted
+from an expectation are recorded but not asserted. Names must resolve uniquely; ambiguous
+names fail rather than selecting an arbitrary object. Every expected file needs at least
+one assertion. Position arrays use each application's coordinate system; Blender converts
+glTF Y-up to Z-up, and Unity changes handedness. Do not compare those arrays directly
+across engines. Unity may add a root or split primitives into separate objects.
+
+Both adapters record node positions, vertex counts, UV-set counts, colour-attribute
+presence, morph targets, materials and animation clip/action names. They sample imported
+animation at the start, midpoint and end, recording changed object names and
+`animatedNodeCount`; this catches inert transform clips but does not prove every keyframe.
+They also compare evaluated local mesh vertices, recording `maxVertexDisplacement` and
+`deformed`. Blender uses its dependency graph; Unity bakes the imported skinned renderer
+to an inspection mesh. This is geometric evaluation, not CPU image rendering.
+Blender samples the imported scene's active animation configuration;
+Unity samples each imported clip on the instantiated prefab. Blender records
+armature modifiers and material metallic/roughness/culling values. Unity records skin
+bone counts, shader names, shader-property names and bound texture slots. For shaders
+exposing glTFast's `metallicFactor`, `roughnessFactor`, and `_CullMode`, Unity also records
+their values with presence flags (assert those flags when asserting values). Nodes also
+record `materialMetallicFactors` and `materialRoughnessFactors` arrays, allowing assertions
+when material names are absent or repeated. A factor of -1 means no supported mapping.
+These are
+observations, not guarantees of shader fidelity or animation behavior. Application-level
+checks must additionally exercise playback, GPU appearance and a Unity player build.
+
+Run the portable assertion tests with:
+
+```sh
+bun test scripts/integration/check-receipt.test.mjs
+```
+
+## Deformation and thin-surface fixtures
+
+Generate the candidate's explicit skin, morph, and culling-control fixtures:
+
+```sh
+bun scripts/integration/generate-deformation-fixtures.ts --output /path/to/new-glbs
+node scripts/integration/run-imports.mjs \
+ --input /path/to/new-glbs --output /path/to/new-receipts \
+ --manifest scripts/integration/deformation-expectations.json \
+ --blender /path/to/blender
+```
+
+Add Unity arguments as above for its corresponding checks. These expectations target
+Blender 5.2 and Unity 6000.2 with glTFast 6.20; changed importer representations should
+be investigated before updating expectations.
+
+The skin fixture rotates its second bone by 60 degrees. Its furthest weighted vertex
+lies 0.2 m horizontally and 0.5 m vertically from that joint, so the expected displacement
+is `sqrt(0.2² + 0.5²) = 0.53851648 m`. The morph clip displaces its upper vertices by
+exactly 0.6 m. Both must deform after real import. Identical sheets differing only in
+material sidedness provide a culling control. Structural checks verify the material
+flag; actual GPU front/back rendering is still required to qualify shader behavior.
+
+After importing those four fixtures into a disposable Unity project, Windows hosts can
+build and run the GPU check without opening a visible player window:
+
+```sh
+node scripts/integration/run-deformation-player.mjs \
+ --unity /path/to/Unity.exe --unity-project /path/to/disposable-project \
+ --output /path/to/new-player-receipts
+```
+
+This profile builds a Windows player with serialized fixture references, then uses
+Direct3D11 to render front/back views and animation poses. It checks substantial skin
+and morph deformation, changed rendered pixels, visible two-sided back faces, culled
+single-sided back faces, and absence of unsupported shaders. Pose captures run on
+separate frames because Unity caches GPU skinning within a frame. The second pose is
+at 99.9% of clip duration to avoid a looping clip wrapping back to its start.
+
+The player receipt includes GPU identity and measured results; the runner records
+asset, helper-script, and package-lock hashes. This qualifies this explicit importer,
+player and render-pipeline combination. It does not establish runtime-downloaded GLB
+shader inclusion, other platforms, or physically identical shading across applications.
diff --git a/scripts/integration/browser-export-fixtures.mjs b/scripts/integration/browser-export-fixtures.mjs
new file mode 100644
index 00000000..4a824972
--- /dev/null
+++ b/scripts/integration/browser-export-fixtures.mjs
@@ -0,0 +1,349 @@
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { communitySceneDocument } from '../../src/community-exporter.ts';
+import { createGltfIO } from '../../src/gltf-io.ts';
+
+const SIZE = 192;
+const requireThat = (condition, message) => {
+ if (!condition) throw new Error(message);
+};
+const pixels = new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255]);
+function texture() {
+ const map = new THREE.DataTexture(pixels.slice(), 2, 2, THREE.RGBAFormat);
+ map.colorSpace = THREE.SRGBColorSpace;
+ map.magFilter = THREE.NearestFilter;
+ map.minFilter = THREE.NearestFilter;
+ map.needsUpdate = true;
+ return map;
+}
+async function fixture(kind) {
+ const root = new THREE.Group();
+ root.name = 'Asset';
+ let clips = [];
+ let mesh;
+ if (kind === 'skin') {
+ const geometry = new THREE.PlaneGeometry(1, 2, 1, 4);
+ geometry.translate(0, 1, 0);
+ const position = geometry.getAttribute('position');
+ const indices = [];
+ const weights = [];
+ for (let i = 0; i < position.count; i++) {
+ const influence = Math.max(0, Math.min(1, position.getY(i) - 0.5));
+ indices.push(0, 1, 0, 0);
+ weights.push(1 - influence, influence, 0, 0);
+ }
+ geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(indices, 4));
+ geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(weights, 4));
+ mesh = new THREE.SkinnedMesh(
+ geometry,
+ new THREE.MeshStandardMaterial({ color: 0x44aa77, side: THREE.DoubleSide }),
+ );
+ const base = new THREE.Bone();
+ base.name = 'Joint_Base';
+ const tip = new THREE.Bone();
+ tip.name = 'Joint_Tip';
+ tip.position.y = 0.5;
+ base.add(tip);
+ mesh.add(base);
+ mesh.bind(new THREE.Skeleton([base, tip]));
+ clips = [
+ new THREE.AnimationClip('Bend', 1, [
+ new THREE.QuaternionKeyframeTrack(
+ 'Joint_Tip.quaternion',
+ [0, 1],
+ [0, 0, 0, 1, 0, 0, 0.5, Math.sqrt(0.75)],
+ ),
+ ]),
+ ];
+ } else if (kind === 'morph') {
+ const geometry = new THREE.BoxGeometry(1, 1, 0.4);
+ const morph = geometry.getAttribute('position').clone();
+ for (let i = 0; i < morph.count; i++) {
+ if (morph.getY(i) > 0)
+ morph.setXYZ(i, morph.getX(i) + 0.7, morph.getY(i) + 0.5, morph.getZ(i));
+ }
+ geometry.morphAttributes.position = [morph];
+ mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ color: 0xaa7744 }));
+ mesh.name = 'Mesh_Surface';
+ clips = [
+ new THREE.AnimationClip('Morph', 1, [
+ new THREE.NumberKeyframeTrack('Mesh_Surface.morphTargetInfluences[0]', [0, 1], [0, 1]),
+ ]),
+ ];
+ } else if (kind === 'sheen') {
+ mesh = new THREE.Mesh(
+ new THREE.SphereGeometry(0.7, 32, 16),
+ new THREE.MeshPhysicalMaterial({
+ color: 0x446688,
+ roughness: 0.7,
+ sheen: 0.6,
+ sheenColor: 0xaa2222,
+ sheenRoughness: 0.35,
+ }),
+ );
+ } else {
+ const map = texture();
+ if (kind === 'encoded') {
+ const canvas = new OffscreenCanvas(2, 2);
+ const ctx = canvas.getContext('2d');
+ ctx.putImageData(new ImageData(new Uint8ClampedArray(pixels), 2, 2), 0, 0);
+ map.userData.encoded = {
+ mime: 'image/png',
+ bytes: new Uint8Array(await (await canvas.convertToBlob()).arrayBuffer()),
+ };
+ }
+ if (kind.startsWith('uv-')) {
+ map.wrapS = THREE.RepeatWrapping;
+ map.wrapT = THREE.MirroredRepeatWrapping;
+ map.offset.set(0.17, 0.23);
+ map.repeat.set(1.7, kind === 'uv-uniform' ? 1.7 : 1.3);
+ map.rotation = 0.37;
+ if (kind === 'uv-center' || kind === 'uv-uniform') map.center.set(0.5, 0.5);
+ if (kind === 'uv-matrix') {
+ map.matrixAutoUpdate = false;
+ map.matrix.set(1.2, 0.3, 0.13, 0.2, 0.8, 0.21, 0, 0, 1);
+ }
+ if (kind === 'uv-native-matrix') {
+ map.matrixAutoUpdate = false;
+ const c = Math.cos(0.37);
+ const s = Math.sin(0.37);
+ map.matrix.set(1.7 * c, 1.3 * s, 0.17, -1.7 * s, 1.3 * c, 0.23, 0, 0, 1);
+ }
+ }
+ mesh = new THREE.Mesh(
+ new THREE.PlaneGeometry(1.5, 1.5),
+ new THREE.MeshStandardMaterial({
+ map,
+ roughness: 0.6,
+ side: kind === 'double-sided' ? THREE.DoubleSide : THREE.FrontSide,
+ }),
+ );
+ if (kind === 'raw' || kind === 'encoded') {
+ clips = [
+ new THREE.AnimationClip('Turn', 1, [
+ new THREE.QuaternionKeyframeTrack(
+ 'Mesh_Surface.quaternion',
+ [0, 1],
+ [0, 0, 0, 1, 0, 0.382683432365, 0, 0.923879532511],
+ ),
+ ]),
+ ];
+ }
+ }
+ mesh.name = 'Mesh_Surface';
+ mesh.userData.private = 'must-not-export';
+ root.add(mesh);
+ return { root, clips, mesh };
+}
+function comparePixels(a, b) {
+ let max = 0;
+ let total = 0;
+ let large = 0;
+ let foreground = 0;
+ for (let i = 0; i < a.length; i++) {
+ const delta = Math.abs(a[i] - b[i]);
+ max = Math.max(max, delta);
+ total += delta;
+ if (delta > 8) large++;
+ if (i % 4 !== 3 && a[i] > 5) foreground++;
+ }
+ return {
+ maxByteDifference: max,
+ meanByteDifference: total / a.length,
+ largeDifferenceFraction: large / a.length,
+ foregroundChannels: foreground,
+ };
+}
+function poseVertices(mesh) {
+ mesh.updateWorldMatrix(true, false);
+ if (mesh.isSkinnedMesh) mesh.skeleton.update();
+ const result = [];
+ const point = new THREE.Vector3();
+ for (let i = 0; i < mesh.geometry.getAttribute('position').count; i++) {
+ mesh.getVertexPosition(i, point).applyMatrix4(mesh.matrixWorld);
+ result.push(...point.toArray());
+ }
+ return result;
+}
+async function run() {
+ const canvas = document.createElement('canvas');
+ document.body.append(canvas);
+ const renderer = new THREE.WebGLRenderer({ canvas });
+ renderer.setSize(SIZE, SIZE);
+ const gl = renderer.getContext();
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
+ const gpu = info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
+ requireThat(!/swiftshader|llvmpipe|software/i.test(gpu), `Hardware GPU required: ${gpu}`);
+ const target = new THREE.WebGLRenderTarget(SIZE, SIZE);
+ const results = [];
+ for (const kind of [
+ 'raw',
+ 'encoded',
+ 'skin',
+ 'morph',
+ 'sheen',
+ 'uv-transform',
+ 'uv-center',
+ 'uv-uniform',
+ 'uv-matrix',
+ 'uv-native-matrix',
+ 'double-sided',
+ ]) {
+ const expectedRejection = ['uv-transform', 'uv-center', 'uv-matrix'].includes(kind);
+ const row = { case: kind, expectedRejection };
+ results.push(row);
+ try {
+ const { root, clips, mesh } = await fixture(kind);
+ const docs = [
+ await communitySceneDocument(root, clips),
+ await communitySceneDocument(root, clips),
+ ];
+ requireThat(
+ !expectedRejection,
+ 'Unrepresentable UV fixture unexpectedly exported; qualify a lossless supported path before changing this expectation',
+ );
+ const bytes = await Promise.all(docs.map((doc) => createGltfIO().writeBinary(doc)));
+ row.bytes = Array.from(bytes[0]);
+ requireThat(
+ bytes[0].length === bytes[1].length && bytes[0].every((value, i) => value === bytes[1][i]),
+ 'Nondeterministic browser export',
+ );
+ const loaded = await new GLTFLoader().parseAsync(bytes[0].buffer, '');
+ const importedMesh = loaded.scene.getObjectByName('Mesh_Surface');
+ if (kind.startsWith('uv-')) {
+ if (mesh.material.map.matrixAutoUpdate) mesh.material.map.updateMatrix();
+ row.textureDiagnostic = {
+ original: {
+ matrix: mesh.material.map.matrix.toArray(),
+ flipY: mesh.material.map.flipY,
+ wrapS: mesh.material.map.wrapS,
+ wrapT: mesh.material.map.wrapT,
+ minFilter: mesh.material.map.minFilter,
+ magFilter: mesh.material.map.magFilter,
+ },
+ imported: {
+ matrix: importedMesh.material.map.matrix.toArray(),
+ flipY: importedMesh.material.map.flipY,
+ wrapS: importedMesh.material.map.wrapS,
+ wrapT: importedMesh.material.map.wrapT,
+ minFilter: importedMesh.material.map.minFilter,
+ magFilter: importedMesh.material.map.magFilter,
+ },
+ };
+ }
+ requireThat(importedMesh?.isMesh, 'Export lost named mesh');
+ requireThat(!('private' in importedMesh.userData), 'Private metadata leaked');
+ if (kind === 'skin')
+ requireThat(
+ importedMesh.isSkinnedMesh && importedMesh.skeleton.bones.length === 2,
+ 'Skin/bones lost',
+ );
+ if (kind === 'morph')
+ requireThat(importedMesh.morphTargetInfluences.length === 1, 'Morph target lost');
+ if (kind.startsWith('uv-'))
+ requireThat(
+ docs[0]
+ .getRoot()
+ .listExtensionsUsed()
+ .some((ext) => ext.extensionName === 'KHR_texture_transform'),
+ 'UV transform extension missing',
+ );
+ if (kind === 'double-sided')
+ requireThat(importedMesh.material.side === THREE.DoubleSide, 'Double-sided material lost');
+ row.samples = [];
+ let firstImage;
+ let finalImage;
+ const times = clips.length ? [0, 0.25, 0.5, 0.75, 1] : [0];
+ const views = kind === 'double-sided' ? ['front', 'back'] : ['front'];
+ for (const view of views)
+ for (const time of times) {
+ const images = [];
+ const vertices = [];
+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
+ const centerY = kind === 'skin' ? 0.8 : 0;
+ camera.position.set(0, centerY, view === 'back' ? -4 : 4);
+ camera.lookAt(0, centerY, 0);
+ for (const [object, animation, surface] of [
+ [root, clips[0], mesh],
+ [loaded.scene, loaded.animations[0], importedMesh],
+ ]) {
+ let mixer;
+ if (animation) {
+ mixer = new THREE.AnimationMixer(object);
+ const action = mixer.clipAction(animation);
+ action.setLoop(THREE.LoopOnce, 1);
+ action.clampWhenFinished = true;
+ action.play();
+ mixer.setTime(time);
+ }
+ object.updateMatrixWorld(true);
+ vertices.push(poseVertices(surface));
+ const scene = new THREE.Scene();
+ scene.add(object, new THREE.HemisphereLight(0xffffff, 0x555555, 3));
+ renderer.setRenderTarget(target);
+ renderer.render(scene, camera);
+ const image = new Uint8Array(SIZE * SIZE * 4);
+ renderer.readRenderTargetPixels(target, 0, 0, SIZE, SIZE, image);
+ images.push(image);
+ renderer.setRenderTarget(null);
+ renderer.render(scene, camera);
+ mixer?.stopAllAction();
+ }
+ const difference = comparePixels(images[0], images[1]);
+ let maxVertexDifference = 0;
+ requireThat(vertices[0].length === vertices[1].length, 'Vertex count changed');
+ vertices[0].forEach((value, i) => {
+ maxVertexDifference = Math.max(maxVertexDifference, Math.abs(value - vertices[1][i]));
+ });
+ row.samples.push({ view, time, ...difference, maxVertexDifference });
+ requireThat(
+ maxVertexDifference < 1e-5,
+ `Deformed vertices differ: ${maxVertexDifference}`,
+ );
+ requireThat(
+ difference.meanByteDifference <= 0.1 && difference.largeDifferenceFraction <= 0.001,
+ `GPU parity failed: ${JSON.stringify(difference)}`,
+ );
+ requireThat(difference.foregroundChannels > 1000, `Fixture not visible from ${view}`);
+ firstImage ??= images[0];
+ finalImage = images[0];
+ }
+ if (clips.length) {
+ row.motion = comparePixels(firstImage, finalImage);
+ requireThat(row.motion.largeDifferenceFraction > 0.005, 'Animation did not visibly move');
+ }
+ if (kind === 'sheen') {
+ mesh.material.sheen = 0;
+ const scene = new THREE.Scene();
+ scene.add(root, new THREE.HemisphereLight(0xffffff, 0x555555, 3));
+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
+ camera.position.set(0, 0, 4);
+ camera.lookAt(0, 0, 0);
+ renderer.setRenderTarget(target);
+ renderer.render(scene, camera);
+ const withoutSheen = new Uint8Array(SIZE * SIZE * 4);
+ renderer.readRenderTargetPixels(target, 0, 0, SIZE, SIZE, withoutSheen);
+ renderer.setRenderTarget(null);
+ row.sheenEffect = comparePixels(firstImage, withoutSheen);
+ requireThat(
+ row.sheenEffect.meanByteDifference > 0.01,
+ 'Sheen did not visibly affect the fixture',
+ );
+ }
+ row.passed = true;
+ row.supported = true;
+ } catch (error) {
+ row.passed =
+ expectedRejection &&
+ String(error).includes(
+ 'UV matrix contains shear or perspective that KHR_texture_transform cannot represent',
+ );
+ row.supported = false;
+ row.error = String(error);
+ }
+ }
+ target.dispose();
+ renderer.dispose();
+ return { gpu, size: SIZE, results };
+}
+window.audit = run();
diff --git a/scripts/integration/browser-export.md b/scripts/integration/browser-export.md
new file mode 100644
index 00000000..91979686
--- /dev/null
+++ b/scripts/integration/browser-export.md
@@ -0,0 +1,59 @@
+# Browser exporter GPU gate
+
+Run the community exporter directly in an isolated hardware-accelerated Chrome session, reimport
+the GLB with Three.js GLTFLoader, and compare original/reimported GPU readbacks and deformed vertex
+positions. This does not use the CPU preview renderer or live model providers.
+
+```sh
+node scripts/integration/run-browser-export.mjs
+```
+
+Requires Bun, Playwright, and installed Chrome with a working GPU. Optional arguments:
+
+- `--playwright <module-or-absolute-package-path>`: resolve an existing Playwright installation.
+- `--browser <channel-or-absolute-executable>`: defaults to the `chrome` channel.
+- `--bun <executable>`: choose the Bun executable used for the direct browser bundle.
+
+The script does not install dependencies or change any existing browser profile. It writes a fresh
+temporary folder containing `receipt.json`, the exact browser bundle, retained GLBs, and a GPU
+screenshot. The receipt includes the browser version, GPU identity, bundle SHA-256, output hashes,
+Khronos validation counts, pixel/vertex errors, and expected unsupported cases. Failures return a
+nonzero exit code. Software GPU fallback is explicitly rejected.
+
+## Coverage
+
+- Raw and encoded textures with a quaternion animation.
+- Two-bone weighted skin deformation and morph-target animation, each sampled five times.
+- Physical-material sheen at intensity 0.6, with a sheen-disabled visibility control.
+- Uniform texture scale with rotation and nonzero center.
+- A manually assigned, glTF-representable UV matrix.
+- A double-sided thin surface viewed from both front and back.
+
+Animations must visibly change the image, and every sample must contain visible geometry. The
+comparison checks deformed vertex positions as well as pixels. Geometry tolerance is `1e-5` scene
+units; pixel tolerances are a mean channel difference at most 0.1/255 and at most 0.1% of channels
+differing by more than 8/255. Receipts preserve the actual measured errors, including exact matches.
+
+Three explicitly unsupported UV fixtures assert the precise rejection diagnostic: nonuniform
+Three.js scale combined with rotation, that transform with a nonzero center, and a manually sheared
+matrix. Their receipts say `supported: false`, `expectedRejection: true`. Passing these negative
+tests means data loss was prevented; it does **not** mean these UV configurations are supported.
+glTF's texture transform composes translation/rotation/scale in a different order from Three.js.
+Lossless UV baking or another qualified strategy is needed before expanding this boundary.
+
+## Latest measured evidence
+
+On Chrome 152.0.7977.83 with NVIDIA RTX 3070 through ANGLE Direct3D11, eight supported fixtures
+passed 25 original/reimported GPU comparisons with **zero channel differences**. Maximum deformed
+vertex difference was `1.49e-8`. All eight exported GLBs passed Khronos validation with zero errors.
+The three unsupported UV configurations were rejected explicitly. The sheen-disabled control
+changed the image (maximum 25/255, mean 0.105/255), showing the sheen fixture exercised an actual
+visible effect. Browser bundle SHA-256:
+`c64461b92f628f4b4dd350a5fc9ddf206ca4270d41b19e8334598cbc8a52bb7a`.
+This final rerun includes the texture-resource naming fix and corresponds to runtime build identity
+`413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8`.
+
+These are small deterministic fixtures, not full material-portfolio certification. They do not
+qualify Unity/Blender appearance, shader variants in player builds, macOS/Linux GPUs, compression,
+normal-map tangent edge cases, all skin bindings, all morph interpolation, or every combination of
+material extensions. A successful browser gate is one part of exporter qualification.
diff --git a/scripts/integration/check-receipt.mjs b/scripts/integration/check-receipt.mjs
new file mode 100644
index 00000000..01ef703c
--- /dev/null
+++ b/scripts/integration/check-receipt.mjs
@@ -0,0 +1,59 @@
+/** Explicit engine-specific expectations: no import-success-only acceptance. */
+export function checkReceipt(receipt, manifest) {
+ const errors = [];
+ if (!receipt.engine || !receipt.version) errors.push('missing engine/version identity');
+ if (!Object.keys(manifest.files ?? {}).length) errors.push('missing file expectations');
+ const equal = (actual, expected) =>
+ typeof expected === 'number'
+ ? Number.isFinite(actual) && Math.abs(actual - expected) <= (manifest.tolerance ?? 1e-5)
+ : Array.isArray(expected)
+ ? Array.isArray(actual) &&
+ actual.length === expected.length &&
+ expected.every((v, i) => equal(actual[i], v))
+ : actual === expected;
+ for (const [file, expected] of Object.entries(manifest.files ?? {})) {
+ const matches = (receipt.files ?? []).filter((r) => r.file === file);
+ if (matches.length !== 1) {
+ errors.push(`${file}: missing or duplicate receipt`);
+ continue;
+ }
+ const actual = matches[0];
+ if (actual.error) {
+ errors.push(`${file}: ${actual.error}`);
+ continue;
+ }
+ if (
+ !expected.nodes?.length &&
+ !expected.materials?.length &&
+ expected.animationCount === undefined
+ )
+ errors.push(`${file}: no assertions`);
+ if (
+ expected.animationCount !== undefined &&
+ actual.animations?.length !== expected.animationCount
+ )
+ errors.push(`${file}: animationCount mismatch`);
+ if (
+ expected.animatedNodeCount !== undefined &&
+ actual.animatedNodeCount !== expected.animatedNodeCount
+ )
+ errors.push(`${file}: animatedNodeCount mismatch`);
+ for (const collection of ['nodes', 'materials'])
+ for (const item of expected[collection] ?? []) {
+ const found = (actual[collection] ?? []).filter((entry) => entry.name === item.name);
+ if (found.length !== 1) {
+ errors.push(`${file}: ${collection}/${item.name} missing or ambiguous`);
+ continue;
+ }
+ for (const [key, value] of Object.entries(item))
+ if (!equal(found[0][key], value))
+ errors.push(
+ `${file}: ${collection}/${item.name}.${key} expected ${JSON.stringify(value)}, got ${JSON.stringify(found[0][key])}`,
+ );
+ }
+ }
+ for (const record of receipt.files ?? [])
+ if (!manifest.files?.[record.file])
+ errors.push(`${record.file}: no expectations${record.error ? `; ${record.error}` : ''}`);
+ return errors;
+}
diff --git a/scripts/integration/check-receipt.test.mjs b/scripts/integration/check-receipt.test.mjs
new file mode 100644
index 00000000..ffc66712
--- /dev/null
+++ b/scripts/integration/check-receipt.test.mjs
@@ -0,0 +1,59 @@
+import { test, expect } from 'bun:test';
+import { checkReceipt } from './check-receipt.mjs';
+
+const manifest = {
+ files: {
+ 'prop.glb': {
+ nodes: [{ name: 'Pennant', parent: 'Pivot', uvSets: 2, morphTargets: 1 }],
+ materials: [{ name: 'Cloth', metallic: 0.2 }],
+ animationCount: 1,
+ },
+ },
+};
+const receipt = {
+ engine: 'test',
+ version: '1',
+ files: [
+ {
+ file: 'prop.glb',
+ nodes: [{ name: 'Pennant', parent: 'Pivot', uvSets: 2, morphTargets: 1 }],
+ materials: [{ name: 'Cloth', metallic: 0.20000001 }],
+ animations: ['Turn'],
+ },
+ ],
+};
+test('checks structural and numeric expectations with tolerance', () =>
+ expect(checkReceipt(receipt, manifest)).toEqual([]));
+test('rejects a missing file rather than passing an empty import', () =>
+ expect(checkReceipt({ ...receipt, files: [] }, manifest).join()).toContain('missing'));
+test('detects feature loss', () => {
+ const broken = structuredClone(receipt);
+ broken.files[0].nodes[0].uvSets = 1;
+ expect(checkReceipt(broken, manifest).join()).toContain('uvSets');
+});
+test('rejects ambiguous names and importer errors', () => {
+ const broken = structuredClone(receipt);
+ broken.files[0].nodes.push(broken.files[0].nodes[0]);
+ expect(checkReceipt(broken, manifest).join()).toContain('ambiguous');
+ broken.files[0].error = 'failed';
+ expect(checkReceipt(broken, manifest).join()).toContain('failed');
+});
+test('requires a nonempty expectation set and engine identity', () => {
+ expect(checkReceipt(receipt, { files: {} }).length).toBeGreaterThan(0);
+ expect(checkReceipt({ ...receipt, version: '' }, manifest).length).toBeGreaterThan(0);
+});
+test('rejects unasserted imports', () => {
+ const extra = structuredClone(receipt);
+ extra.files.push({ file: 'uncovered.glb' });
+ expect(checkReceipt(extra, manifest).join()).toContain('no expectations');
+});
+test('detects clips that import but do not move their target', () => {
+ const expectations = structuredClone(manifest);
+ expectations.files['prop.glb'].animatedNodeCount = 1;
+ expect(
+ checkReceipt(
+ { ...receipt, files: [{ ...receipt.files[0], animatedNodeCount: 0 }] },
+ expectations,
+ ).join(),
+ ).toContain('animatedNodeCount');
+});
diff --git a/scripts/integration/deformation-expectations.json b/scripts/integration/deformation-expectations.json
new file mode 100644
index 00000000..babee105
--- /dev/null
+++ b/scripts/integration/deformation-expectations.json
@@ -0,0 +1,14 @@
+{
+ "blender":{"files":{
+ "skin.glb":{"animationCount":1,"nodes":[{"name":"Mesh_Skin","bones":2},{"name":"Mesh_0","deformed":true,"maxVertexDisplacement":0.5385164807}]},
+ "morph.glb":{"animationCount":1,"nodes":[{"name":"Mesh_Morph","morphTargets":1,"deformed":true,"maxVertexDisplacement":0.6}]},
+ "double-sided.glb":{"animationCount":0,"nodes":[{"name":"Mesh_Sheet","deformed":false}],"materials":[{"name":"Surface","doubleSided":true}]},
+ "single-sided.glb":{"animationCount":0,"nodes":[{"name":"Mesh_Sheet","deformed":false}],"materials":[{"name":"Surface","doubleSided":false}]}
+ }},
+ "unity":{"files":{
+ "skin.glb":{"animationCount":1,"nodes":[{"name":"Mesh_Skin","bones":2,"deformed":true,"maxVertexDisplacement":0.5385164807}]},
+ "morph.glb":{"animationCount":1,"nodes":[{"name":"Mesh_Morph","morphTargets":1,"deformed":true,"maxVertexDisplacement":0.6}]},
+ "double-sided.glb":{"animationCount":0,"nodes":[{"name":"Mesh_Sheet","deformed":false}],"materials":[{"name":"Surface","hasCullMode":true,"cullMode":0}]},
+ "single-sided.glb":{"animationCount":0,"nodes":[{"name":"Mesh_Sheet","deformed":false}],"materials":[{"name":"Surface","hasCullMode":true,"cullMode":2}]}
+ }}
+}
diff --git a/scripts/integration/generate-deformation-fixtures.ts b/scripts/integration/generate-deformation-fixtures.ts
new file mode 100644
index 00000000..ead71afe
--- /dev/null
+++ b/scripts/integration/generate-deformation-fixtures.ts
@@ -0,0 +1,80 @@
+import * as T from 'three';
+import { renderSceneToGLB } from '../../src/render';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { resolve, join } from 'node:path';
+import { parseArgs } from 'node:util';
+const { values } = parseArgs({ options: { output: { type: 'string' } } });
+if (!values.output) throw new Error('Required: --output EMPTY_GLB_DIRECTORY');
+const output = resolve(values.output);
+process.env['KILN_GLTF_EXPORTER'] = 'three';
+await mkdir(output, { recursive: true });
+for (const kind of ['skin', 'morph', 'double-sided', 'single-sided']) {
+ const root = new T.Group();
+ root.name = 'Fixture';
+ const material = new T.MeshStandardMaterial({
+ color: 0x22aa55,
+ roughness: 0.55,
+ metalness: 0.1,
+ side: kind === 'single-sided' ? T.FrontSide : T.DoubleSide,
+ });
+ material.name = 'Surface';
+ let clips: T.AnimationClip[] = [];
+ if (kind === 'skin') {
+ const geo = new T.PlaneGeometry(0.4, 1, 1, 2);
+ geo.translate(0, 0.5, 0);
+ const count = geo.getAttribute('position').count,
+ indices = [],
+ weights = [];
+ for (let i = 0; i < count; i++) {
+ const y = geo.getAttribute('position').getY(i);
+ indices.push(y > 0.5 ? 1 : 0, 0, 0, 0);
+ weights.push(1, 0, 0, 0);
+ }
+ geo.setAttribute('skinIndex', new T.Uint16BufferAttribute(indices, 4));
+ geo.setAttribute('skinWeight', new T.Float32BufferAttribute(weights, 4));
+ const mesh = new T.SkinnedMesh(geo, material);
+ mesh.name = 'Mesh_Skin';
+ const base = new T.Bone();
+ base.name = 'Bone_Base';
+ const tip = new T.Bone();
+ tip.name = 'Bone_Tip';
+ tip.position.y = 0.5;
+ base.add(tip);
+ mesh.add(base);
+ root.add(mesh);
+ root.updateMatrixWorld(true);
+ mesh.bind(new T.Skeleton([base, tip]));
+ clips = [
+ new T.AnimationClip('Bend', 2, [
+ new T.QuaternionKeyframeTrack(
+ 'Bone_Tip.quaternion',
+ [0, 2],
+ [0, 0, 0, 1, 0, 0, Math.sin(Math.PI / 6), Math.cos(Math.PI / 6)],
+ ),
+ ]),
+ ];
+ } else if (kind === 'morph') {
+ const geo = new T.BoxGeometry(0.4, 0.4, 0.2);
+ const target = geo.getAttribute('position').clone();
+ for (let i = 0; i < target.count; i++)
+ target.setX(i, target.getX(i) + (target.getY(i) > 0 ? 0.6 : 0));
+ geo.morphAttributes.position = [target];
+ const mesh = new T.Mesh(geo, material);
+ mesh.name = 'Mesh_Morph';
+ mesh.updateMorphTargets();
+ root.add(mesh);
+ clips = [
+ new T.AnimationClip('Stretch', 2, [
+ new T.NumberKeyframeTrack('Mesh_Morph.morphTargetInfluences[0]', [0, 2], [0, 1]),
+ ]),
+ ];
+ } else {
+ const mesh = new T.Mesh(new T.PlaneGeometry(0.8, 0.8), material);
+ mesh.name = 'Mesh_Sheet';
+ root.add(mesh);
+ }
+ const result = await renderSceneToGLB(root, { clips, derivative: true, optimize: 'off' });
+ if (result.gltfValidation.issues.numErrors) throw new Error(`${kind}: invalid GLB`);
+ await writeFile(join(output, `${kind}.glb`), result.bytes, { flag: 'wx' });
+ console.log(kind, result.bytes.length);
+}
diff --git a/scripts/integration/import-blender.py b/scripts/integration/import-blender.py
new file mode 100644
index 00000000..b33b829b
--- /dev/null
+++ b/scripts/integration/import-blender.py
@@ -0,0 +1,77 @@
+"""Headless structural inspection only; does not render or modify source assets."""
+import bpy
+import json
+import os
+import sys
+import glob
+
+input_dir, output = sys.argv[sys.argv.index('--') + 1:]
+report = {'engine': 'blender', 'version': bpy.app.version_string, 'files': []}
+def deformed_vertices(obj):
+ evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
+ mesh = evaluated.to_mesh()
+ try:
+ return [v.co.copy() for v in mesh.vertices]
+ finally:
+ evaluated.to_mesh_clear()
+
+for path in sorted(glob.glob(os.path.join(input_dir, '*.glb'))):
+ record = {'file': os.path.basename(path), 'nodes': [], 'materials': [], 'animations': []}
+ report['files'].append(record)
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ try:
+ bpy.ops.import_scene.gltf(filepath=path)
+ bpy.context.view_layer.update()
+ for obj in bpy.context.scene.objects:
+ mesh = obj.data if obj.type == 'MESH' else None
+ record['nodes'].append({
+ 'name': obj.name, 'parent': obj.parent.name if obj.parent else None,
+ 'localPosition': list(obj.location), 'worldPosition': list(obj.matrix_world.translation),
+ 'vertices': len(mesh.vertices) if mesh else 0,
+ 'uvSets': len(mesh.uv_layers) if mesh else 0,
+ 'colors': len(mesh.color_attributes) if mesh else 0,
+ 'morphTargets': len(mesh.shape_keys.key_blocks) - 1 if mesh and mesh.shape_keys else 0,
+ 'bones': len(obj.data.bones) if obj.type == 'ARMATURE' else 0,
+ 'armatureModifiers': sum(m.type == 'ARMATURE' for m in obj.modifiers),
+ })
+ factors = []
+ for slot in obj.material_slots:
+ mat = slot.material
+ bsdf = next((n for n in mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED'), None) if mat and mat.use_nodes else None
+ factors.append((bsdf.inputs['Metallic'].default_value, bsdf.inputs['Roughness'].default_value) if bsdf else (-1, -1))
+ record['nodes'][-1].update(materialMetallicFactors=[f[0] for f in factors], materialRoughnessFactors=[f[1] for f in factors])
+ for mat in bpy.data.materials:
+ bsdf = next((n for n in mat.node_tree.nodes if n.type == 'BSDF_PRINCIPLED'), None) if mat.use_nodes else None
+ material = {'name': mat.name, 'doubleSided': not mat.use_backface_culling}
+ if bsdf:
+ material.update(metallic=bsdf.inputs['Metallic'].default_value, roughness=bsdf.inputs['Roughness'].default_value)
+ material['textures'] = sorted(n.image.name for n in mat.node_tree.nodes if n.type == 'TEX_IMAGE' and n.image) if mat.use_nodes else []
+ record['materials'].append(material)
+ record['animations'] = sorted(a.name for a in bpy.data.actions)
+ bpy.context.scene.frame_set(0)
+ initial = {o.name: o.matrix_basis.copy() for o in bpy.context.scene.objects}
+ mesh_objects = [o for o in bpy.context.scene.objects if o.type == 'MESH']
+ initial_vertices = {o.name: deformed_vertices(o) for o in mesh_objects}
+ displacements = {o.name: 0.0 for o in mesh_objects}
+ moving = set()
+ for action in bpy.data.actions:
+ for frame in [int(action.frame_range[1] / 2), int(action.frame_range[1])]:
+ bpy.context.scene.frame_set(frame)
+ for obj in bpy.context.scene.objects:
+ if max(abs(obj.matrix_basis[r][c] - initial[obj.name][r][c]) for r in range(4) for c in range(4)) > 1e-5:
+ moving.add(obj.name)
+ for obj in mesh_objects:
+ current = deformed_vertices(obj)
+ original = initial_vertices[obj.name]
+ if len(current) != len(original):
+ raise ValueError('Animation changed vertex count: ' + obj.name)
+ displacements[obj.name] = max(displacements[obj.name], max(((a - b).length for a, b in zip(current, original)), default=0))
+ for node in record['nodes']:
+ node['maxVertexDisplacement'] = displacements.get(node['name'], 0)
+ node['deformed'] = node['maxVertexDisplacement'] > 1e-5
+ record['animatedNodes'] = sorted(moving)
+ record['animatedNodeCount'] = len(moving)
+ except Exception as error:
+ record['error'] = str(error)
+with open(output, 'w', encoding='utf-8') as stream:
+ json.dump(report, stream, indent=2)
diff --git a/scripts/integration/run-browser-export.mjs b/scripts/integration/run-browser-export.mjs
new file mode 100644
index 00000000..a0f1e9a1
--- /dev/null
+++ b/scripts/integration/run-browser-export.mjs
@@ -0,0 +1,94 @@
+/** Optional GPU gate: requires Bun and Playwright, plus hardware-accelerated Chrome/Chromium. */
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import validator from 'gltf-validator';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const args = process.argv.slice(2);
+const option = (name, fallback) => (args.includes(name) ? args[args.indexOf(name) + 1] : fallback);
+const output = await mkdtemp(path.join(os.tmpdir(), 'kiln-browser-export-'));
+const entry = path.join(root, 'scripts/integration/browser-export-fixtures.mjs');
+const bundle = path.join(output, 'browser.js');
+const built = spawnSync(
+ option('--bun', 'bun'),
+ ['build', entry, '--target=browser', `--outfile=${bundle}`],
+ { cwd: root, encoding: 'utf8', windowsHide: true },
+);
+if (built.status !== 0) throw new Error(`Browser bundle failed: ${built.error ?? built.stderr}`);
+const require = createRequire(import.meta.url);
+const { chromium } = require(option('--playwright', 'playwright'));
+const script = await readFile(bundle);
+const server = createServer((request, response) => {
+ response.setHeader(
+ 'Content-Type',
+ request.url === '/browser.js' ? 'text/javascript' : 'text/html',
+ );
+ response.end(
+ request.url === '/browser.js'
+ ? script
+ : '<html><body><script type="module" src="/browser.js"></script></body></html>',
+ );
+});
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+let browser;
+try {
+ const selected = option('--browser', 'chrome');
+ browser = await chromium.launch({
+ ...(path.isAbsolute(selected) ? { executablePath: selected } : { channel: selected }),
+ headless: true,
+ args: ['--enable-gpu', ...(process.platform === 'win32' ? ['--use-angle=d3d11'] : [])],
+ });
+ const page = await browser.newPage();
+ await page.goto(`http://127.0.0.1:${server.address().port}`);
+ await page.waitForFunction(() => window.audit);
+ const receipt = await page.evaluate(() => window.audit);
+ receipt.browser = browser.version();
+ receipt.bundleSha256 = createHash('sha256').update(script).digest('hex');
+ receipt.directory = output;
+ for (const row of receipt.results) {
+ if (!row.bytes) continue;
+ const bytes = Buffer.from(row.bytes);
+ await writeFile(path.join(output, `${row.case}.glb`), bytes);
+ const validation = await validator.validateBytes(bytes);
+ row.validationErrors = validation.issues.numErrors;
+ row.validationWarnings = validation.issues.numWarnings;
+ if (validation.issues.numErrors) row.passed = false;
+ row.sha256 = createHash('sha256').update(bytes).digest('hex');
+ row.bytes = bytes.length;
+ }
+ receipt.passed = receipt.results.every((row) => row.passed);
+ await page.screenshot({ path: path.join(output, 'gpu.png') });
+ await writeFile(path.join(output, 'receipt.json'), `${JSON.stringify(receipt, null, 2)}\n`);
+ console.log(
+ JSON.stringify(
+ {
+ directory: output,
+ gpu: receipt.gpu,
+ browser: receipt.browser,
+ passed: receipt.passed,
+ results: receipt.results.map(
+ ({ case: name, passed, supported, expectedRejection, error, validationErrors }) => ({
+ name,
+ passed,
+ supported,
+ expectedRejection,
+ error,
+ validationErrors,
+ }),
+ ),
+ },
+ null,
+ 2,
+ ),
+ );
+ if (!receipt.passed) process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await new Promise((resolve) => server.close(resolve));
+}
diff --git a/scripts/integration/run-deformation-player.mjs b/scripts/integration/run-deformation-player.mjs
new file mode 100644
index 00000000..2dccb567
--- /dev/null
+++ b/scripts/integration/run-deformation-player.mjs
@@ -0,0 +1,107 @@
+/** Optional Windows/D3D11 GPU qualification in a disposable Unity project. */
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parseArgs } from 'node:util';
+
+const { values } = parseArgs({
+ options: Object.fromEntries(
+ ['unity', 'unity-project', 'output'].map((key) => [key, { type: 'string' }]),
+ ),
+});
+if (process.platform !== 'win32')
+ throw new Error('This qualification profile currently requires Windows and Direct3D11.');
+if (!values.unity || !values['unity-project'] || !values.output)
+ throw new Error(
+ 'Required: --unity EXECUTABLE --unity-project DISPOSABLE_PROJECT --output NEW_DIRECTORY',
+ );
+const output = resolve(values.output),
+ project = resolve(values['unity-project']);
+if (existsSync(output)) throw new Error(`Choose a new output directory: ${output}`);
+if (!existsSync(join(project, 'Assets', 'KilnImportFixtures')))
+ throw new Error('First import the four deformation fixtures using run-imports.mjs');
+mkdirSync(output, { recursive: true });
+const scripts = dirname(fileURLToPath(import.meta.url));
+const hash = (path) => createHash('sha256').update(readFileSync(path)).digest('hex');
+for (const [file, directory] of [
+ ['KilnDeformationGpuSmoke.cs', 'Assets'],
+ ['KilnDeformationGpuBuild.cs', 'Assets/Editor'],
+]) {
+ const source = join(scripts, file),
+ target = join(project, directory, file);
+ if (existsSync(target) && hash(target) !== hash(source))
+ throw new Error(`Refusing to overwrite different script: ${target}`);
+ if (!existsSync(target)) copyFileSync(source, target);
+}
+writeFileSync(
+ join(output, 'inputs.json'),
+ JSON.stringify(
+ {
+ assets: Object.fromEntries(
+ ['double-sided', 'morph', 'single-sided', 'skin'].map((name) => [
+ name,
+ hash(join(project, 'Assets', 'KilnImportFixtures', `${name}.glb`)),
+ ]),
+ ),
+ scripts: Object.fromEntries(
+ ['KilnDeformationGpuSmoke.cs', 'KilnDeformationGpuBuild.cs'].map((file) => [
+ file,
+ hash(join(scripts, file)),
+ ]),
+ ),
+ packages: hash(join(project, 'Packages', 'packages-lock.json')),
+ },
+ null,
+ 2,
+ ),
+);
+const executable = join(output, 'build', 'KilnDeformation.exe');
+function run(executable, args, log, timeout) {
+ const child = spawnSync(executable, args, {
+ windowsHide: true,
+ encoding: 'utf8',
+ timeout,
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ writeFileSync(log, `${child.stdout ?? ''}\n${child.stderr ?? ''}`);
+ if (child.error || child.status !== 0)
+ throw new Error(`Process failed (${child.error?.message ?? child.status}); inspect ${log}`);
+}
+run(
+ values.unity,
+ [
+ '-batchmode',
+ '-nographics',
+ '-projectPath',
+ project,
+ '-executeMethod',
+ 'KilnDeformationGpuBuild.Run',
+ '-quit',
+ '-logFile',
+ join(output, 'build.log'),
+ '-playerOutput',
+ executable,
+ ],
+ join(output, 'build-process.log'),
+ 600_000,
+);
+const receipts = join(output, 'receipts');
+run(
+ executable,
+ [
+ '-batchmode',
+ '-force-d3d11',
+ '-receiptDirectory',
+ receipts,
+ '-logFile',
+ join(output, 'player.log'),
+ ],
+ join(output, 'player-process.log'),
+ 60_000,
+);
+const receipt = JSON.parse(readFileSync(join(receipts, 'player.json'), 'utf8'));
+if (receipt.passed !== true || receipt.api !== 'Direct3D11')
+ throw new Error('GPU deformation/culling checks failed');
+console.log(`GPU deformation and culling checks passed on ${receipt.device}; ${receipts}`);
diff --git a/scripts/integration/run-imports.mjs b/scripts/integration/run-imports.mjs
new file mode 100644
index 00000000..84d344ef
--- /dev/null
+++ b/scripts/integration/run-imports.mjs
@@ -0,0 +1,126 @@
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import {
+ readFileSync,
+ mkdirSync,
+ writeFileSync,
+ existsSync,
+ readdirSync,
+ copyFileSync,
+} from 'node:fs';
+import { resolve, join, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parseArgs } from 'node:util';
+import { checkReceipt } from './check-receipt.mjs';
+
+const { values } = parseArgs({
+ options: Object.fromEntries(
+ ['input', 'output', 'manifest', 'blender', 'unity', 'unity-project'].map((key) => [
+ key,
+ { type: 'string' },
+ ]),
+ ),
+});
+if (!values.input || !values.output || !values.manifest || (!values.blender && !values.unity))
+ throw new Error(
+ 'Required: --input GLB_DIRECTORY --output RECEIPT_DIRECTORY --manifest EXPECTATIONS.json and --blender EXECUTABLE and/or --unity EXECUTABLE --unity-project DISPOSABLE_PROJECT',
+ );
+const input = resolve(values.input),
+ output = resolve(values.output);
+if (!readdirSync(input).some((file) => file.endsWith('.glb')))
+ throw new Error('Input contains no GLB files');
+mkdirSync(output, { recursive: true });
+const scripts = dirname(fileURLToPath(import.meta.url));
+const manifest = JSON.parse(readFileSync(resolve(values.manifest), 'utf8'));
+const hash = (path) => createHash('sha256').update(readFileSync(path)).digest('hex');
+writeFileSync(
+ join(output, 'inputs.json'),
+ JSON.stringify(
+ {
+ manifestSha256: hash(resolve(values.manifest)),
+ files: Object.fromEntries(
+ readdirSync(input)
+ .filter((file) => file.endsWith('.glb'))
+ .sort()
+ .map((file) => [file, hash(join(input, file))]),
+ ),
+ },
+ null,
+ 2,
+ ),
+);
+const failures = [];
+for (const engine of ['blender', 'unity']) {
+ if (!values[engine]) continue;
+ const receipt = join(output, `${engine}.json`);
+ if (existsSync(receipt))
+ throw new Error(`Refusing stale receipt path: ${receipt}; choose a new output directory`);
+ let args;
+ if (engine === 'blender')
+ args = [
+ '--background',
+ '--factory-startup',
+ '--python',
+ join(scripts, 'import-blender.py'),
+ '--',
+ input,
+ receipt,
+ ];
+ else {
+ if (!values['unity-project'])
+ throw new Error(
+ '--unity-project is required; use a disposable project with glTFast installed',
+ );
+ const project = resolve(values['unity-project']);
+ const editor = join(project, 'Assets', 'Editor');
+ mkdirSync(editor, { recursive: true });
+ const target = join(editor, 'KilnImportAudit.cs');
+ if (existsSync(target)) throw new Error(`Refusing to overwrite ${target}`);
+ copyFileSync(join(scripts, 'KilnImportAudit.cs'), target);
+ args = [
+ '-batchmode',
+ '-nographics',
+ '-projectPath',
+ project,
+ '-executeMethod',
+ 'KilnImportAudit.Run',
+ '-quit',
+ '-logFile',
+ join(output, 'unity.log'),
+ '-kilnInput',
+ input,
+ '-kilnReceipt',
+ receipt,
+ ];
+ }
+ const process = spawnSync(values[engine], args, {
+ encoding: 'utf8',
+ timeout: 600_000,
+ maxBuffer: 16 * 1024 * 1024,
+ });
+ writeFileSync(
+ join(output, `${engine}-process.log`),
+ `${process.stdout ?? ''}\n${process.stderr ?? ''}`,
+ );
+ if (process.error || process.status !== 0 || !existsSync(receipt)) {
+ failures.push(`${engine}: process/import failed: ${process.error?.message ?? process.status}`);
+ continue;
+ }
+ if (!manifest[engine]) {
+ failures.push(`${engine}: missing engine-specific expectations`);
+ continue;
+ }
+ failures.push(
+ ...checkReceipt(JSON.parse(readFileSync(receipt, 'utf8')), manifest[engine]).map(
+ (failure) => `${engine}: ${failure}`,
+ ),
+ );
+}
+writeFileSync(
+ join(output, 'checks.json'),
+ JSON.stringify({ passed: failures.length === 0, failures }, null, 2),
+);
+if (failures.length) {
+ console.error(failures.join('\n'));
+ process.exitCode = 1;
+} else console.log(`Structural import assertions passed; receipts: ${output}`);
diff --git a/scripts/smoke-package-exporter.mjs b/scripts/smoke-package-exporter.mjs
new file mode 100644
index 00000000..54b1c31b
--- /dev/null
+++ b/scripts/smoke-package-exporter.mjs
@@ -0,0 +1,82 @@
+/** Candidate-only distribution coverage. Resolves every dependency from the fresh install. */
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { readFile, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+export async function smokePackageExporter({ runtime, workspace, cli, command }) {
+ const require = createRequire(join(runtime, 'package.json'));
+ const load = (name) => import(pathToFileURL(require.resolve(name)).href);
+ // Optional to normal users, required for this explicit textured candidate qualification.
+ const canvasPath = require.resolve('@napi-rs/canvas');
+ const source = join(workspace, 'community-texture.kiln.js');
+ const output = join(workspace, 'community-texture.glb');
+ await writeFile(
+ source,
+ `const meta = { name: 'PackedCommunityTexture', category: 'prop' };
+function build() {
+ const root = createRoot('PackedCommunityTexture');
+ const albedo = proceduralTexture({schemaVersion:2,size:8,usage:'albedo',layers:[{op:'checker',colorA:0xff0000,colorB:0x0000ff,squares:2}]});
+ const pivot = createPivot('TexturePivot', [0.2,0.3,0.1], root);
+ createPart('Painted', boxGeo(0.6,0.2,0.1), pbrMaterial({albedo,roughness:0.4,doubleSided:true}), {parent:pivot});
+ createPart('Lamp', boxGeo(0.1,0.1,0.1), gameMaterial(0xffffff,{emissive:0xffffff,emissiveIntensity:2}), {position:[0,0.2,0],parent:pivot});
+ return root;
+}
+function animate() {return [createClip('turn',1,[rotationTrack('Joint_TexturePivot',[{time:0,rotation:[0,0,0]},{time:1,rotation:[0,90,0]}])])];}
+`,
+ );
+ const log = await command([cli, 'render', source, '--out', output], workspace, {
+ KILN_GLTF_EXPORTER: 'three',
+ KILN_EVALUATOR_MODE: 'subprocess',
+ KILN_BUILD_CACHE: 'off',
+ });
+ const bytes = await readFile(output);
+ const { NodeIO } = await load('@gltf-transform/core');
+ const { ALL_EXTENSIONS } = await load('@gltf-transform/extensions');
+ const validator = require('gltf-validator');
+ const validation = await validator.validateBytes(new Uint8Array(bytes));
+ assert.equal(validation.issues.numErrors, 0, JSON.stringify(validation.issues));
+ const doc = await new NodeIO().registerExtensions(ALL_EXTENSIONS).readBinary(bytes);
+ const root = doc.getRoot();
+ const pivot = root.listNodes().find((node) => node.getName() === 'Joint_TexturePivot');
+ assert(pivot, 'Packed candidate lost its named pivot');
+ assert.deepEqual(pivot.getTranslation(), [0.2, 0.3, 0.1]);
+ assert.equal(pivot.listChildren().length, 2);
+ assert.equal(root.listAnimations().length, 1);
+ assert.equal(root.listAnimations()[0].listChannels()[0].getTargetNode(), pivot);
+ const painted = root.listMaterials().find((material) => material.getBaseColorTexture());
+ assert(painted, 'Packed candidate lost its texture binding');
+ assert.equal(painted.getDoubleSided(), true);
+ const texture = painted.getBaseColorTexture();
+ assert.equal(texture.getMimeType(), 'image/png');
+ const sharp = require('sharp');
+ const decoded = await sharp(Buffer.from(texture.getImage()))
+ .ensureAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ assert.equal(decoded.info.width, 8);
+ assert.equal(decoded.info.height, 8);
+ const colours = new Set();
+ for (let i = 0; i < decoded.data.length; i += 4)
+ colours.add(decoded.data.subarray(i, i + 4).toString('hex'));
+ assert.deepEqual([...colours].sort(), ['0000ffff', 'ff0000ff']);
+ const emissive = root
+ .listMaterials()
+ .map((material) => material.getExtension('KHR_materials_emissive_strength'))
+ .find(Boolean);
+ assert.equal(emissive?.getEmissiveStrength(), 2, 'Candidate selector did not reach the worker');
+ assert(log.includes('tris'), 'Packaged subprocess must complete a real export');
+ return {
+ exporter: 'three',
+ evaluator: 'subprocess',
+ canvasPath,
+ glbSha256: createHash('sha256').update(bytes).digest('hex'),
+ bytes: bytes.length,
+ validationErrors: validation.issues.numErrors,
+ textureSize: [decoded.info.width, decoded.info.height],
+ textureColours: [...colours].sort(),
+ emissiveStrength: emissive.getEmissiveStrength(),
+ };
+}
diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjs
index 1072baa3..c2242b3d 100644
--- a/scripts/smoke-package.mjs
+++ b/scripts/smoke-package.mjs
@@ -8,6 +8,7 @@ import { createRequire } from 'node:module';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
+import { smokePackageExporter } from './smoke-package-exporter.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const root = await mkdtemp(join(tmpdir(), 'kiln-package-café-'));
@@ -396,6 +397,9 @@ try {
sha(await readFile(join(workspace, 'asset.glb'))),
);
receipt.checks.push('packaged-node-worker');
+ // Export/reload only: the native canvas encodes texture pixels; no CPU/GPU views.
+ receipt.communityExporter = await smokePackageExporter({ runtime, workspace, cli, command });
+ receipt.checks.push('community-exporter-textured-subprocess');
const server = join(runtime, 'dist/mcp-server.mjs'),
store = join(workspace, '.kiln/programs');
const session = await connect(server, root, store);
diff --git a/scripts/verify-package-receipt.mjs b/scripts/verify-package-receipt.mjs
index 9709cc66..7d93be1a 100644
--- a/scripts/verify-package-receipt.mjs
+++ b/scripts/verify-package-receipt.mjs
@@ -23,6 +23,7 @@ import { fileURLToPath } from 'node:url';
/** Checks the smoke run must report, named individually so a silent drop is a failure. */
const REQUIRED_CHECKS = [
'packaged-node-worker',
+ 'community-exporter-textured-subprocess',
'source-reference-edit-images',
'server-restart-persistence',
'exact-source-export',
diff --git a/scripts/verify-package-receipt.test.mjs b/scripts/verify-package-receipt.test.mjs
index 744d3107..bfdeef0e 100644
--- a/scripts/verify-package-receipt.test.mjs
+++ b/scripts/verify-package-receipt.test.mjs
@@ -22,6 +22,7 @@ const good = () => ({
tarball: '/nonexistent.tgz',
checks: [
'packaged-node-worker',
+ 'community-exporter-textured-subprocess',
'source-reference-edit-images',
'server-restart-persistence',
'exact-source-export',
@@ -58,7 +59,15 @@ describe('package receipt verification', () => {
});
test('a receipt with no checks at all reports every one of them', () => {
- expect(receiptProblems({ ...good(), checks: undefined }, target)).toHaveLength(4);
+ expect(receiptProblems({ ...good(), checks: undefined }, target)).toHaveLength(5);
+ });
+
+ test('a package missing candidate texture coverage is rejected', () => {
+ const receipt = good();
+ receipt.checks = receipt.checks.filter((c) => c !== 'community-exporter-textured-subprocess');
+ expect(receiptProblems(receipt, target)).toEqual([
+ 'missing check: community-exporter-textured-subprocess',
+ ]);
});
// The end-to-end path, including the hash the release actually depends on.
diff --git a/skills/kiln-author-asset/SKILL.md b/skills/kiln-author-asset/SKILL.md
index d07f7568..690d87d3 100644
--- a/skills/kiln-author-asset/SKILL.md
+++ b/skills/kiln-author-asset/SKILL.md
@@ -12,6 +12,8 @@ Read the [program contract](references/program-contract.md) when writing source.
Establish the subject, scale, style, and destination constraints from the request. Build a recognizable silhouette and meaningful construction details. Name parts by their role. Use metres, +X forward, +Y up, +Z right; ground contact normally sits at Y=0.
+For Blender, Unity or an FBX handoff, read the [engine handoff guide](references/engine-handoff.md). Prefer direct GLB import. The established exporter remains the default; the guide explains when an explicitly identified experimental comparison is useful. Preserve the baseline output, report the selected backend and destination checks, and do not change global host settings silently.
+
Write ordinary JavaScript with `meta` and `build()`. Keep dimensions that should change together in named parameters. Use [geometry recipes](references/geometry-recipes.md) for freeform surfaces, deformations, lofts, Boolean materials, or repeated parts. A model can author its own equations and topology; it does not need to assemble everything from boxes.
Submit `code` once to `kiln_render` or `kiln_validate`, then retain its `programRef`, including on a failed build. In a generated asset workspace, `node kiln.mjs source asset.kiln.js` imports a file directly. Copy the returned reference exactly for later views and edits. Built-in stores return short handles such as `p_7c94a132b8e0`; full SHA-256 references also work. Do not construct a handle or retransmit the program.
diff --git a/skills/kiln-author-asset/references/engine-handoff.md b/skills/kiln-author-asset/references/engine-handoff.md
new file mode 100644
index 00000000..a661c0c9
--- /dev/null
+++ b/skills/kiln-author-asset/references/engine-handoff.md
@@ -0,0 +1,131 @@
+# Blender and Unity handoff
+
+Kiln exports GLB files. **The established exporter is still the default.** Use the normal
+CLI/MCP workflow first; choosing Blender or Unity does not require an exporter switch.
+The experimental Three.js exporter is included in builds containing this integration,
+but older installed releases do not gain it by setting an environment variable.
+
+## Choose the import route
+
+| Destination | Start here | Check in the destination |
+| --- | --- | --- |
+| Blender | Import the GLB through Blender's glTF importer. | Hierarchy, named pivots, materials and intermediate animation poses. |
+| Unity | Use the project's glTF importer; glTFast is the tested route. | Importer version, Built-in/URP/HDRP pipeline, shader support, animation and a player build. |
+| FBX-only workflow | Keep the original GLB and make a separate Blender-to-FBX derivative. | Child offsets, axes, animation and material loss after conversion. |
+
+For Unity, follow the installed importer's setup instructions rather than assuming that
+copying a GLB into Assets is sufficient. Our tested combination is Unity 6000.2.3f1,
+Built-in RP and glTFast 6.20.0. Blender checks used 5.2.0 LTS. These are measured profiles,
+not requirements to downgrade another working project or claims about every pipeline.
+
+glTFast supports more than base colour, including double-sided surfaces, but individual
+material extensions have pipeline-specific limits. Preserve glTF-compatible materials
+when importing; replacing them with a different shader can change the result.
+See the [glTFast feature matrix](https://docs.unity3d.com/Packages/[email protected]/manual/features.html).
+
+## When to try the experimental exporter
+
+Try a comparison if the default export reports a feature it cannot preserve, or the task
+requires candidate capabilities such as vertex colours, extra UV sets, skin/morph data or
+additional physical-material extensions. It can also help isolate an exporter defect from
+an importer problem. **It is not an automatic fix for all Blender/Unity issues.**
+
+Keep the source and baseline GLB. Write the candidate to a different filename, import both
+with the same consumer settings, and report what actually changed. Agents should identify
+the candidate as experimental when using it. Do not silently switch a shared host or claim
+an untested importer works. If the default already meets the task, there is no need to switch.
+
+## CLI: compare without changing the machine configuration
+
+In an asset workspace, use its existing `kiln.mjs` launcher. These PowerShell commands scope
+the selection to the current process and restore its previous value even if export fails:
+
+```powershell
+$previousExporter = $env:KILN_GLTF_EXPORTER
+try {
+ $env:KILN_GLTF_EXPORTER = 'legacy'
+ node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Baseline export failed' }
+
+ $env:KILN_GLTF_EXPORTER = 'three'
+ node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Experimental export failed' }
+} finally {
+ if ($null -eq $previousExporter) { Remove-Item Env:KILN_GLTF_EXPORTER -ErrorAction SilentlyContinue }
+ else { $env:KILN_GLTF_EXPORTER = $previousExporter }
+}
+```
+
+`--render gpu` requires a working GPU renderer and fails if unavailable; it does not accept
+a CPU fallback as material evidence. See Kiln's
+[GPU setup](https://github.com/matthew-kissinger/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
+In a repository clone, use `node dist/cli.mjs` instead of `node kiln.mjs`, after
+`bun install --frozen-lockfile` and `bun run build:runtime`. For an installed distribution,
+use the CLI launcher you already use, from a distribution containing this feature.
+
+In a POSIX shell, selection can be scoped to each invocation:
+
+```sh
+KILN_GLTF_EXPORTER=legacy node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+KILN_GLTF_EXPORTER=three node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+```
+
+## MCP: select at host startup
+
+The exporter is **not a `kiln_render` tool argument**. Set `KILN_GLTF_EXPORTER=three` in the
+environment of the existing Kiln MCP server entry, preserving its command, arguments and
+other settings. For hosts using an `env` object, add this field to that object:
+
+```json
+{ "KILN_GLTF_EXPORTER": "three" }
+```
+
+Restart/reconnect that server so it captures the new setting. Continue using the same tools
+and saved `programRef` values; build caches distinguish backends. To restore the established
+exporter, remove that field or set it to `legacy`, then restart/reconnect again. If an agent
+cannot configure the host, it must not claim to have switched it; a separate CLI comparison
+is available when the agent has terminal access.
+
+New workspaces receive this guide through the authoring/QA skills. Existing workspace skills
+are local copies; updating the engine or running workspace repair does not automatically
+replace edited skills. Consult the updated runtime documentation when working in an older workspace.
+
+## Geometry, materials and moving parts
+
+- **Backfaces:** a single-sided sheet disappearing from behind is expected culling. Use a
+ double-sided material for an intentionally thin surface when the importer supports it.
+ Author actual thickness when the object needs thickness, collision or different surfaces;
+ do not automatically extrude every quad to hide an import problem.
+- **Pivots:** give moving groups stable, descriptive names such as `Joint_VaneSwivel`, with
+ visible geometry beneath them, for example `Mesh_Pennant`. This is an authoring convention,
+ not a required engine prefix. Preserve names across revisions and report the actual part paths.
+- **Unity root names:** glTFast can replace a static single-root name with the asset filename.
+ Check its Scene Object Creation setting; test `Always` if an authored root under a wrapper is
+ needed. Resolve parts relative to the imported root instead of assuming one universal path.
+- **Animation:** play the imported clip and inspect intermediate poses. A clip existing in the
+ file is not proof that its target moves. Check skin/morph deformation where applicable.
+- **FBX:** in Blender's FBX export, leave the experimental Apply Transform option
+ (`bake_space_transform`) disabled for the tested nested-part route. This is separate from
+ Bake Animation. Reimport the FBX and check offsets; materials and sidedness can still change.
+ See [Blender's option documentation](https://docs.blender.org/api/main/bpy.ops.export_scene.html).
+
+## Known experimental limits
+
+- Rotated nonuniform Three.js UV scaling and manually sheared/perspective UV matrices are
+ rejected when they cannot be represented losslessly in glTF texture TRS. Do not remove
+ the transform or silently change the asset just to make export succeed.
+- Textured headless candidate exports need the optional native canvas dependency. If it is
+ unavailable, fix the installation or report the limitation; textures are not silently dropped.
+- Lines/points are outside the candidate's qualified triangle/sprite pipeline.
+- Preserved emissive/unlit properties may look different from older exports that dropped them.
+- More extensions in a valid GLB do not guarantee support in every importer or shader. GPU
+ appearance, runtime-loaded shader inclusion, compression codecs and other render pipelines
+ need their own checks. This option does not change KTX2 defaults or fix unsupported Node versions.
+
+## Delivery checklist for users and agents
+
+Record the source revision, chosen exporter, delivered GLB, consumer/importer versions and
+render pipeline. Check scale and orientation alongside a known object; hierarchy and pivots;
+front/back visibility; materials/textures; and animation/deformation. For Unity delivery,
+exercise a player build as well as the editor. Say which checks were not run. Keep the baseline
+and source so a consumer-specific problem can be reproduced without regenerating the asset.
diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.md
index c8275b09..4e73e12d 100644
--- a/skills/kiln-qa-asset/SKILL.md
+++ b/skills/kiln-qa-asset/SKILL.md
@@ -18,6 +18,8 @@ Check material and camera fidelity independently. A fallback image may still ans
## In the destination
+For Blender, Unity or FBX, read the [engine handoff guide](references/engine-handoff.md) before choosing import settings or trying the experimental exporter. Check the actual target importer and render pipeline; a successful Kiln preview alone does not establish destination compatibility.
+
Use the project's existing loader and renderer. Read the [integration checks](references/integration-checks.md) for manifests, frames, composition options, and limits.
Confirm scale alongside existing objects, forward direction, ground contact, placement, and useful viewing distance. Check textures and lighting in the destination renderer. Exercise relevant animation, interaction, and collision; sample intermediate poses when checking motion. For web projects use the actual browser view, and for native projects use the destination runtime.
diff --git a/skills/kiln-qa-asset/references/engine-handoff.md b/skills/kiln-qa-asset/references/engine-handoff.md
new file mode 100644
index 00000000..a661c0c9
--- /dev/null
+++ b/skills/kiln-qa-asset/references/engine-handoff.md
@@ -0,0 +1,131 @@
+# Blender and Unity handoff
+
+Kiln exports GLB files. **The established exporter is still the default.** Use the normal
+CLI/MCP workflow first; choosing Blender or Unity does not require an exporter switch.
+The experimental Three.js exporter is included in builds containing this integration,
+but older installed releases do not gain it by setting an environment variable.
+
+## Choose the import route
+
+| Destination | Start here | Check in the destination |
+| --- | --- | --- |
+| Blender | Import the GLB through Blender's glTF importer. | Hierarchy, named pivots, materials and intermediate animation poses. |
+| Unity | Use the project's glTF importer; glTFast is the tested route. | Importer version, Built-in/URP/HDRP pipeline, shader support, animation and a player build. |
+| FBX-only workflow | Keep the original GLB and make a separate Blender-to-FBX derivative. | Child offsets, axes, animation and material loss after conversion. |
+
+For Unity, follow the installed importer's setup instructions rather than assuming that
+copying a GLB into Assets is sufficient. Our tested combination is Unity 6000.2.3f1,
+Built-in RP and glTFast 6.20.0. Blender checks used 5.2.0 LTS. These are measured profiles,
+not requirements to downgrade another working project or claims about every pipeline.
+
+glTFast supports more than base colour, including double-sided surfaces, but individual
+material extensions have pipeline-specific limits. Preserve glTF-compatible materials
+when importing; replacing them with a different shader can change the result.
+See the [glTFast feature matrix](https://docs.unity3d.com/Packages/[email protected]/manual/features.html).
+
+## When to try the experimental exporter
+
+Try a comparison if the default export reports a feature it cannot preserve, or the task
+requires candidate capabilities such as vertex colours, extra UV sets, skin/morph data or
+additional physical-material extensions. It can also help isolate an exporter defect from
+an importer problem. **It is not an automatic fix for all Blender/Unity issues.**
+
+Keep the source and baseline GLB. Write the candidate to a different filename, import both
+with the same consumer settings, and report what actually changed. Agents should identify
+the candidate as experimental when using it. Do not silently switch a shared host or claim
+an untested importer works. If the default already meets the task, there is no need to switch.
+
+## CLI: compare without changing the machine configuration
+
+In an asset workspace, use its existing `kiln.mjs` launcher. These PowerShell commands scope
+the selection to the current process and restore its previous value even if export fails:
+
+```powershell
+$previousExporter = $env:KILN_GLTF_EXPORTER
+try {
+ $env:KILN_GLTF_EXPORTER = 'legacy'
+ node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Baseline export failed' }
+
+ $env:KILN_GLTF_EXPORTER = 'three'
+ node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+ if ($LASTEXITCODE -ne 0) { throw 'Experimental export failed' }
+} finally {
+ if ($null -eq $previousExporter) { Remove-Item Env:KILN_GLTF_EXPORTER -ErrorAction SilentlyContinue }
+ else { $env:KILN_GLTF_EXPORTER = $previousExporter }
+}
+```
+
+`--render gpu` requires a working GPU renderer and fails if unavailable; it does not accept
+a CPU fallback as material evidence. See Kiln's
+[GPU setup](https://github.com/matthew-kissinger/kiln/blob/main/docs/rendering.md#running-the-gpu-renderer).
+In a repository clone, use `node dist/cli.mjs` instead of `node kiln.mjs`, after
+`bun install --frozen-lockfile` and `bun run build:runtime`. For an installed distribution,
+use the CLI launcher you already use, from a distribution containing this feature.
+
+In a POSIX shell, selection can be scoped to each invocation:
+
+```sh
+KILN_GLTF_EXPORTER=legacy node kiln.mjs render asset.kiln.js --out asset-baseline.glb --views asset-baseline.png --render gpu
+KILN_GLTF_EXPORTER=three node kiln.mjs render asset.kiln.js --out asset-experimental.glb --views asset-experimental.png --render gpu
+```
+
+## MCP: select at host startup
+
+The exporter is **not a `kiln_render` tool argument**. Set `KILN_GLTF_EXPORTER=three` in the
+environment of the existing Kiln MCP server entry, preserving its command, arguments and
+other settings. For hosts using an `env` object, add this field to that object:
+
+```json
+{ "KILN_GLTF_EXPORTER": "three" }
+```
+
+Restart/reconnect that server so it captures the new setting. Continue using the same tools
+and saved `programRef` values; build caches distinguish backends. To restore the established
+exporter, remove that field or set it to `legacy`, then restart/reconnect again. If an agent
+cannot configure the host, it must not claim to have switched it; a separate CLI comparison
+is available when the agent has terminal access.
+
+New workspaces receive this guide through the authoring/QA skills. Existing workspace skills
+are local copies; updating the engine or running workspace repair does not automatically
+replace edited skills. Consult the updated runtime documentation when working in an older workspace.
+
+## Geometry, materials and moving parts
+
+- **Backfaces:** a single-sided sheet disappearing from behind is expected culling. Use a
+ double-sided material for an intentionally thin surface when the importer supports it.
+ Author actual thickness when the object needs thickness, collision or different surfaces;
+ do not automatically extrude every quad to hide an import problem.
+- **Pivots:** give moving groups stable, descriptive names such as `Joint_VaneSwivel`, with
+ visible geometry beneath them, for example `Mesh_Pennant`. This is an authoring convention,
+ not a required engine prefix. Preserve names across revisions and report the actual part paths.
+- **Unity root names:** glTFast can replace a static single-root name with the asset filename.
+ Check its Scene Object Creation setting; test `Always` if an authored root under a wrapper is
+ needed. Resolve parts relative to the imported root instead of assuming one universal path.
+- **Animation:** play the imported clip and inspect intermediate poses. A clip existing in the
+ file is not proof that its target moves. Check skin/morph deformation where applicable.
+- **FBX:** in Blender's FBX export, leave the experimental Apply Transform option
+ (`bake_space_transform`) disabled for the tested nested-part route. This is separate from
+ Bake Animation. Reimport the FBX and check offsets; materials and sidedness can still change.
+ See [Blender's option documentation](https://docs.blender.org/api/main/bpy.ops.export_scene.html).
+
+## Known experimental limits
+
+- Rotated nonuniform Three.js UV scaling and manually sheared/perspective UV matrices are
+ rejected when they cannot be represented losslessly in glTF texture TRS. Do not remove
+ the transform or silently change the asset just to make export succeed.
+- Textured headless candidate exports need the optional native canvas dependency. If it is
+ unavailable, fix the installation or report the limitation; textures are not silently dropped.
+- Lines/points are outside the candidate's qualified triangle/sprite pipeline.
+- Preserved emissive/unlit properties may look different from older exports that dropped them.
+- More extensions in a valid GLB do not guarantee support in every importer or shader. GPU
+ appearance, runtime-loaded shader inclusion, compression codecs and other render pipelines
+ need their own checks. This option does not change KTX2 defaults or fix unsupported Node versions.
+
+## Delivery checklist for users and agents
+
+Record the source revision, chosen exporter, delivered GLB, consumer/importer versions and
+render pipeline. Check scale and orientation alongside a known object; hierarchy and pivots;
+front/back visibility; materials/textures; and animation/deformation. For Unity delivery,
+exercise a player build as well as the editor. Say which checks were not run. Keep the baseline
+and source so a consumer-specific problem can be reproduced without regenerating the asset.
diff --git a/src/__tests__/architecture-expansion-gate.test.ts b/src/__tests__/architecture-expansion-gate.test.ts
index ae3cda19..86753946 100644
--- a/src/__tests__/architecture-expansion-gate.test.ts
+++ b/src/__tests__/architecture-expansion-gate.test.ts
@@ -21,7 +21,16 @@ import {
type AssetIntentV1,
type SemanticLocalFrameV1,
} from '../contracts';
-import { optimizeGlbBytes, renderSceneToGLB } from '../render';
+import {
+ optimizeGlbBytes,
+ renderSceneToGLB as exportScene,
+ type RenderSceneOptions,
+} from '../render';
+
+// These historical architecture experiment hashes remain pinned to their original converter.
+// Candidate geometry parity is measured independently by integration-corpus.mjs.
+const renderSceneToGLB = (root: THREE.Object3D, options: RenderSceneOptions) =>
+ exportScene(root, { ...options, gltfExporter: 'legacy' });
import { loadTexture } from '../textures';
const PUBLIC_HELPER_MINIMUM_LIFT = 0.15;
diff --git a/src/__tests__/community-exporter.test.ts b/src/__tests__/community-exporter.test.ts
new file mode 100644
index 00000000..13044523
--- /dev/null
+++ b/src/__tests__/community-exporter.test.ts
@@ -0,0 +1,360 @@
+import { afterEach, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { WebIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import sharp from 'sharp';
+import { createLocalToolContext } from '../local-runtime';
+import { renderSceneToGLB, optimizeGlbBytes } from '../render';
+
+const previous = process.env['KILN_GLTF_EXPORTER'];
+afterEach(() => {
+ if (previous === undefined) delete process.env['KILN_GLTF_EXPORTER'];
+ else process.env['KILN_GLTF_EXPORTER'] = previous;
+});
+function fixture() {
+ const root = new THREE.Group();
+ root.name = 'Asset';
+ const pivot = new THREE.Group();
+ pivot.name = 'Joint_Vane';
+ pivot.position.set(0.2, 1.1, -0.3);
+ root.add(pivot);
+ const geometry = new THREE.BoxGeometry(0.6, 0.2, 0.01);
+ geometry.setAttribute(
+ 'color',
+ new THREE.Float32BufferAttribute(new Array(24).fill([1, 0, 0]).flat(), 3),
+ );
+ geometry.setAttribute('uv1', geometry.getAttribute('uv').clone());
+ const mesh = new THREE.Mesh(
+ geometry,
+ new THREE.MeshPhysicalMaterial({
+ color: 0x4477aa,
+ metalness: 0.65,
+ roughness: 0.27,
+ clearcoat: 0.8,
+ transmission: 0.5,
+ side: THREE.DoubleSide,
+ vertexColors: true,
+ }),
+ );
+ mesh.name = 'Mesh_Pennant';
+ mesh.userData['privatePayload'] = 'do not export';
+ pivot.add(mesh);
+ return root;
+}
+const io = () => new WebIO().registerExtensions(ALL_EXTENSIONS);
+
+test('experimental exporter preserves attributes and physical extensions without arbitrary metadata', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const result = await renderSceneToGLB(fixture(), { optimize: 'off', derivative: true });
+ expect(result.gltfValidation.issues.numErrors).toBe(0);
+ const doc = await io().readBinary(result.bytes);
+ const primitive = doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!;
+ expect(primitive.getAttribute('COLOR_0')).not.toBeNull();
+ expect(primitive.getAttribute('TEXCOORD_1')).not.toBeNull();
+ expect(
+ doc
+ .getRoot()
+ .listExtensionsUsed()
+ .map((extension) => extension.extensionName),
+ ).toContain('KHR_materials_clearcoat');
+ expect(
+ doc
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === 'Mesh_Pennant')!
+ .getExtras(),
+ ).toEqual({});
+ expect(result.warnings.some((warning) => warning.includes('color is not preserved'))).toBe(false);
+});
+
+test('existing exporter stays the default and candidate selection fails closed on typos', async () => {
+ delete process.env['KILN_GLTF_EXPORTER'];
+ const baseline = await renderSceneToGLB(fixture(), { optimize: 'off', derivative: true });
+ process.env['KILN_GLTF_EXPORTER'] = 'legacy';
+ expect((await renderSceneToGLB(fixture(), { optimize: 'off', derivative: true })).bytes).toEqual(
+ baseline.bytes,
+ );
+ process.env['KILN_GLTF_EXPORTER'] = 'thre';
+ expect(renderSceneToGLB(fixture())).rejects.toThrow('KILN_GLTF_EXPORTER');
+});
+
+test('physical extensions survive downstream optimization', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const result = await renderSceneToGLB(fixture(), { optimize: 'off', derivative: true });
+ const optimized = await optimizeGlbBytes(result.bytes, { mode: 'palette' });
+ expect(optimized).toBeDefined();
+ const doc = await io().readBinary(optimized!.bytes);
+ expect(
+ doc
+ .getRoot()
+ .listExtensionsUsed()
+ .map((extension) => extension.extensionName),
+ ).toContain('KHR_materials_clearcoat');
+});
+
+test('headless textures retain pixels and source state across concurrent exports', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh<
+ THREE.BufferGeometry,
+ THREE.MeshPhysicalMaterial
+ >;
+ const pixels = Uint8Array.from([
+ 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255,
+ ]);
+ const texture = new THREE.DataTexture(pixels, 2, 2);
+ texture.colorSpace = THREE.SRGBColorSpace;
+ const source = texture.source;
+ const sourceImage = texture.image;
+ mesh.material.map = texture;
+ const [a, b] = await Promise.all([
+ renderSceneToGLB(root, { derivative: true }),
+ renderSceneToGLB(root, { derivative: true }),
+ ]);
+ expect(a.bytes).toEqual(b.bytes);
+ const doc = await io().readBinary(a.bytes);
+ const image = doc.getRoot().listTextures()[0]!.getImage()!;
+ expect(new Uint8Array(await sharp(image).ensureAlpha().raw().toBuffer())).toEqual(pixels);
+ expect(mesh.material.map).toBe(texture);
+ expect(texture.source).toBe(source);
+ expect(texture.image).toBe(sourceImage);
+ expect(mesh.userData['privatePayload']).toBe('do not export');
+});
+
+test('candidate preserves morph and skin data and does not mutate bone references', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = new THREE.Group();
+ const geometry = new THREE.BoxGeometry();
+ geometry.morphAttributes.position = [geometry.getAttribute('position').clone()];
+ geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(new Uint16Array(24 * 4), 4));
+ geometry.setAttribute(
+ 'skinWeight',
+ new THREE.Float32BufferAttribute(new Array(24).fill([1, 0, 0, 0]).flat(), 4),
+ );
+ const mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshStandardMaterial());
+ const bone = new THREE.Bone();
+ bone.name = 'Bone';
+ mesh.add(bone);
+ mesh.bind(new THREE.Skeleton([bone]));
+ root.add(mesh);
+ const result = await renderSceneToGLB(root, { derivative: true, geometryPolicy: 'strict' });
+ const doc = await io().readBinary(result.bytes);
+ expect(doc.getRoot().listSkins()).toHaveLength(1);
+ expect(doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!.listTargets()).toHaveLength(1);
+ expect(mesh.skeleton.bones[0]).toBe(bone);
+});
+
+test('candidate retains sprite quad geometry and camera-facing semantics', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = new THREE.Group();
+ const sprite = new THREE.Sprite(
+ new THREE.SpriteMaterial({ color: 0xff4400, opacity: 0.5, transparent: true }),
+ );
+ sprite.name = 'Card';
+ sprite.material.name = 'SmokeMaterial';
+ sprite.center.set(0, 0);
+ sprite.position.set(1, 2, 3);
+ root.add(sprite);
+ const result = await renderSceneToGLB(root, { derivative: true });
+ const doc = await io().readBinary(result.bytes);
+ const card = doc
+ .getRoot()
+ .listNodes()
+ .find((node) => node.getName() === 'Card')!;
+ expect(card.getTranslation()).toEqual([1, 2, 3]);
+ expect(card.getMesh()!.listPrimitives()[0]!.getAttribute('POSITION')!.getCount()).toBe(4);
+ expect(card.getMesh()!.listPrimitives()[0]!.getMaterial()!.getName()).toBe('SmokeMaterial');
+ expect(JSON.stringify(card.getExtras())).toContain('vfx.facing.camera-spherical');
+ expect(root.children[0]).toBe(sprite);
+});
+
+test('local subprocess carries the host exporter choice without ambient environment', async () => {
+ const local = createLocalToolContext({}, { KILN_GLTF_EXPORTER: 'three' });
+ const result = await local.evaluatorPort!.render(
+ `function build(){const root=createRoot('Root');const g=boxGeo(1,1,1);g.setAttribute('color',new THREE.Float32BufferAttribute(new Array(24).fill([1,0,0]).flat(),3));createPart('Body',g,new THREE.MeshStandardMaterial({vertexColors:true}),{parent:root});return root;}`,
+ );
+ const doc = await io().readBinary(result.glb);
+ expect(
+ doc.getRoot().listMeshes()[0]!.listPrimitives()[0]!.getAttribute('COLOR_0'),
+ ).not.toBeNull();
+ expect(local.localExecution.mode).toBe('subprocess');
+});
+
+test('candidate rejects invalid material groups before upstream export', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh;
+ mesh.material = [new THREE.MeshStandardMaterial(), new THREE.MeshStandardMaterial()];
+ mesh.geometry.clearGroups();
+ mesh.geometry.addGroup(0, 3, 4);
+ await expect(renderSceneToGLB(root, { derivative: true })).rejects.toThrow('material');
+});
+
+test('candidate rejects overlapping material groups', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh;
+ mesh.material = [new THREE.MeshStandardMaterial(), new THREE.MeshStandardMaterial()];
+ mesh.geometry.clearGroups();
+ mesh.geometry.addGroup(0, 36, 0);
+ mesh.geometry.addGroup(0, 36, 1);
+ await expect(renderSceneToGLB(root, { derivative: true })).rejects.toThrow('material groups');
+});
+
+test('candidate keeps transformed Scene roots as named transform nodes', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const root = new THREE.Scene();
+ root.name = 'MovedScene';
+ root.position.set(1, 2, 3);
+ root.add(fixture());
+ const result = await renderSceneToGLB(root, { derivative: true });
+ const doc = await io().readBinary(result.bytes);
+ const node = doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getName() === 'MovedScene');
+ expect(node?.getTranslation()).toEqual([1, 2, 3]);
+});
+
+test('unresolved advisory animation tracks do not produce invalid empty glTF animations', async () => {
+ process.env['KILN_GLTF_EXPORTER'] = 'three';
+ const clip = new THREE.AnimationClip('Missing', 1, [
+ new THREE.VectorKeyframeTrack('NoSuchNode.position', [0, 1], [0, 0, 0, 1, 0, 0]),
+ ]);
+ const result = await renderSceneToGLB(fixture(), { clips: [clip], derivative: true });
+ expect(result.gltfValidation.issues.numErrors).toBe(0);
+ expect((await io().readBinary(result.bytes)).getRoot().listAnimations()).toHaveLength(0);
+ expect(result.warnings.some((w) => w.includes('NoSuchNode'))).toBe(true);
+});
+
+test('candidate preserves texture rotation around a nonzero center without mutating source', async () => {
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh<
+ THREE.BufferGeometry,
+ THREE.MeshPhysicalMaterial
+ >;
+ const texture = new THREE.DataTexture(new Uint8Array([255, 0, 0, 255]), 1, 1);
+ texture.offset.set(0.2, -0.1);
+ texture.repeat.set(1.3, 1.3);
+ texture.center.set(0.4, 0.6);
+ texture.rotation = 0.35;
+ texture.updateMatrix();
+ const originalMatrix = texture.matrix.clone();
+ mesh.material.map = texture;
+ const result = await renderSceneToGLB(root, { gltfExporter: 'three', derivative: true });
+ const json = (await io().writeJSON(await io().readBinary(result.bytes))).json;
+ const transform = json.materials![0]!.pbrMetallicRoughness!.baseColorTexture!.extensions![
+ 'KHR_texture_transform'
+ ] as { offset: number[]; scale: number[]; rotation: number };
+ const c = Math.cos(transform.rotation);
+ const s = Math.sin(transform.rotation);
+ const restored = new THREE.Matrix3().set(
+ transform.scale[0]! * c,
+ transform.scale[1]! * s,
+ transform.offset[0]!,
+ -transform.scale[0]! * s,
+ transform.scale[1]! * c,
+ transform.offset[1]!,
+ 0,
+ 0,
+ 1,
+ );
+ for (let i = 0; i < 9; i++)
+ expect(restored.elements[i]).toBeCloseTo(originalMatrix.elements[i]!, 6);
+ expect(texture.center.toArray()).toEqual([0.4, 0.6]);
+ expect(texture.offset.toArray()).toEqual([0.2, -0.1]);
+ expect(texture.matrix.equals(originalMatrix)).toBe(true);
+});
+
+test('candidate refuses sheared UV transforms instead of silently changing texture placement', async () => {
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh<
+ THREE.BufferGeometry,
+ THREE.MeshPhysicalMaterial
+ >;
+ const texture = new THREE.DataTexture(new Uint8Array([255, 0, 0, 255]), 1, 1);
+ texture.name = 'ShearedSail';
+ texture.repeat.set(1.7, 1.3);
+ texture.rotation = 0.35;
+ mesh.material.map = texture;
+ await expect(renderSceneToGLB(root, { gltfExporter: 'three', derivative: true })).rejects.toThrow(
+ 'ShearedSail: UV matrix contains shear',
+ );
+});
+
+test('candidate preserves a manual glTF-order UV matrix', async () => {
+ const root = fixture();
+ const mesh = root.getObjectByName('Mesh_Pennant') as THREE.Mesh<
+ THREE.BufferGeometry,
+ THREE.MeshPhysicalMaterial
+ >;
+ const texture = new THREE.DataTexture(new Uint8Array([255, 0, 0, 255]), 1, 1);
+ texture.matrixAutoUpdate = false;
+ const c = Math.cos(0.3),
+ s = Math.sin(0.3);
+ texture.matrix.set(1.7 * c, 1.3 * s, 0.2, -1.7 * s, 1.3 * c, -0.1, 0, 0, 1);
+ mesh.material.map = texture;
+ const result = await renderSceneToGLB(root, { gltfExporter: 'three', derivative: true });
+ const json = (await io().writeJSON(await io().readBinary(result.bytes))).json;
+ const transform = json.materials![0]!.pbrMetallicRoughness!.baseColorTexture!.extensions![
+ 'KHR_texture_transform'
+ ] as { offset: number[]; scale: number[]; rotation: number };
+ expect(transform.offset).toEqual([0.2, -0.1]);
+ expect(transform.scale[0]).toBeCloseTo(1.7, 6);
+ expect(transform.scale[1]).toBeCloseTo(1.3, 6);
+ expect(transform.rotation).toBeCloseTo(0.3, 6);
+ expect(texture.matrixAutoUpdate).toBe(false);
+ expect(texture.offset.toArray()).toEqual([0, 0]);
+});
+
+test('physical material factors survive export and palette rewrite', async () => {
+ const root = fixture();
+ const material = (root.getObjectByName('Mesh_Pennant') as THREE.Mesh)
+ .material as THREE.MeshPhysicalMaterial;
+ material.clearcoat = 0.7;
+ material.clearcoatRoughness = 0.23;
+ material.transmission = 0.65;
+ material.thickness = 0.4;
+ material.attenuationDistance = 2.5;
+ material.attenuationColor.setRGB(0.2, 0.4, 0.6);
+ material.ior = 1.4;
+ material.specularIntensity = 0.55;
+ material.specularColor.setRGB(0.7, 0.8, 0.9);
+ material.sheen = 0.6;
+ material.sheenColor.setRGB(0.3, 0.5, 0.7);
+ material.sheenRoughness = 0.4;
+ material.iridescence = 0.35;
+ material.iridescenceIOR = 1.6;
+ material.iridescenceThicknessRange = [110, 370];
+ material.anisotropy = 0.45;
+ material.anisotropyRotation = 0.2;
+ const original = await renderSceneToGLB(root, { gltfExporter: 'three', derivative: true });
+ const rewritten = await optimizeGlbBytes(original.bytes, { mode: 'palette' });
+ if (!rewritten) throw new Error('Expected palette rewrite result');
+ for (const bytes of [original.bytes, rewritten.bytes]) {
+ const json = (await io().writeJSON(await io().readBinary(bytes))).json;
+ const output = json.materials![0]!;
+ expect(output.doubleSided).toBe(true);
+ expect(output.pbrMetallicRoughness!.metallicFactor).toBe(0.65);
+ expect(output.pbrMetallicRoughness!.roughnessFactor).toBe(0.27);
+ expect(output.extensions).toMatchObject({
+ KHR_materials_clearcoat: { clearcoatFactor: 0.7, clearcoatRoughnessFactor: 0.23 },
+ KHR_materials_transmission: { transmissionFactor: 0.65 },
+ KHR_materials_volume: {
+ thicknessFactor: 0.4,
+ attenuationDistance: 2.5,
+ attenuationColor: [0.2, 0.4, 0.6],
+ },
+ KHR_materials_ior: { ior: 1.4 },
+ KHR_materials_specular: { specularFactor: 0.55, specularColorFactor: [0.7, 0.8, 0.9] },
+ KHR_materials_sheen: { sheenColorFactor: [0.18, 0.3, 0.42], sheenRoughnessFactor: 0.4 },
+ KHR_materials_iridescence: {
+ iridescenceFactor: 0.35,
+ iridescenceIor: 1.6,
+ iridescenceThicknessMinimum: 110,
+ iridescenceThicknessMaximum: 370,
+ },
+ KHR_materials_anisotropy: { anisotropyStrength: 0.45, anisotropyRotation: 0.2 },
+ });
+ }
+});
diff --git a/src/__tests__/exporter-deformation.test.ts b/src/__tests__/exporter-deformation.test.ts
new file mode 100644
index 00000000..958277b3
--- /dev/null
+++ b/src/__tests__/exporter-deformation.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { renderSceneToGLB, optimizeGlbBytes } from '../render';
+
+function deformingScene() {
+ const root = new THREE.Group();
+ root.name = 'Rig';
+ root.position.set(0.3, 0.2, -0.4);
+ const geometry = new THREE.PlaneGeometry(1, 2, 1, 2);
+ const positions = geometry.getAttribute('position');
+ const indices: number[] = [];
+ const weights: number[] = [];
+ const morph = positions.clone();
+ for (let i = 0; i < positions.count; i++) {
+ const weight = (positions.getY(i) + 1) / 2;
+ indices.push(0, 1, 0, 0);
+ weights.push(1 - weight, weight, 0, 0);
+ morph.setZ(i, 0.4 * weight);
+ }
+ geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(indices, 4));
+ geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(weights, 4));
+ geometry.morphAttributes.position = [morph];
+ const mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshStandardMaterial());
+ mesh.name = 'Sail';
+ const base = new THREE.Bone();
+ base.name = 'Base';
+ const tip = new THREE.Bone();
+ tip.name = 'Tip';
+ tip.position.y = 1;
+ base.add(tip);
+ mesh.add(base);
+ root.add(mesh);
+ root.updateMatrixWorld(true);
+ mesh.bind(new THREE.Skeleton([base, tip]));
+ const quaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), 0.6);
+ const clip = new THREE.AnimationClip('Bend', 1, [
+ new THREE.QuaternionKeyframeTrack(
+ 'Tip.quaternion',
+ [0, 1],
+ [0, 0, 0, 1, ...quaternion.toArray()],
+ ),
+ new THREE.NumberKeyframeTrack('Sail.morphTargetInfluences[0]', [0, 1], [0, 0.8]),
+ ]);
+ return { root, clip };
+}
+
+function sampledVertices(root: THREE.Object3D, clip: THREE.AnimationClip, time: number) {
+ const mixer = new THREE.AnimationMixer(root);
+ mixer.clipAction(clip).setLoop(THREE.LoopOnce, 1).play();
+ mixer.setTime(time);
+ root.updateMatrixWorld(true);
+ const mesh = root.getObjectByName('Sail') as THREE.SkinnedMesh;
+ mesh.skeleton.update();
+ const vertices = Array.from({ length: mesh.geometry.getAttribute('position').count }, (_, i) =>
+ mesh.getVertexPosition(i, new THREE.Vector3()).applyMatrix4(mesh.matrixWorld).toArray(),
+ );
+ mixer.stopAllAction();
+ return vertices.sort((a, b) => a[0]! - b[0]! || a[1]! - b[1]! || a[2]! - b[2]!);
+}
+
+test('community export and full optimization preserve sampled combined skin and morph motion', async () => {
+ const { root, clip } = deformingScene();
+ const exported = await renderSceneToGLB(root, {
+ gltfExporter: 'three',
+ clips: [clip],
+ optimize: 'off',
+ derivative: true,
+ });
+ const optimized = await optimizeGlbBytes(exported.bytes, { mode: 'full' });
+ if (!optimized) throw new Error('Expected the requested optimization to produce an artifact');
+ for (const bytes of [exported.bytes, optimized.bytes]) {
+ const loaded = await new GLTFLoader().parseAsync(new Uint8Array(bytes).buffer, '');
+ expect(loaded.animations).toHaveLength(1);
+ const first = sampledVertices(loaded.scene, loaded.animations[0]!, 0);
+ const last = sampledVertices(loaded.scene, loaded.animations[0]!, 0.75);
+ expect(last).not.toEqual(first);
+ for (const time of [0, 0.25, 0.5, 0.75]) {
+ const expected = sampledVertices(root, clip, time);
+ const actual = sampledVertices(loaded.scene, loaded.animations[0]!, time);
+ expect(actual).toHaveLength(expected.length);
+ for (let i = 0; i < expected.length; i++) {
+ for (let axis = 0; axis < 3; axis++)
+ expect(actual[i]![axis]).toBeCloseTo(expected[i]![axis]!, 5);
+ }
+ }
+ }
+});
diff --git a/src/__tests__/geometry-export-contract.test.ts b/src/__tests__/geometry-export-contract.test.ts
index 01a14c14..6f3e26e1 100644
--- a/src/__tests__/geometry-export-contract.test.ts
+++ b/src/__tests__/geometry-export-contract.test.ts
@@ -44,17 +44,22 @@ describe('custom mesh export contract', () => {
it('identifies dropped attributes and rejects them in strict mode', async () => {
const { root, geometry } = fixture();
- geometry.setAttribute('uv1', new THREE.Float32BufferAttribute([0, 0, 1, 0, 0, 1], 2));
+ geometry.setAttribute(
+ 'customDisplacement',
+ new THREE.Float32BufferAttribute([0, 0, 1, 0, 0, 1], 2),
+ );
const result = await renderSceneToGLB(root);
expect(
result.warnings.some(
(warning) =>
warning.includes('CustomPanel') &&
- warning.includes('uv1') &&
+ warning.includes('customDisplacement') &&
warning.includes('EXPORT_ATTRIBUTE_UNSUPPORTED'),
),
).toBe(true);
- await expect(renderSceneToGLB(root, { geometryPolicy: 'strict' })).rejects.toThrow('uv1');
+ await expect(renderSceneToGLB(root, { geometryPolicy: 'strict' })).rejects.toThrow(
+ 'customDisplacement',
+ );
});
it('rejects nonfinite positions before writing invalid bytes', async () => {
diff --git a/src/__tests__/geometry-policy-runtime.test.ts b/src/__tests__/geometry-policy-runtime.test.ts
index 1db49833..7038d244 100644
--- a/src/__tests__/geometry-policy-runtime.test.ts
+++ b/src/__tests__/geometry-policy-runtime.test.ts
@@ -4,7 +4,7 @@ import { createEvaluatorRequestV1, decodeEvaluatorRequestV1 } from '../evaluator
import { createKilnProgramToolRegistry } from '../tools/registry';
import { createLocalToolContext } from '../local-runtime';
const code = (colors = false) =>
- `const meta={name:'policy',category:'prop'};function build(){const root=createRoot('Root');const geo=boxGeo(1,1,1);${colors ? "geo.setAttribute('color',geo.getAttribute('position').clone());" : ''}createPart('Body',geo,gameMaterial('#888888'),{parent:root});return root;}`;
+ `const meta={name:'policy',category:'prop'};function build(){const root=createRoot('Root');const geo=boxGeo(1,1,1);${colors ? "geo.setAttribute('customDisplacement',geo.getAttribute('position').clone());" : ''}createPart('Body',geo,gameMaterial('#888888'),{parent:root});return root;}`;
test('geometry export policy roundtrips through strict worker protocol and rejects unknown policy', () => {
const request = createEvaluatorRequestV1({
requestId: 'policy',
@@ -20,7 +20,7 @@ test('geometry export policy roundtrips through strict worker protocol and rejec
}),
).toThrow();
});
-test('subprocess strict accepts supported geometry and rejects vertex colors while default warns', async () => {
+test('subprocess strict accepts supported geometry and rejects custom attributes while default warns', async () => {
expect(
(await renderGLBViaSubprocess(code(), { geometryPolicy: 'strict' })).glb.byteLength,
).toBeGreaterThan(0);
diff --git a/src/__tests__/persistent-local-cache.test.ts b/src/__tests__/persistent-local-cache.test.ts
index c67457cb..c5d2bd77 100644
--- a/src/__tests__/persistent-local-cache.test.ts
+++ b/src/__tests__/persistent-local-cache.test.ts
@@ -26,7 +26,7 @@ it('reuses a packaged Node build across fresh CLI host instances and invalidates
"const meta={name:'CachedBox'};function build(){const r=createRoot('Box');createPart('Body',boxGeo(1,1,1),gameMaterial('#aaaaaa'),{parent:r});return r;}";
const probe = `import {createPackagedLocalToolContext} from ${JSON.stringify(join(repo, 'src/local-runtime.ts'))};
import {createKilnProgramToolRegistry} from ${JSON.stringify(join(repo, 'src/tools/registry.ts'))};
-const context=await createPackagedLocalToolContext({}, {KILN_PROGRAM_STORE:${JSON.stringify(join(root, 'programs'))}}, ${JSON.stringify(root)});
+const context=await createPackagedLocalToolContext({}, {KILN_PROGRAM_STORE:${JSON.stringify(join(root, 'programs'))},KILN_GLTF_EXPORTER:process.env.KILN_GLTF_EXPORTER}, ${JSON.stringify(root)});
if(context.localExecution.cacheScope!=='disk') throw new Error(JSON.stringify(context.localExecution));
const tool=createKilnProgramToolRegistry(context).find(t=>t.name==='kiln_render');
const result=await tool.run({code:process.argv[2]==='changed'?${JSON.stringify(code.replace('boxGeo(1,1,1)', 'boxGeo(1,2,1)'))}:${JSON.stringify(code)},capture:{preset:'1x1'}});
diff --git a/src/__tests__/textures.test.ts b/src/__tests__/textures.test.ts
index bdfd5455..728f5964 100644
--- a/src/__tests__/textures.test.ts
+++ b/src/__tests__/textures.test.ts
@@ -266,7 +266,11 @@ describe('Wave 3B: loadTexture + pbrMaterial', () => {
expect(base).not.toBeNull();
const img = base!.getImage();
expect(img).not.toBeNull();
- expect(img!.byteLength).toBe(png.length);
+ // Encoders may choose different PNG compression/metadata. Pixel identity
+ // is the round-trip contract for both converters.
+ expect(await sharp(img!).ensureAlpha().raw().toBuffer()).toEqual(
+ await sharp(png).ensureAlpha().raw().toBuffer(),
+ );
});
it('untextured gameMaterial still exports without maps (regression)', async () => {
diff --git a/src/community-exporter.ts b/src/community-exporter.ts
new file mode 100644
index 00000000..f9473541
--- /dev/null
+++ b/src/community-exporter.ts
@@ -0,0 +1,252 @@
+import * as THREE from 'three';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import type { Document } from '@gltf-transform/core';
+import { createGltfIO } from './gltf-io';
+import {
+ KILN_SEMANTIC_EXTRAS_KEY,
+ validateSemanticMetadataV1,
+ cloneSemanticMetadataV1,
+ createSemanticMetadataV1,
+} from './contracts';
+
+export function resolveGltfExporter(
+ value: string | undefined = typeof process !== 'undefined'
+ ? process.env['KILN_GLTF_EXPORTER']
+ : undefined,
+): 'legacy' | 'three' {
+ if (value === undefined || value === 'legacy') return 'legacy';
+ if (value === 'three') return 'three';
+ throw new Error(`Invalid KILN_GLTF_EXPORTER ${JSON.stringify(value)}; use legacy or three.`);
+}
+
+export interface ExportPlatform {
+ prepare(hasTextures: boolean): Promise<void>;
+ decode(bytes: Uint8Array): Promise<{ data: Uint8Array; width: number; height: number }>;
+}
+
+const browserPlatform: ExportPlatform = {
+ async prepare() {},
+ async decode(bytes) {
+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]), {
+ colorSpaceConversion: 'none',
+ });
+ try {
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (!context) throw new Error('A 2D canvas is required to decode export textures.');
+ context.drawImage(bitmap, 0, 0);
+ const image = context.getImageData(0, 0, bitmap.width, bitmap.height);
+ return { data: new Uint8Array(image.data), width: bitmap.width, height: bitmap.height };
+ } finally {
+ bitmap.close();
+ }
+ },
+};
+
+/** Clone through the object's public API without serializing arbitrary userData. */
+function cleanClone<
+ T extends { userData: Record<string, unknown>; clone: (...args: never[]) => T },
+>(source: T): T {
+ const shadow = Object.create(source) as T;
+ shadow.userData = {};
+ return shadow.clone();
+}
+
+export async function communitySceneDocument(
+ root: THREE.Object3D,
+ clips: THREE.AnimationClip[],
+ platform: ExportPlatform = browserPlatform,
+): Promise<Document> {
+ const materials = new Map<THREE.Material, THREE.Material>();
+ const textures = new Map<THREE.Texture, THREE.Texture>();
+ const nodes = new Map<THREE.Object3D, THREE.Object3D>();
+ const encoded: Array<Promise<void>> = [];
+ function texture(source: THREE.Texture): THREE.Texture {
+ const found = textures.get(source);
+ if (found) return found;
+ const copy = cleanClone(source);
+ normalizeTextureTransform(copy);
+ // Texture.copy shares Source. Detach it before decoding into the export copy.
+ copy.source = new THREE.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData['encoded'] as { bytes?: Uint8Array; mime?: string } | undefined;
+ if (bytes?.bytes) {
+ encoded.push(
+ (async () => {
+ copy.image = await platform.decode(bytes.bytes!);
+ Object.defineProperty(copy, 'isDataTexture', { value: true });
+ copy.format = THREE.RGBAFormat;
+ copy.type = THREE.UnsignedByteType;
+ })(),
+ );
+ }
+ return copy;
+ }
+ function material(source: THREE.Material): THREE.Material {
+ const found = materials.get(source);
+ if (found) return found;
+ const copy = cleanClone(source);
+ const physical = copy as THREE.MeshPhysicalMaterial;
+ if (physical.isMeshPhysicalMaterial && physical.sheen > 0) {
+ // glTF has a sheen color factor, but no separate intensity. Match the
+ // effective color used by Three's renderer on this detached material.
+ physical.sheenColor.multiplyScalar(physical.sheen);
+ physical.sheen = 1;
+ }
+ for (const [key, value] of Object.entries(copy)) {
+ if (value instanceof THREE.Texture)
+ (copy as unknown as Record<string, unknown>)[key] = texture(value);
+ }
+ materials.set(source, copy);
+ return copy;
+ }
+ function node(source: THREE.Object3D): THREE.Object3D {
+ if ((source as THREE.Line).isLine || (source as THREE.Points).isPoints)
+ throw new Error(
+ 'Experimental glTF exporter supports triangle meshes and sprites, not lines or points.',
+ );
+ // Object3D.clone defaults to recursive; call copy with recursion disabled.
+ const shadow = Object.create(source) as THREE.Object3D;
+ shadow.userData = {};
+ let copy = shadow.clone(false);
+ if ((source as THREE.Scene).isScene) {
+ copy = new THREE.Group();
+ copy.copy(shadow, false);
+ }
+ if ((source as THREE.Sprite).isSprite) {
+ const sprite = source as THREE.Sprite;
+ const geometry = new THREE.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE.MeshBasicMaterial({
+ name: sprite.material.name,
+ color: sprite.material.color,
+ opacity: sprite.material.opacity,
+ transparent: sprite.material.transparent,
+ alphaTest: sprite.material.alphaTest,
+ side: sprite.material.side,
+ map: sprite.material.map ? texture(sprite.material.map) : null,
+ });
+ copy = new THREE.Mesh(geometry, spriteMaterial);
+ THREE.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
+ if (semantic !== undefined) {
+ const checked = validateSemanticMetadataV1(semantic);
+ if (!checked.valid || !checked.value)
+ throw new TypeError(`Invalid ${KILN_SEMANTIC_EXTRAS_KEY} on ${source.name}`);
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = cloneSemanticMetadataV1(checked.value);
+ }
+ if ((source as THREE.Sprite).isSprite) {
+ const metadata = copy.userData[KILN_SEMANTIC_EXTRAS_KEY] as
+ | ReturnType<typeof createSemanticMetadataV1>
+ | undefined;
+ copy.userData[KILN_SEMANTIC_EXTRAS_KEY] = createSemanticMetadataV1({
+ ...metadata,
+ roles: [
+ ...(metadata?.roles ?? []).filter((role) => !role.startsWith('vfx.facing.')),
+ 'vfx.facing.camera-spherical',
+ ...(metadata?.roles.some((role) => role.startsWith('vfx.effect.surface'))
+ ? []
+ : ['vfx.effect.surface.card']),
+ ],
+ });
+ }
+ if ((source as THREE.Mesh).isMesh) {
+ const original = source as THREE.Mesh;
+ const mesh = copy as THREE.Mesh;
+ mesh.geometry = cleanClone(original.geometry);
+ mesh.material = Array.isArray(original.material)
+ ? original.material.map(material)
+ : material(original.material);
+ }
+ nodes.set(source, copy);
+ for (const child of source.children) copy.add(node(child));
+ return copy;
+ }
+ const copy = node(root);
+ for (const [source, target] of nodes) {
+ if (!(source as THREE.SkinnedMesh).isSkinnedMesh) continue;
+ const original = source as THREE.SkinnedMesh;
+ const mesh = target as THREE.SkinnedMesh;
+ mesh.skeleton = original.skeleton.clone();
+ mesh.skeleton.bones = original.skeleton.bones.map((bone) => {
+ const mapped = nodes.get(bone);
+ if (!mapped) throw new Error(`Skin bone ${bone.name} is outside the exported hierarchy.`);
+ return mapped as THREE.Bone;
+ });
+ mesh.bind(mesh.skeleton, original.bindMatrix);
+ }
+ await Promise.all(encoded);
+ await platform.prepare(textures.size > 0);
+ const exportClips = clips.map((clip) => {
+ const cloned = cleanClone(clip);
+ // UUID-targeted clips must point at the export copy, not the live scene.
+ for (const track of cloned.tracks) {
+ for (const [source, target] of nodes) {
+ if (track.name.startsWith(`${source.uuid}.`))
+ track.name = target.uuid + track.name.slice(source.uuid.length);
+ }
+ }
+ // Keep advisory unresolved tracks in Kiln's review extras, not in native
+ // glTF animations. Upstream otherwise emits invalid empty clip entities.
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE.PropertyBinding.parseTrackName(track.name);
+ return (
+ ['position', 'quaternion', 'scale', 'morphTargetInfluences'].includes(
+ binding.propertyName,
+ ) && THREE.PropertyBinding.findNode(copy, binding.nodeName) !== null
+ );
+ } catch {
+ return false;
+ }
+ });
+ return cloned;
+ });
+ const bytes = await new GLTFExporter().parseAsync(copy, {
+ binary: true,
+ trs: true,
+ onlyVisible: false,
+ animations: exportClips.filter((clip) => clip.tracks.length > 0),
+ });
+ const io = createGltfIO();
+ const json = await io.binaryToJSON(new Uint8Array(bytes as ArrayBuffer));
+ // Three names texture/sampler bindings; glTF Transform models textures by
+ // image. Carry the first named binding onto an unnamed shared image so the
+ // conversion retains a useful authored resource name without duplicating it.
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name) continue;
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name) image.name = binding.name;
+ }
+ return io.readJSON(json);
+}
+
+/** Encode the effective UV matrix in glTF's T*R*S order, including manual
+ * matrices and Three's center. A sheared UV basis needs baking, not TRS. */
+function normalizeTextureTransform(texture: THREE.Texture): void {
+ if (texture.matrixAutoUpdate) texture.updateMatrix();
+ const e = texture.matrix.elements;
+ const sx = Math.hypot(e[0], e[1]);
+ const rotation = sx > 0 ? Math.atan2(-e[1], e[0]) : Math.atan2(e[3], e[4]);
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ const sy = e[3] * s + e[4] * c;
+ const reconstructed = [sx * c, -sx * s, 0, sy * s, sy * c, 0, e[6], e[7], 1];
+ const tolerance = 1e-7 * Math.max(1, ...e.map(Math.abs));
+ if (
+ e.some((value, i) => !Number.isFinite(value) || Math.abs(value - reconstructed[i]!) > tolerance)
+ ) {
+ throw new Error(
+ `Texture ${texture.name || '<unnamed>'}: UV matrix contains shear or perspective that KHR_texture_transform cannot represent; lossless UV baking is not yet qualified.`,
+ );
+ }
+ texture.offset.set(e[6], e[7]);
+ texture.repeat.set(sx, sy);
+ texture.rotation = rotation;
+ texture.center.set(0, 0);
+ // GLTFExporter reads TRS fields, not this matrix. Retain the exact matrix so
+ // any host-side texture operations continue to see the authored mapping.
+ texture.matrixAutoUpdate = false;
+}
diff --git a/src/evaluator/protocol.ts b/src/evaluator/protocol.ts
index 28321a2e..27dabebf 100644
--- a/src/evaluator/protocol.ts
+++ b/src/evaluator/protocol.ts
@@ -259,11 +259,22 @@ export function createEvaluatorRequestV1(input: CreateEvaluatorRequestV1Input):
function parseOptions(value: unknown): Omit<RenderGlbOptions, 'textureResolver'> {
if (
!isRecord(value) ||
- !hasExactKeys(value, ['optimize', 'instance', 'intent', 'category', 'geometryPolicy'])
+ !hasExactKeys(value, [
+ 'optimize',
+ 'instance',
+ 'intent',
+ 'category',
+ 'geometryPolicy',
+ 'gltfExporter',
+ ])
) {
return fail('request');
}
const options: Omit<RenderGlbOptions, 'textureResolver'> = {};
+ if (value.gltfExporter !== undefined) {
+ if (value.gltfExporter !== 'legacy' && value.gltfExporter !== 'three') fail('request');
+ options.gltfExporter = value.gltfExporter;
+ }
if (value.geometryPolicy !== undefined) {
if (!['warn', 'strict'].includes(String(value.geometryPolicy))) fail('request');
options.geometryPolicy = value.geometryPolicy as 'warn' | 'strict';
diff --git a/src/evaluator/subprocess.test.ts b/src/evaluator/subprocess.test.ts
index b06e033e..4052a00d 100644
--- a/src/evaluator/subprocess.test.ts
+++ b/src/evaluator/subprocess.test.ts
@@ -16,10 +16,16 @@ function build() {
describe('subprocess evaluator scaffold', () => {
test('exports the same deterministic GLB through the v1 protocol', async () => {
- const direct = await renderGLBInProcess(BOX_CODE);
- const contained = await renderGLBViaSubprocess(BOX_CODE, {}, { deadlineMs: 30_000 });
- expect(contained.artifactGlbSha256).toBe(direct.artifactGlbSha256);
- expect(contained.glb).toEqual(direct.glb);
+ for (const gltfExporter of ['legacy', 'three'] as const) {
+ const direct = await renderGLBInProcess(BOX_CODE, { gltfExporter });
+ const contained = await renderGLBViaSubprocess(
+ BOX_CODE,
+ { gltfExporter },
+ { deadlineMs: 30_000 },
+ );
+ expect(contained.artifactGlbSha256).toBe(direct.artifactGlbSha256);
+ expect(contained.glb).toEqual(direct.glb);
+ }
}, 60_000);
test('does not inherit provider, AWS, loader, or Kiln environment variables', () => {
diff --git a/src/exporter-node.ts b/src/exporter-node.ts
new file mode 100644
index 00000000..9a00f568
--- /dev/null
+++ b/src/exporter-node.ts
@@ -0,0 +1,68 @@
+/** Loaded only for the experimental exporter in a headless host. Never creates
+ * a fake document/window: those change environment detection in other libraries. */
+import type { ExportPlatform } from './community-exporter';
+
+export const nodeExportPlatform: ExportPlatform = {
+ prepare: prepareNodeExport,
+ async decode(bytes) {
+ const { default: sharp } = await import('sharp');
+ const decoded = await sharp(bytes).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
+ return {
+ data: new Uint8Array(decoded.data),
+ width: decoded.info.width,
+ height: decoded.info.height,
+ };
+ },
+};
+
+export async function prepareNodeExport(hasTextures: boolean): Promise<void> {
+ const host = globalThis as unknown as Record<string, unknown>;
+ if (!host['FileReader']) host['FileReader'] = ExportFileReader;
+ if (!hasTextures || host['OffscreenCanvas'] || host['document']) return;
+ const { Canvas, ImageData } = await import('@napi-rs/canvas');
+ class ExportCanvas extends Canvas {
+ override async convertToBlob(
+ options: { type?: string; mime?: string; quality?: number } = {},
+ ): Promise<Blob> {
+ const type = options.type ?? options.mime ?? 'image/png';
+ if (type !== 'image/png' && type !== 'image/jpeg' && type !== 'image/webp')
+ throw new Error(`Unsupported export image type: ${type}`);
+ const bytes = type === 'image/png' ? this.toBuffer('image/png') : this.toBuffer(type);
+ return new Blob([new Uint8Array(bytes)], { type });
+ }
+ }
+ host['OffscreenCanvas'] = ExportCanvas;
+ if (!host['ImageData']) host['ImageData'] = ImageData;
+}
+
+/** The exporter needs only Blob reads. This adapter is deliberately private to
+ * export hosts; it does not claim to implement the full DOM FileReader API. */
+export class ExportFileReader {
+ result: ArrayBuffer | string | null = null;
+ error: unknown = null;
+ onloadend: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+
+ readAsArrayBuffer(blob: Blob): void {
+ this.read(blob, false);
+ }
+ readAsDataURL(blob: Blob): void {
+ this.read(blob, true);
+ }
+
+ private read(blob: Blob, dataUrl: boolean): void {
+ void blob.arrayBuffer().then(
+ (bytes) => {
+ this.result = dataUrl
+ ? `data:${blob.type};base64,${Buffer.from(bytes).toString('base64')}`
+ : bytes;
+ this.onloadend?.();
+ },
+ (error: unknown) => {
+ this.error = error;
+ this.onerror?.();
+ this.onloadend?.();
+ },
+ );
+ }
+}
diff --git a/src/geometry-export.ts b/src/geometry-export.ts
index e62e77c5..d042e8c5 100644
--- a/src/geometry-export.ts
+++ b/src/geometry-export.ts
@@ -8,6 +8,39 @@ export const EXPORTED_GEOMETRY_ATTRIBUTES: Readonly<Record<string, number>> = {
tangent: 4,
};
+/** Both converters require a complete, non-overlapping triangle partition. */
+export function validateMaterialGroups(
+ geometry: THREE.BufferGeometry,
+ materialCount: number,
+ name: string,
+) {
+ const length = geometry.getIndex()?.count ?? geometry.getAttribute('position').count;
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
+ let covered = 0;
+ for (const group of groups) {
+ const materialIndex = group.materialIndex ?? 0;
+ if (
+ group.start !== covered ||
+ !Number.isInteger(group.start) ||
+ !Number.isInteger(group.count) ||
+ group.count <= 0 ||
+ group.start % 3 ||
+ group.count % 3 ||
+ group.start + group.count > length ||
+ !Number.isInteger(materialIndex) ||
+ materialIndex < 0 ||
+ materialIndex >= materialCount
+ )
+ throw new TypeError(
+ `${name}: material groups must cover every triangle exactly once with valid material indices.`,
+ );
+ covered = group.start + group.count;
+ }
+ if (covered !== length)
+ throw new TypeError(`${name}: material groups do not cover every triangle.`);
+ return groups;
+}
+
/** Read logical values, including interleaved stride/offset and normalized integer attributes. */
export function geometryAttributeValues(
attribute: THREE.BufferAttribute | THREE.InterleavedBufferAttribute,
@@ -25,6 +58,7 @@ export function geometryAttributeValues(
export function inspectGeometryExport(
root: THREE.Object3D,
policy: GeometryExportPolicy = 'warn',
+ exporter: 'legacy' | 'three' = 'legacy',
): string[] {
const warnings: string[] = [];
root.traverse((node) => {
@@ -40,7 +74,20 @@ export function inspectGeometryExport(
const position = geometry.getAttribute('position');
if (position?.itemSize !== 3) throw new TypeError(`${name}: position requires xyz vertices.`);
for (const [key, attribute] of Object.entries(geometry.attributes)) {
- const expected = EXPORTED_GEOMETRY_ATTRIBUTES[key];
+ const expected =
+ EXPORTED_GEOMETRY_ATTRIBUTES[key] ??
+ (exporter === 'three'
+ ? (
+ {
+ color: attribute.itemSize === 4 ? 4 : 3,
+ uv1: 2,
+ uv2: 2,
+ uv3: 2,
+ skinIndex: 4,
+ skinWeight: 4,
+ } as Record<string, number>
+ )[key]
+ : undefined);
if (expected === undefined) {
unsupported(key);
continue;
@@ -68,9 +115,12 @@ export function inspectGeometryExport(
throw new TypeError(`${name}: index ${i} is outside the position attribute.`);
}
}
- // Material arrays are supported by bridgeGeometry's exact group-range validation.
- for (const key of Object.keys(geometry.morphAttributes)) unsupported(`morph ${key}`);
- if ((mesh as THREE.SkinnedMesh).isSkinnedMesh) unsupported('skinning');
+ if (exporter === 'three' && Array.isArray(mesh.material))
+ validateMaterialGroups(geometry, mesh.material.length, name);
+ if (exporter === 'legacy') {
+ for (const key of Object.keys(geometry.morphAttributes)) unsupported(`morph ${key}`);
+ if ((mesh as THREE.SkinnedMesh).isSkinnedMesh) unsupported('skinning');
+ }
for (const key of ['kilnAttributeWarnings', 'kilnGeometryWarnings']) {
const notes: unknown = geometry.userData[key];
if (!Array.isArray(notes)) continue;
diff --git a/src/gltf-io.ts b/src/gltf-io.ts
new file mode 100644
index 00000000..095bd6f9
--- /dev/null
+++ b/src/gltf-io.ts
@@ -0,0 +1,8 @@
+import { WebIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+
+/** Keep standard extensions through every document round trip. Codec-dependent
+ * extensions still require their decoder; registration does not invent one. */
+export function createGltfIO(): WebIO {
+ return new WebIO().registerExtensions(ALL_EXTENSIONS);
+}
diff --git a/src/local-runtime.ts b/src/local-runtime.ts
index 04ae6712..406f9c9d 100644
--- a/src/local-runtime.ts
+++ b/src/local-runtime.ts
@@ -5,6 +5,7 @@ import { renderGLBViaIsolatedEvaluator } from './evaluator/isolation';
import { renderGLBInProcess, resolveEvaluatorMode, type RenderGlbOptions } from './render';
import { FileProgramStore } from './program-store-node';
import { createCachedEvaluatorPort, MemoryBuildCache } from './build-cache';
+import { resolveGltfExporter } from './community-exporter';
import { FileBuildCache } from './build-cache-node';
import { installedRuntimeIdentity } from './runtime-identity';
import { dirname, join, resolve } from 'node:path';
@@ -66,6 +67,7 @@ export function createLocalToolContext(
? (env.KILN_BAKE_INSTANCE as RenderGlbOptions['instance'])
: 'auto';
const maxGlbBytes = 16 * 1024 * 1024;
+ const gltfExporter = resolveGltfExporter(env.KILN_GLTF_EXPORTER ?? 'legacy');
const maxResponseBytes = 32 * 1024 * 1024;
const evaluatorPort: EvaluatorPortV1 = {
async render(code, options = {}, controls = {}) {
@@ -79,6 +81,7 @@ export function createLocalToolContext(
)
throw new Error('geometryPolicy must be warn or strict');
const resolved: RenderGlbOptions = {
+ ...(gltfExporter === 'three' ? { gltfExporter } : {}),
optimize,
instance,
...options,
@@ -197,6 +200,7 @@ export async function createPackagedLocalToolContext(
qa: env.KILN_QA_MODE ?? 'enforce',
geometryPolicy: context.geometryPolicy,
timezone: env.TZ,
+ ...(env.KILN_GLTF_EXPORTER === 'three' ? { gltfExporter: 'three' } : {}),
})}`;
context.localExecution = {
...context.localExecution,
diff --git a/src/qa/breadth-final.ts b/src/qa/breadth-final.ts
index 446ea088..2b27959e 100644
--- a/src/qa/breadth-final.ts
+++ b/src/qa/breadth-final.ts
@@ -1,5 +1,4 @@
-import { WebIO } from '@gltf-transform/core';
-import { EXTMeshGPUInstancing } from '@gltf-transform/extensions';
+import { createGltfIO } from '../gltf-io';
import * as THREE from 'three';
import {
@@ -143,7 +142,7 @@ function finalEffectAxis(
* the pre-export Three.js scene.
*/
export async function analyzeFinalVfxGlbBytesV1(bytes: Uint8Array): Promise<FinalVfxGlbEvidenceV1> {
- const io = new WebIO().registerExtensions([EXTMeshGPUInstancing]);
+ const io = createGltfIO();
const document = await io.readBinary(bytes);
const root = document.getRoot();
const renderableNodes = root.listNodes().filter((node) => node.getMesh() !== null);
diff --git a/src/render.ts b/src/render.ts
index b8a0adf1..7b02912c 100644
--- a/src/render.ts
+++ b/src/render.ts
@@ -12,18 +12,16 @@ import { rethrowAuthoringError } from './evaluator/authoring-diagnostic';
*/
import * as THREE from 'three';
+import { createGltfIO } from './gltf-io';
+import { communitySceneDocument, resolveGltfExporter } from './community-exporter';
import {
geometryAttributeValues,
inspectGeometryExport,
+ validateMaterialGroups,
type GeometryExportPolicy,
} from './geometry-export';
import { createHash } from 'node:crypto';
-import { Document, WebIO, getBounds } from '@gltf-transform/core';
-import {
- EXTMeshGPUInstancing,
- KHRMaterialsVariants,
- KHRTextureBasisu,
-} from '@gltf-transform/extensions';
+import { Document, getBounds } from '@gltf-transform/core';
import {
dedup,
instance,
@@ -126,8 +124,7 @@ export type CapturedDiagnosticV1 = CharacterCapturedDiagnosticV1 | VehicleCaptur
// Variants and Basisu are registered for READS as much as writes: once the kit
// pass has run, every later pass that parses these bytes (metrics, optimize,
// palette snap) would silently drop both extensions without them.
-const engineIO = (): WebIO =>
- new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRMaterialsVariants, KHRTextureBasisu]);
+const engineIO = createGltfIO;
/**
* World-space AABB of a stored GLB, computed from its bytes alone — node
@@ -635,23 +632,8 @@ function bridgeGeometry(
const indexValues = indexAttr
? Array.from(indexAttr.array)
: Array.from({ length: posAttr!.count }, (_, i) => i);
- const groups = [...geometry.groups].sort((a, b) => a.start - b.start);
- let covered = 0;
+ const groups = validateMaterialGroups(geometry, material.length, meshName);
for (const group of groups) {
- if (
- group.start !== covered ||
- !Number.isInteger(group.start) ||
- !Number.isInteger(group.count) ||
- group.count <= 0 ||
- group.start % 3 ||
- group.count % 3 ||
- group.start + group.count > indexValues.length ||
- !material[group.materialIndex ?? 0]
- ) {
- throw new TypeError(
- `${meshName}: material groups must cover every triangle exactly once with valid material indices.`,
- );
- }
const part = doc.createPrimitive().setMaterial(material[group.materialIndex ?? 0]!);
for (const semantic of prim.listSemantics())
part.setAttribute(semantic, prim.getAttribute(semantic)!);
@@ -664,10 +646,7 @@ function bridgeGeometry(
.setBuffer(buf),
);
mesh.addPrimitive(part);
- covered += group.count;
}
- if (covered !== indexValues.length)
- throw new TypeError(`${meshName}: material groups do not cover every triangle.`);
prim.dispose();
return mesh;
}
@@ -1016,6 +995,8 @@ export interface RenderSceneResult {
}
export interface RenderSceneOptions {
+ /** Host-only migration option; omitted keeps the established exporter. */
+ gltfExporter?: 'legacy' | 'three';
/** Warn about unsupported custom attributes (default), or reject before export. */
geometryPolicy?: GeometryExportPolicy;
/** Name of the glTF scene. Defaults to 'Scene'. */
@@ -1330,7 +1311,8 @@ export async function renderSceneToGLB(
const clips = opts.clips ?? [];
if (opts.geometryPolicy !== undefined && !['warn', 'strict'].includes(opts.geometryPolicy))
throw new Error('geometryPolicy must be warn or strict');
- const warnings = inspectGeometryExport(root, opts.geometryPolicy);
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ const warnings = inspectGeometryExport(root, opts.geometryPolicy, exporter);
const tris = countTriangles(root);
const intent =
opts.intent ??
@@ -1396,7 +1378,14 @@ export async function renderSceneToGLB(
warnings.push(`${blocked.message} — block suppressed by ${qaSuppressedBy}`);
}
- const doc = new Document();
+ const doc =
+ exporter === 'three'
+ ? await communitySceneDocument(
+ root,
+ clips,
+ (await import('./exporter-node')).nodeExportPlatform,
+ )
+ : new Document();
// `asset.generator` defaults to the serializer's own version string, which put
// `glTF-Transform v4.4.1` inside every artifact's bytes -- and therefore inside
// `artifactHash`. Taking 4.5.0 moved all 83 recorded hashes and failed the
@@ -1407,19 +1396,26 @@ export async function renderSceneToGLB(
// Kiln's own version deliberately stays out too: it belongs in the provenance
// record, where changing it does not move artifact bytes.
doc.getRoot().getAsset().generator = 'Kiln';
- const buf = doc.createBuffer();
- const matCache = new Map<THREE.Material, GtMaterial>();
- const meshCache = new Map<string, GtMesh>();
- const texCache = new Map<THREE.Texture, GtTexture>();
- const nodeMap = new Map<string, GtNode>();
-
- const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
- const gltfScene = doc.createScene(opts.sceneName ?? 'Scene').addChild(rootNode);
- doc.getRoot().setDefaultScene(gltfScene);
-
- if (clips.length > 0) {
- gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
- bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ if (exporter === 'legacy') {
+ const buf = doc.createBuffer();
+ const matCache = new Map<THREE.Material, GtMaterial>();
+ const meshCache = new Map<string, GtMesh>();
+ const texCache = new Map<THREE.Texture, GtTexture>();
+ const nodeMap = new Map<string, GtNode>();
+
+ const rootNode = bridgeNode(doc, buf, root, matCache, nodeMap, meshCache, texCache);
+ const gltfScene = doc.createScene(opts.sceneName ?? 'Scene').addChild(rootNode);
+ doc.getRoot().setDefaultScene(gltfScene);
+
+ if (clips.length > 0) {
+ gltfScene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
+ bridgeAnimations(doc, buf, clips, nodeMap, warnings);
+ }
+ } else {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene) throw new Error('Community exporter produced no scene.');
+ scene.setName(opts.sceneName ?? 'Scene');
+ if (clips.length > 0) scene.setExtras({ [REVIEW_CLIPS_EXTRAS_KEY]: reviewClipExtras(clips) });
}
// Dedupe accessors/materials/meshes so instanced parts (4 wheels, 10 posts,
@@ -1600,6 +1596,8 @@ export async function renderSceneToGLB(
* Pure function: no file I/O, no globals, no WebGL.
*/
export interface RenderGlbOptions {
+ /** Host-only migration option, transported explicitly to isolated workers. */
+ gltfExporter?: 'legacy' | 'three';
geometryPolicy?: GeometryExportPolicy;
optimize?: OptimizeMode;
instance?: InstanceMode;
@@ -1626,6 +1624,7 @@ export async function renderGLBInProcess(
});
const requestedCategory = opts.intent?.category ?? opts.category;
const scene = await renderSceneToGLB(root, {
+ gltfExporter: opts.gltfExporter,
sceneName: meta.name || 'Scene',
geometryPolicy: opts.geometryPolicy,
clips,
@@ -1692,6 +1691,8 @@ export function resolveEvaluatorMode(
*/
export async function renderGLB(code: string, opts: RenderGlbOptions = {}): Promise<RenderResult> {
const mode = resolveEvaluatorMode();
+ const exporter = resolveGltfExporter(opts.gltfExporter);
+ if (exporter === 'three') opts = { ...opts, gltfExporter: exporter };
if (mode === 'in-process') return renderGLBInProcess(code, opts);
if (mode === 'subprocess') {
const { renderGLBViaSubprocess } = await import('./evaluator/subprocess');
diff --git a/src/tools/registry.ts b/src/tools/registry.ts
index 9903a020..981f4161 100644
--- a/src/tools/registry.ts
+++ b/src/tools/registry.ts
@@ -2275,6 +2275,7 @@ function withBuildCache(context: KilnToolContext): KilnToolContext {
env['KILN_QA_MODE'],
env['KILN_BAKE_OPTIMIZE'],
env['KILN_BAKE_INSTANCE'],
+ ...(env['KILN_GLTF_EXPORTER'] === 'three' ? ['three'] : []),
]);
},
}),
diff --git a/src/views/glb.ts b/src/views/glb.ts
index 2d7bd068..8d8b6fbf 100644
--- a/src/views/glb.ts
+++ b/src/views/glb.ts
@@ -1,17 +1,12 @@
/** GLB-native input adapter for the deterministic CPU geometry-flat renderer. */
+import { createGltfIO } from '../gltf-io';
import {
Primitive,
- WebIO,
type Accessor,
type Material,
type Texture as GltfTexture,
} from '@gltf-transform/core';
-import {
- EXTMeshGPUInstancing,
- KHRMaterialsVariants,
- KHRTextureBasisu,
-} from '@gltf-transform/extensions';
import {
BufferAttribute,
BufferGeometry,
@@ -117,8 +112,7 @@ export interface LoadedGlbReviewScene extends LoadedGlbGeometryFlatScene {
clips: AnimationClip[];
}
-const glbIO = (): WebIO =>
- new WebIO().registerExtensions([EXTMeshGPUInstancing, KHRMaterialsVariants, KHRTextureBasisu]);
+const glbIO = createGltfIO;
function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);