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.

feat(qa): add a host validation profile to requirements (#208) (#236)

Matthew Kissingerccf7c4111e24
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88f4faf6..fa6e9528 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -118,6 +118,21 @@ does not publish a package.
`GEO_PART_EXTERNAL_SUPPORT` naming the declaration. Undeclared parts, parts at another
height and every other disposition are unchanged. The declaration is covered by the policy
hash.
+- Add natural material presets `beach-sand`, `coral-limestone`, `coral-limestone-wet`,
+ `palm-frond`, `driftwood` and `thatch`, tagged by family (`ground`, `rock`, `foliage`,
+ `wood`, `fiber`). `palm-frond` is an alpha-tested, double-sided cutout saved as a
+ `schemaVersion:2` record; `createMaterialPresetDraftAny` returns any preset's draft, and
+ preset summaries report `recordSchemaVersion`. The docs list the presets as a table that a
+ test keeps in step with the catalog (#210).
+- Add an opt-in host validation profile to requirements ([#208](https://github.com/instruktlabs/kiln/issues/208)).
+ A host binding can carry `requirements.validation`, a closed `kiln.validation-profile.v1`
+ statement that selects final GLB nodes by name and checks primitive counts, required
+ attributes, an attribute range or gradient along a local axis, and material alpha mode
+ and sidedness. The exact rule `HOST_VALIDATION_PROFILE` evaluates it on the final bytes;
+ in `enforce` mode its findings block `kiln_render` and `kiln_save`. The profile is part
+ of the policy hash, so changing it refuses earlier reviewed artifacts. Tool input and
+ source cannot weaken it, and Discovery capabilities show it as host-declared. Bindings
+ without the key are unchanged.
## 1.3.1 (2026-10-17)
diff --git a/dist/agent-run.mjs b/dist/agent-run.mjs
index 5d8bf6fa..5bc60475 100644
--- a/dist/agent-run.mjs
+++ b/dist/agent-run.mjs
@@ -528,14 +528,115 @@ var init_asset = __esm(() => {
THREE_DEGREES = Math.PI / 180;
});
-// src/contracts/requirements.ts
+// src/contracts/validation-profile.ts
import { z } from "zod";
+var VALIDATION_PROFILE_VERSION = "kiln.validation-profile.v1", MAX_VALIDATION_PROFILE_BYTES, MAX_VALIDATION_CHECKS = 16, MAX_VALIDATION_PATTERN_CHARS = 128, MAX_VALIDATION_PATTERN_STARS = 4, MAX_VALIDATION_MATCHES = 512, VALIDATION_SEMANTICS, VALIDATION_SEMANTIC_SIZE, VALIDATION_AXES, finite, id = (max) => z.string().min(1).max(max).regex(/^[A-Za-z0-9._-]+$/, 'Use letters, digits, ".", "_" or "-".'), pattern, componentFits = (value) => value.component < VALIDATION_SEMANTIC_SIZE[value.attribute], componentMessage, gradient, range, check, ValidationProfileV1Schema;
+var init_validation_profile = __esm(() => {
+ MAX_VALIDATION_PROFILE_BYTES = 8 * 1024;
+ VALIDATION_SEMANTICS = [
+ "POSITION",
+ "NORMAL",
+ "TANGENT",
+ "TEXCOORD_0",
+ "TEXCOORD_1",
+ "COLOR_0",
+ "JOINTS_0",
+ "WEIGHTS_0"
+ ];
+ VALIDATION_SEMANTIC_SIZE = {
+ POSITION: 3,
+ NORMAL: 3,
+ TANGENT: 4,
+ TEXCOORD_0: 2,
+ TEXCOORD_1: 2,
+ COLOR_0: 4,
+ JOINTS_0: 4,
+ WEIGHTS_0: 4
+ };
+ VALIDATION_AXES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
+ finite = z.number().finite();
+ pattern = z.string().min(1).refine((value) => Array.from(value).length <= MAX_VALIDATION_PATTERN_CHARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_CHARS} characters.`
+ }).refine((value) => value.split("*").length - 1 <= MAX_VALIDATION_PATTERN_STARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_STARS} "*".`
+ });
+ componentMessage = {
+ message: "component is outside the attribute.",
+ path: ["component"]
+ };
+ gradient = z.strictObject({
+ attribute: z.enum(["TEXCOORD_0", "TEXCOORD_1", "COLOR_0"]),
+ component: z.number().int().min(0).max(3),
+ axis: z.enum(VALIDATION_AXES),
+ from: finite,
+ to: finite,
+ tolerance: finite.positive().max(0.5),
+ monotonic: z.boolean()
+ }).refine((value) => value.from !== value.to, {
+ message: "from and to must differ."
+ }).refine(componentFits, componentMessage);
+ range = z.strictObject({
+ attribute: z.enum(VALIDATION_SEMANTICS),
+ component: z.number().int().min(0).max(3),
+ min: finite,
+ max: finite,
+ tolerance: finite.nonnegative()
+ }).refine((value) => value.min <= value.max, {
+ message: "min must not exceed max."
+ }).refine(componentFits, componentMessage);
+ check = z.strictObject({
+ id: id(48),
+ select: z.strictObject({
+ names: z.array(pattern).min(1).max(8),
+ minMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ maxMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional()
+ }).refine((value) => value.maxMatches === undefined || (value.minMatches ?? 1) <= value.maxMatches, { message: "minMatches must not exceed maxMatches." }),
+ primitives: z.union([
+ z.strictObject({ exactly: z.number().int().min(1).max(64) }),
+ z.strictObject({ max: z.number().int().min(1).max(64) })
+ ]).optional(),
+ attributes: z.array(z.enum(VALIDATION_SEMANTICS)).min(1).max(8).refine((values) => new Set(values).size === values.length, {
+ message: "Attributes must be unique."
+ }).optional(),
+ gradient: gradient.optional(),
+ range: range.optional(),
+ material: z.strictObject({
+ alphaMode: z.enum(["OPAQUE", "MASK", "BLEND"]).optional(),
+ doubleSided: z.boolean().optional()
+ }).refine((value) => value.alphaMode !== undefined || value.doubleSided !== undefined, {
+ message: "A material check needs alphaMode or doubleSided."
+ }).optional()
+ }).refine((value) => value.primitives !== undefined || value.attributes !== undefined || value.gradient !== undefined || value.range !== undefined || value.material !== undefined, { message: "A check needs at least one assertion." });
+ ValidationProfileV1Schema = z.strictObject({
+ version: z.literal(VALIDATION_PROFILE_VERSION),
+ profileId: id(64).regex(/^[a-z0-9._-]+$/, 'Use lowercase letters, digits, ".", "_" or "-".'),
+ mode: z.enum(["warn", "enforce"]),
+ checks: z.array(check).min(1).max(MAX_VALIDATION_CHECKS)
+ }).superRefine((value, context) => {
+ const ids = value.checks.map((item) => item.id);
+ if (new Set(ids).size !== ids.length)
+ context.addIssue({
+ code: "custom",
+ path: ["checks"],
+ message: "Check ids must be unique."
+ });
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_VALIDATION_PROFILE_BYTES)
+ context.addIssue({
+ code: "custom",
+ message: `A validation profile serializes to at most ${MAX_VALIDATION_PROFILE_BYTES} bytes (got ${bytes}).`
+ });
+ });
+});
+
+// src/contracts/requirements.ts
+import { z as z2 } from "zod";
function statement(value) {
- return z.discriminatedUnion("state", [
- z.strictObject({ state: z.literal("requested"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("inferred"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("unknown"), reason: text.optional() }),
- z.strictObject({ state: z.literal("inapplicable"), reason: text.optional() })
+ return z2.discriminatedUnion("state", [
+ z2.strictObject({ state: z2.literal("requested"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inferred"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("unknown"), reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inapplicable"), reason: text.optional() })
]);
}
function validateAssetRequirementsV1(value) {
@@ -565,157 +666,159 @@ var text, positive, nonnegative, count, names, marker, supportParts, roof, struc
var init_requirements = __esm(() => {
init_asset();
init_breadth();
- text = z.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
- positive = z.number().finite().positive();
- nonnegative = z.number().finite().nonnegative();
- count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
- names = z.array(text).refine((values) => new Set(values).size === values.length, {
+ init_validation_profile();
+ text = z2.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
+ positive = z2.number().finite().positive();
+ nonnegative = z2.number().finite().nonnegative();
+ count = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+ names = z2.array(text).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- marker = z.strictObject({});
- supportParts = z.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
+ marker = z2.strictObject({});
+ supportParts = z2.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- roof = z.strictObject({
+ roof = z2.strictObject({
type: text.optional(),
- ridgeAxis: z.enum(["x", "z"]).optional(),
+ ridgeAxis: z2.enum(["x", "z"]).optional(),
rise: nonnegative.optional(),
- pitchDegrees: z.number().min(0).max(90).optional(),
+ pitchDegrees: z2.number().min(0).max(90).optional(),
overhang: nonnegative.optional(),
- closedEnds: z.boolean().optional()
+ closedEnds: z2.boolean().optional()
});
- structure = z.strictObject({
+ structure = z2.strictObject({
subtype: text.optional(),
- enterable: z.boolean().optional(),
+ enterable: z2.boolean().optional(),
storeyCount: count.min(1).optional(),
- interiorMode: z.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
- roofMode: z.enum(ARCHITECTURE_ROOF_MODES).optional(),
- footprint: z.strictObject({ spanX: positive, spanZ: positive, units: z.literal("m") }).optional(),
+ interiorMode: z2.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
+ roofMode: z2.enum(ARCHITECTURE_ROOF_MODES).optional(),
+ footprint: z2.strictObject({ spanX: positive, spanZ: positive, units: z2.literal("m") }).optional(),
wallHeight: positive.optional(),
- scaleMode: z.enum(ARCHITECTURE_SCALE_MODES).optional(),
+ scaleMode: z2.enum(ARCHITECTURE_SCALE_MODES).optional(),
roof: roof.optional(),
- portal: z.strictObject({ width: positive, height: positive, depth: positive }).optional()
+ portal: z2.strictObject({ width: positive, height: positive, depth: positive }).optional()
}).refine((value) => value.enterable === undefined || value.interiorMode === undefined || value.enterable === (value.interiorMode === "navigable"), {
message: "enterable and interiorMode must agree when both are specified."
});
- effects = z.strictObject({
- schemaVersion: z.literal(1),
- subtype: z.enum(VFX_SUBTYPES),
- portability: z.enum(VFX_PORTABILITY_MODES),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES),
- doubleSided: z.boolean(),
- facing: z.strictObject({
- source: z.enum(["explicit", "inferred"]),
- mode: z.enum(VFX_FACING_MODES),
- normalAxis: z.enum(VFX_AXIS_DIRECTIONS).optional(),
- directionAxis: z.enum(VFX_AXIS_DIRECTIONS).optional()
+ effects = z2.strictObject({
+ schemaVersion: z2.literal(1),
+ subtype: z2.enum(VFX_SUBTYPES),
+ portability: z2.enum(VFX_PORTABILITY_MODES),
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES),
+ doubleSided: z2.boolean(),
+ facing: z2.strictObject({
+ source: z2.enum(["explicit", "inferred"]),
+ mode: z2.enum(VFX_FACING_MODES),
+ normalAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional(),
+ directionAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional()
}),
- animation: z.strictObject({
- playback: z.enum(VFX_PLAYBACK_POLICIES),
+ animation: z2.strictObject({
+ playback: z2.enum(VFX_PLAYBACK_POLICIES),
durationSeconds: nonnegative,
- endpointBehavior: z.enum(VFX_ENDPOINT_BEHAVIORS),
- driver: z.enum(VFX_RUNTIME_DRIVERS),
+ endpointBehavior: z2.enum(VFX_ENDPOINT_BEHAVIORS),
+ driver: z2.enum(VFX_RUNTIME_DRIVERS),
clipName: text.optional(),
timeUniformName: text.optional()
}),
- sidecar: z.strictObject({ kind: z.literal("tsl"), id: text, version: text }).optional()
+ sidecar: z2.strictObject({ kind: z2.literal("tsl"), id: text, version: text }).optional()
}).superRefine((value, context) => {
for (const issue of validateVfxIntentV1(value).issues) {
context.addIssue({ code: "custom", path: issue.path.split("."), message: issue.message });
}
});
- requirements = z.strictObject({
- grounding: statement(z.strictObject({ planeY: z.number().finite().optional() })).optional(),
+ requirements = z2.strictObject({
+ grounding: statement(z2.strictObject({ planeY: z2.number().finite().optional() })).optional(),
articulation: statement(marker).optional(),
opening: statement(marker).optional(),
- navigation: statement(z.strictObject({ minWidth: positive.optional(), minHeight: positive.optional() })).optional(),
+ navigation: statement(z2.strictObject({ minWidth: positive.optional(), minHeight: positive.optional() })).optional(),
tiling: statement(marker).optional(),
- mobility: statement(z.strictObject({
+ mobility: statement(z2.strictObject({
subtype: text.optional(),
supportAssemblies: names.optional(),
propulsionAssemblies: names.optional(),
- frontFrame: z.literal("+X").optional(),
+ frontFrame: z2.literal("+X").optional(),
wheelCount: count.optional(),
axleCount: count.optional(),
- steering: z.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
- supportPolicy: z.enum(VEHICLE_SUPPORT_POLICIES).optional(),
+ steering: z2.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
+ supportPolicy: z2.enum(VEHICLE_SUPPORT_POLICIES).optional(),
animationAssemblies: names.optional()
})).optional(),
structure: statement(structure).optional(),
- rig: statement(z.strictObject({
- bodyPlan: z.enum(CHARACTER_BODY_PLANS).optional(),
- grounded: z.boolean().optional(),
- locomotion: z.enum(CHARACTER_LOCOMOTION_MODES).optional(),
+ rig: statement(z2.strictObject({
+ bodyPlan: z2.enum(CHARACTER_BODY_PLANS).optional(),
+ grounded: z2.boolean().optional(),
+ locomotion: z2.enum(CHARACTER_LOCOMOTION_MODES).optional(),
gait: text.optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- clips: z.array(z.strictObject({ name: text, playback: z.enum(["loop", "oneShot"]) })).optional(),
- heldItem: z.strictObject({ required: z.boolean(), attachmentRole: text }).optional()
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ clips: z2.array(z2.strictObject({ name: text, playback: z2.enum(["loop", "oneShot"]) })).optional(),
+ heldItem: z2.strictObject({ required: z2.boolean(), attachmentRole: text }).optional()
})).optional(),
- foliage: statement(z.strictObject({
+ foliage: statement(z2.strictObject({
subtype: text.optional(),
- growthState: z.enum(VEGETATION_GROWTH_STATES).optional(),
- canopyProfile: z.enum(VEGETATION_CANOPY_PROFILES).optional(),
- standalone: z.boolean().optional(),
- grounded: z.boolean().optional()
+ growthState: z2.enum(VEGETATION_GROWTH_STATES).optional(),
+ canopyProfile: z2.enum(VEGETATION_CANOPY_PROFILES).optional(),
+ standalone: z2.boolean().optional(),
+ grounded: z2.boolean().optional()
})).optional(),
- spatialLayout: statement(z.strictObject({
+ spatialLayout: statement(z2.strictObject({
subtype: text.optional(),
- tileable: z.boolean().optional(),
- navigable: z.boolean().optional()
+ tileable: z2.boolean().optional(),
+ navigable: z2.boolean().optional()
})).optional(),
effects: statement(effects).optional(),
- material: statement(z.strictObject({
- mode: z.enum(MATERIAL_INTENT_MODES).optional(),
+ material: statement(z2.strictObject({
+ mode: z2.enum(MATERIAL_INTENT_MODES).optional(),
recipeId: text.optional(),
paletteId: text.optional(),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES).optional()
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES).optional()
})).optional(),
- animation: statement(z.strictObject({
+ animation: statement(z2.strictObject({
clips: names,
- locomotionDirection: z.literal("+X").optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- loop: z.boolean().optional(),
+ locomotionDirection: z2.literal("+X").optional(),
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ loop: z2.boolean().optional(),
gait: text.optional()
})).optional(),
- bounds: statement(z.strictObject({
- units: z.literal("m"),
+ bounds: statement(z2.strictObject({
+ units: z2.literal("m"),
x: positive.optional(),
y: positive.optional(),
z: positive.optional()
})).optional(),
- parts: statement(z.strictObject({ required: names, forbiddenExtras: names })).optional(),
- modular: statement(z.strictObject({
- schemaVersion: z.literal(1),
- units: z.literal("m"),
- grid: z.tuple([positive, positive, positive])
+ parts: statement(z2.strictObject({ required: names, forbiddenExtras: names })).optional(),
+ modular: statement(z2.strictObject({
+ schemaVersion: z2.literal(1),
+ units: z2.literal("m"),
+ grid: z2.tuple([positive, positive, positive])
})).optional(),
- representation: statement(z.strictObject({
- transparentSurface: z.boolean().optional(),
- runtimeShader: z.boolean().optional(),
- precomputedTangents: z.boolean().optional(),
- skinned: z.boolean().optional()
+ representation: statement(z2.strictObject({
+ transparentSurface: z2.boolean().optional(),
+ runtimeShader: z2.boolean().optional(),
+ precomputedTangents: z2.boolean().optional(),
+ skinned: z2.boolean().optional()
})).optional(),
- externalSupport: statement(z.strictObject({
- supports: z.array(z.strictObject({
+ externalSupport: statement(z2.strictObject({
+ supports: z2.array(z2.strictObject({
parts: supportParts,
- planeY: z.number().finite(),
+ planeY: z2.number().finite(),
tolerance: nonnegative.max(0.5).optional()
})).min(1).max(32)
})).optional(),
- access: statement(z.strictObject({ enterable: z.boolean().optional(), driveable: z.boolean().optional() })).optional()
+ access: statement(z2.strictObject({ enterable: z2.boolean().optional(), driveable: z2.boolean().optional() })).optional(),
+ validation: statement(ValidationProfileV1Schema).optional()
});
- AssetRequirementsV1Schema = z.strictObject({
- kind: z.literal("kiln.asset-requirements"),
- schemaVersion: z.literal(1),
+ AssetRequirementsV1Schema = z2.strictObject({
+ kind: z2.literal("kiln.asset-requirements"),
+ schemaVersion: z2.literal(1),
labels: names,
- frame: z.strictObject({
- units: z.literal("m"),
- forward: z.literal("+X"),
- up: z.literal("+Y"),
- right: z.literal("+Z"),
- groundY: z.literal(0)
+ frame: z2.strictObject({
+ units: z2.literal("m"),
+ forward: z2.literal("+X"),
+ up: z2.literal("+Y"),
+ right: z2.literal("+Z"),
+ groundY: z2.literal(0)
}),
- scope: statement(z.enum(ASSET_SCOPES)).optional(),
+ scope: statement(z2.enum(ASSET_SCOPES)).optional(),
requirements
}).superRefine((record, context) => {
const requests = record.requirements;
@@ -832,7 +935,7 @@ var init_requirements_json = __esm(() => {
// src/requirements-context.ts
import { createHash as createHash2 } from "node:crypto";
-import { z as z2 } from "zod";
+import { z as z3 } from "zod";
function canonical2(value) {
if (Array.isArray(value))
return `[${value.map(canonical2).join(",")}]`;
@@ -900,26 +1003,26 @@ var init_requirements_context = __esm(() => {
init_requirements();
init_requirements_identity();
init_requirements_json();
- text2 = z2.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
- hash = z2.string().regex(/^[a-f0-9]{64}$/);
- revision = z2.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
- change = z2.strictObject({
+ text2 = z3.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
+ hash = z3.string().regex(/^[a-f0-9]{64}$/);
+ revision = z3.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
+ change = z3.strictObject({
actor: text2,
reason: text2,
- source: z2.enum(["brief", "automation", "migration", "restore"]),
+ source: z3.enum(["brief", "automation", "migration", "restore"]),
revision,
policyHash: hash,
previousPolicyHash: hash.optional()
});
- RequirementsBindingSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-binding"),
- schemaVersion: z2.literal(1),
+ RequirementsBindingSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-binding"),
+ schemaVersion: z3.literal(1),
taskId: text2,
lineageId: text2,
revision,
policyHash: hash,
requirements: AssetRequirementsV1Schema,
- history: z2.array(change).min(1)
+ history: z3.array(change).min(1)
}).superRefine((binding, context) => {
const issue = (message) => context.addIssue({ code: "custom", message });
if (binding.policyHash !== assetRequirementsPolicyHash(binding.requirements))
@@ -934,9 +1037,9 @@ var init_requirements_context = __esm(() => {
if (binding.history.at(-1)?.policyHash !== binding.policyHash)
issue("Requirements binding history does not end at its current policy.");
});
- CheckpointSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-checkpoint.v1"),
- programRef: z2.string().regex(/^sha256:[a-f0-9]{64}$/),
+ CheckpointSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-checkpoint.v1"),
+ programRef: z3.string().regex(/^sha256:[a-f0-9]{64}$/),
binding: RequirementsBindingSchema
});
});
@@ -1598,7 +1701,7 @@ function strict(value, keys, label) {
throw new Error(`${label}.${key} is unknown${hint ? `; use ${KEY_HINTS[key]}` : ""}; accepted keys: ${keys.join(", ")}`);
}
}
-function finite(n, label) {
+function finite2(n, label) {
if (!Number.isFinite(n))
throw new Error(`${label} must be finite`);
return n;
@@ -1737,7 +1840,7 @@ function validateResolvedAssetCamera(value) {
throw new Error("camera target must differ from position");
if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
throw new Error("camera up must be non-zero and not collinear with view");
- if (finite(camera.aspect, "aspect") <= 0 || finite(camera.near, "near") <= 0 || finite(camera.far, "far") <= camera.near)
+ if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
throw new Error("camera requires positive aspect and 0 < near < far");
if (camera.projection === "orthographic") {
if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
@@ -1767,7 +1870,7 @@ function resolveAssetCamera(root, shot = {}) {
const relative = request.relativeTo ?? "world";
if (!["world", "asset", "part"].includes(relative))
throw new Error("invalid relativeTo");
- const dir = vec(orbitDir(finite(request.azimuthDeg ?? 45, "azimuthDeg"), finite(request.elevationDeg ?? 25, "elevationDeg")));
+ const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));
let up;
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
@@ -1845,7 +1948,7 @@ function resolveAssetCamera(root, shot = {}) {
far: request.far ?? fit.far
};
else {
- const fov = finite(request.fovDeg ?? 50, "fovDeg");
+ const fov = finite2(request.fovDeg ?? 50, "fovDeg");
if (fov <= 0 || fov >= 180)
throw new Error("invalid fovDeg");
const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
@@ -3423,7 +3526,7 @@ function integer(value, path, fallback, min, max) {
}
return value;
}
-function finite2(value, path, fallback, min, max, diagnostic) {
+function finite3(value, path, fallback, min, max, diagnostic) {
if (value === undefined)
return fallback;
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
@@ -3432,7 +3535,7 @@ function finite2(value, path, fallback, min, max, diagnostic) {
return value;
}
function unit(value, path, fallback) {
- return finite2(value, path, fallback, 0, 1, "MATERIAL_FRACTION_RANGE");
+ return finite3(value, path, fallback, 0, 1, "MATERIAL_FRACTION_RANGE");
}
function optionalName(value, path) {
if (value === undefined)
@@ -3455,7 +3558,7 @@ function usage(value, path, fallback) {
return value;
}
function angle(value, path) {
- const bounded = finite2(value, path, 0, -36000, 36000);
+ const bounded = finite3(value, path, 0, -36000, 36000);
const normalized = (bounded % 360 + 360) % 360;
return Object.is(normalized, -0) ? 0 : normalized;
}
@@ -3734,7 +3837,7 @@ function canonicalizePortableMaterialSpecV2(input) {
...record["emissive"] !== undefined ? {
emissive: color(record["emissive"], "portableMaterial.emissive", "PORTABLE_COLOR_ARGUMENT")
} : {},
- emissiveIntensity: finite2(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),
+ emissiveIntensity: finite3(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),
alphaMode,
alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),
doubleSided: record["doubleSided"] === true,
@@ -4660,58 +4763,58 @@ var init_texture_atlas_contract = __esm(() => {
});
// src/material-authoring-schema.ts
-import { z as z3 } from "zod";
+import { z as z4 } from "zod";
function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema = canonicalLegacyV2FieldSchema) {
- const integer = (min, max) => z3.number().int().min(min).max(max);
+ const integer = (min, max) => z4.number().int().min(min).max(max);
const byte = integer(0, 255);
const coordinate = integer(-4096, 4096);
- const point = z3.tuple([coordinate, coordinate]);
- const rgba = z3.tuple([byte, byte, byte, byte]);
- const usage = z3.enum(TEXTURE_USAGES);
- const hash = z3.templateLiteral(["sha256:", z3.string().regex(/^[a-f0-9]{64}$/)]);
- const name = z3.string().min(1).max(80);
- const stableId = z3.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- const mapId = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ const point = z4.tuple([coordinate, coordinate]);
+ const rgba = z4.tuple([byte, byte, byte, byte]);
+ const usage = z4.enum(TEXTURE_USAGES);
+ const hash = z4.templateLiteral(["sha256:", z4.string().regex(/^[a-f0-9]{64}$/)]);
+ const name = z4.string().min(1).max(80);
+ const stableId = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ const mapId = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
const dimensions = { width: integer(1, 4096), height: integer(1, 4096) };
- const pixelRectangleSchema = z3.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
- const atlasRectangleSchema = z3.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
- const shape = z3.discriminatedUnion("kind", [
- pixelRectangleSchema.extend({ kind: z3.literal("rectangle") }).strict(),
- pixelRectangleSchema.extend({ kind: z3.literal("ellipse") }).strict(),
- z3.object({
- kind: z3.literal("polygon"),
- points: z3.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
+ const pixelRectangleSchema = z4.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
+ const atlasRectangleSchema = z4.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
+ const shape = z4.discriminatedUnion("kind", [
+ pixelRectangleSchema.extend({ kind: z4.literal("rectangle") }).strict(),
+ pixelRectangleSchema.extend({ kind: z4.literal("ellipse") }).strict(),
+ z4.object({
+ kind: z4.literal("polygon"),
+ points: z4.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
}).strict(),
- z3.object({ kind: z3.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
+ z4.object({ kind: z4.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
]);
- const paint = z3.object({ op: z3.literal("paint"), shape, rgba, opacity: byte }).strict();
- const mask = z3.object({ op: z3.literal("mask"), shape, alpha: byte, invert: z3.boolean() }).strict();
- const stamps = z3.object({
- op: z3.literal("stamps"),
+ const paint = z4.object({ op: z4.literal("paint"), shape, rgba, opacity: byte }).strict();
+ const mask = z4.object({ op: z4.literal("mask"), shape, alpha: byte, invert: z4.boolean() }).strict();
+ const stamps = z4.object({
+ op: z4.literal("stamps"),
shape,
rgba,
opacity: byte,
count: integer(1, MAX_PROCEDURAL_V3_STAMPS),
seed: integer(0, 4294967295),
area: pixelRectangleSchema,
- periodic: z3.boolean()
+ periodic: z4.boolean()
}).strict();
- const legacy = z3.object({ op: z3.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
- const palette = z3.object({
- colors: z3.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
- dither: z3.enum(["none", "bayer4"])
+ const legacy = z4.object({ op: z4.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
+ const palette = z4.object({
+ colors: z4.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
+ dither: z4.enum(["none", "bayer4"])
}).strict();
const proceduralBase = {
- schemaVersion: z3.literal(3),
+ schemaVersion: z4.literal(3),
width: integer(4, MAX_PROCEDURAL_V3_EDGE),
height: integer(4, MAX_PROCEDURAL_V3_EDGE),
usage,
name: name.optional(),
background: rgba
};
- const canonicalProceduralTextureSpecV3Schema = z3.object({
+ const canonicalProceduralTextureSpecV3Schema = z4.object({
...proceduralBase,
- operations: z3.array(z3.discriminatedUnion("op", [
+ operations: z4.array(z4.discriminatedUnion("op", [
paint,
mask,
stamps,
@@ -4719,11 +4822,11 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.optional()
}).strict();
- const proceduralTextureSpecV3Schema = z3.object({
+ const proceduralTextureSpecV3Schema = z4.object({
...proceduralBase,
usage: usage.optional(),
background: rgba.optional(),
- operations: z3.array(z3.discriminatedUnion("op", [
+ operations: z4.array(z4.discriminatedUnion("op", [
paint.partial({ opacity: true }),
mask.partial({ alpha: true, invert: true }),
stamps.partial({ opacity: true, periodic: true }),
@@ -4731,110 +4834,110 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.partial({ dither: true }).optional()
}).strict();
- const portableSamplerSchema = z3.object({
- minFilter: z3.enum(PORTABLE_MIN_FILTERS_V1),
- magFilter: z3.enum(PORTABLE_MAG_FILTERS_V1),
- wrapS: z3.enum(PORTABLE_WRAPS_V1),
- wrapT: z3.enum(PORTABLE_WRAPS_V1)
+ const portableSamplerSchema = z4.object({
+ minFilter: z4.enum(PORTABLE_MIN_FILTERS_V1),
+ magFilter: z4.enum(PORTABLE_MAG_FILTERS_V1),
+ wrapS: z4.enum(PORTABLE_WRAPS_V1),
+ wrapT: z4.enum(PORTABLE_WRAPS_V1)
}).strict();
- const materialMapPinSchema = z3.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
- const resourceSource = z3.object({
- kind: z3.literal("resource"),
+ const materialMapPinSchema = z4.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
+ const resourceSource = z4.object({
+ kind: z4.literal("resource"),
resourceId: mapId,
pin: materialMapPinSchema,
- expected: z3.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
+ expected: z4.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
}).strict();
- const region = z3.object({
+ const region = z4.object({
name: stableId,
content: atlasRectangleSchema,
gutter: integer(0, 32),
- edgeMode: z3.enum(["copy-edge", "mask-rgb-dilate"]),
- source: z3.discriminatedUnion("kind", [
- z3.object({ kind: z3.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
+ edgeMode: z4.enum(["copy-edge", "mask-rgb-dilate"]),
+ source: z4.discriminatedUnion("kind", [
+ z4.object({ kind: z4.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
resourceSource
]),
crop: atlasRectangleSchema.optional(),
- packed: z3.literal(true).optional()
+ packed: z4.literal(true).optional()
}).strict();
const atlasBase = {
- schemaVersion: z3.literal(1),
+ schemaVersion: z4.literal(1),
width: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
height: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
usage,
sampler: portableSamplerSchema
};
- const packEdge = z3.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z3.literal(edge)));
- const canonicalTextureAtlasSpecV1Schema = z3.object({
+ const packEdge = z4.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z4.literal(edge)));
+ const canonicalTextureAtlasSpecV1Schema = z4.object({
...atlasBase,
- regions: z3.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
- pack: z3.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z3.literal("maxrects") }).strict().optional()
+ regions: z4.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
+ pack: z4.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z4.literal("maxrects") }).strict().optional()
}).strict();
- const textureAtlasSpecV1Schema = z3.object({
+ const textureAtlasSpecV1Schema = z4.object({
...atlasBase,
width: atlasBase.width.optional(),
height: atlasBase.height.optional(),
- pack: z3.object({
+ pack: z4.object({
edge: packEdge,
gutter: integer(0, 32).optional(),
- algorithm: z3.literal("maxrects").optional()
+ algorithm: z4.literal("maxrects").optional()
}).strict().optional(),
sampler: portableSamplerSchema.optional(),
- regions: z3.array(region.extend({
- source: z3.discriminatedUnion("kind", [
- z3.object({ kind: z3.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
+ regions: z4.array(region.extend({
+ source: z4.discriminatedUnion("kind", [
+ z4.object({ kind: z4.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
resourceSource
])
}).partial({ content: true, gutter: true, edgeMode: true })).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions)
}).strict();
- const verifiedPinnedMaterialMapDescriptorSchema = z3.object({
+ const verifiedPinnedMaterialMapDescriptorSchema = z4.object({
materialId: stableId,
revisionId: hash,
resourceId: mapId,
- slot: z3.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ slot: z4.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
usage,
- colorSpace: z3.enum(["srgb", "linear"]),
+ colorSpace: z4.enum(["srgb", "linear"]),
...dimensions,
encodedByteLength: integer(1, TEXTURE_ATLAS_LIMITS.encodedSourceBytes),
imageSha256: hash,
decodedPixelHash: hash.optional()
}).strict();
const sourceManifestBase = {
- id: z3.string().min(1).max(1024),
+ id: z4.string().min(1).max(1024),
...dimensions,
decodedPixelHash: hash
};
- const sourceManifest = z3.discriminatedUnion("kind", [
- z3.object({
+ const sourceManifest = z4.discriminatedUnion("kind", [
+ z4.object({
...sourceManifestBase,
- kind: z3.literal("procedural"),
+ kind: z4.literal("procedural"),
recipeHash: hash,
- compilerId: z3.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
+ compilerId: z4.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
}).strict(),
- z3.object({
+ z4.object({
...sourceManifestBase,
- kind: z3.literal("resource"),
+ kind: z4.literal("resource"),
descriptor: verifiedPinnedMaterialMapDescriptorSchema
}).strict()
]);
- const textureAtlasManifestV1Schema = z3.object({
- version: z3.literal("kiln.atlas-manifest.v1"),
- compilerId: z3.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ const textureAtlasManifestV1Schema = z4.object({
+ version: z4.literal("kiln.atlas-manifest.v1"),
+ compilerId: z4.enum(TEXTURE_ATLAS_COMPILER_IDS),
width: atlasBase.width,
height: atlasBase.height,
usage,
- origin: z3.literal("top-left"),
+ origin: z4.literal("top-left"),
sampler: portableSamplerSchema,
specHash: hash,
layoutHash: hash,
decodedPixelHash: hash,
atlasPixelHash: hash,
- sources: z3.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
- regions: z3.array(z3.object({
+ sources: z4.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
+ regions: z4.array(z4.object({
name: stableId,
content: atlasRectangleSchema,
allocation: atlasRectangleSchema,
crop: atlasRectangleSchema,
- sourceId: z3.string().min(1).max(1024)
+ sourceId: z4.string().min(1).max(1024)
}).strict()).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
manifestHash: hash
}).strict();
@@ -4857,36 +4960,36 @@ var init_material_authoring_schema = __esm(() => {
init_portable_sampler();
init_texture_contract();
canonicalLegacyV2FieldSchema = (() => {
- const color = z3.number().int().min(0).max(16777215);
- const count = z3.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
- const angleDeg = z3.number().min(-36000).max(36000);
- const unit = z3.number().min(0).max(1);
- const common = { blend: z3.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
- return z3.object({
- schemaVersion: z3.literal(2),
- size: z3.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
- usage: z3.enum(TEXTURE_USAGES),
- name: z3.string().min(1).max(80).optional(),
- layers: z3.array(z3.discriminatedUnion("op", [
- z3.object({ op: z3.literal("solid"), color, ...common }).strict(),
- z3.object({
- op: z3.literal("checker"),
+ const color = z4.number().int().min(0).max(16777215);
+ const count = z4.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
+ const angleDeg = z4.number().min(-36000).max(36000);
+ const unit = z4.number().min(0).max(1);
+ const common = { blend: z4.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
+ return z4.object({
+ schemaVersion: z4.literal(2),
+ size: z4.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
+ usage: z4.enum(TEXTURE_USAGES),
+ name: z4.string().min(1).max(80).optional(),
+ layers: z4.array(z4.discriminatedUnion("op", [
+ z4.object({ op: z4.literal("solid"), color, ...common }).strict(),
+ z4.object({
+ op: z4.literal("checker"),
colorA: color,
colorB: color,
squares: count,
...common
}).strict(),
- z3.object({
- op: z3.literal("stripes"),
+ z4.object({
+ op: z4.literal("stripes"),
colorA: color,
colorB: color,
count,
angleDeg,
...common
}).strict(),
- z3.object({ op: z3.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
- z3.object({
- op: z3.literal("bricks"),
+ z4.object({ op: z4.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
+ z4.object({
+ op: z4.literal("bricks"),
brick: color,
mortar: color,
rows: count,
@@ -4895,13 +4998,13 @@ var init_material_authoring_schema = __esm(() => {
stagger: unit,
...common
}).strict(),
- z3.object({
- op: z3.literal("noise"),
+ z4.object({
+ op: z4.literal("noise"),
colorA: color,
colorB: color,
scale: count,
- octaves: z3.number().int().min(1).max(MAX_NOISE_OCTAVES),
- seed: z3.number().int().min(-2147483648).max(2147483647),
+ octaves: z4.number().int().min(1).max(MAX_NOISE_OCTAVES),
+ seed: z4.number().int().min(-2147483648).max(2147483647),
...common
}).strict()
])).min(1).max(MAX_PROCEDURAL_LAYERS)
@@ -4910,7 +5013,7 @@ var init_material_authoring_schema = __esm(() => {
});
// src/material-library.ts
-import { z as z4 } from "zod";
+import { z as z5 } from "zod";
function assertMaterialJson(value, allowBytes = false, depth = 0) {
if (depth > 30)
throw new Error("Material JSON exceeds nesting limit");
@@ -5167,23 +5270,23 @@ var init_material_library = __esm(() => {
emissive: "emissive",
occlusion: "occlusion"
};
- materialLibraryIdSchema = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- materialLibraryHashSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
- text4 = z4.string().min(1).max(1000);
- url = z4.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
- materialSourceSchema = z4.object({
+ materialLibraryIdSchema = z5.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ materialLibraryHashSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text4 = z5.string().min(1).max(1000);
+ url = z5.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
+ materialSourceSchema = z5.object({
id: materialLibraryIdSchema,
- kind: z4.enum(["external", "procedural"]),
+ kind: z5.enum(["external", "procedural"]),
provider: text4,
creator: text4,
assetId: text4.optional(),
assetUrl: url.optional(),
- accessedAt: z4.string().datetime().optional(),
- license: z4.object({ spdx: text4, url, attribution: z4.string().max(4000) }).strict(),
- originalFiles: z4.array(z4.object({
- name: z4.string().min(1).max(200),
+ accessedAt: z5.string().datetime().optional(),
+ license: z5.object({ spdx: text4, url, attribution: z5.string().max(4000) }).strict(),
+ originalFiles: z5.array(z5.object({
+ name: z5.string().min(1).max(200),
sha256: materialLibraryHashSchema,
- bytes: z4.number().int().positive().max(1024 * 1024 * 1024)
+ bytes: z5.number().int().positive().max(1024 * 1024 * 1024)
}).strict()).max(20)
}).strict().superRefine((source, context) => {
if (source.kind === "external" && (!source.assetUrl || !source.originalFiles.length))
@@ -5194,22 +5297,22 @@ var init_material_library = __esm(() => {
if (new Set(source.originalFiles.map((file) => file.name)).size !== source.originalFiles.length)
context.addIssue({ code: "custom", message: "Duplicate original filename" });
});
- materialTransformSchema = z4.object({
+ materialTransformSchema = z5.object({
operation: text4,
tool: text4,
version: text4,
- parameters: z4.record(z4.string().max(100), z4.union([z4.string().max(2000), z4.number().finite(), z4.boolean()])).optional()
+ parameters: z5.record(z5.string().max(100), z5.union([z5.string().max(2000), z5.number().finite(), z5.boolean()])).optional()
}).strict();
- color2 = z4.number().int().min(0).max(16777215);
- count2 = z4.number().int().min(1).max(256);
+ color2 = z5.number().int().min(0).max(16777215);
+ count2 = z5.number().int().min(1).max(256);
layerCommon = {
- blend: z4.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
- opacity: z4.number().min(0).max(1).default(1)
+ blend: z5.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
+ opacity: z5.number().min(0).max(1).default(1)
};
- materialProceduralSpecSchema = z4.object({
- schemaVersion: z4.literal(2),
- size: z4.number().int().min(4).max(1024).default(256),
- usage: z4.enum([
+ materialProceduralSpecSchema = z5.object({
+ schemaVersion: z5.literal(2),
+ size: z5.number().int().min(4).max(1024).default(256),
+ usage: z5.enum([
"albedo",
"normal",
"roughness",
@@ -5218,90 +5321,90 @@ var init_material_library = __esm(() => {
"emissive",
"occlusion"
]).default("albedo"),
- name: z4.string().min(1).max(80).optional(),
- layers: z4.array(z4.discriminatedUnion("op", [
- z4.object({ op: z4.literal("solid"), color: color2, ...layerCommon }).strict(),
- z4.object({
- op: z4.literal("checker"),
+ name: z5.string().min(1).max(80).optional(),
+ layers: z5.array(z5.discriminatedUnion("op", [
+ z5.object({ op: z5.literal("solid"), color: color2, ...layerCommon }).strict(),
+ z5.object({
+ op: z5.literal("checker"),
colorA: color2,
colorB: color2,
squares: count2.default(8),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("stripes"),
+ z5.object({
+ op: z5.literal("stripes"),
colorA: color2,
colorB: color2,
count: count2.default(8),
- angleDeg: z4.number().min(-36000).max(36000).default(0),
+ angleDeg: z5.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("gradient"),
+ z5.object({
+ op: z5.literal("gradient"),
from: color2,
to: color2,
- angleDeg: z4.number().min(-36000).max(36000).default(0),
+ angleDeg: z5.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("bricks"),
+ z5.object({
+ op: z5.literal("bricks"),
brick: color2,
mortar: color2,
rows: count2.default(8),
cols: count2.default(4),
- mortarWidth: z4.number().min(0).max(1).default(0.06),
- stagger: z4.number().min(0).max(1).default(0.5),
+ mortarWidth: z5.number().min(0).max(1).default(0.06),
+ stagger: z5.number().min(0).max(1).default(0.5),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("noise"),
+ z5.object({
+ op: z5.literal("noise"),
colorA: color2,
colorB: color2,
scale: count2.default(8),
- octaves: z4.number().int().min(1).max(6).default(3),
- seed: z4.number().int().min(-2147483648).max(2147483647).default(0),
+ octaves: z5.number().int().min(1).max(6).default(3),
+ seed: z5.number().int().min(-2147483648).max(2147483647).default(0),
...layerCommon
}).strict()
])).min(1).max(8)
}).strict();
- materialNormalDerivationSchema = z4.object({
- kind: z4.literal("normal-from-height"),
- strength: z4.number().finite().positive().max(64)
+ materialNormalDerivationSchema = z5.object({
+ kind: z5.literal("normal-from-height"),
+ strength: z5.number().finite().positive().max(64)
}).strict();
- proceduralSchema = z4.object({
- compiler: z4.literal("kiln.procedural-texture.v2"),
+ proceduralSchema = z5.object({
+ compiler: z5.literal("kiln.procedural-texture.v2"),
spec: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional(),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text4 }).strict()
+ encoder: z5.object({ name: z5.literal("sharp"), version: text4 }).strict()
}).strict();
- parametersSchema = z4.object({
- baseColor: z4.number().int().min(0).max(16777215).optional(),
- roughness: z4.number().min(0).max(1).default(1),
- metalness: z4.number().min(0).max(1).default(0),
- emissive: z4.number().int().min(0).max(16777215).optional(),
- emissiveIntensity: z4.number().min(0).max(64).default(1),
- alphaMode: z4.enum(["opaque", "mask", "blend"]).default("opaque"),
- alphaCutoff: z4.number().min(0).max(1).default(0.5),
- doubleSided: z4.boolean().default(false)
+ parametersSchema = z5.object({
+ baseColor: z5.number().int().min(0).max(16777215).optional(),
+ roughness: z5.number().min(0).max(1).default(1),
+ metalness: z5.number().min(0).max(1).default(0),
+ emissive: z5.number().int().min(0).max(16777215).optional(),
+ emissiveIntensity: z5.number().min(0).max(64).default(1),
+ alphaMode: z5.enum(["opaque", "mask", "blend"]).default("opaque"),
+ alphaCutoff: z5.number().min(0).max(1).default(0.5),
+ doubleSided: z5.boolean().default(false)
}).strict();
- materialManifestSchema = z4.object({
- schemaVersion: z4.literal(1),
+ materialManifestSchema = z5.object({
+ schemaVersion: z5.literal(1),
materialId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
- name: z4.string().min(1).max(200),
- tags: z4.array(z4.string().min(1).max(80)).max(30),
- tileable: z4.boolean(),
- physicalSizeMeters: z4.object({
- width: z4.number().finite().positive().max(1e5),
- height: z4.number().finite().positive().max(1e5)
+ name: z5.string().min(1).max(200),
+ tags: z5.array(z5.string().min(1).max(80)).max(30),
+ tileable: z5.boolean(),
+ physicalSizeMeters: z5.object({
+ width: z5.number().finite().positive().max(1e5),
+ height: z5.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema,
- sources: z4.array(materialSourceSchema).min(1).max(20),
- maps: z4.array(z4.object({
- slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
- file: z4.enum([
+ sources: z5.array(materialSourceSchema).min(1).max(20),
+ maps: z5.array(z5.object({
+ slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
+ file: z5.enum([
"baseColor.png",
"normal.png",
"metallicRoughness.png",
@@ -5309,45 +5412,45 @@ var init_material_library = __esm(() => {
"occlusion.png"
]),
sha256: materialLibraryHashSchema,
- bytes: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
- width: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- height: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- usage: z4.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
- colorSpace: z4.enum(["srgb", "linear"]),
- normalConvention: z4.literal("opengl").optional(),
- channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ bytes: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
+ width: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ height: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ usage: z5.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ colorSpace: z5.enum(["srgb", "linear"]),
+ normalConvention: z5.literal("opengl").optional(),
+ channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
sourceId: materialLibraryIdSchema,
- originalFile: z4.string().min(1).max(200).optional(),
- transforms: z4.array(materialTransformSchema).max(30),
+ originalFile: z5.string().min(1).max(200).optional(),
+ transforms: z5.array(materialTransformSchema).max(30),
procedural: proceduralSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- proceduralMaterialDraftSchema = z4.object({
+ proceduralMaterialDraftSchema = z5.object({
materialId: materialLibraryIdSchema,
- name: z4.string().min(1).max(200),
- tags: z4.array(z4.string().min(1).max(80)).max(30).optional(),
- tileable: z4.boolean(),
- physicalSizeMeters: z4.object({
- width: z4.number().finite().positive().max(1e5),
- height: z4.number().finite().positive().max(1e5)
+ name: z5.string().min(1).max(200),
+ tags: z5.array(z5.string().min(1).max(80)).max(30).optional(),
+ tileable: z5.boolean(),
+ physicalSizeMeters: z5.object({
+ width: z5.number().finite().positive().max(1e5),
+ height: z5.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema.partial().optional(),
- sources: z4.array(materialSourceSchema).min(1).max(20),
- maps: z4.array(z4.object({
- slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
+ sources: z5.array(materialSourceSchema).min(1).max(20),
+ maps: z5.array(z5.object({
+ slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
sourceId: materialLibraryIdSchema,
- transforms: z4.array(materialTransformSchema).max(30),
- normalConvention: z4.literal("opengl").optional(),
- channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ transforms: z5.array(materialTransformSchema).max(30),
+ normalConvention: z5.literal("opengl").optional(),
+ channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
procedural: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialLibraryPayloadSchema = z4.object({
- schemaVersion: z4.literal(1),
- records: z4.array(z4.object({
+ materialLibraryPayloadSchema = z5.object({
+ schemaVersion: z5.literal(1),
+ records: z5.array(z5.object({
manifest: materialManifestSchema,
- files: z4.record(z4.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z4.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
+ files: z5.record(z5.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z5.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
}).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
authoringSchemas = makeMaterialAuthoringSchemas(materialProceduralSpecSchema);
@@ -5356,27 +5459,27 @@ var init_material_library = __esm(() => {
v3SpecSchema = authoringSchemas.canonicalProceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, true), afterShape);
atlasSpecSchema = authoringSchemas.canonicalTextureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, true), afterShape);
atlasManifestSchema = authoringSchemas.textureAtlasManifestV1Schema;
- materialMapPinSchema = z4.object({
+ materialMapPinSchema = z5.object({
resourceId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
sha256: materialLibraryHashSchema
}).strict().refine((pin) => pin.sha256 === pin.revisionId, "Material pin hash must match revision");
- materialRecipeV2Schema = z4.discriminatedUnion("kind", [
- z4.object({
- kind: z4.literal("procedural"),
- compilerId: z4.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
- spec: z4.union([materialProceduralSpecSchema, v3SpecSchema]),
+ materialRecipeV2Schema = z5.discriminatedUnion("kind", [
+ z5.object({
+ kind: z5.literal("procedural"),
+ compilerId: z5.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
+ spec: z5.union([materialProceduralSpecSchema, v3SpecSchema]),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text4 }).strict(),
+ encoder: z5.object({ name: z5.literal("sharp"), version: text4 }).strict(),
derive: materialNormalDerivationSchema.optional()
}).strict(),
- z4.object({
- kind: z4.literal("atlas"),
- compilerId: z4.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ z5.object({
+ kind: z5.literal("atlas"),
+ compilerId: z5.enum(TEXTURE_ATLAS_COMPILER_IDS),
spec: atlasSpecSchema,
manifest: atlasManifestSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text4 }).strict()
+ encoder: z5.object({ name: z5.literal("sharp"), version: text4 }).strict()
}).strict().superRefine((recipe, context) => {
try {
validateTextureAtlasManifestV1(recipe.manifest, recipe.spec);
@@ -5388,45 +5491,45 @@ var init_material_library = __esm(() => {
}, afterShape)
]);
materialManifestV2Schema = materialManifestSchema.omit({ schemaVersion: true, maps: true }).extend({
- schemaVersion: z4.literal(2),
- dependencies: z4.array(materialMapPinSchema).max(16),
- maps: z4.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z5.literal(2),
+ dependencies: z5.array(materialMapPinSchema).max(16),
+ maps: z5.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
pixelHash: materialLibraryHashSchema,
recipe: materialRecipeV2Schema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialManifestAnySchema = z4.discriminatedUnion("schemaVersion", [
+ materialManifestAnySchema = z5.discriminatedUnion("schemaVersion", [
materialManifestSchema,
materialManifestV2Schema
]);
materialLibraryPayloadV2Schema = materialLibraryPayloadSchema.extend({
- schemaVersion: z4.literal(2),
- records: z4.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
+ schemaVersion: z5.literal(2),
+ records: z5.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
- materialLibraryPayloadAnySchema = z4.discriminatedUnion("schemaVersion", [
+ materialLibraryPayloadAnySchema = z5.discriminatedUnion("schemaVersion", [
materialLibraryPayloadSchema,
materialLibraryPayloadV2Schema
]);
proceduralMaterialDraftV2Schema = proceduralMaterialDraftSchema.extend({
- schemaVersion: z4.literal(2),
- maps: z4.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z5.literal(2),
+ maps: z5.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
- procedural: z4.union([
+ procedural: z5.union([
materialProceduralSpecSchema,
authoringSchemas.proceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, false), afterShape)
]).optional(),
atlas: authoringSchemas.textureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, false), afterShape).optional()
}).strict().refine((map) => map.procedural !== undefined !== (map.atlas !== undefined), "Supply exactly one procedural or atlas recipe")).min(1).max(5)
}).strict();
- proceduralMaterialDraftAnySchema = z4.union([
+ proceduralMaterialDraftAnySchema = z5.union([
proceduralMaterialDraftSchema,
proceduralMaterialDraftV2Schema
]);
});
// src/assets.ts
-import { z as z5 } from "zod";
+import { z as z6 } from "zod";
import { zipSync, unzipSync } from "three/addons/libs/fflate.module.js";
function assetMaterialRootManifests(record) {
const roots = new Map;
@@ -5548,38 +5651,38 @@ var init_assets = __esm(() => {
init_background();
init_material_library();
ASSET_LIMIT = 64 * 1024 * 1024;
- assetIdSchema = z5.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- hash3 = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
- assetManifestSchema = z5.object({
- version: z5.literal("kiln.asset.v1"),
+ assetIdSchema = z6.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ hash3 = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
+ assetManifestSchema = z6.object({
+ version: z6.literal("kiln.asset.v1"),
assetId: assetIdSchema,
revisionId: assetIdSchema,
parentRevision: assetIdSchema.optional(),
- name: z5.string().min(1).max(200),
- tags: z5.array(z5.string().max(80)).max(30),
- createdAt: z5.string().datetime(),
- description: z5.string().max(4000).optional(),
- brief: z5.string().max(8000).optional(),
- attribution: z5.object({
- model: z5.string().max(200).optional(),
- harness: z5.string().max(200).optional(),
- author: z5.string().max(200).optional()
+ name: z6.string().min(1).max(200),
+ tags: z6.array(z6.string().max(80)).max(30),
+ createdAt: z6.string().datetime(),
+ description: z6.string().max(4000).optional(),
+ brief: z6.string().max(8000).optional(),
+ attribution: z6.object({
+ model: z6.string().max(200).optional(),
+ harness: z6.string().max(200).optional(),
+ author: z6.string().max(200).optional()
}).optional(),
- editable: z5.boolean(),
- files: z5.record(z5.string(), z5.object({ sha256: hash3, bytes: z5.number().int().nonnegative().max(ASSET_LIMIT) })),
- build: z5.object({
- engine: z5.string(),
- options: z5.record(z5.string(), z5.unknown()),
- warnings: z5.array(z5.string()),
- integration: z5.unknown().optional(),
- qa: z5.unknown().optional(),
- dependencies: z5.array(z5.unknown()).optional(),
- rebuild: z5.enum(["engine-required", "external-dependencies-required"])
+ editable: z6.boolean(),
+ files: z6.record(z6.string(), z6.object({ sha256: hash3, bytes: z6.number().int().nonnegative().max(ASSET_LIMIT) })),
+ build: z6.object({
+ engine: z6.string(),
+ options: z6.record(z6.string(), z6.unknown()),
+ warnings: z6.array(z6.string()),
+ integration: z6.unknown().optional(),
+ qa: z6.unknown().optional(),
+ dependencies: z6.array(z6.unknown()).optional(),
+ rebuild: z6.enum(["engine-required", "external-dependencies-required"])
}).optional(),
- preview: z5.object({
- fidelity: z5.unknown().optional(),
- error: z5.string().optional(),
- backdrop: z5.enum(BACKDROP_IDS).optional()
+ preview: z6.object({
+ fidelity: z6.unknown().optional(),
+ error: z6.string().optional(),
+ backdrop: z6.enum(BACKDROP_IDS).optional()
}).optional()
});
ASSET_MATERIAL_BYTES = 24 * 1024 * 1024;
@@ -9737,11 +9840,11 @@ var init_character = __esm(() => {
});
// src/projects.ts
-import { z as z9 } from "zod";
+import { z as z10 } from "zod";
function checkContent(data, ctx) {
const unique = (items, path) => {
if (new Set(items).size !== items.length)
- ctx.addIssue({ code: z9.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
+ ctx.addIssue({ code: z10.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
};
unique(data.inventory.map((v) => v.id), "inventory");
unique(data.references.map((v) => v.id), "references");
@@ -9757,20 +9860,20 @@ function checkContent(data, ctx) {
unique(item.references, `inventory.${item.id}.references`);
if (item.references.some((id) => !references.has(id)))
ctx.addIssue({
- code: z9.ZodIssueCode.custom,
+ code: z10.ZodIssueCode.custom,
path: ["inventory"],
message: "Unknown reference"
});
}
if (data.reviews.some((review) => !inventory.has(review.inventoryId)))
ctx.addIssue({
- code: z9.ZodIssueCode.custom,
+ code: z10.ZodIssueCode.custom,
path: ["reviews"],
message: "Unknown inventory item"
});
if (data.design.materialRoles.some((role) => role.resourceId && !resources.has(role.resourceId)))
ctx.addIssue({
- code: z9.ZodIssueCode.custom,
+ code: z10.ZodIssueCode.custom,
path: ["design"],
message: "Material role requires a locked resource"
});
@@ -9778,80 +9881,80 @@ function checkContent(data, ctx) {
var MAX_PROJECT_BYTES, projectIdSchema, projectRevisionIdSchema, hash4, text6, resourceId2, assetReference, projectDesignSchema, projectMaterialDependencySchema, materialDependenciesSchema, content, projectDraftSchema, projectPatchSchema, projectRevisionSchema, ProjectNotFoundError;
var init_projects = __esm(() => {
MAX_PROJECT_BYTES = 1024 * 1024;
- projectIdSchema = z9.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
- projectRevisionIdSchema = z9.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
- hash4 = z9.string().regex(/^sha256:[a-f0-9]{64}$/);
- text6 = z9.string().max(4000);
- resourceId2 = z9.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
- assetReference = z9.object({
+ projectIdSchema = z10.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
+ projectRevisionIdSchema = z10.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
+ hash4 = z10.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text6 = z10.string().max(4000);
+ resourceId2 = z10.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ assetReference = z10.object({
collectionId: projectIdSchema,
assetId: projectIdSchema,
revisionId: projectIdSchema
}).strict();
- projectDesignSchema = z9.object({
+ projectDesignSchema = z10.object({
style: text6.default(""),
- scale: z9.string().max(1000).default(""),
- palette: z9.array(z9.object({
- role: z9.string().min(1).max(100),
- color: z9.string().regex(/^#[a-fA-F0-9]{6}$/)
+ scale: z10.string().max(1000).default(""),
+ palette: z10.array(z10.object({
+ role: z10.string().min(1).max(100),
+ color: z10.string().regex(/^#[a-fA-F0-9]{6}$/)
}).strict()).max(64).default([]),
- materialRoles: z9.array(z9.object({
- role: z9.string().min(1).max(100),
+ materialRoles: z10.array(z10.object({
+ role: z10.string().min(1).max(100),
description: text6.default(""),
resourceId: resourceId2.optional()
}).strict()).max(128).default([]),
- conventions: z9.array(z9.string().max(1000)).max(100).default([]),
- exceptions: z9.array(z9.string().max(1000)).max(100).default([])
+ conventions: z10.array(z10.string().max(1000)).max(100).default([]),
+ exceptions: z10.array(z10.string().max(1000)).max(100).default([])
}).strict();
- projectMaterialDependencySchema = z9.object({
+ projectMaterialDependencySchema = z10.object({
resourceId: resourceId2,
- revisionId: z9.string().min(1).max(200),
+ revisionId: z10.string().min(1).max(200),
sha256: hash4,
- role: z9.string().max(100).optional()
+ role: z10.string().max(100).optional()
}).strict();
- materialDependenciesSchema = z9.array(projectMaterialDependencySchema).max(512);
+ materialDependenciesSchema = z10.array(projectMaterialDependencySchema).max(512);
content = {
- name: z9.string().trim().min(1).max(200),
- brief: z9.string().max(16000).default(""),
+ name: z10.string().trim().min(1).max(200),
+ brief: z10.string().max(16000).default(""),
design: projectDesignSchema.default(() => projectDesignSchema.parse({})),
- inventory: z9.array(z9.object({
+ inventory: z10.array(z10.object({
id: projectIdSchema,
- name: z9.string().trim().min(1).max(200),
- kind: z9.enum(["asset", "environment"]).default("asset"),
+ name: z10.string().trim().min(1).max(200),
+ kind: z10.enum(["asset", "environment"]).default("asset"),
brief: text6.default(""),
- references: z9.array(projectIdSchema).max(64).default([]),
+ references: z10.array(projectIdSchema).max(64).default([]),
asset: assetReference.optional()
}).strict()).max(1000).default([]),
- deliveryProfiles: z9.array(z9.object({
+ deliveryProfiles: z10.array(z10.object({
id: projectIdSchema,
- target: z9.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
+ target: z10.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
description: text6.default(""),
- performanceIntent: z9.string().max(1000).default(""),
- constraints: z9.array(z9.string().max(1000)).max(100).default([])
+ performanceIntent: z10.string().max(1000).default(""),
+ constraints: z10.array(z10.string().max(1000)).max(100).default([])
}).strict()).max(32).default([]),
materialDependencies: materialDependenciesSchema.default([]),
- references: z9.array(z9.object({
+ references: z10.array(z10.object({
id: projectIdSchema,
- title: z9.string().min(1).max(200),
- uri: z9.string().min(1).max(2048),
+ title: z10.string().min(1).max(200),
+ uri: z10.string().min(1).max(2048),
description: text6.default(""),
sha256: hash4.optional()
}).strict()).max(256).default([]),
- reviews: z9.array(z9.object({
+ reviews: z10.array(z10.object({
id: projectIdSchema,
inventoryId: projectIdSchema,
projectRevisionId: projectRevisionIdSchema,
asset: assetReference,
- reviewer: z9.string().trim().min(1).max(200),
- verdict: z9.enum(["comment", "changes-requested", "accepted"]),
+ reviewer: z10.string().trim().min(1).max(200),
+ verdict: z10.enum(["comment", "changes-requested", "accepted"]),
notes: text6
}).strict()).max(2000).default([])
};
- projectDraftSchema = z9.object({
+ projectDraftSchema = z10.object({
projectId: projectIdSchema.optional(),
...content
}).strict().superRefine(checkContent);
- projectPatchSchema = z9.object({
+ projectPatchSchema = z10.object({
name: content.name.optional(),
brief: content.brief.removeDefault().optional(),
design: content.design.removeDefault().optional(),
@@ -9861,12 +9964,12 @@ var init_projects = __esm(() => {
references: content.references.removeDefault().optional(),
reviews: content.reviews.removeDefault().optional()
}).strict();
- projectRevisionSchema = z9.object({
- version: z9.literal("kiln.project.v1"),
+ projectRevisionSchema = z10.object({
+ version: z10.literal("kiln.project.v1"),
projectId: projectIdSchema,
revisionId: projectRevisionIdSchema,
parentRevision: projectRevisionIdSchema.optional(),
- createdAt: z9.string().datetime(),
+ createdAt: z10.string().datetime(),
...content
}).strict().superRefine(checkContent);
ProjectNotFoundError = class ProjectNotFoundError extends Error {
@@ -9940,7 +10043,8 @@ function resolveRequirementsApplicability(requirements) {
bounds: ["units", "x", "y", "z"],
animation: ["clips"],
representation: ["precomputedTangents"],
- externalSupport: ["supports"]
+ externalSupport: ["supports"],
+ validation: ["version", "profileId", "mode", "checks"]
};
for (const [key, statement] of Object.entries(requirements.requirements)) {
if (statement?.state !== "requested")
@@ -10057,7 +10161,8 @@ var init_requirements_applicability = __esm(() => {
kernel: "connectivity"
},
{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },
- { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" }
+ { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },
+ { id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }
];
});
@@ -12553,16 +12658,16 @@ var init_material_library_node = __esm(() => {
});
// src/rebuild-options.ts
-import { z as z13 } from "zod";
+import { z as z14 } from "zod";
var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
- rebuildOptionsSchema = z13.object({
- indexPolicy: z13.enum(["indexed", "asBuilt"]).optional(),
- gltfExporter: z13.enum(["legacy", "three"]),
- geometryPolicy: z13.enum(["warn", "strict"]),
- optimize: z13.enum(["off", "auto", "palette", "full"]),
- optimizationPipeline: z13.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
- instance: z13.enum(["off", "auto", "on"])
+ rebuildOptionsSchema = z14.object({
+ indexPolicy: z14.enum(["indexed", "asBuilt"]).optional(),
+ gltfExporter: z14.enum(["legacy", "three"]),
+ geometryPolicy: z14.enum(["warn", "strict"]),
+ optimize: z14.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z14.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
+ instance: z14.enum(["off", "auto", "on"])
});
});
@@ -22689,319 +22794,1538 @@ var init_environment2 = __esm(() => {
];
});
-// src/qa/reference-comparison.ts
-function isEvidence(value) {
- if (typeof value !== "object" || value === null)
- return false;
- const candidate = value;
- return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";
-}
-function referenceComparisonFindings(evidence, profile) {
- if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)
- return [];
- const findings = [];
- if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {
- findings.push({
- code: "REF_SILHOUETTE_AGREEMENT",
- disposition: "observe",
- dimension: "promptAlignment",
- profile,
- message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,
- measurement: {
- name: "silhouetteIoU",
- actual: evidence.silhouetteIoU,
- threshold: SILHOUETTE_IOU_OBSERVE
- },
- repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."
- });
- }
- if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {
- findings.push({
- code: "REF_COLOR_AGREEMENT",
- disposition: "observe",
- dimension: "promptAlignment",
- profile,
- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,
- measurement: {
- name: "colorAgreement",
- actual: evidence.colorAgreement,
- threshold: COLOR_AGREEMENT_OBSERVE
- },
- repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."
- });
+// src/metrics.ts
+function primTris(prim) {
+ const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
+ switch (prim.getMode()) {
+ case 4:
+ return Math.floor(count / 3);
+ case 5:
+ case 6:
+ return Math.max(0, count - 2);
+ default:
+ return 0;
}
- return findings;
}
-var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;
-var init_reference_comparison = __esm(() => {
- init_registry();
- REFERENCE_COMPARISON_QA_RULE = Object.freeze({
- id: "REF_COMPARISON",
- profile: "reference.comparison",
- scope: { kind: "universal" },
- ruleClass: "heuristic",
- owner: KILN_ENGINE_QA_OWNER,
- defaultMode: "observe",
- evaluate(context) {
- const evidence = context.derivedEvidence?.["referenceComparison"];
- if (!isEvidence(evidence))
- return [];
- return referenceComparisonFindings(evidence, "reference.comparison");
- }
- });
-});
-
-// src/qa/run.ts
-function gltfReportFindings(report, profile) {
- return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
- code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),
- disposition: issue.severity === 0 ? "block" : "warn",
- dimension: "exportIntegrity",
- profile,
- message: issue.message,
- ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}
- }));
+function instanceCopies(node) {
+ const ext = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!ext)
+ return 1;
+ return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
}
-function isExpectedKtx2ValidatorLimitation(report, issue) {
- const required = report.info?.["extensionsRequired"];
- if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))
- return false;
- if (issue.code === "VALUE_NOT_IN_LIST") {
- return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";
- }
- return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";
+function isHiddenGltfNode(node) {
+ const visibility = node.getExtension("KHR_node_visibility");
+ return visibility?.getVisible?.() === false;
}
-function qaPolicyFromEnv(env = process.env) {
- const mode = env["KILN_QA_MODE"];
- return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};
+function nodeTriangles(node) {
+ return subtreeTriangles(node, false);
}
-function qaBlockingEnabled(env = process.env) {
- const mode = env["KILN_QA_MODE"];
- return mode !== "observe" && mode !== "off";
+function drawnNodeTriangles(node) {
+ return subtreeTriangles(node, true);
}
-var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;
-var init_run = __esm(() => {
- init_material();
- init_architecture();
- init_character2();
- init_character_advisory();
- init_vehicle2();
- init_vegetation();
- init_prop();
- init_part_connectivity();
- init_reference_comparison();
- init_self_intersection();
- init_sweep();
- init_environment2();
- init_breadth2();
- init_breadth_evidence();
- init_registry();
- init_types();
- init_universal();
- DETERMINISTIC_QA_REGISTRY = new QaRegistry([
- ...UNIVERSAL_QA_RULES,
- MATERIAL_QA_RULE,
- ...ARCHITECTURE_QA_RULES,
- CHARACTER_QA_RULE,
- CHARACTER_ADVISORY_QA_RULE,
- ...VEHICLE_QA_RULES,
- ...VEGETATION_QA_RULES,
- ...PROP_QA_RULES,
- ...ENVIRONMENT_QA_RULES,
- ...W7_BREADTH_QA_RULES,
- SELF_INTERSECTION_QA_RULE,
- SWEEP_QA_RULE,
- PART_CONNECTIVITY_QA_RULE,
- REFERENCE_COMPARISON_QA_RULE
- ]);
- AssetQaBlockedError = class AssetQaBlockedError extends Error {
- report;
- stage;
- gltfValidation;
- constructor(report, stage, gltfValidation) {
- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");
- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.affected ? ` AFFECTED: ${JSON.stringify(finding.affected)}` : ""}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);
- const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";
- super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);
- this.name = "AssetQaBlockedError";
- this.report = report;
- this.stage = stage;
- this.gltfValidation = gltfValidation;
+function subtreeTriangles(node, drawn) {
+ if (drawn && isHiddenGltfNode(node))
+ return 0;
+ let triangles = 0;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ for (const prim of mesh.listPrimitives())
+ triangles += primTris(prim) * copies;
+ }
+ for (const child of node.listChildren())
+ triangles += subtreeTriangles(child, drawn);
+ return triangles;
+}
+function collectGlbMetrics(doc, triangles) {
+ const root = doc.getRoot();
+ const geomSet = new Set;
+ const matSet = new Set;
+ let drawCalls = 0;
+ let derivedTris = 0;
+ let meshNodes = 0;
+ let meshInstances = 0;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ meshNodes += 1;
+ meshInstances += copies;
+ for (const prim of mesh.listPrimitives()) {
+ drawCalls += 1;
+ geomSet.add(prim);
+ derivedTris += primTris(prim) * copies;
+ const mat = prim.getMaterial();
+ if (mat)
+ matSet.add(mat);
+ }
}
+ for (const child of node.listChildren())
+ visit(child);
};
-});
-
-// src/qa/requirements-run.ts
-import { Object3D as Object3D15 } from "three";
-function sceneDecisions(context, policy) {
- const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));
- return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);
-}
-async function collectRequirementsSceneEvidence(context, scene, policy = {}) {
- if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))
- return {};
- try {
- return { partPenetration: await analyzePartPenetration(scene) };
- } catch {
- return { partPenetrationFailed: true };
+ for (const scene of root.listScenes()) {
+ for (const node of scene.listChildren())
+ visit(node);
}
+ const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
+ return {
+ uniqueGeometries: geomSet.size,
+ uniqueMaterials: matSet.size,
+ meshNodes,
+ meshInstances,
+ drawCalls,
+ textureCount: root.listTextures().length,
+ skinned: root.listSkins().length > 0,
+ transparentMaterials,
+ triangles: triangles ?? derivedTris
+ };
}
-function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {
- const needs = context.requirements.requirements;
- const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];
- const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;
- const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;
- const requiredClips = [
- ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
];
- const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;
- const findings = [];
- const decisions = sceneDecisions(context, policy);
- const geometryMetrics = {};
- const mobilityInput = {
- scene,
- mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];
- const executedRules = [];
- const rigInput = {
- scene,
- clips,
- rig,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const foliageInput = {
- scene,
- foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,
- materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;
- const scope = context.requirements.scope;
- const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;
- const effectsInput = {
- effects,
- derivedEvidence: {
- source: "engine-scene-analysis",
- ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
}
+ for (const child of node.listChildren())
+ visit(child);
};
- const spatialInput = {
- scene,
- tileable: needs.tiling?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.tileable === true,
- navigable: needs.navigation?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.navigable === true,
- navigation: needs.navigation?.state === "requested" ? needs.navigation.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
- };
- const spatialFindings = decisions.some((d) => d.ruleId.startsWith("ENVIRONMENT_") && d.mode !== "off") ? [
- ...inspectPlacementSockets(spatialInput),
- ...inspectTileEdges(spatialInput),
- ...inspectNavigationClearance(spatialInput),
- ...inspectSpatialSupport(spatialInput)
- ] : [];
- const structureFindings = needs.structure?.state === "requested" && decisions.some((d) => d.ruleId.startsWith("ARCHITECTURE_") && d.mode !== "off") ? inspectStructure({
- scene,
- structure: needs.structure.value,
- opening: needs.opening?.state === "requested"
- }) : [];
- for (const decision of decisions) {
- if (decision.mode === "off")
- continue;
- if (decision.ruleId === SELF_INTERSECTION_QA_RULE.id) {
- const volume = evidence.partPenetration;
- if (volume) {
- const acknowledged = volume.acknowledged?.length ?? 0;
- const partial = volume.truncated || volume.skipped.length > 0 || acknowledged > 0;
- if (!partial)
- executedRules.push(decision.ruleId);
- findings.push(...inspectPartPenetration(volume));
- Object.assign(geometryMetrics, {
- partVolumeCoverage: partial ? "partial" : "complete-static-pairs",
- partVolumeScope: "Visible static closed mesh pairs, except alternates on different LOD levels; excludes intra-mesh intersections, motion, open surfaces and usable passage space. Positive overlap may be intentional.",
- partVolumeEligibleParts: volume.partsAnalyzed,
- partVolumeCandidatePairs: volume.candidatePairs,
- partVolumeCandidatesLowerBound: volume.broadPhaseTruncated === true,
- partVolumePairsTested: volume.pairsTested,
- partVolumeUnmeasurablePairs: volume.pairsUnmeasurable,
- partVolumePairsNotReached: volume.pairsNotReached,
- partVolumeLodAlternatePairs: volume.pairsLodAlternates,
- partVolumeSkipped: volume.skipped.length,
- ...acknowledged > 0 ? {
- partVolumeAcknowledgedParts: acknowledged,
- partVolumeAcknowledgedPairs: volume.pairsUnmeasurableAcknowledged ?? 0
- } : {}
- });
- } else if (evidence.partPenetrationFailed) {
- findings.push({
- code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",
- disposition: "observe",
- dimension: "visualQuality",
- profile: "geometry.selfIntersection",
- message: "Part-volume analysis could not complete. Overlap and clearance remain unmeasured."
- });
- geometryMetrics.partVolumeCoverage = "unavailable";
- }
- continue;
- }
- if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
- continue;
- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
- continue;
- executedRules.push(decision.ruleId);
- if (decision.ruleId === PROP_EXACT_QA_RULE.id) {
- const measured = [
- ...needs.articulation?.state === "requested" ? inspectArticulation({ scene }) : [],
- ...needs.opening?.state === "requested" ? inspectContainerOpening({ scene }) : []
- ];
- for (const finding of measured)
- findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
continue;
- }
- const measured = decision.ruleId === SWEEP_QA_RULE.id ? inspectSweepGeometry(scene) : decision.ruleId === PART_CONNECTIVITY_QA_RULE.id ? inspectPartConnectivity(scene, needs.externalSupport?.state === "requested" ? needs.externalSupport.value.supports : undefined) : decision.ruleId === ASSET_SCOPE_QA_RULE.id && scope?.state === "requested" ? inspectAssetScope({
- profile: "asset.requirements.v1",
- scope: { schemaVersion: 1, scope: scope.value, explicit: true },
- derivedEvidence: { source: "engine-scene-analysis", assetScope: scopeObservation }
- }) : decision.ruleId === "CHARACTER_PROFILE" ? inspectRig(rigInput) : decision.ruleId === "CHARACTER_ADVISORY_PROFILE" ? inspectRigAdvisory(rigInput) : decision.ruleId === "VEGETATION_CONTACT_PROFILE" ? inspectFoliageContact(foliageInput) : decision.ruleId === "VEGETATION_ADVISORY_PROFILE" ? inspectFoliageAdvisory(foliageInput) : decision.ruleId === MATERIAL_QA_RULE.id ? inspectPortableSceneMaterials(scene, tangents) : decision.ruleId === "VFX_EXACT_PROFILE" ? inspectEffectsExact(effectsInput) : decision.ruleId === "VFX_ADVISORY_PROFILE" ? inspectEffectsAdvisory(effectsInput) : decision.ruleId === "ARCHITECTURE_PROFILE" ? structureFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ARCHITECTURE_ADVISORY_PROFILE" ? structureFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "ENVIRONMENT_EXACT_PROFILE" ? spatialFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ENVIRONMENT_ADVISORY_PROFILE" ? spatialFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_PROFILE" ? mobilityFindings.filter((f) => f.disposition === "block") : decision.ruleId === "VEHICLE_ADVISORY_PROFILE" ? mobilityFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_W6_ADVISORY_PROFILE" ? inspectMobilityAdvisory(mobilityInput) : decision.ruleId === PROP_ADVISORY_QA_RULE.id ? inspectPlacement({
- scene,
- bounds: needs.bounds?.state === "requested" ? needs.bounds.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
- }) : UNIVERSAL_QA_KERNELS[decision.ruleId]({
- scene,
- clips,
- requiredParts: parts,
- animation: { clips: requiredClips }
- });
- for (const finding of measured)
- findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
}
- return createRequirementsQaReport(context, {
- findings,
- executedRules,
- modes: Object.fromEntries(decisions.map((x) => [x.ruleId, x.mode])),
- metrics: {
- ...Object.keys(geometryMetrics).length ? { visualQuality: geometryMetrics } : {},
- ...scopeObservation ? {
- promptAlignment: {
- scopeTopLevelAssetRoots: scopeObservation.topLevelAssetRoots,
- scopeReusableMemberCount: scopeObservation.reusableMemberCount,
- scopeDressingSignalCount: scopeObservation.sceneDressingRoles.length
- }
- } : {}
- },
- ...scopeObservation ? {
- evaluatedDimensions: ["exportIntegrity", "requirementReadiness", "promptAlignment"]
- } : {}
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
});
}
-function appendRequirementsQa(context, report, findings, metrics = {}) {
- const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
- const merged = { ...priorMetrics };
- for (const [dimension, value] of Object.entries(metrics ?? {}))
- merged[dimension] = { ...priorMetrics[dimension], ...value };
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
+function gradeInstanceability(metrics, opts = {}) {
+ const m = metrics;
+ const band = materialBand(m.uniqueMaterials);
+ let grade = band.grade;
+ const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
+ const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
+ const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
+ const drivers = [];
+ const also = [];
+ if ((grade === "A" || grade === "B") && (transparency || textures)) {
+ grade = "C";
+ if (transparency)
+ drivers.push(`${transparency} (lowers A/B to C)`);
+ if (textures)
+ drivers.push(`${textures} (over 4 lowers A/B to C)`);
+ also.push(materials);
+ } else {
+ drivers.push(materials);
+ if (transparency)
+ also.push(`${transparency} (lowers only A/B to C)`);
+ if (textures)
+ also.push(`${textures} (over 4 lowers only A/B to C)`);
+ }
+ also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
+ if (m.skinned)
+ also.push("skinned (clone-rendered, not penalized)");
+ const setBy = drivers.join(" and ");
+ const reasons = [
+ `grade ${grade} set by ${setBy}`,
+ `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
+ ];
+ if (transparency)
+ reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
+ if (textures)
+ reasons.push(`${m.textureCount} textures (consider atlasing)`);
+ if (m.skinned)
+ reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
+ if (opts.category)
+ reasons.push(`category: ${opts.category}`);
+ const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
+}
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
+var init_metrics = __esm(() => {
+ MATERIAL_GRADE_BANDS = [
+ { grade: "A", max: 1, range: "0-1" },
+ { grade: "B", max: 3, range: "2-3" },
+ { grade: "C", max: 6, range: "4-6" },
+ { grade: "D", max: 12, range: "7-12" },
+ { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
+ ];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
+});
+
+// src/written-nodes.ts
+function exportedRoot(doc, purpose) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ const top = scene?.listChildren() ?? [];
+ if (top.length !== 1)
+ throw new Error(`${purpose} expects the exporter to write one root node.`);
+ return top[0];
+}
+function writtenNodeResolver(root, doc, purpose) {
+ const top = exportedRoot(doc, purpose);
+ return (node) => {
+ const path = [];
+ for (let current = node;current !== root; current = current.parent) {
+ if (!current.parent)
+ throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
+ path.unshift(current.parent.children.indexOf(current));
+ }
+ let target = top;
+ for (const index of path)
+ target = target?.listChildren()[index];
+ if (!target || (target.getName() || "") !== (node.name || ""))
+ throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
+ return target;
+ };
+}
+
+// src/node-visibility.ts
+import { KHRNodeVisibility } from "@gltf-transform/extensions";
+import * as THREE25 from "three";
+function applyNodeVisibility(root, doc) {
+ const hidden = [];
+ root.traverse((node) => {
+ if (node.visible === false)
+ hidden.push(node);
+ });
+ if (hidden.length === 0)
+ return;
+ const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
+ const extension = doc.createExtension(KHRNodeVisibility);
+ for (const node of written)
+ node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
+}
+function summarizeHiddenNodes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const found = [];
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment2(name, occurrence)}`;
+ if (isHiddenGltfNode(node))
+ found.push({ path, name, triangles: nodeTriangles(node) });
+ else
+ visit(node.listChildren(), path);
+ }
+ };
+ visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
+ return found;
+}
+function drawnSceneBounds(scene) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const base = new THREE25.Matrix4().fromArray(node.getWorldMatrix());
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ const matrices = [];
+ for (let i = 0;i < countInstances; i++) {
+ const t = translation?.getElement(i, []) ?? [0, 0, 0];
+ const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
+ const s = scale?.getElement(i, []) ?? [1, 1, 1];
+ const localMatrix = new THREE25.Matrix4().compose(new THREE25.Vector3().fromArray(t), new THREE25.Quaternion().fromArray(r), new THREE25.Vector3().fromArray(s));
+ matrices.push(base.clone().multiply(localMatrix).toArray());
+ }
+ const local = [0, 0, 0];
+ for (const primitive of mesh.listPrimitives()) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const m of matrices)
+ for (let i = 0;i < count; i++) {
+ position.getElement(indices ? indices.getScalar(i) : i, local);
+ const [x, y, z] = local;
+ const world = [
+ m[0] * x + m[4] * y + m[8] * z + m[12],
+ m[1] * x + m[5] * y + m[9] * z + m[13],
+ m[2] * x + m[6] * y + m[10] * z + m[14]
+ ];
+ for (let k = 0;k < 3; k++) {
+ if (world[k] < min[k])
+ min[k] = world[k];
+ if (world[k] > max[k])
+ max[k] = world[k];
+ }
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const node of scene.listChildren())
+ visit(node);
+ return { min, max };
+}
+var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var init_node_visibility = __esm(() => {
+ init_metrics();
+});
+
+// src/delivery-inspect.ts
+import * as THREE26 from "three";
+import { PropertyType as PropertyType2 } from "@gltf-transform/core";
+function decompose(matrix) {
+ const translation = new THREE26.Vector3;
+ const rotation = new THREE26.Quaternion;
+ const scale = new THREE26.Vector3;
+ matrix.decompose(translation, rotation, scale);
+ const clean = (value) => Object.is(value, -0) ? 0 : value;
+ return {
+ translation: translation.toArray().map(clean),
+ rotation: rotation.toArray().map(clean),
+ scale: scale.toArray().map(clean)
+ };
+}
+function drawnTriangles(visited) {
+ const values = [];
+ const local = [0, 0, 0];
+ const point = new THREE26.Vector3;
+ for (const { node, roles, hidden } of visited) {
+ const mesh = node.getMesh();
+ if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
+ continue;
+ const base = worldMatrix(node);
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ const matrices = [];
+ for (let i = 0;i < copies; i++) {
+ const instance = new THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE26.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE26.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
+ matrices.push(base.clone().multiply(instance));
+ }
+ for (const primitive of mesh.listPrimitives()) {
+ if (primitive.getMode() !== 4)
+ continue;
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const matrix of matrices)
+ for (let i = 0;i + 2 < count; i += 3)
+ for (let k = 0;k < 3; k++) {
+ position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
+ point.fromArray(local).applyMatrix4(matrix);
+ values.push(point.x, point.y, point.z);
+ }
+ }
+ }
+ return Float64Array.from(values);
+}
+function triangleOverlapsBox(a, b, c, h, tolerance) {
+ const verts = [a, b, c];
+ const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
+ for (let axis = 0;axis < 3; axis++) {
+ const values = verts.map((v) => v.getComponent(axis));
+ if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
+ return false;
+ }
+ const e = [
+ new THREE26.Vector3().subVectors(b, a),
+ new THREE26.Vector3().subVectors(c, b),
+ new THREE26.Vector3().subVectors(a, c)
+ ];
+ const normal = new THREE26.Vector3().crossVectors(e[0], e[1]);
+ const axes = [normal];
+ const units = [
+ new THREE26.Vector3(1, 0, 0),
+ new THREE26.Vector3(0, 1, 0),
+ new THREE26.Vector3(0, 0, 1)
+ ];
+ for (const unit of units)
+ for (const edge of e)
+ axes.push(new THREE26.Vector3().crossVectors(unit, edge));
+ for (const axis of axes) {
+ if (axis.lengthSq() < 0.000000000000000000000001)
+ continue;
+ const projections = verts.map((v) => v.dot(axis));
+ const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
+ if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
+ return false;
+ }
+ return true;
+}
+function closestPointOnTriangle(p, a, b, c) {
+ const ab = new THREE26.Vector3().subVectors(b, a);
+ const ac = new THREE26.Vector3().subVectors(c, a);
+ const ap = new THREE26.Vector3().subVectors(p, a);
+ const d1 = ab.dot(ap);
+ const d2 = ac.dot(ap);
+ if (d1 <= 0 && d2 <= 0)
+ return a.clone();
+ const bp = new THREE26.Vector3().subVectors(p, b);
+ const d3 = ab.dot(bp);
+ const d4 = ac.dot(bp);
+ if (d3 >= 0 && d4 <= d3)
+ return b.clone();
+ const vc = d1 * d4 - d3 * d2;
+ if (vc <= 0 && d1 >= 0 && d3 <= 0)
+ return a.clone().addScaledVector(ab, d1 / (d1 - d3));
+ const cp = new THREE26.Vector3().subVectors(p, c);
+ const d5 = ab.dot(cp);
+ const d6 = ac.dot(cp);
+ if (d6 >= 0 && d5 <= d6)
+ return c.clone();
+ const vb = d5 * d2 - d1 * d6;
+ if (vb <= 0 && d2 >= 0 && d6 <= 0)
+ return a.clone().addScaledVector(ac, d2 / (d2 - d6));
+ const va = d3 * d6 - d5 * d4;
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
+ return b.clone().addScaledVector(new THREE26.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
+ const denominator = 1 / (va + vb + vc);
+ return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
+}
+function segmentSegmentDistanceSq(p1, q1, p2, q2) {
+ const d1 = new THREE26.Vector3().subVectors(q1, p1);
+ const d2 = new THREE26.Vector3().subVectors(q2, p2);
+ const r = new THREE26.Vector3().subVectors(p1, p2);
+ const a = d1.dot(d1);
+ const e = d2.dot(d2);
+ const f = d2.dot(r);
+ let s = 0;
+ let t = 0;
+ if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
+ return r.lengthSq();
+ if (a <= 0.000000000000000000000001)
+ t = THREE26.MathUtils.clamp(f / e, 0, 1);
+ else {
+ const c = d1.dot(r);
+ if (e <= 0.000000000000000000000001)
+ s = THREE26.MathUtils.clamp(-c / a, 0, 1);
+ else {
+ const b = d1.dot(d2);
+ const denominator = a * e - b * b;
+ s = denominator !== 0 ? THREE26.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
+ t = (b * s + f) / e;
+ if (t < 0) {
+ t = 0;
+ s = THREE26.MathUtils.clamp(-c / a, 0, 1);
+ } else if (t > 1) {
+ t = 1;
+ s = THREE26.MathUtils.clamp((b - c) / a, 0, 1);
+ }
+ }
+ }
+ const c1 = p1.clone().addScaledVector(d1, s);
+ const c2 = p2.clone().addScaledVector(d2, t);
+ return c1.distanceToSquared(c2);
+}
+function segmentCrossesTriangle(p, q, a, b, c) {
+ const hit = new THREE26.Vector3;
+ const ray = new THREE26.Ray(p, new THREE26.Vector3().subVectors(q, p));
+ const length = ray.direction.length();
+ if (length === 0)
+ return false;
+ ray.direction.divideScalar(length);
+ return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
+}
+function triangleTouchesCapsule(a, b, c, p, q, radius) {
+ const r2 = radius * radius;
+ if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
+ return true;
+ if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
+ return true;
+ for (const [s, e] of [
+ [a, b],
+ [b, c],
+ [c, a]
+ ])
+ if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
+ return true;
+ return segmentCrossesTriangle(p, q, a, b, c);
+}
+function deliveryNodePaths(doc) {
+ const paths = new Map;
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return paths;
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ paths.set(node, path);
+ visit(node.listChildren(), path);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ return paths;
+}
+function summarizeVertexAttributes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const groups = new Map;
+ const order = [];
+ const record = (node, path) => {
+ const mesh = node.getMesh();
+ if (!mesh)
+ return;
+ const bake = mesh.getExtras().kilnSurfaceBakeV1;
+ const names = new Set;
+ for (const primitive of mesh.listPrimitives())
+ for (const semantic of primitive.listSemantics())
+ if (semantic.startsWith("_"))
+ names.add(semantic);
+ for (const name of names) {
+ const params = bake && typeof bake === "object" ? bake[name] : undefined;
+ const key = `${name}\x00${JSON.stringify(params ?? null)}`;
+ let group = groups.get(key);
+ if (!group) {
+ group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
+ groups.set(key, group);
+ order.push(key);
+ }
+ if (!group.meshes.includes(path))
+ group.meshes.push(path);
+ }
+ };
+ const visit = (siblings, parentPath) => {
+ siblings.forEach((node, index) => {
+ const at = (name) => {
+ let occurrence = 0;
+ for (let i = 0;i < index; i++)
+ if (siblings[i].getName() === name)
+ occurrence++;
+ return `${parentPath}${segment3(name, occurrence)}`;
+ };
+ const path = at(node.getName());
+ record(node, path);
+ visit(node.listChildren(), path);
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
+ for (const level of lower) {
+ const levelPath = at(level.getName());
+ record(level, levelPath);
+ visit(level.listChildren(), levelPath);
+ }
+ });
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
+ return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
+}
+function inspectDelivery(doc) {
+ const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return summary;
+ const visited = [];
+ const visit = (siblings, parentPath, hidden, module) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
+ const nodeHidden = hidden || isHiddenGltfNode(node);
+ const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
+ visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
+ visit(node.listChildren(), path, nodeHidden, nodeModule);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0), false, undefined);
+ const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
+ const { min, max } = drawnSceneBounds(scene);
+ const bounds = new THREE26.Box3(new THREE26.Vector3(...min), new THREE26.Vector3(...max));
+ const finiteBounds = [...min, ...max].every(Number.isFinite);
+ const diagonal = finiteBounds ? bounds.getSize(new THREE26.Vector3).length() : 0;
+ const tolerance = Math.max(0.0001, diagonal * 0.0001);
+ const colliderNodes = [];
+ for (const entry of visited) {
+ const { node, path, roles } = entry;
+ for (const role of roles) {
+ const matrix = worldMatrix(node);
+ const transform = decompose(matrix);
+ for (const shape of ["box", "capsule", "hull"]) {
+ const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
+ if (id === undefined)
+ continue;
+ const scale = transform.scale;
+ const record = {
+ role,
+ id,
+ path,
+ name: node.getName(),
+ transform,
+ shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
+ kind: "hull",
+ vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
+ }
+ };
+ summary.colliders.push(record);
+ colliderNodes.push({ visit: entry, record });
+ }
+ const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
+ if (anchorTail !== undefined) {
+ const [kind, ...rest] = anchorTail.split(".");
+ summary.anchors.push({
+ role,
+ kind,
+ id: rest.join("."),
+ path,
+ name: node.getName(),
+ transform
+ });
+ }
+ const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
+ if (portId !== undefined)
+ summary.ports.push({
+ role,
+ id: portId,
+ path,
+ name: node.getName(),
+ ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
+ transform
+ });
+ if (role === KILN_SEMANTIC_ROLES.kitModule) {
+ const extras = node.getExtras()[KILN_KIT_KEY];
+ let spec;
+ try {
+ const { schemaVersion, ...rest } = extras ?? {};
+ spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
+ } catch {
+ spec = undefined;
+ }
+ if (!spec)
+ finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
+ else if (summary.kit)
+ finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
+ else
+ summary.kit = {
+ role,
+ path,
+ name: node.getName(),
+ footprint: spec.footprint,
+ height: spec.height,
+ snapAxis: spec.snapAxis,
+ origin: spec.origin,
+ transform
+ };
+ }
+ }
+ }
+ const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
+ const triangleCount = triangles.length / 9;
+ let overlapTests = 0;
+ const a = new THREE26.Vector3;
+ const b = new THREE26.Vector3;
+ const c = new THREE26.Vector3;
+ for (const { visit: entry, record } of colliderNodes) {
+ if (!entry.hidden)
+ finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
+ const matrix = worldMatrix(entry.node);
+ const proxyBounds = new THREE26.Box3;
+ const mesh = entry.node.getMesh();
+ const local = [0, 0, 0];
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const position = primitive.getAttribute("POSITION");
+ for (let i = 0;i < (position?.getCount() ?? 0); i++)
+ proxyBounds.expandByPoint(new THREE26.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
+ }
+ if (proxyBounds.isEmpty())
+ proxyBounds.expandByPoint(new THREE26.Vector3().setFromMatrixPosition(matrix));
+ const expanded = bounds.clone().expandByScalar(tolerance);
+ if (!finiteBounds || !expanded.containsBox(proxyBounds))
+ finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
+ if (record.shape.kind === "hull")
+ continue;
+ if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
+ finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
+ continue;
+ }
+ overlapTests += triangleCount;
+ const toLocal = new THREE26.Matrix4;
+ let touches = false;
+ if (record.shape.kind === "box") {
+ toLocal.copy(matrix).invert();
+ const half = new THREE26.Vector3(0.5, 0.5, 0.5);
+ const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
+ }
+ } else {
+ const { translation, rotation } = record.transform;
+ toLocal.compose(new THREE26.Vector3(...translation), new THREE26.Quaternion(...rotation), new THREE26.Vector3(1, 1, 1)).invert();
+ const { radius, height } = record.shape;
+ const p = new THREE26.Vector3(0, -height / 2 + radius, 0);
+ const q = new THREE26.Vector3(0, height / 2 - radius, 0);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
+ }
+ }
+ if (!touches)
+ finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
+ }
+ for (const record of summary.ports) {
+ const entry = visited.find((item) => item.path === record.path);
+ const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
+ const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
+ if (!spec) {
+ finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
+ continue;
+ }
+ const point = new THREE26.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
+ const [width, depth] = spec.footprint;
+ const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
+ const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
+ if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
+ finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
+ }
+ for (const record of summary.anchors) {
+ const entry = visited.find((item) => item.path === record.path);
+ if (entry.node.listChildren().length > 0)
+ finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
+ }
+ return summary;
+}
+var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE26.Matrix4().fromArray(node.getWorldMatrix());
+var init_delivery_inspect = __esm(() => {
+ init_gltf_io();
+ init_semantic();
+ init_delivery();
+ init_metrics();
+ init_node_visibility();
+});
+
+// src/qa/validation-profile.ts
+function matchValidationPattern(pattern, name) {
+ const p = Array.from(pattern);
+ const s = Array.from(name);
+ let pi = 0;
+ let si = 0;
+ let star = -1;
+ let resume = 0;
+ while (si < s.length) {
+ if (pi < p.length && (p[pi] === "?" || p[pi] !== "*" && p[pi] === s[si])) {
+ pi++;
+ si++;
+ } else if (pi < p.length && p[pi] === "*") {
+ star = pi++;
+ resume = si;
+ } else if (star >= 0) {
+ pi = star + 1;
+ si = ++resume;
+ } else
+ return false;
+ }
+ while (pi < p.length && p[pi] === "*")
+ pi++;
+ return pi === p.length;
+}
+function component(accessor, index, slot, element) {
+ accessor.getElement(index, element);
+ return element[slot];
+}
+function evaluateValidationProfileDocument(profile, doc, options = {}) {
+ const disposition = profile.mode === "enforce" ? "block" : "warn";
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ const budget = options.maxAttributeReads ?? MAX_VALIDATION_ATTRIBUTE_READS;
+ const paths = deliveryNodePaths(doc);
+ const candidates = [...paths.entries()].filter(([node]) => node.getMesh() !== null);
+ const findings = [];
+ let complete = true;
+ let reads = 0;
+ let matchedNodes = 0;
+ let notMeasured = 0;
+ for (const check of profile.checks) {
+ const kept = new Map;
+ const omitted = new Map;
+ const push = (code, assertion, message, measurement, affected, findingDisposition) => findings.push({
+ code,
+ disposition: findingDisposition,
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation check ${check.id}: ${message}`,
+ ...affected ? { affected } : {},
+ measurement: {
+ name: `checks.${check.id}.${assertion}`,
+ ...measurement
+ }
+ });
+ const report = (code, assertion, message, { affected, measurement }, findingDisposition = disposition) => {
+ const used = kept.get(code) ?? 0;
+ if (used < MAX_VALIDATION_FINDINGS_PER_CODE) {
+ kept.set(code, used + 1);
+ push(code, assertion, message, measurement, affected, findingDisposition);
+ return;
+ }
+ const entry = omitted.get(code) ?? {
+ count: 0,
+ assertion,
+ disposition: findingDisposition
+ };
+ entry.count++;
+ omitted.set(code, entry);
+ };
+ const matched = candidates.filter(([node]) => check.select.names.some((pattern) => matchValidationPattern(pattern, node.getName())));
+ const minMatches = check.select.minMatches ?? 1;
+ if (matched.length < minMatches || check.select.maxMatches !== undefined && matched.length > check.select.maxMatches) {
+ const expected = check.select.maxMatches === undefined ? `>= ${minMatches}` : minMatches === check.select.maxMatches ? `${minMatches}` : `${minMatches}..${check.select.maxMatches}`;
+ report("HOST_VALIDATION_SELECTOR_UNMATCHED", "select", `${matched.length} default-scene mesh node(s) match ${JSON.stringify(check.select.names)}; the host expects ${expected}. Node names come from the final GLB.`, { measurement: { actual: matched.length, expected } });
+ }
+ const measured = matched.slice(0, MAX_VALIDATION_MATCHES);
+ if (matched.length > measured.length) {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "select", `${matched.length - measured.length} matched node(s) beyond the ${MAX_VALIDATION_MATCHES}-node limit were not measured.`, {
+ measurement: {
+ actual: matched.length,
+ threshold: MAX_VALIDATION_MATCHES,
+ breakdown: { nodesNotMeasured: matched.length - measured.length }
+ }
+ }, "observe");
+ }
+ for (const [node, nodePath] of measured) {
+ const primitives = node.getMesh().listPrimitives();
+ const cost = primitives.reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0) * ((check.gradient ? 2 : 0) + (check.range ? 1 : 0)), 0);
+ if (notMeasured > 0 || reads + cost > budget) {
+ notMeasured++;
+ continue;
+ }
+ reads += cost;
+ matchedNodes++;
+ const affected = { node: node.getName(), nodePath };
+ if (check.primitives) {
+ const limit = "exactly" in check.primitives ? check.primitives.exactly : check.primitives.max;
+ const fails = "exactly" in check.primitives ? primitives.length !== limit : primitives.length > limit;
+ if (fails)
+ report("HOST_VALIDATION_PRIMITIVE_COUNT", "primitives", `${node.getName()} has ${primitives.length} primitive(s) in the final GLB; the host expects ${"exactly" in check.primitives ? "exactly" : "at most"} ${limit}. Each material group exports as its own primitive.`, {
+ affected,
+ measurement: {
+ actual: primitives.length,
+ expected: limit
+ }
+ });
+ }
+ primitives.forEach((primitive, index) => {
+ const where = `${node.getName()} primitive ${index}`;
+ for (const semantic of check.attributes ?? []) {
+ if (primitive.getAttribute(semantic))
+ continue;
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "attributes", `${where} has no ${semantic} attribute.`, {
+ affected: { ...affected, attribute: semantic },
+ measurement: { actual: false, expected: true }
+ });
+ }
+ if (check.gradient) {
+ const outcome = measureGradient(primitive, check.gradient);
+ if (outcome.kind === "missing")
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "gradient", `${where} cannot be measured: ${outcome.reason}.`, {
+ affected: { ...affected, attribute: outcome.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else if (outcome.kind === "unmeasured") {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "gradient", `${where} has no extent along ${check.gradient.axis}; the gradient is unmeasured.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: { actual: null }
+ }, "observe");
+ } else if (outcome.failures.length > 0)
+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: {
+ actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,
+ expected: `${check.gradient.from}..${check.gradient.to}`,
+ threshold: check.gradient.tolerance,
+ breakdown: {
+ fromMean: round2(outcome.fromMean),
+ toMean: round2(outcome.toMean),
+ worstRegression: round2(outcome.worstRegression)
+ }
+ }
+ });
+ }
+ if (check.range) {
+ const accessor = primitive.getAttribute(check.range.attribute);
+ if (!accessor || check.range.component >= accessor.getElementSize())
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "range", `${where} has no ${check.range.attribute}[${check.range.component}].`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else {
+ const element = [];
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0;i < accessor.getCount(); i++) {
+ const value = component(accessor, i, check.range.component, element);
+ if (value < min)
+ min = value;
+ if (value > max)
+ max = value;
+ }
+ const { tolerance } = check.range;
+ if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))
+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: {
+ actual: `${round2(min)}..${round2(max)}`,
+ expected: `${check.range.min}..${check.range.max}`,
+ threshold: tolerance
+ }
+ });
+ }
+ }
+ if (check.material) {
+ const material = primitive.getMaterial();
+ const label = material?.getName() || (material ? `materials[${doc.getRoot().listMaterials().indexOf(material)}]` : "(glTF default)");
+ const alphaMode = material?.getAlphaMode() ?? "OPAQUE";
+ const doubleSided = material?.getDoubleSided() ?? false;
+ if (check.material.alphaMode !== undefined && alphaMode !== check.material.alphaMode)
+ report("HOST_VALIDATION_MATERIAL_ALPHA_MODE", "material", `${where} uses alphaMode ${alphaMode}; the host expects ${check.material.alphaMode}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: alphaMode,
+ expected: check.material.alphaMode
+ }
+ });
+ if (check.material.doubleSided !== undefined && doubleSided !== check.material.doubleSided)
+ report("HOST_VALIDATION_MATERIAL_DOUBLE_SIDED", "material", `${where} is ${doubleSided ? "double-sided" : "single-sided"}; the host expects ${check.material.doubleSided ? "double-sided" : "single-sided"}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: doubleSided,
+ expected: check.material.doubleSided
+ }
+ });
+ }
+ });
+ }
+ for (const [code, entry] of omitted)
+ push(code, entry.assertion, `${entry.count} more ${code} finding(s) omitted after the first ${MAX_VALIDATION_FINDINGS_PER_CODE}.`, { actual: entry.count, breakdown: { omitted: entry.count } }, undefined, entry.disposition);
+ }
+ if (notMeasured > 0) {
+ complete = false;
+ findings.push({
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation stopped at its ${budget} attribute-read budget; ${notMeasured} matched node(s) were not measured.`,
+ measurement: {
+ name: "checks.*.budget",
+ actual: reads,
+ threshold: budget,
+ breakdown: { nodesNotMeasured: notMeasured }
+ }
+ });
+ }
+ return {
+ findings,
+ complete,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: matchedNodes,
+ hostValidationAttributeReads: reads,
+ hostValidationComplete: complete
+ }
+ };
+}
+function measureGradient(primitive, gradient) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ return {
+ kind: "missing",
+ attribute: "POSITION",
+ reason: "no POSITION attribute"
+ };
+ const values = primitive.getAttribute(gradient.attribute);
+ if (!values || gradient.component >= values.getElementSize())
+ return {
+ kind: "missing",
+ attribute: gradient.attribute,
+ reason: `no ${gradient.attribute}[${gradient.component}]`
+ };
+ const count = Math.min(position.getCount(), values.getCount());
+ const axis = AXIS_INDEX[gradient.axis[1]];
+ const sign = gradient.axis[0] === "-" ? -1 : 1;
+ const t = new Float64Array(count);
+ const v = new Float64Array(count);
+ const element = [];
+ let tMin = Infinity;
+ let tMax = -Infinity;
+ for (let i = 0;i < count; i++) {
+ t[i] = sign * component(position, i, axis, element);
+ v[i] = component(values, i, gradient.component, element);
+ if (t[i] < tMin)
+ tMin = t[i];
+ if (t[i] > tMax)
+ tMax = t[i];
+ }
+ if (!(tMax - tMin >= MIN_AXIS_EXTENT))
+ return { kind: "unmeasured" };
+ const sums = new Float64Array(GRADIENT_BINS);
+ const counts = new Uint32Array(GRADIENT_BINS);
+ let fromSum = 0;
+ let fromCount = 0;
+ let toSum = 0;
+ let toCount = 0;
+ for (let i = 0;i < count; i++) {
+ const s = (t[i] - tMin) / (tMax - tMin);
+ if (s <= ENDPOINT_BAND) {
+ fromSum += v[i];
+ fromCount++;
+ }
+ if (s >= 1 - ENDPOINT_BAND) {
+ toSum += v[i];
+ toCount++;
+ }
+ const bin = Math.min(GRADIENT_BINS - 1, Math.floor(s * GRADIENT_BINS));
+ sums[bin] = sums[bin] + v[i];
+ counts[bin] = counts[bin] + 1;
+ }
+ const fromMean = fromSum / fromCount;
+ const toMean = toSum / toCount;
+ const direction = Math.sign(gradient.to - gradient.from);
+ let worstRegression = 0;
+ let previous;
+ for (let bin = 0;bin < GRADIENT_BINS; bin++) {
+ if (counts[bin] === 0)
+ continue;
+ const mean = sums[bin] / counts[bin];
+ if (previous !== undefined)
+ worstRegression = Math.max(worstRegression, (previous - mean) * direction);
+ previous = mean;
+ }
+ const failures = [];
+ if (Math.abs(fromMean - gradient.from) > gradient.tolerance || Math.abs(toMean - gradient.to) > gradient.tolerance)
+ failures.push("endpoints");
+ if (gradient.monotonic && worstRegression > gradient.tolerance)
+ failures.push("monotonic");
+ return { kind: "measured", fromMean, toMean, worstRegression, failures };
+}
+async function evaluateValidationProfileGlb(profile, bytes, options = {}) {
+ let doc;
+ try {
+ doc = await createGltfIO().readBinary(bytes);
+ } catch (error) {
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ return {
+ findings: [
+ {
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation could not read the final GLB: ${error instanceof Error ? error.message : String(error)}`,
+ measurement: { name: "checks.*.read", actual: null }
+ }
+ ],
+ complete: false,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: 0,
+ hostValidationAttributeReads: 0,
+ hostValidationComplete: false
+ }
+ };
+ }
+ return evaluateValidationProfileDocument(profile, doc, options);
+}
+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;
+var init_validation_profile2 = __esm(() => {
+ init_gltf_io();
+ init_delivery_inspect();
+ init_validation_profile();
+ init_registry();
+ HOST_VALIDATION_QA_RULE = Object.freeze({
+ id: HOST_VALIDATION_RULE_ID,
+ profile: "host.validation-profile",
+ scope: { kind: "universal" },
+ ruleClass: "exact",
+ owner: KILN_ENGINE_QA_OWNER,
+ promotion: conformancePromotionAuthorization("host-validation-profile-v1", "src/qa/validation-profile.test.ts", "b6b60fcbba0238688cb0d3ef497fa3ed837757422b43207f18fc8cbe0a412ffc", KILN_ENGINE_QA_OWNER, "2026-10-22T00:00:00.000Z", "enforce", "cpu-raster:1.3.1"),
+ defaultMode: "enforce",
+ evaluate: () => []
+ });
+ AXIS_INDEX = { X: 0, Y: 1, Z: 2 };
+});
+
+// src/qa/reference-comparison.ts
+function isEvidence(value) {
+ if (typeof value !== "object" || value === null)
+ return false;
+ const candidate = value;
+ return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";
+}
+function referenceComparisonFindings(evidence, profile) {
+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)
+ return [];
+ const findings = [];
+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {
+ findings.push({
+ code: "REF_SILHOUETTE_AGREEMENT",
+ disposition: "observe",
+ dimension: "promptAlignment",
+ profile,
+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,
+ measurement: {
+ name: "silhouetteIoU",
+ actual: evidence.silhouetteIoU,
+ threshold: SILHOUETTE_IOU_OBSERVE
+ },
+ repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."
+ });
+ }
+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {
+ findings.push({
+ code: "REF_COLOR_AGREEMENT",
+ disposition: "observe",
+ dimension: "promptAlignment",
+ profile,
+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,
+ measurement: {
+ name: "colorAgreement",
+ actual: evidence.colorAgreement,
+ threshold: COLOR_AGREEMENT_OBSERVE
+ },
+ repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."
+ });
+ }
+ return findings;
+}
+var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;
+var init_reference_comparison = __esm(() => {
+ init_registry();
+ REFERENCE_COMPARISON_QA_RULE = Object.freeze({
+ id: "REF_COMPARISON",
+ profile: "reference.comparison",
+ scope: { kind: "universal" },
+ ruleClass: "heuristic",
+ owner: KILN_ENGINE_QA_OWNER,
+ defaultMode: "observe",
+ evaluate(context) {
+ const evidence = context.derivedEvidence?.["referenceComparison"];
+ if (!isEvidence(evidence))
+ return [];
+ return referenceComparisonFindings(evidence, "reference.comparison");
+ }
+ });
+});
+
+// src/qa/run.ts
+function gltfReportFindings(report, profile) {
+ return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
+ code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),
+ disposition: issue.severity === 0 ? "block" : "warn",
+ dimension: "exportIntegrity",
+ profile,
+ message: issue.message,
+ ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}
+ }));
+}
+function isExpectedKtx2ValidatorLimitation(report, issue) {
+ const required = report.info?.["extensionsRequired"];
+ if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))
+ return false;
+ if (issue.code === "VALUE_NOT_IN_LIST") {
+ return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";
+ }
+ return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";
+}
+function qaPolicyFromEnv(env = process.env) {
+ const mode = env["KILN_QA_MODE"];
+ return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};
+}
+function qaBlockingEnabled(env = process.env) {
+ const mode = env["KILN_QA_MODE"];
+ return mode !== "observe" && mode !== "off";
+}
+var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;
+var init_run = __esm(() => {
+ init_material();
+ init_architecture();
+ init_character2();
+ init_character_advisory();
+ init_vehicle2();
+ init_vegetation();
+ init_prop();
+ init_part_connectivity();
+ init_reference_comparison();
+ init_self_intersection();
+ init_sweep();
+ init_environment2();
+ init_breadth2();
+ init_breadth_evidence();
+ init_registry();
+ init_types();
+ init_universal();
+ init_validation_profile2();
+ DETERMINISTIC_QA_REGISTRY = new QaRegistry([
+ ...UNIVERSAL_QA_RULES,
+ MATERIAL_QA_RULE,
+ ...ARCHITECTURE_QA_RULES,
+ CHARACTER_QA_RULE,
+ CHARACTER_ADVISORY_QA_RULE,
+ ...VEHICLE_QA_RULES,
+ ...VEGETATION_QA_RULES,
+ ...PROP_QA_RULES,
+ ...ENVIRONMENT_QA_RULES,
+ ...W7_BREADTH_QA_RULES,
+ SELF_INTERSECTION_QA_RULE,
+ SWEEP_QA_RULE,
+ PART_CONNECTIVITY_QA_RULE,
+ REFERENCE_COMPARISON_QA_RULE,
+ HOST_VALIDATION_QA_RULE
+ ]);
+ AssetQaBlockedError = class AssetQaBlockedError extends Error {
+ report;
+ stage;
+ gltfValidation;
+ constructor(report, stage, gltfValidation) {
+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");
+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.affected ? ` AFFECTED: ${JSON.stringify(finding.affected)}` : ""}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);
+ const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";
+ super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);
+ this.name = "AssetQaBlockedError";
+ this.report = report;
+ this.stage = stage;
+ this.gltfValidation = gltfValidation;
+ }
+ };
+});
+
+// src/qa/requirements-run.ts
+import { Object3D as Object3D15 } from "three";
+function sceneDecisions(context, policy) {
+ const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));
+ return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);
+}
+async function collectRequirementsSceneEvidence(context, scene, policy = {}) {
+ if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))
+ return {};
+ try {
+ return { partPenetration: await analyzePartPenetration(scene) };
+ } catch {
+ return { partPenetrationFailed: true };
+ }
+}
+function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {
+ const needs = context.requirements.requirements;
+ const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];
+ const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;
+ const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;
+ const requiredClips = [
+ ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])
+ ];
+ const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;
+ const findings = [];
+ const decisions = sceneDecisions(context, policy);
+ const geometryMetrics = {};
+ const mobilityInput = {
+ scene,
+ mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];
+ const executedRules = [];
+ const rigInput = {
+ scene,
+ clips,
+ rig,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const foliageInput = {
+ scene,
+ foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,
+ materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;
+ const scope = context.requirements.scope;
+ const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;
+ const effectsInput = {
+ effects,
+ derivedEvidence: {
+ source: "engine-scene-analysis",
+ ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}
+ }
+ };
+ const spatialInput = {
+ scene,
+ tileable: needs.tiling?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.tileable === true,
+ navigable: needs.navigation?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.navigable === true,
+ navigation: needs.navigation?.state === "requested" ? needs.navigation.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
+ };
+ const spatialFindings = decisions.some((d) => d.ruleId.startsWith("ENVIRONMENT_") && d.mode !== "off") ? [
+ ...inspectPlacementSockets(spatialInput),
+ ...inspectTileEdges(spatialInput),
+ ...inspectNavigationClearance(spatialInput),
+ ...inspectSpatialSupport(spatialInput)
+ ] : [];
+ const structureFindings = needs.structure?.state === "requested" && decisions.some((d) => d.ruleId.startsWith("ARCHITECTURE_") && d.mode !== "off") ? inspectStructure({
+ scene,
+ structure: needs.structure.value,
+ opening: needs.opening?.state === "requested"
+ }) : [];
+ for (const decision of decisions) {
+ if (decision.mode === "off")
+ continue;
+ if (decision.ruleId === SELF_INTERSECTION_QA_RULE.id) {
+ const volume = evidence.partPenetration;
+ if (volume) {
+ const acknowledged = volume.acknowledged?.length ?? 0;
+ const partial = volume.truncated || volume.skipped.length > 0 || acknowledged > 0;
+ if (!partial)
+ executedRules.push(decision.ruleId);
+ findings.push(...inspectPartPenetration(volume));
+ Object.assign(geometryMetrics, {
+ partVolumeCoverage: partial ? "partial" : "complete-static-pairs",
+ partVolumeScope: "Visible static closed mesh pairs, except alternates on different LOD levels; excludes intra-mesh intersections, motion, open surfaces and usable passage space. Positive overlap may be intentional.",
+ partVolumeEligibleParts: volume.partsAnalyzed,
+ partVolumeCandidatePairs: volume.candidatePairs,
+ partVolumeCandidatesLowerBound: volume.broadPhaseTruncated === true,
+ partVolumePairsTested: volume.pairsTested,
+ partVolumeUnmeasurablePairs: volume.pairsUnmeasurable,
+ partVolumePairsNotReached: volume.pairsNotReached,
+ partVolumeLodAlternatePairs: volume.pairsLodAlternates,
+ partVolumeSkipped: volume.skipped.length,
+ ...acknowledged > 0 ? {
+ partVolumeAcknowledgedParts: acknowledged,
+ partVolumeAcknowledgedPairs: volume.pairsUnmeasurableAcknowledged ?? 0
+ } : {}
+ });
+ } else if (evidence.partPenetrationFailed) {
+ findings.push({
+ code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",
+ disposition: "observe",
+ dimension: "visualQuality",
+ profile: "geometry.selfIntersection",
+ message: "Part-volume analysis could not complete. Overlap and clearance remain unmeasured."
+ });
+ geometryMetrics.partVolumeCoverage = "unavailable";
+ }
+ continue;
+ }
+ if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
+ continue;
+ if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)
+ continue;
+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
+ continue;
+ executedRules.push(decision.ruleId);
+ if (decision.ruleId === PROP_EXACT_QA_RULE.id) {
+ const measured = [
+ ...needs.articulation?.state === "requested" ? inspectArticulation({ scene }) : [],
+ ...needs.opening?.state === "requested" ? inspectContainerOpening({ scene }) : []
+ ];
+ for (const finding of measured)
+ findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
+ continue;
+ }
+ const measured = decision.ruleId === SWEEP_QA_RULE.id ? inspectSweepGeometry(scene) : decision.ruleId === PART_CONNECTIVITY_QA_RULE.id ? inspectPartConnectivity(scene, needs.externalSupport?.state === "requested" ? needs.externalSupport.value.supports : undefined) : decision.ruleId === ASSET_SCOPE_QA_RULE.id && scope?.state === "requested" ? inspectAssetScope({
+ profile: "asset.requirements.v1",
+ scope: { schemaVersion: 1, scope: scope.value, explicit: true },
+ derivedEvidence: { source: "engine-scene-analysis", assetScope: scopeObservation }
+ }) : decision.ruleId === "CHARACTER_PROFILE" ? inspectRig(rigInput) : decision.ruleId === "CHARACTER_ADVISORY_PROFILE" ? inspectRigAdvisory(rigInput) : decision.ruleId === "VEGETATION_CONTACT_PROFILE" ? inspectFoliageContact(foliageInput) : decision.ruleId === "VEGETATION_ADVISORY_PROFILE" ? inspectFoliageAdvisory(foliageInput) : decision.ruleId === MATERIAL_QA_RULE.id ? inspectPortableSceneMaterials(scene, tangents) : decision.ruleId === "VFX_EXACT_PROFILE" ? inspectEffectsExact(effectsInput) : decision.ruleId === "VFX_ADVISORY_PROFILE" ? inspectEffectsAdvisory(effectsInput) : decision.ruleId === "ARCHITECTURE_PROFILE" ? structureFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ARCHITECTURE_ADVISORY_PROFILE" ? structureFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "ENVIRONMENT_EXACT_PROFILE" ? spatialFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ENVIRONMENT_ADVISORY_PROFILE" ? spatialFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_PROFILE" ? mobilityFindings.filter((f) => f.disposition === "block") : decision.ruleId === "VEHICLE_ADVISORY_PROFILE" ? mobilityFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_W6_ADVISORY_PROFILE" ? inspectMobilityAdvisory(mobilityInput) : decision.ruleId === PROP_ADVISORY_QA_RULE.id ? inspectPlacement({
+ scene,
+ bounds: needs.bounds?.state === "requested" ? needs.bounds.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
+ }) : UNIVERSAL_QA_KERNELS[decision.ruleId]({
+ scene,
+ clips,
+ requiredParts: parts,
+ animation: { clips: requiredClips }
+ });
+ for (const finding of measured)
+ findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
+ }
+ return createRequirementsQaReport(context, {
+ findings,
+ executedRules,
+ modes: Object.fromEntries(decisions.map((x) => [x.ruleId, x.mode])),
+ metrics: {
+ ...Object.keys(geometryMetrics).length ? { visualQuality: geometryMetrics } : {},
+ ...scopeObservation ? {
+ promptAlignment: {
+ scopeTopLevelAssetRoots: scopeObservation.topLevelAssetRoots,
+ scopeReusableMemberCount: scopeObservation.reusableMemberCount,
+ scopeDressingSignalCount: scopeObservation.sceneDressingRoles.length
+ }
+ } : {}
+ },
+ ...scopeObservation ? {
+ evaluatedDimensions: ["exportIntegrity", "requirementReadiness", "promptAlignment"]
+ } : {}
+ });
+}
+function appendRequirementsQa(context, report, findings, metrics = {}, executedRules = []) {
+ const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
+ const merged = { ...priorMetrics };
+ for (const [dimension, value] of Object.entries(metrics ?? {}))
+ merged[dimension] = { ...priorMetrics[dimension], ...value };
return createRequirementsQaReport(context, {
findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
- executedRules: report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ executedRules: [
+ ...report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ ...executedRules
+ ],
modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
evaluatedDimensions: [
...new Set([
@@ -23077,6 +24401,16 @@ async function appendRequirementsFinalQa(context, report, gltf, bytes, instancea
exportIntegrity: finalEffectsMetrics(evidence)
});
}
+ const validation = context.requirements.requirements.validation;
+ const hostRule = report.rules.find((r) => r.id === HOST_VALIDATION_QA_RULE.id);
+ if (validation?.state === "requested" && hostRule && hostRule.status !== "notRequested" && hostRule.mode !== "off") {
+ const evaluation = await evaluateValidationProfileGlb(validation.value, bytes);
+ const findings = hostRule.mode === "enforce" ? evaluation.findings : evaluation.findings.map((f) => ({
+ ...f,
+ disposition: f.disposition === "observe" ? f.disposition : hostRule.mode
+ }));
+ result = appendRequirementsQa(context, result, findings, { requirementReadiness: evaluation.metrics }, evaluation.complete ? [HOST_VALIDATION_QA_RULE.id] : []);
+ }
return result;
}
var registry;
@@ -23099,6 +24433,7 @@ var init_requirements_run = __esm(() => {
init_architecture();
init_environment2();
init_requirements_applicability();
+ init_validation_profile2();
init_requirements_report();
init_run();
registry = new QaRegistry([
@@ -23117,12 +24452,13 @@ var init_requirements_run = __esm(() => {
CHARACTER_ADVISORY_QA_RULE,
VFX_EXACT_QA_RULE,
VFX_ADVISORY_QA_RULE,
- ASSET_SCOPE_QA_RULE
+ ASSET_SCOPE_QA_RULE,
+ HOST_VALIDATION_QA_RULE
]);
});
// src/qa/skin-integrity.ts
-import * as THREE25 from "three";
+import * as THREE27 from "three";
function validAttribute(a, count, size) {
if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)
return false;
@@ -23169,9 +24505,9 @@ function inspectSkinIntegrity(root) {
}
while (chain.length) {
const n = chain.pop();
- const local = n.matrixAutoUpdate ? new THREE25.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
+ const local = n.matrixAutoUpdate ? new THREE27.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
const parent = n.parent ? worlds.get(n.parent) : undefined;
- const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE25.Matrix4().multiplyMatrices(parent, local) : local;
+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE27.Matrix4().multiplyMatrices(parent, local) : local;
worlds.set(n, value);
}
return worlds.get(node);
@@ -23221,7 +24557,7 @@ function inspectSkinIntegrity(root) {
if (result.truncated)
break;
}
- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE25.AttachedBindMode, THREE25.DetachedBindMode].includes(mesh.bindMode)) {
+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE27.AttachedBindMode, THREE27.DetachedBindMode].includes(mesh.bindMode)) {
add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");
}
const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;
@@ -23270,7 +24606,7 @@ function inspectSkinIntegrity(root) {
add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");
continue;
}
- const inverse = mesh.bindMode === THREE25.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
+ const inverse = mesh.bindMode === THREE27.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
const matrices = [];
for (let joint = 0;joint < bones.length; joint++) {
const boneWorld = world(bones[joint]);
@@ -23278,13 +24614,13 @@ function inspectSkinIntegrity(root) {
add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);
break;
}
- matrices.push(new THREE25.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
+ matrices.push(new THREE27.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
}
if (result.findings.length !== start)
continue;
- const base = new THREE25.Vector3, posed = new THREE25.Vector3, temp = new THREE25.Vector3, box = new THREE25.Box3;
+ const base = new THREE27.Vector3, posed = new THREE27.Vector3, temp = new THREE27.Vector3, box = new THREE27.Box3;
for (let vertex = 0;vertex < count; vertex++) {
- THREE25.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
+ THREE27.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
posed.set(0, 0, 0);
for (let lane = 0;lane < 4; lane++) {
const weight = weights.getComponent(vertex, lane);
@@ -23306,334 +24642,8 @@ function inspectSkinIntegrity(root) {
var MAX_FINDINGS = 64, WEIGHT_TOLERANCE = 0.00001;
var init_skin_integrity = () => {};
-// src/metrics.ts
-function primTris(prim) {
- const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
- switch (prim.getMode()) {
- case 4:
- return Math.floor(count / 3);
- case 5:
- case 6:
- return Math.max(0, count - 2);
- default:
- return 0;
- }
-}
-function instanceCopies(node) {
- const ext = node.getExtension("EXT_mesh_gpu_instancing");
- if (!ext)
- return 1;
- return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
-}
-function isHiddenGltfNode(node) {
- const visibility = node.getExtension("KHR_node_visibility");
- return visibility?.getVisible?.() === false;
-}
-function nodeTriangles(node) {
- return subtreeTriangles(node, false);
-}
-function drawnNodeTriangles(node) {
- return subtreeTriangles(node, true);
-}
-function subtreeTriangles(node, drawn) {
- if (drawn && isHiddenGltfNode(node))
- return 0;
- let triangles = 0;
- const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- for (const prim of mesh.listPrimitives())
- triangles += primTris(prim) * copies;
- }
- for (const child of node.listChildren())
- triangles += subtreeTriangles(child, drawn);
- return triangles;
-}
-function collectGlbMetrics(doc, triangles) {
- const root = doc.getRoot();
- const geomSet = new Set;
- const matSet = new Set;
- let drawCalls = 0;
- let derivedTris = 0;
- let meshNodes = 0;
- let meshInstances = 0;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- meshNodes += 1;
- meshInstances += copies;
- for (const prim of mesh.listPrimitives()) {
- drawCalls += 1;
- geomSet.add(prim);
- derivedTris += primTris(prim) * copies;
- const mat = prim.getMaterial();
- if (mat)
- matSet.add(mat);
- }
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const scene of root.listScenes()) {
- for (const node of scene.listChildren())
- visit(node);
- }
- const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
- return {
- uniqueGeometries: geomSet.size,
- uniqueMaterials: matSet.size,
- meshNodes,
- meshInstances,
- drawCalls,
- textureCount: root.listTextures().length,
- skinned: root.listSkins().length > 0,
- transparentMaterials,
- triangles: triangles ?? derivedTris
- };
-}
-function rubricGrade(m) {
- const grade = materialBand(m.uniqueMaterials).grade;
- return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
-}
-function textureSlots(m) {
- return [
- [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
- [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
- [m.getNormalTexture(), m.getNormalTextureInfo()],
- [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
- [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
- ];
-}
-function shadingKey(m, textures) {
- const binding = (info) => info && [
- info.getTexCoord(),
- info.getWrapS(),
- info.getWrapT(),
- info.getMagFilter(),
- info.getMinFilter(),
- extensionNames(info)
- ];
- return JSON.stringify([
- m.getAlphaMode(),
- m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
- m.getDoubleSided(),
- textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
- extensionNames(m),
- m.getExtras()
- ]);
-}
-function differingFactors(group) {
- const [first, ...rest] = group;
- const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
- for (const extension of first.listExtensions())
- if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- const slots = textureSlots(first);
- slots.forEach(([, info], slot) => {
- for (const extension of info?.listExtensions() ?? [])
- if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- });
- return [...new Set(differs)];
-}
-function mergeNeeds(differs) {
- const needs = [];
- if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
- needs.push("colours in a shared texture, an atlas region or vertex colours");
- if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
- needs.push("one metallic/roughness value or a shared metallicRoughness texture");
- if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
- needs.push("one normal scale and occlusion strength");
- if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
- needs.push("one setting for each differing extension");
- return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
-}
-function materialMergeCandidates(doc) {
- const root = doc.getRoot();
- const parts = new Map;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
- for (const primitive of mesh?.listPrimitives() ?? []) {
- const material = primitive.getMaterial();
- if (!material)
- continue;
- const list = parts.get(material) ?? [];
- if (!list.includes(name))
- list.push(name);
- parts.set(material, list);
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const scene of root.listScenes())
- for (const node of scene.listChildren())
- visit(node);
- const materials = root.listMaterials();
- const textures = root.listTextures();
- const groups = new Map;
- for (const material of materials) {
- if (!parts.has(material))
- continue;
- const key = shadingKey(material, textures);
- const group = groups.get(key);
- if (group)
- group.push(material);
- else
- groups.set(key, [material]);
- }
- return [...groups.values()].filter((group) => group.length > 1).map((group) => {
- const differs = differingFactors(group);
- return {
- materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
- parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
- alphaMode: group[0].getAlphaMode(),
- differs,
- needs: mergeNeeds(differs)
- };
- });
-}
-function shortList(names, shown, joiner) {
- const head = names.slice(0, shown).join(joiner);
- return names.length > shown ? `${head} and ${names.length - shown} more` : head;
-}
-function mergeAdvice(m, candidates) {
- const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
- const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
- const projected = {
- ...m,
- uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
- transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
- };
- const projectedGrade = rubricGrade(projected);
- const band = materialBand(projected.uniqueMaterials);
- const named = (c) => shortList(c.materials, 4, " + ");
- const groups = candidates.slice(0, 3).map((c) => {
- const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
- return `${named(c)} (${why})`;
- });
- if (candidates.length > 3)
- groups.push(`${candidates.length - 3} more groups`);
- const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
- const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
- const reasons = candidates.map((c) => {
- const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
- return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
- });
- return {
- advice: {
- optional: true,
- materialMerges: [...candidates],
- projectedMaterials: projected.uniqueMaterials,
- projectedGrade
- },
- summary,
- reasons
- };
-}
-function gradeInstanceability(metrics, opts = {}) {
- const m = metrics;
- const band = materialBand(m.uniqueMaterials);
- let grade = band.grade;
- const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
- const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
- const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
- const drivers = [];
- const also = [];
- if ((grade === "A" || grade === "B") && (transparency || textures)) {
- grade = "C";
- if (transparency)
- drivers.push(`${transparency} (lowers A/B to C)`);
- if (textures)
- drivers.push(`${textures} (over 4 lowers A/B to C)`);
- also.push(materials);
- } else {
- drivers.push(materials);
- if (transparency)
- also.push(`${transparency} (lowers only A/B to C)`);
- if (textures)
- also.push(`${textures} (over 4 lowers only A/B to C)`);
- }
- also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
- if (m.skinned)
- also.push("skinned (clone-rendered, not penalized)");
- const setBy = drivers.join(" and ");
- const reasons = [
- `grade ${grade} set by ${setBy}`,
- `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
- ];
- if (transparency)
- reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
- if (textures)
- reasons.push(`${m.textureCount} textures (consider atlasing)`);
- if (m.skinned)
- reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
- if (opts.category)
- reasons.push(`category: ${opts.category}`);
- const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- if (!opts.mergeCandidates?.length)
- return { grade, summary, reasons, metrics: m };
- const merge = mergeAdvice(m, opts.mergeCandidates);
- return {
- grade,
- summary: summary + merge.summary,
- reasons: [...reasons, ...merge.reasons],
- metrics: m,
- advice: merge.advice
- };
-}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
-var init_metrics = __esm(() => {
- MATERIAL_GRADE_BANDS = [
- { grade: "A", max: 1, range: "0-1" },
- { grade: "B", max: 3, range: "2-3" },
- { grade: "C", max: 6, range: "4-6" },
- { grade: "D", max: 12, range: "7-12" },
- { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
- ];
- MERGE_FACTORS = [
- ["baseColorFactor", (m) => m.getBaseColorFactor()],
- ["emissiveFactor", (m) => m.getEmissiveFactor()],
- ["metallicFactor", (m) => m.getMetallicFactor()],
- ["roughnessFactor", (m) => m.getRoughnessFactor()],
- ["normalScale", (m) => m.getNormalScale()],
- ["occlusionStrength", (m) => m.getOcclusionStrength()]
- ];
-});
-
-// src/written-nodes.ts
-function exportedRoot(doc, purpose) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- const top = scene?.listChildren() ?? [];
- if (top.length !== 1)
- throw new Error(`${purpose} expects the exporter to write one root node.`);
- return top[0];
-}
-function writtenNodeResolver(root, doc, purpose) {
- const top = exportedRoot(doc, purpose);
- return (node) => {
- const path = [];
- for (let current = node;current !== root; current = current.parent) {
- if (!current.parent)
- throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
- path.unshift(current.parent.children.indexOf(current));
- }
- let target = top;
- for (const index of path)
- target = target?.listChildren()[index];
- if (!target || (target.getName() || "") !== (node.name || ""))
- throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
- return target;
- };
-}
-
// src/lod-export.ts
-import { PropertyType as PropertyType2 } from "@gltf-transform/core";
+import { PropertyType as PropertyType3 } from "@gltf-transform/core";
function applyLodChains(root, sets, doc) {
if (sets.length === 0)
return;
@@ -23673,9 +24683,9 @@ function listLodChainNodes(doc) {
const chains = [];
const visit = (siblings, parentPath) => {
siblings.forEach((node, index) => {
- const at = (name) => `${parentPath}${segment2(name, occurrence(siblings, index, name))}`;
+ const at = (name) => `${parentPath}${segment4(name, occurrence(siblings, index, name))}`;
const path = at(node.getName());
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
if (lower.length > 0)
chains.push({
levels: [node, ...lower],
@@ -23684,7 +24694,7 @@ function listLodChainNodes(doc) {
visit(node.listChildren(), path);
});
};
- visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
+ visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
return chains;
}
function isImpostorLevel(node) {
@@ -23707,109 +24717,13 @@ function summarizeLodChains(doc) {
};
});
}
-var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
var init_lod_export = __esm(() => {
init_semantic();
init_gltf_io();
init_metrics();
});
-// src/node-visibility.ts
-import { KHRNodeVisibility } from "@gltf-transform/extensions";
-import * as THREE26 from "three";
-function applyNodeVisibility(root, doc) {
- const hidden = [];
- root.traverse((node) => {
- if (node.visible === false)
- hidden.push(node);
- });
- if (hidden.length === 0)
- return;
- const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
- const extension = doc.createExtension(KHRNodeVisibility);
- for (const node of written)
- node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
-}
-function summarizeHiddenNodes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const found = [];
- const visit = (siblings, parentPath) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment3(name, occurrence)}`;
- if (isHiddenGltfNode(node))
- found.push({ path, name, triangles: nodeTriangles(node) });
- else
- visit(node.listChildren(), path);
- }
- };
- visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
- return found;
-}
-function drawnSceneBounds(scene) {
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- if (mesh) {
- const base = new THREE26.Matrix4().fromArray(node.getWorldMatrix());
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < countInstances; i++) {
- const t = translation?.getElement(i, []) ?? [0, 0, 0];
- const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
- const s = scale?.getElement(i, []) ?? [1, 1, 1];
- const localMatrix = new THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(t), new THREE26.Quaternion().fromArray(r), new THREE26.Vector3().fromArray(s));
- matrices.push(base.clone().multiply(localMatrix).toArray());
- }
- const local = [0, 0, 0];
- for (const primitive of mesh.listPrimitives()) {
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const m of matrices)
- for (let i = 0;i < count; i++) {
- position.getElement(indices ? indices.getScalar(i) : i, local);
- const [x, y, z] = local;
- const world = [
- m[0] * x + m[4] * y + m[8] * z + m[12],
- m[1] * x + m[5] * y + m[9] * z + m[13],
- m[2] * x + m[6] * y + m[10] * z + m[14]
- ];
- for (let k = 0;k < 3; k++) {
- if (world[k] < min[k])
- min[k] = world[k];
- if (world[k] > max[k])
- max[k] = world[k];
- }
- }
- }
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const node of scene.listChildren())
- visit(node);
- return { min, max };
-}
-var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
-var init_node_visibility = __esm(() => {
- init_metrics();
-});
-
// src/rig-export.ts
function rigExtrasForExport(node) {
const extras = {};
@@ -23853,7 +24767,7 @@ var init_material_export = __esm(() => {
});
// src/community-exporter.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
import { GLB_BUFFER } from "@gltf-transform/core";
function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
@@ -23883,7 +24797,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
return found;
const copy = cleanClone(source);
normalizeTextureTransform(copy);
- copy.source = new THREE27.TextureSource(source.image);
+ copy.source = new THREE28.TextureSource(source.image);
textures.set(source, copy);
const bytes = source.userData["encoded"];
if (bytes?.bytes) {
@@ -23892,8 +24806,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
encoded.push((async () => {
copy.image = await platform.decode(bytes.bytes);
Object.defineProperty(copy, "isDataTexture", { value: true });
- copy.format = THREE27.RGBAFormat;
- copy.type = THREE27.UnsignedByteType;
+ copy.format = THREE28.RGBAFormat;
+ copy.type = THREE28.UnsignedByteType;
})());
}
return copy;
@@ -23910,7 +24824,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
physical.sheen = 1;
}
for (const [key, value] of Object.entries(copy)) {
- if (value instanceof THREE27.Texture)
+ if (value instanceof THREE28.Texture)
copy[key] = texture(value);
}
materials.set(source, copy);
@@ -23926,15 +24840,15 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
if (!copy.matrixAutoUpdate)
copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);
if (source.isScene) {
- copy = new THREE27.Group;
+ copy = new THREE28.Group;
copy.copy(shadow, false);
}
if (source.isSprite) {
const sprite = source;
- const geometry = new THREE27.PlaneGeometry(1, 1);
+ const geometry = new THREE28.PlaneGeometry(1, 1);
geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
geometry.rotateZ(sprite.material.rotation);
- const spriteMaterial = new THREE27.MeshBasicMaterial({
+ const spriteMaterial = new THREE28.MeshBasicMaterial({
name: sprite.material.name,
color: sprite.material.color,
opacity: sprite.material.opacity,
@@ -23945,8 +24859,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
});
Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));
originalMaterials.set(spriteMaterial, sprite.material);
- copy = new THREE27.Mesh(geometry, spriteMaterial);
- THREE27.Object3D.prototype.copy.call(copy, shadow, false);
+ copy = new THREE28.Mesh(geometry, spriteMaterial);
+ THREE28.Object3D.prototype.copy.call(copy, shadow, false);
}
Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));
const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
@@ -24010,8 +24924,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
if (!context)
throw new Error("A 2D canvas is required to prepare export texture channels.");
context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);
- const adapted = new THREE27.Texture().copy(map);
- adapted.source = new THREE27.TextureSource(canvas);
+ const adapted = new THREE28.Texture().copy(map);
+ adapted.source = new THREE28.TextureSource(canvas);
canvasInputs.set(map, adapted);
const direct = directImages.get(map);
if (direct)
@@ -24020,7 +24934,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
};
for (const material of materials.values()) {
for (const [key, value] of Object.entries(material)) {
- if (value instanceof THREE27.Texture && value.flipY && value.image?.data)
+ if (value instanceof THREE28.Texture && value.flipY && value.image?.data)
material[key] = canvasInput(value);
}
const standard = material;
@@ -24042,8 +24956,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
}
cloned.tracks = cloned.tracks.filter((track) => {
try {
- const binding = THREE27.PropertyBinding.parseTrackName(track.name);
- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE27.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ const binding = THREE28.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE28.PropertyBinding.findNode(copy, binding.nodeName) !== null;
} catch {
return false;
}
@@ -24237,443 +25151,6 @@ function applyIndexPolicy(doc, policy) {
}
var init_index_policy = () => {};
-// src/delivery-inspect.ts
-import * as THREE28 from "three";
-import { PropertyType as PropertyType3 } from "@gltf-transform/core";
-function decompose(matrix) {
- const translation = new THREE28.Vector3;
- const rotation = new THREE28.Quaternion;
- const scale = new THREE28.Vector3;
- matrix.decompose(translation, rotation, scale);
- const clean = (value) => Object.is(value, -0) ? 0 : value;
- return {
- translation: translation.toArray().map(clean),
- rotation: rotation.toArray().map(clean),
- scale: scale.toArray().map(clean)
- };
-}
-function drawnTriangles(visited) {
- const values = [];
- const local = [0, 0, 0];
- const point = new THREE28.Vector3;
- for (const { node, roles, hidden } of visited) {
- const mesh = node.getMesh();
- if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
- continue;
- const base = worldMatrix(node);
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < copies; i++) {
- const instance = new THREE28.Matrix4().compose(new THREE28.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE28.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE28.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
- matrices.push(base.clone().multiply(instance));
- }
- for (const primitive of mesh.listPrimitives()) {
- if (primitive.getMode() !== 4)
- continue;
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const matrix of matrices)
- for (let i = 0;i + 2 < count; i += 3)
- for (let k = 0;k < 3; k++) {
- position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
- point.fromArray(local).applyMatrix4(matrix);
- values.push(point.x, point.y, point.z);
- }
- }
- }
- return Float64Array.from(values);
-}
-function triangleOverlapsBox(a, b, c, h, tolerance) {
- const verts = [a, b, c];
- const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
- for (let axis = 0;axis < 3; axis++) {
- const values = verts.map((v) => v.getComponent(axis));
- if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
- return false;
- }
- const e = [
- new THREE28.Vector3().subVectors(b, a),
- new THREE28.Vector3().subVectors(c, b),
- new THREE28.Vector3().subVectors(a, c)
- ];
- const normal = new THREE28.Vector3().crossVectors(e[0], e[1]);
- const axes = [normal];
- const units = [
- new THREE28.Vector3(1, 0, 0),
- new THREE28.Vector3(0, 1, 0),
- new THREE28.Vector3(0, 0, 1)
- ];
- for (const unit of units)
- for (const edge of e)
- axes.push(new THREE28.Vector3().crossVectors(unit, edge));
- for (const axis of axes) {
- if (axis.lengthSq() < 0.000000000000000000000001)
- continue;
- const projections = verts.map((v) => v.dot(axis));
- const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
- if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
- return false;
- }
- return true;
-}
-function closestPointOnTriangle(p, a, b, c) {
- const ab = new THREE28.Vector3().subVectors(b, a);
- const ac = new THREE28.Vector3().subVectors(c, a);
- const ap = new THREE28.Vector3().subVectors(p, a);
- const d1 = ab.dot(ap);
- const d2 = ac.dot(ap);
- if (d1 <= 0 && d2 <= 0)
- return a.clone();
- const bp = new THREE28.Vector3().subVectors(p, b);
- const d3 = ab.dot(bp);
- const d4 = ac.dot(bp);
- if (d3 >= 0 && d4 <= d3)
- return b.clone();
- const vc = d1 * d4 - d3 * d2;
- if (vc <= 0 && d1 >= 0 && d3 <= 0)
- return a.clone().addScaledVector(ab, d1 / (d1 - d3));
- const cp = new THREE28.Vector3().subVectors(p, c);
- const d5 = ab.dot(cp);
- const d6 = ac.dot(cp);
- if (d6 >= 0 && d5 <= d6)
- return c.clone();
- const vb = d5 * d2 - d1 * d6;
- if (vb <= 0 && d2 >= 0 && d6 <= 0)
- return a.clone().addScaledVector(ac, d2 / (d2 - d6));
- const va = d3 * d6 - d5 * d4;
- if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
- return b.clone().addScaledVector(new THREE28.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
- const denominator = 1 / (va + vb + vc);
- return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
-}
-function segmentSegmentDistanceSq(p1, q1, p2, q2) {
- const d1 = new THREE28.Vector3().subVectors(q1, p1);
- const d2 = new THREE28.Vector3().subVectors(q2, p2);
- const r = new THREE28.Vector3().subVectors(p1, p2);
- const a = d1.dot(d1);
- const e = d2.dot(d2);
- const f = d2.dot(r);
- let s = 0;
- let t = 0;
- if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
- return r.lengthSq();
- if (a <= 0.000000000000000000000001)
- t = THREE28.MathUtils.clamp(f / e, 0, 1);
- else {
- const c = d1.dot(r);
- if (e <= 0.000000000000000000000001)
- s = THREE28.MathUtils.clamp(-c / a, 0, 1);
- else {
- const b = d1.dot(d2);
- const denominator = a * e - b * b;
- s = denominator !== 0 ? THREE28.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
- t = (b * s + f) / e;
- if (t < 0) {
- t = 0;
- s = THREE28.MathUtils.clamp(-c / a, 0, 1);
- } else if (t > 1) {
- t = 1;
- s = THREE28.MathUtils.clamp((b - c) / a, 0, 1);
- }
- }
- }
- const c1 = p1.clone().addScaledVector(d1, s);
- const c2 = p2.clone().addScaledVector(d2, t);
- return c1.distanceToSquared(c2);
-}
-function segmentCrossesTriangle(p, q, a, b, c) {
- const hit = new THREE28.Vector3;
- const ray = new THREE28.Ray(p, new THREE28.Vector3().subVectors(q, p));
- const length = ray.direction.length();
- if (length === 0)
- return false;
- ray.direction.divideScalar(length);
- return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
-}
-function triangleTouchesCapsule(a, b, c, p, q, radius) {
- const r2 = radius * radius;
- if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
- return true;
- if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
- return true;
- for (const [s, e] of [
- [a, b],
- [b, c],
- [c, a]
- ])
- if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
- return true;
- return segmentCrossesTriangle(p, q, a, b, c);
-}
-function deliveryNodePaths(doc) {
- const paths = new Map;
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return paths;
- const visit = (siblings, parentPath) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment4(name, occurrence)}`;
- paths.set(node, path);
- visit(node.listChildren(), path);
- }
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
- return paths;
-}
-function summarizeVertexAttributes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const groups = new Map;
- const order = [];
- const record = (node, path) => {
- const mesh = node.getMesh();
- if (!mesh)
- return;
- const bake = mesh.getExtras().kilnSurfaceBakeV1;
- const names = new Set;
- for (const primitive of mesh.listPrimitives())
- for (const semantic of primitive.listSemantics())
- if (semantic.startsWith("_"))
- names.add(semantic);
- for (const name of names) {
- const params = bake && typeof bake === "object" ? bake[name] : undefined;
- const key = `${name}\x00${JSON.stringify(params ?? null)}`;
- let group = groups.get(key);
- if (!group) {
- group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
- groups.set(key, group);
- order.push(key);
- }
- if (!group.meshes.includes(path))
- group.meshes.push(path);
- }
- };
- const visit = (siblings, parentPath) => {
- siblings.forEach((node, index) => {
- const at = (name) => {
- let occurrence = 0;
- for (let i = 0;i < index; i++)
- if (siblings[i].getName() === name)
- occurrence++;
- return `${parentPath}${segment4(name, occurrence)}`;
- };
- const path = at(node.getName());
- record(node, path);
- visit(node.listChildren(), path);
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
- for (const level of lower) {
- const levelPath = at(level.getName());
- record(level, levelPath);
- visit(level.listChildren(), levelPath);
- }
- });
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
- const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
- return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
-}
-function inspectDelivery(doc) {
- const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return summary;
- const visited = [];
- const visit = (siblings, parentPath, hidden, module) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment4(name, occurrence)}`;
- const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
- const nodeHidden = hidden || isHiddenGltfNode(node);
- const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
- visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
- visit(node.listChildren(), path, nodeHidden, nodeModule);
- }
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0), false, undefined);
- const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
- const { min, max } = drawnSceneBounds(scene);
- const bounds = new THREE28.Box3(new THREE28.Vector3(...min), new THREE28.Vector3(...max));
- const finiteBounds = [...min, ...max].every(Number.isFinite);
- const diagonal = finiteBounds ? bounds.getSize(new THREE28.Vector3).length() : 0;
- const tolerance = Math.max(0.0001, diagonal * 0.0001);
- const colliderNodes = [];
- for (const entry of visited) {
- const { node, path, roles } = entry;
- for (const role of roles) {
- const matrix = worldMatrix(node);
- const transform = decompose(matrix);
- for (const shape of ["box", "capsule", "hull"]) {
- const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
- if (id === undefined)
- continue;
- const scale = transform.scale;
- const record = {
- role,
- id,
- path,
- name: node.getName(),
- transform,
- shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
- kind: "hull",
- vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
- }
- };
- summary.colliders.push(record);
- colliderNodes.push({ visit: entry, record });
- }
- const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
- if (anchorTail !== undefined) {
- const [kind, ...rest] = anchorTail.split(".");
- summary.anchors.push({
- role,
- kind,
- id: rest.join("."),
- path,
- name: node.getName(),
- transform
- });
- }
- const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
- if (portId !== undefined)
- summary.ports.push({
- role,
- id: portId,
- path,
- name: node.getName(),
- ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
- transform
- });
- if (role === KILN_SEMANTIC_ROLES.kitModule) {
- const extras = node.getExtras()[KILN_KIT_KEY];
- let spec;
- try {
- const { schemaVersion, ...rest } = extras ?? {};
- spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
- } catch {
- spec = undefined;
- }
- if (!spec)
- finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
- else if (summary.kit)
- finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
- else
- summary.kit = {
- role,
- path,
- name: node.getName(),
- footprint: spec.footprint,
- height: spec.height,
- snapAxis: spec.snapAxis,
- origin: spec.origin,
- transform
- };
- }
- }
- }
- const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
- const triangleCount = triangles.length / 9;
- let overlapTests = 0;
- const a = new THREE28.Vector3;
- const b = new THREE28.Vector3;
- const c = new THREE28.Vector3;
- for (const { visit: entry, record } of colliderNodes) {
- if (!entry.hidden)
- finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
- const matrix = worldMatrix(entry.node);
- const proxyBounds = new THREE28.Box3;
- const mesh = entry.node.getMesh();
- const local = [0, 0, 0];
- for (const primitive of mesh?.listPrimitives() ?? []) {
- const position = primitive.getAttribute("POSITION");
- for (let i = 0;i < (position?.getCount() ?? 0); i++)
- proxyBounds.expandByPoint(new THREE28.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
- }
- if (proxyBounds.isEmpty())
- proxyBounds.expandByPoint(new THREE28.Vector3().setFromMatrixPosition(matrix));
- const expanded = bounds.clone().expandByScalar(tolerance);
- if (!finiteBounds || !expanded.containsBox(proxyBounds))
- finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
- if (record.shape.kind === "hull")
- continue;
- if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
- finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
- continue;
- }
- overlapTests += triangleCount;
- const toLocal = new THREE28.Matrix4;
- let touches = false;
- if (record.shape.kind === "box") {
- toLocal.copy(matrix).invert();
- const half = new THREE28.Vector3(0.5, 0.5, 0.5);
- const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
- }
- } else {
- const { translation, rotation } = record.transform;
- toLocal.compose(new THREE28.Vector3(...translation), new THREE28.Quaternion(...rotation), new THREE28.Vector3(1, 1, 1)).invert();
- const { radius, height } = record.shape;
- const p = new THREE28.Vector3(0, -height / 2 + radius, 0);
- const q = new THREE28.Vector3(0, height / 2 - radius, 0);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
- }
- }
- if (!touches)
- finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
- }
- for (const record of summary.ports) {
- const entry = visited.find((item) => item.path === record.path);
- const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
- const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
- if (!spec) {
- finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
- continue;
- }
- const point = new THREE28.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
- const [width, depth] = spec.footprint;
- const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
- const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
- if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
- finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
- }
- for (const record of summary.anchors) {
- const entry = visited.find((item) => item.path === record.path);
- if (entry.node.listChildren().length > 0)
- finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
- }
- return summary;
-}
-var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE28.Matrix4().fromArray(node.getWorldMatrix());
-var init_delivery_inspect = __esm(() => {
- init_gltf_io();
- init_semantic();
- init_delivery();
- init_metrics();
- init_node_visibility();
-});
-
// src/surface-bake.ts
import * as THREE29 from "three";
function settings(value, label) {
@@ -38527,13 +39004,13 @@ var init_asset_export = __esm(() => {
});
// src/project-bundle.ts
-import { z as z14 } from "zod";
+import { z as z15 } from "zod";
import { zipSync as zipSync2, unzipSync as unzipSync2 } from "three/addons/libs/fflate.module.js";
async function projectBundleHash(bytes) {
const result = new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));
return `sha256:${Array.from(result, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}
-var PROJECT_BUNDLE_LIMITS, hashSchema, id2 = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2;
+var PROJECT_BUNDLE_LIMITS, hashSchema, id3 = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2;
var init_project_bundle = __esm(() => {
init_assets();
init_asset_export();
@@ -38545,33 +39022,33 @@ var init_project_bundle = __esm(() => {
maxEntries: 8192,
maxManifestBytes: 2 * 1024 * 1024
});
- hashSchema = z14.string().regex(/^sha256:[a-f0-9]{64}$/);
- pathSchema = z14.string().regex(new RegExp(`^(project\\.json|materials/${id2}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id2}/${id2}/${id2}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
- identitySchema = z14.object({
+ hashSchema = z15.string().regex(/^sha256:[a-f0-9]{64}$/);
+ pathSchema = z15.string().regex(new RegExp(`^(project\\.json|materials/${id3}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id3}/${id3}/${id3}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
+ identitySchema = z15.object({
inventoryId: assetIdSchema,
collectionId: assetIdSchema,
assetId: assetIdSchema,
revisionId: assetIdSchema,
canonicalGlbSha256: hashSchema
}).strict();
- projectBundleManifestSchema = z14.object({
- version: z14.literal("kiln.project-bundle.v1"),
- profile: z14.enum(["editable", "runtime"]),
- editable: z14.boolean(),
- resourceClosure: z14.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
- referenceMediaIncluded: z14.literal(false),
- originalAcquisitionFilesIncluded: z14.literal(false),
- assets: z14.array(identitySchema).max(1000),
- materials: z14.array(z14.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
- files: z14.record(pathSchema, z14.object({
+ projectBundleManifestSchema = z15.object({
+ version: z15.literal("kiln.project-bundle.v1"),
+ profile: z15.enum(["editable", "runtime"]),
+ editable: z15.boolean(),
+ resourceClosure: z15.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
+ referenceMediaIncluded: z15.literal(false),
+ originalAcquisitionFilesIncluded: z15.literal(false),
+ assets: z15.array(identitySchema).max(1000),
+ materials: z15.array(z15.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
+ files: z15.record(pathSchema, z15.object({
sha256: hashSchema,
- bytes: z14.number().int().nonnegative().max(64 * 1024 * 1024)
+ bytes: z15.number().int().nonnegative().max(64 * 1024 * 1024)
}).strict())
}).strict();
projectBundleManifestV2Schema = projectBundleManifestSchema.extend({
- version: z14.literal("kiln.project-bundle.v2")
+ version: z15.literal("kiln.project-bundle.v2")
});
- projectBundleManifestAnySchema = z14.union([
+ projectBundleManifestAnySchema = z15.union([
projectBundleManifestSchema,
projectBundleManifestV2Schema
]);
@@ -38810,10 +39287,10 @@ function createPartPlacementReader(root) {
};
};
}
-var round2 = (value) => {
+var round3 = (value) => {
const rounded = Math.round(value * 1e6) / 1e6;
return rounded === 0 ? 0 : rounded;
-}, rounded2 = (values) => values.map(round2);
+}, rounded2 = (values) => values.map(round3);
var init_part_placement = __esm(() => {
init_raster();
});
@@ -40123,7 +40600,7 @@ import {
// src/tools/registry.ts
init_capture_cache();
init_assets();
-import { z as z23 } from "zod";
+import { z as z24 } from "zod";
// src/requirements-assets.ts
init_requirements_context();
@@ -40154,10 +40631,10 @@ function assertSavedRequirementsAuthorized(manifest, current) {
}
// src/tools/programs.ts
-import { z as z7 } from "zod";
+import { z as z8 } from "zod";
// src/tools/review-detail.ts
-import { z as z6 } from "zod";
+import { z as z7 } from "zod";
var COMPACT_PART_PREVIEW = 24;
var COMPACT_FINDINGS_PER_DIMENSION = 12;
var LEAD_BLOCKERS = 8;
@@ -40167,7 +40644,7 @@ var WARNING_CHARS = 1000;
var DEFAULT_RESULT_LIMIT = 20000;
var MAX_RESULT_LIMIT = 40000;
var COMPACT_DECIMALS = 6;
-var reviewDetailInput = z6.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
+var reviewDetailInput = z7.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
function requestedDetail(input, fallback = "compact") {
const detail = input?.detail;
return detail === "full" || detail === "lean" || detail === "compact" ? detail : fallback;
@@ -40733,19 +41210,19 @@ function compactEditResult(result, detail = "compact", options = {}) {
}
// src/tools/programs.ts
-var refInput = z7.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
+var refInput = z8.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
function withProgramReferences(def, store, readSourceFile) {
- if (!(def.inputSchema instanceof z7.ZodObject))
+ if (!(def.inputSchema instanceof z8.ZodObject))
throw new Error(`${def.name} must have an object input schema.`);
const sources = readSourceFile ? "code, programRef OR file" : "code OR programRef";
const inputSchema = def.inputSchema.extend({
- code: z7.string().optional().describe("New source."),
+ code: z8.string().optional().describe("New source."),
programRef: refInput.optional(),
...readSourceFile ? {
- file: z7.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
+ file: z8.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
} : {},
...def.name === "kiln_edit" ? {
- includeCode: z7.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
+ includeCode: z8.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
} : {}
}).refine((input) => [input.code, input.programRef, input.file].filter((value) => value !== undefined).length === 1, { message: `Supply exactly one of ${sources.replace(" OR ", " or ")}.` });
const summaries = {
@@ -40798,11 +41275,11 @@ function boundIncludedCode(result, limit) {
};
}
function createKilnSourceDef(store) {
- const inputSchema = z7.object({
+ const inputSchema = z8.object({
programRef: refInput,
- offset: z7.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
- limit: z7.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
- query: z7.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
+ offset: z8.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
+ limit: z8.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
+ query: z8.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
});
return {
name: "kiln_source",
@@ -40839,34 +41316,34 @@ function engineIdentity() {
init_helper_specs();
// src/discovery/catalog-schema.ts
-import { z as z8 } from "zod";
-var text5 = z8.string().trim().min(1);
-var texts = z8.array(text5);
-var id = z8.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
+import { z as z9 } from "zod";
+var text5 = z9.string().trim().min(1);
+var texts = z9.array(text5);
+var id2 = z9.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
var common = {
- version: z8.literal("kiln.catalog-entry.v1"),
- id,
+ version: z9.literal("kiln.catalog-entry.v1"),
+ id: id2,
name: text5,
summary: text5.max(500),
family: text5.max(80),
tags: texts,
aliases: texts,
intents: texts,
- stability: z8.enum(["stable", "experimental", "deprecated"]),
- related: z8.array(z8.object({
- id,
- relation: z8.enum(["alternative", "prerequisite", "companion"])
+ stability: z9.enum(["stable", "experimental", "deprecated"]),
+ related: z9.array(z9.object({
+ id: id2,
+ relation: z9.enum(["alternative", "prerequisite", "companion"])
}).strict()),
references: texts,
limitations: texts
};
-var operationContractSchema = z8.object({
+var operationContractSchema = z9.object({
signature: text5,
returns: text5,
units: text5,
axes: text5,
origin: text5,
- execution: z8.enum(["sync", "async"]),
+ execution: z9.enum(["sync", "async"]),
ownership: text5,
coordinates: text5,
parameters: texts,
@@ -40876,24 +41353,24 @@ var operationContractSchema = z8.object({
cost: text5,
example: text5
}).strict();
-var discoveryEntrySchema = z8.discriminatedUnion("kind", [
- z8.object({ ...common, kind: z8.literal("operation"), contract: operationContractSchema }).strict(),
- z8.object({ ...common, kind: z8.literal("assembly"), contract: operationContractSchema }).strict(),
- z8.object({
+var discoveryEntrySchema = z9.discriminatedUnion("kind", [
+ z9.object({ ...common, kind: z9.literal("operation"), contract: operationContractSchema }).strict(),
+ z9.object({ ...common, kind: z9.literal("assembly"), contract: operationContractSchema }).strict(),
+ z9.object({
...common,
- kind: z8.literal("recipe"),
- recipe: z8.object({
- prerequisites: z8.array(id),
+ kind: z9.literal("recipe"),
+ recipe: z9.object({
+ prerequisites: z9.array(id2),
steps: texts.min(1),
example: text5,
adaptations: texts,
checks: texts
}).strict()
}).strict(),
- z8.object({
+ z9.object({
...common,
- kind: z8.literal("shape"),
- shape: z8.object({ tool: text5, field: text5, schema: z8.record(z8.string(), z8.unknown()) }).strict()
+ kind: z9.literal("shape"),
+ shape: z9.object({ tool: text5, field: text5, schema: z9.record(z9.string(), z9.unknown()) }).strict()
}).strict()
]).superRefine((entry, ctx) => {
if (!entry.id.startsWith(`${entry.kind}:`)) {
@@ -40912,7 +41389,7 @@ var discoveryEntrySchema = z8.discriminatedUnion("kind", [
}
});
function parseCatalog(value) {
- const entries = z8.array(discoveryEntrySchema).parse(value);
+ const entries = z9.array(discoveryEntrySchema).parse(value);
const ids = new Set;
const names = new Set;
for (const entry of entries) {
@@ -44507,24 +44984,24 @@ var discoveryRecipes = [
// src/discovery/shapes.ts
init_material_library();
init_projects();
-import { z as z11 } from "zod";
+import { z as z12 } from "zod";
// src/tools/capture-input.ts
init_background();
init_capture_limits();
-import { z as z10 } from "zod";
-var backdropInput = z10.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
-var legacyCaptureInput = z10.object({
- preset: z10.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
- cells: z10.array(z10.object({
- azimuthDeg: z10.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
- elevationDeg: z10.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
- zoom: z10.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
- name: z10.string().optional().describe("Label; defaults to angles.")
+import { z as z11 } from "zod";
+var backdropInput = z11.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
+var legacyCaptureInput = z11.object({
+ preset: z11.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
+ cells: z11.array(z11.object({
+ azimuthDeg: z11.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
+ elevationDeg: z11.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
+ zoom: z11.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
+ name: z11.string().optional().describe("Label; defaults to angles.")
})).optional().describe("Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9)."),
backdrop: backdropInput
}).optional().describe("Sheet layout and cameras; omit for six views in a 3x2 grid.");
-var cameraVec3Input = z10.array(z10.number()).length(3);
+var cameraVec3Input = z11.array(z11.number()).length(3);
var orbitCameraError = (issue) => {
if (issue.code === "unrecognized_keys" && issue.keys?.some((key) => key === "target" || key === "distance")) {
return "Orbit cameras derive target and distance from the selected subject bounds; choose subject and padding, or use an explicit camera with position and target.";
@@ -44544,48 +45021,48 @@ var advancedCaptureError = (issue) => {
}
return;
};
-var cameraShotInput = z10.object({
- name: z10.string().optional(),
- subject: z10.object({ path: z10.string().optional(), name: z10.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
+var cameraShotInput = z11.object({
+ name: z11.string().optional(),
+ subject: z11.object({ path: z11.string().optional(), name: z11.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
message: "Choose subject path OR exact name."
}).optional(),
- visibility: z10.enum(["context", "isolate"]).optional(),
- hide: z10.array(z10.string().min(1).max(1024)).max(64).optional(),
- camera: z10.discriminatedUnion("type", [
- z10.strictObject({
- type: z10.literal("orbit"),
- azimuthDeg: z10.number().optional(),
- elevationDeg: z10.number().optional(),
- relativeTo: z10.enum(["world", "asset", "part"]).optional(),
- padding: z10.number().positive().max(100).optional()
+ visibility: z11.enum(["context", "isolate"]).optional(),
+ hide: z11.array(z11.string().min(1).max(1024)).max(64).optional(),
+ camera: z11.discriminatedUnion("type", [
+ z11.strictObject({
+ type: z11.literal("orbit"),
+ azimuthDeg: z11.number().optional(),
+ elevationDeg: z11.number().optional(),
+ relativeTo: z11.enum(["world", "asset", "part"]).optional(),
+ padding: z11.number().positive().max(100).optional()
}, { error: orbitCameraError }),
- z10.strictObject({
- type: z10.literal("explicit"),
- projection: z10.enum(["orthographic", "perspective"]),
+ z11.strictObject({
+ type: z11.literal("explicit"),
+ projection: z11.enum(["orthographic", "perspective"]),
position: cameraVec3Input,
target: cameraVec3Input.optional(),
- relativeTo: z10.enum(["world", "asset", "part", "local"]).optional(),
- frame: z10.object({
+ relativeTo: z11.enum(["world", "asset", "part", "local"]).optional(),
+ frame: z11.object({
origin: cameraVec3Input.optional(),
rotation: cameraVec3Input.optional()
}).strict().optional(),
- framing: z10.enum(["explicit", "bounds"]).optional(),
- padding: z10.number().positive().max(100).optional(),
+ framing: z11.enum(["explicit", "bounds"]).optional(),
+ padding: z11.number().positive().max(100).optional(),
targetOffset: cameraVec3Input.optional(),
up: cameraVec3Input.optional(),
- halfHeight: z10.number().positive().optional(),
- fovDeg: z10.number().positive().lt(180).optional(),
- near: z10.number().positive().optional(),
- far: z10.number().positive().optional()
+ halfHeight: z11.number().positive().optional(),
+ fovDeg: z11.number().positive().lt(180).optional(),
+ near: z11.number().positive().optional(),
+ far: z11.number().positive().optional()
}, { error: explicitCameraError })
]).optional()
}).strict();
-var advancedCaptureInput = z10.strictObject({
- version: z10.enum(["kiln.capture.v1", "kiln.capture.v2"]),
- shots: z10.array(cameraShotInput).min(1).max(9),
- cols: z10.number().int().min(1).max(3).optional(),
- size: z10.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
- output: z10.enum(["grid", "separate"]).optional(),
+var advancedCaptureInput = z11.strictObject({
+ version: z11.enum(["kiln.capture.v1", "kiln.capture.v2"]),
+ shots: z11.array(cameraShotInput).min(1).max(9),
+ cols: z11.number().int().min(1).max(3).optional(),
+ size: z11.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
+ output: z11.enum(["grid", "separate"]).optional(),
backdrop: backdropInput
}, { error: advancedCaptureError }).superRefine((input, context) => {
if (input.version === "kiln.capture.v1" && input.shots.some((shot) => shot.hide !== undefined))
@@ -44606,19 +45083,19 @@ function taggedCaptureError(issue) {
const details = issues.slice(0, 6).map((problem) => `${problem.path.join(".") || "capture"}: ${problem.message.slice(0, 240)}`);
return `Invalid ${input.version}: ${details.join("; ")}${issues.length > 6 ? "; additional issues omitted" : ""}`;
}
-var captureShapeInput = z10.union([
+var captureShapeInput = z11.union([
advancedCaptureInput,
- z10.strictObject(legacyCaptureInput.unwrap().shape, {
+ z11.strictObject(legacyCaptureInput.unwrap().shape, {
error: taggedCaptureError
})
], { error: taggedCaptureError });
var captureInput = captureShapeInput.optional().describe("Omit for six views; preset/cells for orbit sheets. Use kiln.capture.v1 or v2 with 1..9 shots for exact cameras. v2 adds hide: exact paths or unique names. Framing retains subject bounds.");
-var captureRecordInput = z10.record(z10.string(), z10.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
-var cameraShotRecordInput = z10.record(z10.string(), z10.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
+var captureRecordInput = z11.record(z11.string(), z11.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
+var cameraShotRecordInput = z11.record(z11.string(), z11.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
// src/discovery/shapes.ts
var jsonSchema = (schema) => {
- const { $schema: _dialect, ...rest } = z11.toJSONSchema(schema, { io: "input", reused: "ref" });
+ const { $schema: _dialect, ...rest } = z12.toJSONSchema(schema, { io: "input", reused: "ref" });
return rest;
};
var shape2 = (name, tool, field, summary, schema, extra = {}) => ({
@@ -44816,25 +45293,25 @@ function createLexicalDiscoveryIndex(entries) {
}
// src/discovery/query-schema.ts
-import { z as z12 } from "zod";
-var selector = z12.string().trim().min(1).max(120);
+import { z as z13 } from "zod";
+var selector = z13.string().trim().min(1).max(120);
function discoverySelectorMigration(keys) {
if (!keys.some((key) => ["category", "name", "names"].includes(key)))
return;
return "Legacy Discovery selectors category/name/names were removed. Use query for search, ids (CLI --id) for exact contracts, and family (CLI --family), kind or tags for filtering. See docs/migration.md.";
}
-var discoveryInputSchema = z12.object({
- query: z12.string().trim().min(1).max(500).optional(),
- ids: z12.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
+var discoveryInputSchema = z13.object({
+ query: z13.string().trim().min(1).max(500).optional(),
+ ids: z13.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
message: "Exact IDs must be unique."
}).optional(),
- overview: z12.literal(true).optional(),
- capabilities: z12.literal(true).optional(),
+ overview: z13.literal(true).optional(),
+ capabilities: z13.literal(true).optional(),
family: selector.optional(),
- kind: z12.enum(["operation", "assembly", "recipe", "shape"]).optional(),
- tags: z12.array(selector).min(1).max(8).optional(),
- offset: z12.number().int().min(0).max(1e4).optional(),
- limit: z12.number().int().min(1).max(12).optional()
+ kind: z13.enum(["operation", "assembly", "recipe", "shape"]).optional(),
+ tags: z13.array(selector).min(1).max(8).optional(),
+ offset: z13.number().int().min(0).max(1e4).optional(),
+ limit: z13.number().int().min(1).max(12).optional()
}, {
error: (issue) => issue.code === "unrecognized_keys" ? discoverySelectorMigration(issue.keys) : undefined
}).strict().superRefine((input, context) => {
@@ -45101,6 +45578,7 @@ init_capture_limits();
init_geometry_export();
init_community_exporter();
init_material_resources();
+init_requirements_context();
function createKilnDiscoveryDef(context, presentation = "grouped") {
const run = createDiscovery(() => currentCapabilities(context, presentation), async () => projectNotes(context), presentation === "operations" ? "kiln_capabilities({})" : "capabilities:true");
return {
@@ -45120,6 +45598,15 @@ Suggestions: ${structured.suggestions.join(", ")}` : text;
function configuredProject(context) {
return context.workspace?.configured?.() ?? null;
}
+function hostRequirements(context) {
+ const active = resolveRequirementsContext(context.requirements);
+ const validation = active.requirements.requirements.validation;
+ return {
+ bound: active.binding !== undefined,
+ policyHash: active.policyHash,
+ declared: validation?.state === "requested" ? { source: "host-binding", validationProfile: validation.value } : null
+ };
+}
function projectNotes(context) {
const projectId = configuredProject(context);
return projectId ? [
@@ -45161,6 +45648,7 @@ async function currentCapabilities(context, presentation) {
read: 'kiln_project { action: "get", projectId } returns the brief, design, inventory and material pins'
},
renderer,
+ requirements: hostRequirements(context),
execution: context.localExecution ?? (context.evaluatorPort ? { mode: "host-injected", limits: "unspecified by host" } : context.evaluatorProfile === "evaluator-required" ? { mode: "host-required", available: false } : { mode: "trusted-local", terminable: false }),
source: {
...context.programStore?.stats ? { storage: await context.programStore.stats() } : {},
@@ -45226,7 +45714,7 @@ async function currentCapabilities(context, presentation) {
// src/tools/projects.ts
init_projects();
-import { z as z15 } from "zod";
+import { z as z16 } from "zod";
// src/tools/actions.ts
var list = (fields) => fields.length <= 1 ? fields.join("") : `${fields.slice(0, -1).join(", ")} and ${fields.at(-1)}`;
@@ -45285,16 +45773,16 @@ var REQUIREMENTS = {
},
export: { required: ["projectId"] }
};
-var record10 = (description) => z15.record(z15.string(), z15.unknown()).optional().describe(description);
+var record10 = (description) => z16.record(z16.string(), z16.unknown()).optional().describe(description);
function projectToolInput(actions = PROJECT_ACTIONS) {
- return z15.strictObject({
- action: z15.enum(actions),
+ return z16.strictObject({
+ action: z16.enum(actions),
projectId: projectIdSchema.optional().describe("get, update, export."),
revisionId: projectRevisionIdSchema.optional().describe("get, export: an exact revision; omit for the current one."),
expectedRevision: projectRevisionIdSchema.optional().describe("update: the revision being replaced; a stale value is a conflict."),
draft: record10(nestedRecordDescription("create: name, brief, design, inventory, deliveryProfiles, materialDependencies, references, reviews; optional projectId.", "shape:project-draft")),
patch: record10(nestedRecordDescription("update: the same top-level fields as draft; each supplied field replaces its previous value whole.", "shape:project-patch")),
- profile: z15.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
+ profile: z16.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
});
}
function createKilnProjectDef(store, bundleReader) {
@@ -45378,7 +45866,7 @@ async function listAssetCatalog(library) {
// src/tools/materials.ts
init_material_library();
init_material_library_node();
-import { z as z17 } from "zod";
+import { z as z18 } from "zod";
// src/material-authoring-node.ts
init_material_library();
@@ -45427,7 +45915,7 @@ async function createProceduralMaterialRecord(value, library) {
// src/material-presets.ts
init_material_library();
-import { z as z16 } from "zod";
+import { z as z17 } from "zod";
var catalog2 = [
{
id: "warm-brick",
@@ -45508,10 +45996,10 @@ var catalog2 = [
}
];
var RECORD_V2_PRESETS = new Set(["palm-frond"]);
-var materialPresetOptionsSchema = z16.object({
- seed: z16.number().int().min(-2147483648).max(2147483647),
- size: z16.union([z16.literal(64), z16.literal(128), z16.literal(256), z16.literal(512)]).default(256),
- creator: z16.string().min(1).max(1000),
+var materialPresetOptionsSchema = z17.object({
+ seed: z17.number().int().min(-2147483648).max(2147483647),
+ size: z17.union([z17.literal(64), z17.literal(128), z17.literal(256), z17.literal(512)]).default(256),
+ creator: z17.string().min(1).max(1000),
license: materialSourceSchema.shape.license,
materialId: materialLibraryIdSchema.optional()
}).strict();
@@ -45814,15 +46302,15 @@ var MATERIAL_CONTRACT = {
description: "Import complete normalized material records and embedded PNGs. Does not fetch URLs or execute source."
}
};
-var record11 = (description) => z17.record(z17.string(), z17.unknown()).optional().describe(description);
-var tag = z17.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
-var materialToolInput = z17.strictObject({
- action: z17.enum(MATERIAL_ACTIONS),
+var record11 = (description) => z18.record(z18.string(), z18.unknown()).optional().describe(description);
+var tag = z18.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
+var materialToolInput = z18.strictObject({
+ action: z18.enum(MATERIAL_ACTIONS),
tag,
- presetId: z17.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
- seed: z17.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
- size: z17.union([z17.literal(64), z17.literal(128), z17.literal(256), z17.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
- creator: z17.string().min(1).max(1000).optional().describe("create-preset."),
+ presetId: z18.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
+ seed: z18.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
+ size: z18.union([z18.literal(64), z18.literal(128), z18.literal(256), z18.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
+ creator: z18.string().min(1).max(1000).optional().describe("create-preset."),
license: materialSourceSchema.shape.license.optional().describe("create-preset: spdx, url and attribution."),
materialId: materialLibraryIdSchema.optional().describe("get: the id a project palette lists as resourceId; create-preset: optional id."),
revisionId: materialLibraryHashSchema.optional().describe("get: the immutable revision; omitted, the material's only revision."),
@@ -45939,7 +46427,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {
// src/tools/review.ts
init_assets();
init_requirements_context();
-import { z as z18 } from "zod";
+import { z as z19 } from "zod";
init_background();
// src/tools/preview-fidelity.ts
@@ -45959,8 +46447,8 @@ async function persistedPreviewFidelity(fidelity, glb) {
}
// src/tools/review.ts
-var operationId = z18.string().regex(/^op_[a-f0-9-]{36}$/);
-var assetId = z18.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+var operationId = z19.string().regex(/^op_[a-f0-9-]{36}$/);
+var assetId = z19.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
var REVIEW_ACTIONS = ["list", "get", "pin", "save"];
var REQUIREMENTS2 = {
list: { required: [] },
@@ -45968,20 +46456,20 @@ var REQUIREMENTS2 = {
pin: { required: ["operationId", "pinned"] },
save: { required: ["operationId", "expectedRevision", "name"] }
};
-var reviewToolInput = z18.strictObject({
- action: z18.enum(REVIEW_ACTIONS),
+var reviewToolInput = z19.strictObject({
+ action: z19.enum(REVIEW_ACTIONS),
projectId: assetId.optional().describe("list: only operations bound to this project."),
- offset: z18.number().int().min(0).optional().describe("list: page start; default 0."),
- limit: z18.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
+ offset: z19.number().int().min(0).optional().describe("list: page start; default 0."),
+ limit: z19.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
operationId: operationId.optional().describe("get, pin, save."),
- pinned: z18.boolean().optional().describe("pin: true keeps the operation past normal retention."),
- expectedRevision: z18.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
+ pinned: z19.boolean().optional().describe("pin: true keeps the operation past normal retention."),
+ expectedRevision: z19.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
collection: assetId.optional().describe("save: destination collection; default project."),
- name: z18.string().min(1).max(200).optional().describe("save."),
+ name: z19.string().min(1).max(200).optional().describe("save."),
assetId: assetId.optional().describe("save: revise this asset."),
parentRevision: assetId.optional().describe("save: the revision being revised."),
- description: z18.string().max(4000).optional().describe("save."),
- tags: z18.array(z18.string().max(80)).max(30).optional().describe("save.")
+ description: z19.string().max(4000).optional().describe("save."),
+ tags: z19.array(z19.string().max(80)).max(30).optional().describe("save.")
});
var DEFAULT_PAGE = 20;
function summarizeOperation(operation) {
@@ -46116,7 +46604,7 @@ function createKilnReviewDef(context) {
}))
];
const preview = operation.captures[0] ? await store.readFile(operation.operationId, operation.captures[0].name) : undefined;
- const capture = z18.object({ backdrop: z18.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
+ const capture = z19.object({ backdrop: z19.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
const asset = await context.assetLibrary.save(collection, {
name: input.name,
assetId: input.assetId,
@@ -46153,12 +46641,12 @@ function createKilnReviewDef(context) {
}
// src/tools/workspace.ts
-import { z as z20 } from "zod";
+import { z as z21 } from "zod";
// src/workspace.ts
init_projects();
-import { z as z19 } from "zod";
-var workspaceSelectionSchema = z19.object({
+import { z as z20 } from "zod";
+var workspaceSelectionSchema = z20.object({
projectId: projectIdSchema.nullable().optional().describe("Project; omit for the configured default, null for standalone."),
projectRevision: projectRevisionIdSchema.optional().describe("Exact project revision."),
materialDependencies: materialDependenciesSchema.optional().describe("Pins for this call; each replaces the project pin of its resourceId.")
@@ -46219,7 +46707,7 @@ async function observeWorkspaceOperation(context, tool, input, run) {
function withWorkspaceContext(def, context) {
if (!observed.has(def.name))
return def;
- const schema = context.workspace && def.inputSchema instanceof z20.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
+ const schema = context.workspace && def.inputSchema instanceof z21.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
return {
...def,
inputSchema: schema,
@@ -46235,10 +46723,10 @@ function withWorkspaceContext(def, context) {
}
// src/tools/operations.ts
-import { z as z22 } from "zod";
+import { z as z23 } from "zod";
// src/tools/operation-contract.ts
-import { z as z21 } from "zod";
+import { z as z22 } from "zod";
// src/build-cache.ts
init_protocol();
@@ -46956,11 +47444,11 @@ function derivativeReviewFidelity(receipts) {
...reasonCodes.length ? { reasonCodes } : {}
};
}
-var validateInput = z23.object({
- code: z23.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
+var validateInput = z24.object({
+ code: z24.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
});
-var renderInput = z23.object({
- code: z23.string().describe("Kiln source code to execute and render to an in-memory GLB.")
+var renderInput = z24.object({
+ code: z24.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
var renderViewsInput = renderInput.extend({ capture: captureInput, detail: reviewDetailInput });
var reviewDetailOptions = (context) => ({
@@ -46973,26 +47461,26 @@ var reviewDetailOptions = (context) => ({
}
});
var renderViewsBufferInput = renderViewsInput.omit({ code: true });
-var screenshotAnimationInput = z23.object({
+var screenshotAnimationInput = z24.object({
shot: cameraShotInput.optional(),
- measureParts: z23.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
- frames: z23.number().int().min(2).max(6).optional(),
- frameTimes: z23.array(z23.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
- framing: z23.enum(["locked", "follow"]).optional(),
- size: z23.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
+ measureParts: z24.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
+ frames: z24.number().int().min(2).max(6).optional(),
+ frameTimes: z24.array(z24.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
+ framing: z24.enum(["locked", "follow"]).optional(),
+ size: z24.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
detail: reviewDetailInput,
- code: z23.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
- clip: z23.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
- camera: z23.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
- perFrame: z23.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
+ code: z24.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
+ clip: z24.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
+ camera: z24.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
+ perFrame: z24.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
});
var screenshotAnimationAdvertisedInput = screenshotAnimationInput.extend({
shot: cameraShotRecordInput
});
-var viewInteriorInput = z23.object({
+var viewInteriorInput = z24.object({
capture: advancedCaptureInput.optional(),
- code: z23.string().describe("Kiln source code to execute and render with the roof hidden."),
- nodeName: z23.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
+ code: z24.string().describe("Kiln source code to execute and render with the roof hidden."),
+ nodeName: z24.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
});
var viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureRecordInput });
function runValidate(input, context) {
@@ -47007,11 +47495,11 @@ function runValidate(input, context) {
warnings: result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
};
}
-var partListInput = z23.object({
- query: z23.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
- offset: z23.number().int().min(0).optional(),
- limit: z23.number().int().min(1).max(100).optional(),
- placement: z23.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
+var partListInput = z24.object({
+ query: z24.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
+ offset: z24.number().int().min(0).optional(),
+ limit: z24.number().int().min(1).max(100).optional(),
+ placement: z24.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
}).strict();
var PLACEMENT_PAGE_LIMIT = 50;
async function listPartNames2(root, options = {}) {
@@ -47485,35 +47973,35 @@ function createKilnViewInteriorDef(context = {}) {
};
}
var kilnViewInteriorDef = createKilnViewInteriorDef();
-var attachmentEndpointInput = z23.object({
- subject: z23.object({ path: z23.string().optional(), name: z23.string().optional() }).strict(),
+var attachmentEndpointInput = z24.object({
+ subject: z24.object({ path: z24.string().optional(), name: z24.string().optional() }).strict(),
point: cameraVec3Input.optional()
}).strict();
-var surfacePairInput = z23.array(z23.string().max(4096)).length(2);
-var inspectInput = z23.object({
- image: z23.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
+var surfacePairInput = z24.array(z24.string().max(4096)).length(2);
+var inspectInput = z24.object({
+ image: z24.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
detail: reviewDetailInput,
listParts: partListInput.optional().describe("List exported-scene paths, including nested parts. Default 80, max 100 per page. Follow partListing.nextOffset with the same programRef/query. image:false avoids rendering."),
- surfacePairs: z23.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
- compare: z23.object({
- programRef: z23.string().regex(programRefPattern),
- offset: z23.number().int().min(0).optional(),
- limit: z23.number().int().min(1).max(100).optional(),
- paths: z23.array(z23.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
+ surfacePairs: z24.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
+ compare: z24.object({
+ programRef: z24.string().regex(programRefPattern),
+ offset: z24.number().int().min(0).optional(),
+ limit: z24.number().int().min(1).max(100).optional(),
+ paths: z24.array(z24.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
}).strict().optional().describe("Static geometry/material/transform/bounds under current host settings. Follow nextOffset; paths adds complete subtrees."),
- measure: z23.object({
- mode: z23.enum(["anchors", "surface"]).optional(),
+ measure: z24.object({
+ mode: z24.enum(["anchors", "surface"]).optional(),
from: attachmentEndpointInput,
to: attachmentEndpointInput
}).strict().optional().describe("Default anchors: origin/local-point distance. Surface: disjoint mesh triangles, omit points. Rest pose, asset units. Check status/bounds; no solid clearance/attachment proof."),
shot: cameraShotInput.optional().describe("Exact shot; omit part/view/orbit controls."),
- code: z23.string().describe("Kiln source code to execute and inspect."),
- part: z23.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
- view: z23.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
- azimuthDeg: z23.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
- elevationDeg: z23.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
- zoom: z23.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
- isolate: z23.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
+ code: z24.string().describe("Kiln source code to execute and inspect."),
+ part: z24.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
+ view: z24.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
+ azimuthDeg: z24.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
+ elevationDeg: z24.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
+ zoom: z24.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
+ isolate: z24.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
});
var inspectBufferInput = inspectInput.omit({ code: true });
var inspectAdvertisedInput = inspectInput.extend({ shot: cameraShotRecordInput });
@@ -47673,15 +48161,15 @@ function createKilnInspectDef(context = {}) {
};
}
var kilnInspectDef = createKilnInspectDef();
-var editOperationInput = z23.object({
- oldString: z23.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
- newString: z23.string().describe("The replacement text. Use an empty string to delete."),
- replaceAll: z23.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
-});
-var editInput = z23.object({
- code: z23.string().describe("The Kiln program to patch. The full current source."),
- edits: z23.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
- render: z23.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
+var editOperationInput = z24.object({
+ oldString: z24.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
+ newString: z24.string().describe("The replacement text. Use an empty string to delete."),
+ replaceAll: z24.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
+});
+var editInput = z24.object({
+ code: z24.string().describe("The Kiln program to patch. The full current source."),
+ edits: z24.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
+ render: z24.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
capture: captureInput,
detail: reviewDetailInput
});
@@ -47907,10 +48395,10 @@ function withCaptureCache(context) {
} : {}
};
}
-var rendererInput = z23.strictObject({
- action: z23.enum(["status", "reprobe"]).default("status")
+var rendererInput = z24.strictObject({
+ action: z24.enum(["status", "reprobe"]).default("status")
});
-var rendererStatusInput = z23.strictObject({});
+var rendererStatusInput = z24.strictObject({});
async function runRenderer(context, action) {
if (action === "reprobe" && !context.reprobeRenderer)
return {
@@ -48009,14 +48497,14 @@ function createKilnNativeToolRegistry(suppliedContext, completion) {
programStore: suppliedContext.programStore ?? new MemoryProgramStore,
programArtifacts: suppliedContext.programArtifacts ?? new ProgramArtifactStore
};
- const inputSchema = z23.strictObject({
- programRef: z23.string().regex(programRefPattern)
+ const inputSchema = z24.strictObject({
+ programRef: z24.string().regex(programRefPattern)
});
- const skillResourceInput = z23.strictObject({
- skill: z23.string().min(1).max(64),
- path: z23.string().min(1).max(240).optional(),
- offset: z23.number().int().min(0).max(262144).default(0),
- limit: z23.number().int().min(1).max(16000).default(12000)
+ const skillResourceInput = z24.strictObject({
+ skill: z24.string().min(1).max(64),
+ path: z24.string().min(1).max(240).optional(),
+ offset: z24.number().int().min(0).max(262144).default(0),
+ limit: z24.number().int().min(1).max(16000).default(12000)
});
const delivery = new Set([
"kiln_save",
@@ -48067,9 +48555,9 @@ function createKilnNativeToolRegistry(suppliedContext, completion) {
];
}
var assetSelector = {
- collection: z23.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
- assetId: z23.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
- revisionId: z23.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
+ collection: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
+ assetId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
+ revisionId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
};
var ASSET_CONTRACT = {
collections: {
@@ -48199,36 +48687,36 @@ function createKilnAssetDefs(context, presentation = "grouped") {
resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset),
downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId)
});
- const saveInput = z23.object({
+ const saveInput = z24.object({
collection: selector.collection,
- programRef: z23.string(),
- name: z23.string().min(1).max(200),
+ programRef: z24.string(),
+ name: z24.string().min(1).max(200),
assetId: selector.assetId.optional(),
parentRevision: selector.revisionId.optional(),
- tags: z23.array(z23.string().max(80)).max(30).optional(),
- brief: z23.string().max(8000).optional(),
- description: z23.string().max(4000).optional(),
- attribution: z23.object({
- model: z23.string().max(200).optional(),
- harness: z23.string().max(200).optional(),
- author: z23.string().max(200).optional()
+ tags: z24.array(z24.string().max(80)).max(30).optional(),
+ brief: z24.string().max(8000).optional(),
+ description: z24.string().max(4000).optional(),
+ attribution: z24.object({
+ model: z24.string().max(200).optional(),
+ harness: z24.string().max(200).optional(),
+ author: z24.string().max(200).optional()
}).optional(),
- backdrop: z23.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
+ backdrop: z24.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
});
- const assetsInput = z23.object({
- action: z23.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
+ const assetsInput = z24.object({
+ action: z24.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
collection: selector.collection,
assetId: selector.assetId.optional(),
revisionId: selector.revisionId.optional().describe("get, restore: the saved revision; omitted, the newest."),
- query: z23.string().max(200).optional(),
- offset: z23.number().int().min(0).default(0),
- limit: z23.number().int().min(1).max(50).default(20)
+ query: z24.string().max(200).optional(),
+ offset: z24.number().int().min(0).default(0),
+ limit: z24.number().int().min(1).max(50).default(20)
});
- const exportInput = z23.object(selector);
+ const exportInput = z24.object(selector);
const profileExportInput = exportInput.extend({
- profile: z23.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
+ profile: z24.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
});
- const importInput = z23.object({
+ const importInput = z24.object({
...selector,
sourceCollection: selector.collection
});
@@ -48329,9 +48817,9 @@ function createKilnAssetDefs(context, presentation = "grouped") {
name: "kiln_present",
description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",
inputSchema: exportInput,
- outputSchema: z23.object({
- ok: z23.literal(true),
- collection: z23.string(),
+ outputSchema: z24.object({
+ ok: z24.literal(true),
+ collection: z24.string(),
asset: assetManifestSchema.pick({
assetId: true,
revisionId: true,
@@ -48342,25 +48830,25 @@ function createKilnAssetDefs(context, presentation = "grouped") {
editable: true,
files: true
}).extend({
- build: z23.object({
- engine: z23.string(),
- rebuild: z23.enum(["engine-required", "external-dependencies-required"]),
- warningCount: z23.number().int(),
- warnings: z23.array(z23.string())
+ build: z24.object({
+ engine: z24.string(),
+ rebuild: z24.enum(["engine-required", "external-dependencies-required"]),
+ warningCount: z24.number().int(),
+ warnings: z24.array(z24.string())
}).optional()
}),
- resources: z23.array(z23.object({
- type: z23.literal("resource_link"),
- name: z23.string(),
- uri: z23.string(),
- mimeType: z23.string(),
- size: z23.number().int().nonnegative(),
- annotations: z23.object({
- audience: z23.array(z23.enum(["user", "assistant"])),
- priority: z23.number()
+ resources: z24.array(z24.object({
+ type: z24.literal("resource_link"),
+ name: z24.string(),
+ uri: z24.string(),
+ mimeType: z24.string(),
+ size: z24.number().int().nonnegative(),
+ annotations: z24.object({
+ audience: z24.array(z24.enum(["user", "assistant"])),
+ priority: z24.number()
})
})),
- downloadUrls: z23.record(z23.string(), z23.string()).optional()
+ downloadUrls: z24.record(z24.string(), z24.string()).optional()
}),
ui: {
resourceUri: KILN_ASSET_WIDGET_URI,
diff --git a/dist/build.json b/dist/build.json
index d0f0dc66..c044db6b 100644
--- a/dist/build.json
+++ b/dist/build.json
@@ -2,10 +2,10 @@
"schemaVersion": 1,
"entries": {
"worker": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -37,13 +37,13 @@
},
"target": "node",
"file": "evaluator-worker.mjs",
- "bundleHash": "sha256:326aaf15bc9181bc8ef5b2cf02861c33cc7848347e50830f288330121c0d1f0e"
+ "bundleHash": "sha256:2839cd6aaee99ebea2e55a4f07aa079340b7d281572a7a801484ff489c15624e"
},
"agent-run": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -75,13 +75,13 @@
},
"target": "node",
"file": "agent-run.mjs",
- "bundleHash": "sha256:da18b3f185be4da1105c2336ad7646c95ab67f195da5c2eb977b54e66a4b6f89"
+ "bundleHash": "sha256:fe8d9d536c2c4b24686b2b0e0ea7f521018cb30563cd7545cf51f545786bec74"
},
"agent-providers": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -116,10 +116,10 @@
"bundleHash": "sha256:9d6faf03d307321bc2e3bd5ce5bdee0bbbf61e0ebed8bfebfa1fb072287b83fa"
},
"mcp": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -154,10 +154,10 @@
"bundleHash": "sha256:a246b2c79d629a332cef4430dbe742b0c4a0d2f04f0281e673c3c60ff22706da"
},
"cli": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -189,13 +189,13 @@
},
"target": "node",
"file": "cli.mjs",
- "bundleHash": "sha256:74b24e3e30e1189870d4f16b75036cd4810d9a4ee1135f0b6315ffddbbee69ce"
+ "bundleHash": "sha256:d3d1a48bf2cd1278e376752dfbb0c1e02d5ff07c93eab8922899eca2a08952f9"
},
"engine": {
- "identity": "sha256:3f5b7bae30b5a22807b99ee8a5282c6d7d54e5049806602448881316d397a8f1",
+ "identity": "sha256:307b68fa073b9c29e3423a63b42b0260d29bfd8f7f73671e207468235f6de836",
"engineVersion": "1.3.1",
"toolchain": "[email protected]",
- "sourceHash": "1a29293d5311ba47404f494bf2504898d2d38130cbbf1f9bf5c24c10e6107125",
+ "sourceHash": "741d57e617776ededf08939ad273e519e98172f5cbbddd2fb3f176d3dba576c5",
"rendererSourceHash": "27927c48b377f7694251a76c0cecd05216fcbbb8a7d03e8bf2bd681dabb5573a",
"dependencyHash": "af916d063d319fe3c11d1acc13211950eea82bb5ebb87ae4eb60008d72fa7f10",
"dependencies": {
@@ -227,7 +227,7 @@
},
"target": "node",
"file": "mcp-engine.mjs",
- "bundleHash": "sha256:79792e69aabd5ff5e75b32603e004b910fc5fddb30fd990d8cdb95ac68af88df"
+ "bundleHash": "sha256:e1c924877daae40f96ef9172176279c7b96fc6c5c4e421d26cbb3b30dd342a00"
}
}
}
diff --git a/dist/cli.mjs b/dist/cli.mjs
index 762159ce..4981d8d0 100644
--- a/dist/cli.mjs
+++ b/dist/cli.mjs
@@ -14242,6 +14242,1401 @@ var init_universal = __esm(() => {
};
});
+// src/gltf-io.ts
+import {
+ Extension,
+ ExtensionProperty,
+ PropertyType,
+ RefList,
+ WebIO
+} from "@gltf-transform/core";
+import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
+function createGltfIO() {
+ return new WebIO().registerExtensions([...ALL_EXTENSIONS, MSFTLod]);
+}
+var MSFT_LOD = "MSFT_lod", Lod, MSFTLod;
+var init_gltf_io = __esm(() => {
+ Lod = class Lod extends ExtensionProperty {
+ static EXTENSION_NAME = MSFT_LOD;
+ init() {
+ this.extensionName = MSFT_LOD;
+ this.propertyType = "Lod";
+ this.parentTypes = [PropertyType.NODE, PropertyType.MATERIAL];
+ }
+ getDefaults() {
+ return Object.assign(super.getDefaults(), {
+ levels: new RefList
+ });
+ }
+ addLevel(level) {
+ return this.addRef("levels", level);
+ }
+ listLevels() {
+ return this.listRefs("levels");
+ }
+ };
+ MSFTLod = class MSFTLod extends Extension {
+ extensionName = MSFT_LOD;
+ static EXTENSION_NAME = MSFT_LOD;
+ createLod(name = "") {
+ return new Lod(this.document.getGraph(), name);
+ }
+ read(context) {
+ const json = context.jsonDoc.json;
+ this.readLevels(json.nodes, context.nodes);
+ this.readLevels(json.materials, context.materials);
+ return this;
+ }
+ readLevels(defs, targets) {
+ (defs ?? []).forEach((def, index) => {
+ const ids = def.extensions?.[MSFT_LOD]?.ids;
+ const target = targets[index];
+ if (!target || !Array.isArray(ids))
+ return;
+ const lod = this.createLod();
+ for (const id of ids) {
+ const level = typeof id === "number" ? targets[id] : undefined;
+ if (level && level !== target)
+ lod.addLevel(level);
+ }
+ target.setExtension(MSFT_LOD, lod);
+ });
+ }
+ write(context) {
+ const json = context.jsonDoc.json;
+ const root = this.document.getRoot();
+ for (const node of root.listNodes()) {
+ const index = context.nodeIndexMap.get(node);
+ const ids = node.getExtension(MSFT_LOD)?.listLevels().filter((level) => level.propertyType === PropertyType.NODE).map((level) => context.nodeIndexMap.get(level)).filter((id) => id !== undefined);
+ const def = index === undefined ? undefined : json.nodes?.[index];
+ if (def && ids?.length)
+ def.extensions = { ...def.extensions, [MSFT_LOD]: { ids } };
+ }
+ for (const material of root.listMaterials()) {
+ const index = context.materialIndexMap.get(material);
+ const ids = material.getExtension(MSFT_LOD)?.listLevels().filter((level) => level.propertyType === PropertyType.MATERIAL).map((level) => context.materialIndexMap.get(level)).filter((id) => id !== undefined);
+ const def = index === undefined ? undefined : json.materials?.[index];
+ if (def && ids?.length)
+ def.extensions = { ...def.extensions, [MSFT_LOD]: { ids } };
+ }
+ return this;
+ }
+ };
+});
+
+// src/metrics.ts
+function primTris(prim) {
+ const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
+ switch (prim.getMode()) {
+ case 4:
+ return Math.floor(count / 3);
+ case 5:
+ case 6:
+ return Math.max(0, count - 2);
+ default:
+ return 0;
+ }
+}
+function instanceCopies(node) {
+ const ext = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!ext)
+ return 1;
+ return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
+}
+function isHiddenGltfNode(node) {
+ const visibility = node.getExtension("KHR_node_visibility");
+ return visibility?.getVisible?.() === false;
+}
+function nodeTriangles(node) {
+ return subtreeTriangles(node, false);
+}
+function drawnNodeTriangles(node) {
+ return subtreeTriangles(node, true);
+}
+function subtreeTriangles(node, drawn) {
+ if (drawn && isHiddenGltfNode(node))
+ return 0;
+ let triangles = 0;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ for (const prim of mesh.listPrimitives())
+ triangles += primTris(prim) * copies;
+ }
+ for (const child of node.listChildren())
+ triangles += subtreeTriangles(child, drawn);
+ return triangles;
+}
+function collectGlbMetrics(doc, triangles) {
+ const root = doc.getRoot();
+ const geomSet = new Set;
+ const matSet = new Set;
+ let drawCalls = 0;
+ let derivedTris = 0;
+ let meshNodes = 0;
+ let meshInstances = 0;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ meshNodes += 1;
+ meshInstances += copies;
+ for (const prim of mesh.listPrimitives()) {
+ drawCalls += 1;
+ geomSet.add(prim);
+ derivedTris += primTris(prim) * copies;
+ const mat = prim.getMaterial();
+ if (mat)
+ matSet.add(mat);
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes()) {
+ for (const node of scene.listChildren())
+ visit(node);
+ }
+ const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
+ return {
+ uniqueGeometries: geomSet.size,
+ uniqueMaterials: matSet.size,
+ meshNodes,
+ meshInstances,
+ drawCalls,
+ textureCount: root.listTextures().length,
+ skinned: root.listSkins().length > 0,
+ transparentMaterials,
+ triangles: triangles ?? derivedTris
+ };
+}
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
+}
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
+}
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
+ ]);
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
+ }
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
+}
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
+ };
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
+ };
+}
+function gradeInstanceability(metrics, opts = {}) {
+ const m = metrics;
+ const band = materialBand(m.uniqueMaterials);
+ let grade = band.grade;
+ const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
+ const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
+ const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
+ const drivers = [];
+ const also = [];
+ if ((grade === "A" || grade === "B") && (transparency || textures)) {
+ grade = "C";
+ if (transparency)
+ drivers.push(`${transparency} (lowers A/B to C)`);
+ if (textures)
+ drivers.push(`${textures} (over 4 lowers A/B to C)`);
+ also.push(materials);
+ } else {
+ drivers.push(materials);
+ if (transparency)
+ also.push(`${transparency} (lowers only A/B to C)`);
+ if (textures)
+ also.push(`${textures} (over 4 lowers only A/B to C)`);
+ }
+ also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
+ if (m.skinned)
+ also.push("skinned (clone-rendered, not penalized)");
+ const setBy = drivers.join(" and ");
+ const reasons = [
+ `grade ${grade} set by ${setBy}`,
+ `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
+ ];
+ if (transparency)
+ reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
+ if (textures)
+ reasons.push(`${m.textureCount} textures (consider atlasing)`);
+ if (m.skinned)
+ reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
+ if (opts.category)
+ reasons.push(`category: ${opts.category}`);
+ const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
+}
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
+var init_metrics = __esm(() => {
+ MATERIAL_GRADE_BANDS = [
+ { grade: "A", max: 1, range: "0-1" },
+ { grade: "B", max: 3, range: "2-3" },
+ { grade: "C", max: 6, range: "4-6" },
+ { grade: "D", max: 12, range: "7-12" },
+ { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
+ ];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
+});
+
+// src/written-nodes.ts
+function exportedRoot(doc, purpose) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ const top = scene?.listChildren() ?? [];
+ if (top.length !== 1)
+ throw new Error(`${purpose} expects the exporter to write one root node.`);
+ return top[0];
+}
+function writtenNodeResolver(root, doc, purpose) {
+ const top = exportedRoot(doc, purpose);
+ return (node) => {
+ const path = [];
+ for (let current = node;current !== root; current = current.parent) {
+ if (!current.parent)
+ throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
+ path.unshift(current.parent.children.indexOf(current));
+ }
+ let target = top;
+ for (const index of path)
+ target = target?.listChildren()[index];
+ if (!target || (target.getName() || "") !== (node.name || ""))
+ throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
+ return target;
+ };
+}
+
+// src/node-visibility.ts
+import { KHRNodeVisibility } from "@gltf-transform/extensions";
+import * as THREE21 from "three";
+function applyNodeVisibility(root, doc) {
+ const hidden = [];
+ root.traverse((node) => {
+ if (node.visible === false)
+ hidden.push(node);
+ });
+ if (hidden.length === 0)
+ return;
+ const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
+ const extension = doc.createExtension(KHRNodeVisibility);
+ for (const node of written)
+ node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
+}
+function summarizeHiddenNodes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const found = [];
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment2(name, occurrence)}`;
+ if (isHiddenGltfNode(node))
+ found.push({ path, name, triangles: nodeTriangles(node) });
+ else
+ visit(node.listChildren(), path);
+ }
+ };
+ visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
+ return found;
+}
+function drawnSceneBounds(scene) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const base = new THREE21.Matrix4().fromArray(node.getWorldMatrix());
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ const matrices = [];
+ for (let i = 0;i < countInstances; i++) {
+ const t = translation?.getElement(i, []) ?? [0, 0, 0];
+ const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
+ const s = scale?.getElement(i, []) ?? [1, 1, 1];
+ const localMatrix = new THREE21.Matrix4().compose(new THREE21.Vector3().fromArray(t), new THREE21.Quaternion().fromArray(r), new THREE21.Vector3().fromArray(s));
+ matrices.push(base.clone().multiply(localMatrix).toArray());
+ }
+ const local = [0, 0, 0];
+ for (const primitive of mesh.listPrimitives()) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const m of matrices)
+ for (let i = 0;i < count; i++) {
+ position.getElement(indices ? indices.getScalar(i) : i, local);
+ const [x, y, z] = local;
+ const world = [
+ m[0] * x + m[4] * y + m[8] * z + m[12],
+ m[1] * x + m[5] * y + m[9] * z + m[13],
+ m[2] * x + m[6] * y + m[10] * z + m[14]
+ ];
+ for (let k = 0;k < 3; k++) {
+ if (world[k] < min[k])
+ min[k] = world[k];
+ if (world[k] > max[k])
+ max[k] = world[k];
+ }
+ }
+ }
+ }
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const node of scene.listChildren())
+ visit(node);
+ return { min, max };
+}
+var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var init_node_visibility = __esm(() => {
+ init_metrics();
+});
+
+// src/delivery-inspect.ts
+import * as THREE22 from "three";
+import { PropertyType as PropertyType2 } from "@gltf-transform/core";
+function decompose(matrix) {
+ const translation = new THREE22.Vector3;
+ const rotation = new THREE22.Quaternion;
+ const scale = new THREE22.Vector3;
+ matrix.decompose(translation, rotation, scale);
+ const clean = (value) => Object.is(value, -0) ? 0 : value;
+ return {
+ translation: translation.toArray().map(clean),
+ rotation: rotation.toArray().map(clean),
+ scale: scale.toArray().map(clean)
+ };
+}
+function drawnTriangles(visited) {
+ const values = [];
+ const local = [0, 0, 0];
+ const point = new THREE22.Vector3;
+ for (const { node, roles, hidden } of visited) {
+ const mesh = node.getMesh();
+ if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
+ continue;
+ const base = worldMatrix(node);
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ const matrices = [];
+ for (let i = 0;i < copies; i++) {
+ const instance = new THREE22.Matrix4().compose(new THREE22.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE22.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE22.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
+ matrices.push(base.clone().multiply(instance));
+ }
+ for (const primitive of mesh.listPrimitives()) {
+ if (primitive.getMode() !== 4)
+ continue;
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const matrix of matrices)
+ for (let i = 0;i + 2 < count; i += 3)
+ for (let k = 0;k < 3; k++) {
+ position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
+ point.fromArray(local).applyMatrix4(matrix);
+ values.push(point.x, point.y, point.z);
+ }
+ }
+ }
+ return Float64Array.from(values);
+}
+function triangleOverlapsBox(a, b, c, h, tolerance) {
+ const verts = [a, b, c];
+ const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
+ for (let axis = 0;axis < 3; axis++) {
+ const values = verts.map((v) => v.getComponent(axis));
+ if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
+ return false;
+ }
+ const e = [
+ new THREE22.Vector3().subVectors(b, a),
+ new THREE22.Vector3().subVectors(c, b),
+ new THREE22.Vector3().subVectors(a, c)
+ ];
+ const normal = new THREE22.Vector3().crossVectors(e[0], e[1]);
+ const axes = [normal];
+ const units = [
+ new THREE22.Vector3(1, 0, 0),
+ new THREE22.Vector3(0, 1, 0),
+ new THREE22.Vector3(0, 0, 1)
+ ];
+ for (const unit of units)
+ for (const edge of e)
+ axes.push(new THREE22.Vector3().crossVectors(unit, edge));
+ for (const axis of axes) {
+ if (axis.lengthSq() < 0.000000000000000000000001)
+ continue;
+ const projections = verts.map((v) => v.dot(axis));
+ const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
+ if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
+ return false;
+ }
+ return true;
+}
+function closestPointOnTriangle(p, a, b, c) {
+ const ab = new THREE22.Vector3().subVectors(b, a);
+ const ac = new THREE22.Vector3().subVectors(c, a);
+ const ap = new THREE22.Vector3().subVectors(p, a);
+ const d1 = ab.dot(ap);
+ const d2 = ac.dot(ap);
+ if (d1 <= 0 && d2 <= 0)
+ return a.clone();
+ const bp = new THREE22.Vector3().subVectors(p, b);
+ const d3 = ab.dot(bp);
+ const d4 = ac.dot(bp);
+ if (d3 >= 0 && d4 <= d3)
+ return b.clone();
+ const vc = d1 * d4 - d3 * d2;
+ if (vc <= 0 && d1 >= 0 && d3 <= 0)
+ return a.clone().addScaledVector(ab, d1 / (d1 - d3));
+ const cp = new THREE22.Vector3().subVectors(p, c);
+ const d5 = ab.dot(cp);
+ const d6 = ac.dot(cp);
+ if (d6 >= 0 && d5 <= d6)
+ return c.clone();
+ const vb = d5 * d2 - d1 * d6;
+ if (vb <= 0 && d2 >= 0 && d6 <= 0)
+ return a.clone().addScaledVector(ac, d2 / (d2 - d6));
+ const va = d3 * d6 - d5 * d4;
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
+ return b.clone().addScaledVector(new THREE22.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
+ const denominator = 1 / (va + vb + vc);
+ return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
+}
+function segmentSegmentDistanceSq(p1, q1, p2, q2) {
+ const d1 = new THREE22.Vector3().subVectors(q1, p1);
+ const d2 = new THREE22.Vector3().subVectors(q2, p2);
+ const r = new THREE22.Vector3().subVectors(p1, p2);
+ const a = d1.dot(d1);
+ const e = d2.dot(d2);
+ const f = d2.dot(r);
+ let s = 0;
+ let t = 0;
+ if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
+ return r.lengthSq();
+ if (a <= 0.000000000000000000000001)
+ t = THREE22.MathUtils.clamp(f / e, 0, 1);
+ else {
+ const c = d1.dot(r);
+ if (e <= 0.000000000000000000000001)
+ s = THREE22.MathUtils.clamp(-c / a, 0, 1);
+ else {
+ const b = d1.dot(d2);
+ const denominator = a * e - b * b;
+ s = denominator !== 0 ? THREE22.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
+ t = (b * s + f) / e;
+ if (t < 0) {
+ t = 0;
+ s = THREE22.MathUtils.clamp(-c / a, 0, 1);
+ } else if (t > 1) {
+ t = 1;
+ s = THREE22.MathUtils.clamp((b - c) / a, 0, 1);
+ }
+ }
+ }
+ const c1 = p1.clone().addScaledVector(d1, s);
+ const c2 = p2.clone().addScaledVector(d2, t);
+ return c1.distanceToSquared(c2);
+}
+function segmentCrossesTriangle(p, q, a, b, c) {
+ const hit = new THREE22.Vector3;
+ const ray = new THREE22.Ray(p, new THREE22.Vector3().subVectors(q, p));
+ const length = ray.direction.length();
+ if (length === 0)
+ return false;
+ ray.direction.divideScalar(length);
+ return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
+}
+function triangleTouchesCapsule(a, b, c, p, q, radius) {
+ const r2 = radius * radius;
+ if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
+ return true;
+ if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
+ return true;
+ for (const [s, e] of [
+ [a, b],
+ [b, c],
+ [c, a]
+ ])
+ if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
+ return true;
+ return segmentCrossesTriangle(p, q, a, b, c);
+}
+function deliveryNodePaths(doc) {
+ const paths = new Map;
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return paths;
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ paths.set(node, path);
+ visit(node.listChildren(), path);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ return paths;
+}
+function summarizeVertexAttributes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const groups = new Map;
+ const order = [];
+ const record = (node, path) => {
+ const mesh = node.getMesh();
+ if (!mesh)
+ return;
+ const bake = mesh.getExtras().kilnSurfaceBakeV1;
+ const names = new Set;
+ for (const primitive of mesh.listPrimitives())
+ for (const semantic of primitive.listSemantics())
+ if (semantic.startsWith("_"))
+ names.add(semantic);
+ for (const name of names) {
+ const params = bake && typeof bake === "object" ? bake[name] : undefined;
+ const key = `${name}\x00${JSON.stringify(params ?? null)}`;
+ let group = groups.get(key);
+ if (!group) {
+ group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
+ groups.set(key, group);
+ order.push(key);
+ }
+ if (!group.meshes.includes(path))
+ group.meshes.push(path);
+ }
+ };
+ const visit = (siblings, parentPath) => {
+ siblings.forEach((node, index) => {
+ const at = (name) => {
+ let occurrence = 0;
+ for (let i = 0;i < index; i++)
+ if (siblings[i].getName() === name)
+ occurrence++;
+ return `${parentPath}${segment3(name, occurrence)}`;
+ };
+ const path = at(node.getName());
+ record(node, path);
+ visit(node.listChildren(), path);
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
+ for (const level of lower) {
+ const levelPath = at(level.getName());
+ record(level, levelPath);
+ visit(level.listChildren(), levelPath);
+ }
+ });
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
+ return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
+}
+function inspectDelivery(doc) {
+ const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return summary;
+ const visited = [];
+ const visit = (siblings, parentPath, hidden, module) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
+ const nodeHidden = hidden || isHiddenGltfNode(node);
+ const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
+ visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
+ visit(node.listChildren(), path, nodeHidden, nodeModule);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0), false, undefined);
+ const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
+ const { min, max } = drawnSceneBounds(scene);
+ const bounds = new THREE22.Box3(new THREE22.Vector3(...min), new THREE22.Vector3(...max));
+ const finiteBounds = [...min, ...max].every(Number.isFinite);
+ const diagonal = finiteBounds ? bounds.getSize(new THREE22.Vector3).length() : 0;
+ const tolerance = Math.max(0.0001, diagonal * 0.0001);
+ const colliderNodes = [];
+ for (const entry of visited) {
+ const { node, path, roles } = entry;
+ for (const role of roles) {
+ const matrix = worldMatrix(node);
+ const transform = decompose(matrix);
+ for (const shape of ["box", "capsule", "hull"]) {
+ const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
+ if (id === undefined)
+ continue;
+ const scale = transform.scale;
+ const record = {
+ role,
+ id,
+ path,
+ name: node.getName(),
+ transform,
+ shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
+ kind: "hull",
+ vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
+ }
+ };
+ summary.colliders.push(record);
+ colliderNodes.push({ visit: entry, record });
+ }
+ const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
+ if (anchorTail !== undefined) {
+ const [kind, ...rest] = anchorTail.split(".");
+ summary.anchors.push({
+ role,
+ kind,
+ id: rest.join("."),
+ path,
+ name: node.getName(),
+ transform
+ });
+ }
+ const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
+ if (portId !== undefined)
+ summary.ports.push({
+ role,
+ id: portId,
+ path,
+ name: node.getName(),
+ ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
+ transform
+ });
+ if (role === KILN_SEMANTIC_ROLES.kitModule) {
+ const extras = node.getExtras()[KILN_KIT_KEY];
+ let spec;
+ try {
+ const { schemaVersion, ...rest } = extras ?? {};
+ spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
+ } catch {
+ spec = undefined;
+ }
+ if (!spec)
+ finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
+ else if (summary.kit)
+ finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
+ else
+ summary.kit = {
+ role,
+ path,
+ name: node.getName(),
+ footprint: spec.footprint,
+ height: spec.height,
+ snapAxis: spec.snapAxis,
+ origin: spec.origin,
+ transform
+ };
+ }
+ }
+ }
+ const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
+ const triangleCount = triangles.length / 9;
+ let overlapTests = 0;
+ const a = new THREE22.Vector3;
+ const b = new THREE22.Vector3;
+ const c = new THREE22.Vector3;
+ for (const { visit: entry, record } of colliderNodes) {
+ if (!entry.hidden)
+ finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
+ const matrix = worldMatrix(entry.node);
+ const proxyBounds = new THREE22.Box3;
+ const mesh = entry.node.getMesh();
+ const local = [0, 0, 0];
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const position = primitive.getAttribute("POSITION");
+ for (let i = 0;i < (position?.getCount() ?? 0); i++)
+ proxyBounds.expandByPoint(new THREE22.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
+ }
+ if (proxyBounds.isEmpty())
+ proxyBounds.expandByPoint(new THREE22.Vector3().setFromMatrixPosition(matrix));
+ const expanded = bounds.clone().expandByScalar(tolerance);
+ if (!finiteBounds || !expanded.containsBox(proxyBounds))
+ finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
+ if (record.shape.kind === "hull")
+ continue;
+ if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
+ finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
+ continue;
+ }
+ overlapTests += triangleCount;
+ const toLocal = new THREE22.Matrix4;
+ let touches = false;
+ if (record.shape.kind === "box") {
+ toLocal.copy(matrix).invert();
+ const half = new THREE22.Vector3(0.5, 0.5, 0.5);
+ const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
+ }
+ } else {
+ const { translation, rotation } = record.transform;
+ toLocal.compose(new THREE22.Vector3(...translation), new THREE22.Quaternion(...rotation), new THREE22.Vector3(1, 1, 1)).invert();
+ const { radius, height } = record.shape;
+ const p = new THREE22.Vector3(0, -height / 2 + radius, 0);
+ const q = new THREE22.Vector3(0, height / 2 - radius, 0);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
+ }
+ }
+ if (!touches)
+ finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
+ }
+ for (const record of summary.ports) {
+ const entry = visited.find((item) => item.path === record.path);
+ const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
+ const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
+ if (!spec) {
+ finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
+ continue;
+ }
+ const point = new THREE22.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
+ const [width, depth] = spec.footprint;
+ const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
+ const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
+ if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
+ finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
+ }
+ for (const record of summary.anchors) {
+ const entry = visited.find((item) => item.path === record.path);
+ if (entry.node.listChildren().length > 0)
+ finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
+ }
+ return summary;
+}
+var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE22.Matrix4().fromArray(node.getWorldMatrix());
+var init_delivery_inspect = __esm(() => {
+ init_gltf_io();
+ init_semantic();
+ init_delivery();
+ init_metrics();
+ init_node_visibility();
+});
+
+// src/contracts/validation-profile.ts
+import { z } from "zod";
+var VALIDATION_PROFILE_VERSION = "kiln.validation-profile.v1", MAX_VALIDATION_PROFILE_BYTES, MAX_VALIDATION_CHECKS = 16, MAX_VALIDATION_PATTERN_CHARS = 128, MAX_VALIDATION_PATTERN_STARS = 4, MAX_VALIDATION_MATCHES = 512, VALIDATION_SEMANTICS, VALIDATION_SEMANTIC_SIZE, VALIDATION_AXES, finite2, id = (max) => z.string().min(1).max(max).regex(/^[A-Za-z0-9._-]+$/, 'Use letters, digits, ".", "_" or "-".'), pattern, componentFits = (value) => value.component < VALIDATION_SEMANTIC_SIZE[value.attribute], componentMessage, gradient, range, check, ValidationProfileV1Schema;
+var init_validation_profile = __esm(() => {
+ MAX_VALIDATION_PROFILE_BYTES = 8 * 1024;
+ VALIDATION_SEMANTICS = [
+ "POSITION",
+ "NORMAL",
+ "TANGENT",
+ "TEXCOORD_0",
+ "TEXCOORD_1",
+ "COLOR_0",
+ "JOINTS_0",
+ "WEIGHTS_0"
+ ];
+ VALIDATION_SEMANTIC_SIZE = {
+ POSITION: 3,
+ NORMAL: 3,
+ TANGENT: 4,
+ TEXCOORD_0: 2,
+ TEXCOORD_1: 2,
+ COLOR_0: 4,
+ JOINTS_0: 4,
+ WEIGHTS_0: 4
+ };
+ VALIDATION_AXES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
+ finite2 = z.number().finite();
+ pattern = z.string().min(1).refine((value) => Array.from(value).length <= MAX_VALIDATION_PATTERN_CHARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_CHARS} characters.`
+ }).refine((value) => value.split("*").length - 1 <= MAX_VALIDATION_PATTERN_STARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_STARS} "*".`
+ });
+ componentMessage = {
+ message: "component is outside the attribute.",
+ path: ["component"]
+ };
+ gradient = z.strictObject({
+ attribute: z.enum(["TEXCOORD_0", "TEXCOORD_1", "COLOR_0"]),
+ component: z.number().int().min(0).max(3),
+ axis: z.enum(VALIDATION_AXES),
+ from: finite2,
+ to: finite2,
+ tolerance: finite2.positive().max(0.5),
+ monotonic: z.boolean()
+ }).refine((value) => value.from !== value.to, {
+ message: "from and to must differ."
+ }).refine(componentFits, componentMessage);
+ range = z.strictObject({
+ attribute: z.enum(VALIDATION_SEMANTICS),
+ component: z.number().int().min(0).max(3),
+ min: finite2,
+ max: finite2,
+ tolerance: finite2.nonnegative()
+ }).refine((value) => value.min <= value.max, {
+ message: "min must not exceed max."
+ }).refine(componentFits, componentMessage);
+ check = z.strictObject({
+ id: id(48),
+ select: z.strictObject({
+ names: z.array(pattern).min(1).max(8),
+ minMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ maxMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional()
+ }).refine((value) => value.maxMatches === undefined || (value.minMatches ?? 1) <= value.maxMatches, { message: "minMatches must not exceed maxMatches." }),
+ primitives: z.union([
+ z.strictObject({ exactly: z.number().int().min(1).max(64) }),
+ z.strictObject({ max: z.number().int().min(1).max(64) })
+ ]).optional(),
+ attributes: z.array(z.enum(VALIDATION_SEMANTICS)).min(1).max(8).refine((values) => new Set(values).size === values.length, {
+ message: "Attributes must be unique."
+ }).optional(),
+ gradient: gradient.optional(),
+ range: range.optional(),
+ material: z.strictObject({
+ alphaMode: z.enum(["OPAQUE", "MASK", "BLEND"]).optional(),
+ doubleSided: z.boolean().optional()
+ }).refine((value) => value.alphaMode !== undefined || value.doubleSided !== undefined, {
+ message: "A material check needs alphaMode or doubleSided."
+ }).optional()
+ }).refine((value) => value.primitives !== undefined || value.attributes !== undefined || value.gradient !== undefined || value.range !== undefined || value.material !== undefined, { message: "A check needs at least one assertion." });
+ ValidationProfileV1Schema = z.strictObject({
+ version: z.literal(VALIDATION_PROFILE_VERSION),
+ profileId: id(64).regex(/^[a-z0-9._-]+$/, 'Use lowercase letters, digits, ".", "_" or "-".'),
+ mode: z.enum(["warn", "enforce"]),
+ checks: z.array(check).min(1).max(MAX_VALIDATION_CHECKS)
+ }).superRefine((value, context) => {
+ const ids = value.checks.map((item) => item.id);
+ if (new Set(ids).size !== ids.length)
+ context.addIssue({
+ code: "custom",
+ path: ["checks"],
+ message: "Check ids must be unique."
+ });
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_VALIDATION_PROFILE_BYTES)
+ context.addIssue({
+ code: "custom",
+ message: `A validation profile serializes to at most ${MAX_VALIDATION_PROFILE_BYTES} bytes (got ${bytes}).`
+ });
+ });
+});
+
+// src/qa/validation-profile.ts
+function matchValidationPattern(pattern, name) {
+ const p = Array.from(pattern);
+ const s = Array.from(name);
+ let pi = 0;
+ let si = 0;
+ let star = -1;
+ let resume = 0;
+ while (si < s.length) {
+ if (pi < p.length && (p[pi] === "?" || p[pi] !== "*" && p[pi] === s[si])) {
+ pi++;
+ si++;
+ } else if (pi < p.length && p[pi] === "*") {
+ star = pi++;
+ resume = si;
+ } else if (star >= 0) {
+ pi = star + 1;
+ si = ++resume;
+ } else
+ return false;
+ }
+ while (pi < p.length && p[pi] === "*")
+ pi++;
+ return pi === p.length;
+}
+function component(accessor, index, slot, element) {
+ accessor.getElement(index, element);
+ return element[slot];
+}
+function evaluateValidationProfileDocument(profile, doc, options = {}) {
+ const disposition = profile.mode === "enforce" ? "block" : "warn";
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ const budget = options.maxAttributeReads ?? MAX_VALIDATION_ATTRIBUTE_READS;
+ const paths = deliveryNodePaths(doc);
+ const candidates = [...paths.entries()].filter(([node]) => node.getMesh() !== null);
+ const findings = [];
+ let complete = true;
+ let reads = 0;
+ let matchedNodes = 0;
+ let notMeasured = 0;
+ for (const check of profile.checks) {
+ const kept = new Map;
+ const omitted = new Map;
+ const push = (code, assertion, message, measurement, affected, findingDisposition) => findings.push({
+ code,
+ disposition: findingDisposition,
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation check ${check.id}: ${message}`,
+ ...affected ? { affected } : {},
+ measurement: {
+ name: `checks.${check.id}.${assertion}`,
+ ...measurement
+ }
+ });
+ const report = (code, assertion, message, { affected, measurement }, findingDisposition = disposition) => {
+ const used = kept.get(code) ?? 0;
+ if (used < MAX_VALIDATION_FINDINGS_PER_CODE) {
+ kept.set(code, used + 1);
+ push(code, assertion, message, measurement, affected, findingDisposition);
+ return;
+ }
+ const entry = omitted.get(code) ?? {
+ count: 0,
+ assertion,
+ disposition: findingDisposition
+ };
+ entry.count++;
+ omitted.set(code, entry);
+ };
+ const matched = candidates.filter(([node]) => check.select.names.some((pattern) => matchValidationPattern(pattern, node.getName())));
+ const minMatches = check.select.minMatches ?? 1;
+ if (matched.length < minMatches || check.select.maxMatches !== undefined && matched.length > check.select.maxMatches) {
+ const expected = check.select.maxMatches === undefined ? `>= ${minMatches}` : minMatches === check.select.maxMatches ? `${minMatches}` : `${minMatches}..${check.select.maxMatches}`;
+ report("HOST_VALIDATION_SELECTOR_UNMATCHED", "select", `${matched.length} default-scene mesh node(s) match ${JSON.stringify(check.select.names)}; the host expects ${expected}. Node names come from the final GLB.`, { measurement: { actual: matched.length, expected } });
+ }
+ const measured = matched.slice(0, MAX_VALIDATION_MATCHES);
+ if (matched.length > measured.length) {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "select", `${matched.length - measured.length} matched node(s) beyond the ${MAX_VALIDATION_MATCHES}-node limit were not measured.`, {
+ measurement: {
+ actual: matched.length,
+ threshold: MAX_VALIDATION_MATCHES,
+ breakdown: { nodesNotMeasured: matched.length - measured.length }
+ }
+ }, "observe");
+ }
+ for (const [node, nodePath] of measured) {
+ const primitives = node.getMesh().listPrimitives();
+ const cost = primitives.reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0) * ((check.gradient ? 2 : 0) + (check.range ? 1 : 0)), 0);
+ if (notMeasured > 0 || reads + cost > budget) {
+ notMeasured++;
+ continue;
+ }
+ reads += cost;
+ matchedNodes++;
+ const affected = { node: node.getName(), nodePath };
+ if (check.primitives) {
+ const limit = "exactly" in check.primitives ? check.primitives.exactly : check.primitives.max;
+ const fails = "exactly" in check.primitives ? primitives.length !== limit : primitives.length > limit;
+ if (fails)
+ report("HOST_VALIDATION_PRIMITIVE_COUNT", "primitives", `${node.getName()} has ${primitives.length} primitive(s) in the final GLB; the host expects ${"exactly" in check.primitives ? "exactly" : "at most"} ${limit}. Each material group exports as its own primitive.`, {
+ affected,
+ measurement: {
+ actual: primitives.length,
+ expected: limit
+ }
+ });
+ }
+ primitives.forEach((primitive, index) => {
+ const where = `${node.getName()} primitive ${index}`;
+ for (const semantic of check.attributes ?? []) {
+ if (primitive.getAttribute(semantic))
+ continue;
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "attributes", `${where} has no ${semantic} attribute.`, {
+ affected: { ...affected, attribute: semantic },
+ measurement: { actual: false, expected: true }
+ });
+ }
+ if (check.gradient) {
+ const outcome = measureGradient(primitive, check.gradient);
+ if (outcome.kind === "missing")
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "gradient", `${where} cannot be measured: ${outcome.reason}.`, {
+ affected: { ...affected, attribute: outcome.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else if (outcome.kind === "unmeasured") {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "gradient", `${where} has no extent along ${check.gradient.axis}; the gradient is unmeasured.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: { actual: null }
+ }, "observe");
+ } else if (outcome.failures.length > 0)
+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: {
+ actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,
+ expected: `${check.gradient.from}..${check.gradient.to}`,
+ threshold: check.gradient.tolerance,
+ breakdown: {
+ fromMean: round2(outcome.fromMean),
+ toMean: round2(outcome.toMean),
+ worstRegression: round2(outcome.worstRegression)
+ }
+ }
+ });
+ }
+ if (check.range) {
+ const accessor = primitive.getAttribute(check.range.attribute);
+ if (!accessor || check.range.component >= accessor.getElementSize())
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "range", `${where} has no ${check.range.attribute}[${check.range.component}].`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else {
+ const element = [];
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0;i < accessor.getCount(); i++) {
+ const value = component(accessor, i, check.range.component, element);
+ if (value < min)
+ min = value;
+ if (value > max)
+ max = value;
+ }
+ const { tolerance } = check.range;
+ if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))
+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: {
+ actual: `${round2(min)}..${round2(max)}`,
+ expected: `${check.range.min}..${check.range.max}`,
+ threshold: tolerance
+ }
+ });
+ }
+ }
+ if (check.material) {
+ const material = primitive.getMaterial();
+ const label = material?.getName() || (material ? `materials[${doc.getRoot().listMaterials().indexOf(material)}]` : "(glTF default)");
+ const alphaMode = material?.getAlphaMode() ?? "OPAQUE";
+ const doubleSided = material?.getDoubleSided() ?? false;
+ if (check.material.alphaMode !== undefined && alphaMode !== check.material.alphaMode)
+ report("HOST_VALIDATION_MATERIAL_ALPHA_MODE", "material", `${where} uses alphaMode ${alphaMode}; the host expects ${check.material.alphaMode}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: alphaMode,
+ expected: check.material.alphaMode
+ }
+ });
+ if (check.material.doubleSided !== undefined && doubleSided !== check.material.doubleSided)
+ report("HOST_VALIDATION_MATERIAL_DOUBLE_SIDED", "material", `${where} is ${doubleSided ? "double-sided" : "single-sided"}; the host expects ${check.material.doubleSided ? "double-sided" : "single-sided"}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: doubleSided,
+ expected: check.material.doubleSided
+ }
+ });
+ }
+ });
+ }
+ for (const [code, entry] of omitted)
+ push(code, entry.assertion, `${entry.count} more ${code} finding(s) omitted after the first ${MAX_VALIDATION_FINDINGS_PER_CODE}.`, { actual: entry.count, breakdown: { omitted: entry.count } }, undefined, entry.disposition);
+ }
+ if (notMeasured > 0) {
+ complete = false;
+ findings.push({
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation stopped at its ${budget} attribute-read budget; ${notMeasured} matched node(s) were not measured.`,
+ measurement: {
+ name: "checks.*.budget",
+ actual: reads,
+ threshold: budget,
+ breakdown: { nodesNotMeasured: notMeasured }
+ }
+ });
+ }
+ return {
+ findings,
+ complete,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: matchedNodes,
+ hostValidationAttributeReads: reads,
+ hostValidationComplete: complete
+ }
+ };
+}
+function measureGradient(primitive, gradient) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ return {
+ kind: "missing",
+ attribute: "POSITION",
+ reason: "no POSITION attribute"
+ };
+ const values = primitive.getAttribute(gradient.attribute);
+ if (!values || gradient.component >= values.getElementSize())
+ return {
+ kind: "missing",
+ attribute: gradient.attribute,
+ reason: `no ${gradient.attribute}[${gradient.component}]`
+ };
+ const count = Math.min(position.getCount(), values.getCount());
+ const axis = AXIS_INDEX[gradient.axis[1]];
+ const sign = gradient.axis[0] === "-" ? -1 : 1;
+ const t = new Float64Array(count);
+ const v = new Float64Array(count);
+ const element = [];
+ let tMin = Infinity;
+ let tMax = -Infinity;
+ for (let i = 0;i < count; i++) {
+ t[i] = sign * component(position, i, axis, element);
+ v[i] = component(values, i, gradient.component, element);
+ if (t[i] < tMin)
+ tMin = t[i];
+ if (t[i] > tMax)
+ tMax = t[i];
+ }
+ if (!(tMax - tMin >= MIN_AXIS_EXTENT))
+ return { kind: "unmeasured" };
+ const sums = new Float64Array(GRADIENT_BINS);
+ const counts = new Uint32Array(GRADIENT_BINS);
+ let fromSum = 0;
+ let fromCount = 0;
+ let toSum = 0;
+ let toCount = 0;
+ for (let i = 0;i < count; i++) {
+ const s = (t[i] - tMin) / (tMax - tMin);
+ if (s <= ENDPOINT_BAND) {
+ fromSum += v[i];
+ fromCount++;
+ }
+ if (s >= 1 - ENDPOINT_BAND) {
+ toSum += v[i];
+ toCount++;
+ }
+ const bin = Math.min(GRADIENT_BINS - 1, Math.floor(s * GRADIENT_BINS));
+ sums[bin] = sums[bin] + v[i];
+ counts[bin] = counts[bin] + 1;
+ }
+ const fromMean = fromSum / fromCount;
+ const toMean = toSum / toCount;
+ const direction = Math.sign(gradient.to - gradient.from);
+ let worstRegression = 0;
+ let previous;
+ for (let bin = 0;bin < GRADIENT_BINS; bin++) {
+ if (counts[bin] === 0)
+ continue;
+ const mean = sums[bin] / counts[bin];
+ if (previous !== undefined)
+ worstRegression = Math.max(worstRegression, (previous - mean) * direction);
+ previous = mean;
+ }
+ const failures = [];
+ if (Math.abs(fromMean - gradient.from) > gradient.tolerance || Math.abs(toMean - gradient.to) > gradient.tolerance)
+ failures.push("endpoints");
+ if (gradient.monotonic && worstRegression > gradient.tolerance)
+ failures.push("monotonic");
+ return { kind: "measured", fromMean, toMean, worstRegression, failures };
+}
+async function evaluateValidationProfileGlb(profile, bytes, options = {}) {
+ let doc;
+ try {
+ doc = await createGltfIO().readBinary(bytes);
+ } catch (error) {
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ return {
+ findings: [
+ {
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation could not read the final GLB: ${error instanceof Error ? error.message : String(error)}`,
+ measurement: { name: "checks.*.read", actual: null }
+ }
+ ],
+ complete: false,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: 0,
+ hostValidationAttributeReads: 0,
+ hostValidationComplete: false
+ }
+ };
+ }
+ return evaluateValidationProfileDocument(profile, doc, options);
+}
+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;
+var init_validation_profile2 = __esm(() => {
+ init_gltf_io();
+ init_delivery_inspect();
+ init_validation_profile();
+ init_registry();
+ HOST_VALIDATION_QA_RULE = Object.freeze({
+ id: HOST_VALIDATION_RULE_ID,
+ profile: "host.validation-profile",
+ scope: { kind: "universal" },
+ ruleClass: "exact",
+ owner: KILN_ENGINE_QA_OWNER,
+ promotion: conformancePromotionAuthorization("host-validation-profile-v1", "src/qa/validation-profile.test.ts", "b6b60fcbba0238688cb0d3ef497fa3ed837757422b43207f18fc8cbe0a412ffc", KILN_ENGINE_QA_OWNER, "2026-10-22T00:00:00.000Z", "enforce", "cpu-raster:1.3.1"),
+ defaultMode: "enforce",
+ evaluate: () => []
+ });
+ AXIS_INDEX = { X: 0, Y: 1, Z: 2 };
+});
+
// src/qa/run.ts
function gltfReportFindings(report, profile) {
return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
@@ -14289,6 +15684,7 @@ var init_run = __esm(() => {
init_registry();
init_types();
init_universal();
+ init_validation_profile2();
DETERMINISTIC_QA_REGISTRY = new QaRegistry([
...UNIVERSAL_QA_RULES,
MATERIAL_QA_RULE,
@@ -14303,7 +15699,8 @@ var init_run = __esm(() => {
SELF_INTERSECTION_QA_RULE,
SWEEP_QA_RULE,
PART_CONNECTIVITY_QA_RULE,
- REFERENCE_COMPARISON_QA_RULE
+ REFERENCE_COMPARISON_QA_RULE,
+ HOST_VALIDATION_QA_RULE
]);
AssetQaBlockedError = class AssetQaBlockedError extends Error {
report;
@@ -14323,16 +15720,16 @@ var init_run = __esm(() => {
});
// src/contracts/requirements.ts
-import { z } from "zod";
+import { z as z2 } from "zod";
function requestedRequirement(value, reason) {
return { state: "requested", value, ...reason === undefined ? {} : { reason } };
}
function statement(value) {
- return z.discriminatedUnion("state", [
- z.strictObject({ state: z.literal("requested"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("inferred"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("unknown"), reason: text.optional() }),
- z.strictObject({ state: z.literal("inapplicable"), reason: text.optional() })
+ return z2.discriminatedUnion("state", [
+ z2.strictObject({ state: z2.literal("requested"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inferred"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("unknown"), reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inapplicable"), reason: text.optional() })
]);
}
function validateAssetRequirementsV1(value) {
@@ -14362,157 +15759,159 @@ var text, positive2, nonnegative, count2, names, marker, supportParts, roof, str
var init_requirements = __esm(() => {
init_asset();
init_breadth();
- text = z.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
- positive2 = z.number().finite().positive();
- nonnegative = z.number().finite().nonnegative();
- count2 = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
- names = z.array(text).refine((values) => new Set(values).size === values.length, {
+ init_validation_profile();
+ text = z2.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
+ positive2 = z2.number().finite().positive();
+ nonnegative = z2.number().finite().nonnegative();
+ count2 = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+ names = z2.array(text).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- marker = z.strictObject({});
- supportParts = z.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
+ marker = z2.strictObject({});
+ supportParts = z2.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- roof = z.strictObject({
+ roof = z2.strictObject({
type: text.optional(),
- ridgeAxis: z.enum(["x", "z"]).optional(),
+ ridgeAxis: z2.enum(["x", "z"]).optional(),
rise: nonnegative.optional(),
- pitchDegrees: z.number().min(0).max(90).optional(),
+ pitchDegrees: z2.number().min(0).max(90).optional(),
overhang: nonnegative.optional(),
- closedEnds: z.boolean().optional()
+ closedEnds: z2.boolean().optional()
});
- structure = z.strictObject({
+ structure = z2.strictObject({
subtype: text.optional(),
- enterable: z.boolean().optional(),
+ enterable: z2.boolean().optional(),
storeyCount: count2.min(1).optional(),
- interiorMode: z.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
- roofMode: z.enum(ARCHITECTURE_ROOF_MODES).optional(),
- footprint: z.strictObject({ spanX: positive2, spanZ: positive2, units: z.literal("m") }).optional(),
+ interiorMode: z2.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
+ roofMode: z2.enum(ARCHITECTURE_ROOF_MODES).optional(),
+ footprint: z2.strictObject({ spanX: positive2, spanZ: positive2, units: z2.literal("m") }).optional(),
wallHeight: positive2.optional(),
- scaleMode: z.enum(ARCHITECTURE_SCALE_MODES).optional(),
+ scaleMode: z2.enum(ARCHITECTURE_SCALE_MODES).optional(),
roof: roof.optional(),
- portal: z.strictObject({ width: positive2, height: positive2, depth: positive2 }).optional()
+ portal: z2.strictObject({ width: positive2, height: positive2, depth: positive2 }).optional()
}).refine((value) => value.enterable === undefined || value.interiorMode === undefined || value.enterable === (value.interiorMode === "navigable"), {
message: "enterable and interiorMode must agree when both are specified."
});
- effects = z.strictObject({
- schemaVersion: z.literal(1),
- subtype: z.enum(VFX_SUBTYPES),
- portability: z.enum(VFX_PORTABILITY_MODES),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES),
- doubleSided: z.boolean(),
- facing: z.strictObject({
- source: z.enum(["explicit", "inferred"]),
- mode: z.enum(VFX_FACING_MODES),
- normalAxis: z.enum(VFX_AXIS_DIRECTIONS).optional(),
- directionAxis: z.enum(VFX_AXIS_DIRECTIONS).optional()
+ effects = z2.strictObject({
+ schemaVersion: z2.literal(1),
+ subtype: z2.enum(VFX_SUBTYPES),
+ portability: z2.enum(VFX_PORTABILITY_MODES),
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES),
+ doubleSided: z2.boolean(),
+ facing: z2.strictObject({
+ source: z2.enum(["explicit", "inferred"]),
+ mode: z2.enum(VFX_FACING_MODES),
+ normalAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional(),
+ directionAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional()
}),
- animation: z.strictObject({
- playback: z.enum(VFX_PLAYBACK_POLICIES),
+ animation: z2.strictObject({
+ playback: z2.enum(VFX_PLAYBACK_POLICIES),
durationSeconds: nonnegative,
- endpointBehavior: z.enum(VFX_ENDPOINT_BEHAVIORS),
- driver: z.enum(VFX_RUNTIME_DRIVERS),
+ endpointBehavior: z2.enum(VFX_ENDPOINT_BEHAVIORS),
+ driver: z2.enum(VFX_RUNTIME_DRIVERS),
clipName: text.optional(),
timeUniformName: text.optional()
}),
- sidecar: z.strictObject({ kind: z.literal("tsl"), id: text, version: text }).optional()
+ sidecar: z2.strictObject({ kind: z2.literal("tsl"), id: text, version: text }).optional()
}).superRefine((value, context) => {
for (const issue of validateVfxIntentV1(value).issues) {
context.addIssue({ code: "custom", path: issue.path.split("."), message: issue.message });
}
});
- requirements = z.strictObject({
- grounding: statement(z.strictObject({ planeY: z.number().finite().optional() })).optional(),
+ requirements = z2.strictObject({
+ grounding: statement(z2.strictObject({ planeY: z2.number().finite().optional() })).optional(),
articulation: statement(marker).optional(),
opening: statement(marker).optional(),
- navigation: statement(z.strictObject({ minWidth: positive2.optional(), minHeight: positive2.optional() })).optional(),
+ navigation: statement(z2.strictObject({ minWidth: positive2.optional(), minHeight: positive2.optional() })).optional(),
tiling: statement(marker).optional(),
- mobility: statement(z.strictObject({
+ mobility: statement(z2.strictObject({
subtype: text.optional(),
supportAssemblies: names.optional(),
propulsionAssemblies: names.optional(),
- frontFrame: z.literal("+X").optional(),
+ frontFrame: z2.literal("+X").optional(),
wheelCount: count2.optional(),
axleCount: count2.optional(),
- steering: z.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
- supportPolicy: z.enum(VEHICLE_SUPPORT_POLICIES).optional(),
+ steering: z2.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
+ supportPolicy: z2.enum(VEHICLE_SUPPORT_POLICIES).optional(),
animationAssemblies: names.optional()
})).optional(),
structure: statement(structure).optional(),
- rig: statement(z.strictObject({
- bodyPlan: z.enum(CHARACTER_BODY_PLANS).optional(),
- grounded: z.boolean().optional(),
- locomotion: z.enum(CHARACTER_LOCOMOTION_MODES).optional(),
+ rig: statement(z2.strictObject({
+ bodyPlan: z2.enum(CHARACTER_BODY_PLANS).optional(),
+ grounded: z2.boolean().optional(),
+ locomotion: z2.enum(CHARACTER_LOCOMOTION_MODES).optional(),
gait: text.optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- clips: z.array(z.strictObject({ name: text, playback: z.enum(["loop", "oneShot"]) })).optional(),
- heldItem: z.strictObject({ required: z.boolean(), attachmentRole: text }).optional()
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ clips: z2.array(z2.strictObject({ name: text, playback: z2.enum(["loop", "oneShot"]) })).optional(),
+ heldItem: z2.strictObject({ required: z2.boolean(), attachmentRole: text }).optional()
})).optional(),
- foliage: statement(z.strictObject({
+ foliage: statement(z2.strictObject({
subtype: text.optional(),
- growthState: z.enum(VEGETATION_GROWTH_STATES).optional(),
- canopyProfile: z.enum(VEGETATION_CANOPY_PROFILES).optional(),
- standalone: z.boolean().optional(),
- grounded: z.boolean().optional()
+ growthState: z2.enum(VEGETATION_GROWTH_STATES).optional(),
+ canopyProfile: z2.enum(VEGETATION_CANOPY_PROFILES).optional(),
+ standalone: z2.boolean().optional(),
+ grounded: z2.boolean().optional()
})).optional(),
- spatialLayout: statement(z.strictObject({
+ spatialLayout: statement(z2.strictObject({
subtype: text.optional(),
- tileable: z.boolean().optional(),
- navigable: z.boolean().optional()
+ tileable: z2.boolean().optional(),
+ navigable: z2.boolean().optional()
})).optional(),
effects: statement(effects).optional(),
- material: statement(z.strictObject({
- mode: z.enum(MATERIAL_INTENT_MODES).optional(),
+ material: statement(z2.strictObject({
+ mode: z2.enum(MATERIAL_INTENT_MODES).optional(),
recipeId: text.optional(),
paletteId: text.optional(),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES).optional()
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES).optional()
})).optional(),
- animation: statement(z.strictObject({
+ animation: statement(z2.strictObject({
clips: names,
- locomotionDirection: z.literal("+X").optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- loop: z.boolean().optional(),
+ locomotionDirection: z2.literal("+X").optional(),
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ loop: z2.boolean().optional(),
gait: text.optional()
})).optional(),
- bounds: statement(z.strictObject({
- units: z.literal("m"),
+ bounds: statement(z2.strictObject({
+ units: z2.literal("m"),
x: positive2.optional(),
y: positive2.optional(),
z: positive2.optional()
})).optional(),
- parts: statement(z.strictObject({ required: names, forbiddenExtras: names })).optional(),
- modular: statement(z.strictObject({
- schemaVersion: z.literal(1),
- units: z.literal("m"),
- grid: z.tuple([positive2, positive2, positive2])
+ parts: statement(z2.strictObject({ required: names, forbiddenExtras: names })).optional(),
+ modular: statement(z2.strictObject({
+ schemaVersion: z2.literal(1),
+ units: z2.literal("m"),
+ grid: z2.tuple([positive2, positive2, positive2])
})).optional(),
- representation: statement(z.strictObject({
- transparentSurface: z.boolean().optional(),
- runtimeShader: z.boolean().optional(),
- precomputedTangents: z.boolean().optional(),
- skinned: z.boolean().optional()
+ representation: statement(z2.strictObject({
+ transparentSurface: z2.boolean().optional(),
+ runtimeShader: z2.boolean().optional(),
+ precomputedTangents: z2.boolean().optional(),
+ skinned: z2.boolean().optional()
})).optional(),
- externalSupport: statement(z.strictObject({
- supports: z.array(z.strictObject({
+ externalSupport: statement(z2.strictObject({
+ supports: z2.array(z2.strictObject({
parts: supportParts,
- planeY: z.number().finite(),
+ planeY: z2.number().finite(),
tolerance: nonnegative.max(0.5).optional()
})).min(1).max(32)
})).optional(),
- access: statement(z.strictObject({ enterable: z.boolean().optional(), driveable: z.boolean().optional() })).optional()
+ access: statement(z2.strictObject({ enterable: z2.boolean().optional(), driveable: z2.boolean().optional() })).optional(),
+ validation: statement(ValidationProfileV1Schema).optional()
});
- AssetRequirementsV1Schema = z.strictObject({
- kind: z.literal("kiln.asset-requirements"),
- schemaVersion: z.literal(1),
+ AssetRequirementsV1Schema = z2.strictObject({
+ kind: z2.literal("kiln.asset-requirements"),
+ schemaVersion: z2.literal(1),
labels: names,
- frame: z.strictObject({
- units: z.literal("m"),
- forward: z.literal("+X"),
- up: z.literal("+Y"),
- right: z.literal("+Z"),
- groundY: z.literal(0)
+ frame: z2.strictObject({
+ units: z2.literal("m"),
+ forward: z2.literal("+X"),
+ up: z2.literal("+Y"),
+ right: z2.literal("+Z"),
+ groundY: z2.literal(0)
}),
- scope: statement(z.enum(ASSET_SCOPES)).optional(),
+ scope: statement(z2.enum(ASSET_SCOPES)).optional(),
requirements
}).superRefine((record, context) => {
const requests = record.requirements;
@@ -14661,7 +16060,7 @@ var init_requirements_json = __esm(() => {
// src/requirements-context.ts
import { createHash as createHash4 } from "node:crypto";
-import { z as z2 } from "zod";
+import { z as z3 } from "zod";
function canonical2(value) {
if (Array.isArray(value))
return `[${value.map(canonical2).join(",")}]`;
@@ -14729,26 +16128,26 @@ var init_requirements_context = __esm(() => {
init_requirements();
init_requirements_identity();
init_requirements_json();
- text2 = z2.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
- hash2 = z2.string().regex(/^[a-f0-9]{64}$/);
- revision = z2.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
- change = z2.strictObject({
+ text2 = z3.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
+ hash2 = z3.string().regex(/^[a-f0-9]{64}$/);
+ revision = z3.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
+ change = z3.strictObject({
actor: text2,
reason: text2,
- source: z2.enum(["brief", "automation", "migration", "restore"]),
+ source: z3.enum(["brief", "automation", "migration", "restore"]),
revision,
policyHash: hash2,
previousPolicyHash: hash2.optional()
});
- RequirementsBindingSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-binding"),
- schemaVersion: z2.literal(1),
+ RequirementsBindingSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-binding"),
+ schemaVersion: z3.literal(1),
taskId: text2,
lineageId: text2,
revision,
policyHash: hash2,
requirements: AssetRequirementsV1Schema,
- history: z2.array(change).min(1)
+ history: z3.array(change).min(1)
}).superRefine((binding, context) => {
const issue = (message) => context.addIssue({ code: "custom", message });
if (binding.policyHash !== assetRequirementsPolicyHash(binding.requirements))
@@ -14763,9 +16162,9 @@ var init_requirements_context = __esm(() => {
if (binding.history.at(-1)?.policyHash !== binding.policyHash)
issue("Requirements binding history does not end at its current policy.");
});
- CheckpointSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-checkpoint.v1"),
- programRef: z2.string().regex(/^sha256:[a-f0-9]{64}$/),
+ CheckpointSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-checkpoint.v1"),
+ programRef: z3.string().regex(/^sha256:[a-f0-9]{64}$/),
binding: RequirementsBindingSchema
});
});
@@ -14797,58 +16196,58 @@ async function renameDirectoryAtomically(source, destination, controls = {}) {
var init_atomic_directory = () => {};
// src/material-authoring-schema.ts
-import { z as z3 } from "zod";
+import { z as z4 } from "zod";
function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema = canonicalLegacyV2FieldSchema) {
- const integer = (min, max) => z3.number().int().min(min).max(max);
+ const integer = (min, max) => z4.number().int().min(min).max(max);
const byte = integer(0, 255);
const coordinate = integer(-4096, 4096);
- const point = z3.tuple([coordinate, coordinate]);
- const rgba = z3.tuple([byte, byte, byte, byte]);
- const usage = z3.enum(TEXTURE_USAGES);
- const hash = z3.templateLiteral(["sha256:", z3.string().regex(/^[a-f0-9]{64}$/)]);
- const name = z3.string().min(1).max(80);
- const stableId = z3.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- const mapId = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ const point = z4.tuple([coordinate, coordinate]);
+ const rgba = z4.tuple([byte, byte, byte, byte]);
+ const usage = z4.enum(TEXTURE_USAGES);
+ const hash = z4.templateLiteral(["sha256:", z4.string().regex(/^[a-f0-9]{64}$/)]);
+ const name = z4.string().min(1).max(80);
+ const stableId = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ const mapId = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
const dimensions = { width: integer(1, 4096), height: integer(1, 4096) };
- const pixelRectangleSchema = z3.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
- const atlasRectangleSchema = z3.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
- const shape = z3.discriminatedUnion("kind", [
- pixelRectangleSchema.extend({ kind: z3.literal("rectangle") }).strict(),
- pixelRectangleSchema.extend({ kind: z3.literal("ellipse") }).strict(),
- z3.object({
- kind: z3.literal("polygon"),
- points: z3.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
+ const pixelRectangleSchema = z4.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
+ const atlasRectangleSchema = z4.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
+ const shape = z4.discriminatedUnion("kind", [
+ pixelRectangleSchema.extend({ kind: z4.literal("rectangle") }).strict(),
+ pixelRectangleSchema.extend({ kind: z4.literal("ellipse") }).strict(),
+ z4.object({
+ kind: z4.literal("polygon"),
+ points: z4.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
}).strict(),
- z3.object({ kind: z3.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
+ z4.object({ kind: z4.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
]);
- const paint = z3.object({ op: z3.literal("paint"), shape, rgba, opacity: byte }).strict();
- const mask = z3.object({ op: z3.literal("mask"), shape, alpha: byte, invert: z3.boolean() }).strict();
- const stamps = z3.object({
- op: z3.literal("stamps"),
+ const paint = z4.object({ op: z4.literal("paint"), shape, rgba, opacity: byte }).strict();
+ const mask = z4.object({ op: z4.literal("mask"), shape, alpha: byte, invert: z4.boolean() }).strict();
+ const stamps = z4.object({
+ op: z4.literal("stamps"),
shape,
rgba,
opacity: byte,
count: integer(1, MAX_PROCEDURAL_V3_STAMPS),
seed: integer(0, 4294967295),
area: pixelRectangleSchema,
- periodic: z3.boolean()
+ periodic: z4.boolean()
}).strict();
- const legacy = z3.object({ op: z3.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
- const palette = z3.object({
- colors: z3.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
- dither: z3.enum(["none", "bayer4"])
+ const legacy = z4.object({ op: z4.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
+ const palette = z4.object({
+ colors: z4.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
+ dither: z4.enum(["none", "bayer4"])
}).strict();
const proceduralBase = {
- schemaVersion: z3.literal(3),
+ schemaVersion: z4.literal(3),
width: integer(4, MAX_PROCEDURAL_V3_EDGE),
height: integer(4, MAX_PROCEDURAL_V3_EDGE),
usage,
name: name.optional(),
background: rgba
};
- const canonicalProceduralTextureSpecV3Schema = z3.object({
+ const canonicalProceduralTextureSpecV3Schema = z4.object({
...proceduralBase,
- operations: z3.array(z3.discriminatedUnion("op", [
+ operations: z4.array(z4.discriminatedUnion("op", [
paint,
mask,
stamps,
@@ -14856,11 +16255,11 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.optional()
}).strict();
- const proceduralTextureSpecV3Schema = z3.object({
+ const proceduralTextureSpecV3Schema = z4.object({
...proceduralBase,
usage: usage.optional(),
background: rgba.optional(),
- operations: z3.array(z3.discriminatedUnion("op", [
+ operations: z4.array(z4.discriminatedUnion("op", [
paint.partial({ opacity: true }),
mask.partial({ alpha: true, invert: true }),
stamps.partial({ opacity: true, periodic: true }),
@@ -14868,110 +16267,110 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.partial({ dither: true }).optional()
}).strict();
- const portableSamplerSchema = z3.object({
- minFilter: z3.enum(PORTABLE_MIN_FILTERS_V1),
- magFilter: z3.enum(PORTABLE_MAG_FILTERS_V1),
- wrapS: z3.enum(PORTABLE_WRAPS_V1),
- wrapT: z3.enum(PORTABLE_WRAPS_V1)
+ const portableSamplerSchema = z4.object({
+ minFilter: z4.enum(PORTABLE_MIN_FILTERS_V1),
+ magFilter: z4.enum(PORTABLE_MAG_FILTERS_V1),
+ wrapS: z4.enum(PORTABLE_WRAPS_V1),
+ wrapT: z4.enum(PORTABLE_WRAPS_V1)
}).strict();
- const materialMapPinSchema = z3.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
- const resourceSource = z3.object({
- kind: z3.literal("resource"),
+ const materialMapPinSchema = z4.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
+ const resourceSource = z4.object({
+ kind: z4.literal("resource"),
resourceId: mapId,
pin: materialMapPinSchema,
- expected: z3.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
+ expected: z4.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
}).strict();
- const region = z3.object({
+ const region = z4.object({
name: stableId,
content: atlasRectangleSchema,
gutter: integer(0, 32),
- edgeMode: z3.enum(["copy-edge", "mask-rgb-dilate"]),
- source: z3.discriminatedUnion("kind", [
- z3.object({ kind: z3.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
+ edgeMode: z4.enum(["copy-edge", "mask-rgb-dilate"]),
+ source: z4.discriminatedUnion("kind", [
+ z4.object({ kind: z4.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
resourceSource
]),
crop: atlasRectangleSchema.optional(),
- packed: z3.literal(true).optional()
+ packed: z4.literal(true).optional()
}).strict();
const atlasBase = {
- schemaVersion: z3.literal(1),
+ schemaVersion: z4.literal(1),
width: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
height: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
usage,
sampler: portableSamplerSchema
};
- const packEdge = z3.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z3.literal(edge)));
- const canonicalTextureAtlasSpecV1Schema = z3.object({
+ const packEdge = z4.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z4.literal(edge)));
+ const canonicalTextureAtlasSpecV1Schema = z4.object({
...atlasBase,
- regions: z3.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
- pack: z3.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z3.literal("maxrects") }).strict().optional()
+ regions: z4.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
+ pack: z4.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z4.literal("maxrects") }).strict().optional()
}).strict();
- const textureAtlasSpecV1Schema = z3.object({
+ const textureAtlasSpecV1Schema = z4.object({
...atlasBase,
width: atlasBase.width.optional(),
height: atlasBase.height.optional(),
- pack: z3.object({
+ pack: z4.object({
edge: packEdge,
gutter: integer(0, 32).optional(),
- algorithm: z3.literal("maxrects").optional()
+ algorithm: z4.literal("maxrects").optional()
}).strict().optional(),
sampler: portableSamplerSchema.optional(),
- regions: z3.array(region.extend({
- source: z3.discriminatedUnion("kind", [
- z3.object({ kind: z3.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
+ regions: z4.array(region.extend({
+ source: z4.discriminatedUnion("kind", [
+ z4.object({ kind: z4.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
resourceSource
])
}).partial({ content: true, gutter: true, edgeMode: true })).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions)
}).strict();
- const verifiedPinnedMaterialMapDescriptorSchema = z3.object({
+ const verifiedPinnedMaterialMapDescriptorSchema = z4.object({
materialId: stableId,
revisionId: hash,
resourceId: mapId,
- slot: z3.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ slot: z4.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
usage,
- colorSpace: z3.enum(["srgb", "linear"]),
+ colorSpace: z4.enum(["srgb", "linear"]),
...dimensions,
encodedByteLength: integer(1, TEXTURE_ATLAS_LIMITS.encodedSourceBytes),
imageSha256: hash,
decodedPixelHash: hash.optional()
}).strict();
const sourceManifestBase = {
- id: z3.string().min(1).max(1024),
+ id: z4.string().min(1).max(1024),
...dimensions,
decodedPixelHash: hash
};
- const sourceManifest = z3.discriminatedUnion("kind", [
- z3.object({
+ const sourceManifest = z4.discriminatedUnion("kind", [
+ z4.object({
...sourceManifestBase,
- kind: z3.literal("procedural"),
+ kind: z4.literal("procedural"),
recipeHash: hash,
- compilerId: z3.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
+ compilerId: z4.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
}).strict(),
- z3.object({
+ z4.object({
...sourceManifestBase,
- kind: z3.literal("resource"),
+ kind: z4.literal("resource"),
descriptor: verifiedPinnedMaterialMapDescriptorSchema
}).strict()
]);
- const textureAtlasManifestV1Schema = z3.object({
- version: z3.literal("kiln.atlas-manifest.v1"),
- compilerId: z3.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ const textureAtlasManifestV1Schema = z4.object({
+ version: z4.literal("kiln.atlas-manifest.v1"),
+ compilerId: z4.enum(TEXTURE_ATLAS_COMPILER_IDS),
width: atlasBase.width,
height: atlasBase.height,
usage,
- origin: z3.literal("top-left"),
+ origin: z4.literal("top-left"),
sampler: portableSamplerSchema,
specHash: hash,
layoutHash: hash,
decodedPixelHash: hash,
atlasPixelHash: hash,
- sources: z3.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
- regions: z3.array(z3.object({
+ sources: z4.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
+ regions: z4.array(z4.object({
name: stableId,
content: atlasRectangleSchema,
allocation: atlasRectangleSchema,
crop: atlasRectangleSchema,
- sourceId: z3.string().min(1).max(1024)
+ sourceId: z4.string().min(1).max(1024)
}).strict()).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
manifestHash: hash
}).strict();
@@ -14994,36 +16393,36 @@ var init_material_authoring_schema = __esm(() => {
init_portable_sampler();
init_texture_contract();
canonicalLegacyV2FieldSchema = (() => {
- const color = z3.number().int().min(0).max(16777215);
- const count = z3.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
- const angleDeg = z3.number().min(-36000).max(36000);
- const unit = z3.number().min(0).max(1);
- const common = { blend: z3.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
- return z3.object({
- schemaVersion: z3.literal(2),
- size: z3.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
- usage: z3.enum(TEXTURE_USAGES),
- name: z3.string().min(1).max(80).optional(),
- layers: z3.array(z3.discriminatedUnion("op", [
- z3.object({ op: z3.literal("solid"), color, ...common }).strict(),
- z3.object({
- op: z3.literal("checker"),
+ const color = z4.number().int().min(0).max(16777215);
+ const count = z4.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
+ const angleDeg = z4.number().min(-36000).max(36000);
+ const unit = z4.number().min(0).max(1);
+ const common = { blend: z4.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
+ return z4.object({
+ schemaVersion: z4.literal(2),
+ size: z4.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
+ usage: z4.enum(TEXTURE_USAGES),
+ name: z4.string().min(1).max(80).optional(),
+ layers: z4.array(z4.discriminatedUnion("op", [
+ z4.object({ op: z4.literal("solid"), color, ...common }).strict(),
+ z4.object({
+ op: z4.literal("checker"),
colorA: color,
colorB: color,
squares: count,
...common
}).strict(),
- z3.object({
- op: z3.literal("stripes"),
+ z4.object({
+ op: z4.literal("stripes"),
colorA: color,
colorB: color,
count,
angleDeg,
...common
}).strict(),
- z3.object({ op: z3.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
- z3.object({
- op: z3.literal("bricks"),
+ z4.object({ op: z4.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
+ z4.object({
+ op: z4.literal("bricks"),
brick: color,
mortar: color,
rows: count,
@@ -15032,13 +16431,13 @@ var init_material_authoring_schema = __esm(() => {
stagger: unit,
...common
}).strict(),
- z3.object({
- op: z3.literal("noise"),
+ z4.object({
+ op: z4.literal("noise"),
colorA: color,
colorB: color,
scale: count,
- octaves: z3.number().int().min(1).max(MAX_NOISE_OCTAVES),
- seed: z3.number().int().min(-2147483648).max(2147483647),
+ octaves: z4.number().int().min(1).max(MAX_NOISE_OCTAVES),
+ seed: z4.number().int().min(-2147483648).max(2147483647),
...common
}).strict()
])).min(1).max(MAX_PROCEDURAL_LAYERS)
@@ -15047,7 +16446,7 @@ var init_material_authoring_schema = __esm(() => {
});
// src/material-library.ts
-import { z as z4 } from "zod";
+import { z as z5 } from "zod";
function assertMaterialJson(value, allowBytes = false, depth = 0) {
if (depth > 30)
throw new Error("Material JSON exceeds nesting limit");
@@ -15304,23 +16703,23 @@ var init_material_library = __esm(() => {
emissive: "emissive",
occlusion: "occlusion"
};
- materialLibraryIdSchema = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- materialLibraryHashSchema = z4.string().regex(/^sha256:[a-f0-9]{64}$/);
- text3 = z4.string().min(1).max(1000);
- url = z4.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
- materialSourceSchema = z4.object({
+ materialLibraryIdSchema = z5.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ materialLibraryHashSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text3 = z5.string().min(1).max(1000);
+ url = z5.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
+ materialSourceSchema = z5.object({
id: materialLibraryIdSchema,
- kind: z4.enum(["external", "procedural"]),
+ kind: z5.enum(["external", "procedural"]),
provider: text3,
creator: text3,
assetId: text3.optional(),
assetUrl: url.optional(),
- accessedAt: z4.string().datetime().optional(),
- license: z4.object({ spdx: text3, url, attribution: z4.string().max(4000) }).strict(),
- originalFiles: z4.array(z4.object({
- name: z4.string().min(1).max(200),
+ accessedAt: z5.string().datetime().optional(),
+ license: z5.object({ spdx: text3, url, attribution: z5.string().max(4000) }).strict(),
+ originalFiles: z5.array(z5.object({
+ name: z5.string().min(1).max(200),
sha256: materialLibraryHashSchema,
- bytes: z4.number().int().positive().max(1024 * 1024 * 1024)
+ bytes: z5.number().int().positive().max(1024 * 1024 * 1024)
}).strict()).max(20)
}).strict().superRefine((source, context) => {
if (source.kind === "external" && (!source.assetUrl || !source.originalFiles.length))
@@ -15331,22 +16730,22 @@ var init_material_library = __esm(() => {
if (new Set(source.originalFiles.map((file) => file.name)).size !== source.originalFiles.length)
context.addIssue({ code: "custom", message: "Duplicate original filename" });
});
- materialTransformSchema = z4.object({
+ materialTransformSchema = z5.object({
operation: text3,
tool: text3,
version: text3,
- parameters: z4.record(z4.string().max(100), z4.union([z4.string().max(2000), z4.number().finite(), z4.boolean()])).optional()
+ parameters: z5.record(z5.string().max(100), z5.union([z5.string().max(2000), z5.number().finite(), z5.boolean()])).optional()
}).strict();
- color2 = z4.number().int().min(0).max(16777215);
- count3 = z4.number().int().min(1).max(256);
+ color2 = z5.number().int().min(0).max(16777215);
+ count3 = z5.number().int().min(1).max(256);
layerCommon = {
- blend: z4.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
- opacity: z4.number().min(0).max(1).default(1)
+ blend: z5.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
+ opacity: z5.number().min(0).max(1).default(1)
};
- materialProceduralSpecSchema = z4.object({
- schemaVersion: z4.literal(2),
- size: z4.number().int().min(4).max(1024).default(256),
- usage: z4.enum([
+ materialProceduralSpecSchema = z5.object({
+ schemaVersion: z5.literal(2),
+ size: z5.number().int().min(4).max(1024).default(256),
+ usage: z5.enum([
"albedo",
"normal",
"roughness",
@@ -15355,90 +16754,90 @@ var init_material_library = __esm(() => {
"emissive",
"occlusion"
]).default("albedo"),
- name: z4.string().min(1).max(80).optional(),
- layers: z4.array(z4.discriminatedUnion("op", [
- z4.object({ op: z4.literal("solid"), color: color2, ...layerCommon }).strict(),
- z4.object({
- op: z4.literal("checker"),
+ name: z5.string().min(1).max(80).optional(),
+ layers: z5.array(z5.discriminatedUnion("op", [
+ z5.object({ op: z5.literal("solid"), color: color2, ...layerCommon }).strict(),
+ z5.object({
+ op: z5.literal("checker"),
colorA: color2,
colorB: color2,
squares: count3.default(8),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("stripes"),
+ z5.object({
+ op: z5.literal("stripes"),
colorA: color2,
colorB: color2,
count: count3.default(8),
- angleDeg: z4.number().min(-36000).max(36000).default(0),
+ angleDeg: z5.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("gradient"),
+ z5.object({
+ op: z5.literal("gradient"),
from: color2,
to: color2,
- angleDeg: z4.number().min(-36000).max(36000).default(0),
+ angleDeg: z5.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("bricks"),
+ z5.object({
+ op: z5.literal("bricks"),
brick: color2,
mortar: color2,
rows: count3.default(8),
cols: count3.default(4),
- mortarWidth: z4.number().min(0).max(1).default(0.06),
- stagger: z4.number().min(0).max(1).default(0.5),
+ mortarWidth: z5.number().min(0).max(1).default(0.06),
+ stagger: z5.number().min(0).max(1).default(0.5),
...layerCommon
}).strict(),
- z4.object({
- op: z4.literal("noise"),
+ z5.object({
+ op: z5.literal("noise"),
colorA: color2,
colorB: color2,
scale: count3.default(8),
- octaves: z4.number().int().min(1).max(6).default(3),
- seed: z4.number().int().min(-2147483648).max(2147483647).default(0),
+ octaves: z5.number().int().min(1).max(6).default(3),
+ seed: z5.number().int().min(-2147483648).max(2147483647).default(0),
...layerCommon
}).strict()
])).min(1).max(8)
}).strict();
- materialNormalDerivationSchema = z4.object({
- kind: z4.literal("normal-from-height"),
- strength: z4.number().finite().positive().max(64)
+ materialNormalDerivationSchema = z5.object({
+ kind: z5.literal("normal-from-height"),
+ strength: z5.number().finite().positive().max(64)
}).strict();
- proceduralSchema = z4.object({
- compiler: z4.literal("kiln.procedural-texture.v2"),
+ proceduralSchema = z5.object({
+ compiler: z5.literal("kiln.procedural-texture.v2"),
spec: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional(),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text3 }).strict()
+ encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict()
}).strict();
- parametersSchema = z4.object({
- baseColor: z4.number().int().min(0).max(16777215).optional(),
- roughness: z4.number().min(0).max(1).default(1),
- metalness: z4.number().min(0).max(1).default(0),
- emissive: z4.number().int().min(0).max(16777215).optional(),
- emissiveIntensity: z4.number().min(0).max(64).default(1),
- alphaMode: z4.enum(["opaque", "mask", "blend"]).default("opaque"),
- alphaCutoff: z4.number().min(0).max(1).default(0.5),
- doubleSided: z4.boolean().default(false)
+ parametersSchema = z5.object({
+ baseColor: z5.number().int().min(0).max(16777215).optional(),
+ roughness: z5.number().min(0).max(1).default(1),
+ metalness: z5.number().min(0).max(1).default(0),
+ emissive: z5.number().int().min(0).max(16777215).optional(),
+ emissiveIntensity: z5.number().min(0).max(64).default(1),
+ alphaMode: z5.enum(["opaque", "mask", "blend"]).default("opaque"),
+ alphaCutoff: z5.number().min(0).max(1).default(0.5),
+ doubleSided: z5.boolean().default(false)
}).strict();
- materialManifestSchema = z4.object({
- schemaVersion: z4.literal(1),
+ materialManifestSchema = z5.object({
+ schemaVersion: z5.literal(1),
materialId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
- name: z4.string().min(1).max(200),
- tags: z4.array(z4.string().min(1).max(80)).max(30),
- tileable: z4.boolean(),
- physicalSizeMeters: z4.object({
- width: z4.number().finite().positive().max(1e5),
- height: z4.number().finite().positive().max(1e5)
+ name: z5.string().min(1).max(200),
+ tags: z5.array(z5.string().min(1).max(80)).max(30),
+ tileable: z5.boolean(),
+ physicalSizeMeters: z5.object({
+ width: z5.number().finite().positive().max(1e5),
+ height: z5.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema,
- sources: z4.array(materialSourceSchema).min(1).max(20),
- maps: z4.array(z4.object({
- slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
- file: z4.enum([
+ sources: z5.array(materialSourceSchema).min(1).max(20),
+ maps: z5.array(z5.object({
+ slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
+ file: z5.enum([
"baseColor.png",
"normal.png",
"metallicRoughness.png",
@@ -15446,45 +16845,45 @@ var init_material_library = __esm(() => {
"occlusion.png"
]),
sha256: materialLibraryHashSchema,
- bytes: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
- width: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- height: z4.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- usage: z4.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
- colorSpace: z4.enum(["srgb", "linear"]),
- normalConvention: z4.literal("opengl").optional(),
- channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ bytes: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
+ width: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ height: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ usage: z5.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ colorSpace: z5.enum(["srgb", "linear"]),
+ normalConvention: z5.literal("opengl").optional(),
+ channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
sourceId: materialLibraryIdSchema,
- originalFile: z4.string().min(1).max(200).optional(),
- transforms: z4.array(materialTransformSchema).max(30),
+ originalFile: z5.string().min(1).max(200).optional(),
+ transforms: z5.array(materialTransformSchema).max(30),
procedural: proceduralSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- proceduralMaterialDraftSchema = z4.object({
+ proceduralMaterialDraftSchema = z5.object({
materialId: materialLibraryIdSchema,
- name: z4.string().min(1).max(200),
- tags: z4.array(z4.string().min(1).max(80)).max(30).optional(),
- tileable: z4.boolean(),
- physicalSizeMeters: z4.object({
- width: z4.number().finite().positive().max(1e5),
- height: z4.number().finite().positive().max(1e5)
+ name: z5.string().min(1).max(200),
+ tags: z5.array(z5.string().min(1).max(80)).max(30).optional(),
+ tileable: z5.boolean(),
+ physicalSizeMeters: z5.object({
+ width: z5.number().finite().positive().max(1e5),
+ height: z5.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema.partial().optional(),
- sources: z4.array(materialSourceSchema).min(1).max(20),
- maps: z4.array(z4.object({
- slot: z4.enum(MATERIAL_LIBRARY_SLOTS),
+ sources: z5.array(materialSourceSchema).min(1).max(20),
+ maps: z5.array(z5.object({
+ slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
sourceId: materialLibraryIdSchema,
- transforms: z4.array(materialTransformSchema).max(30),
- normalConvention: z4.literal("opengl").optional(),
- channelPacking: z4.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ transforms: z5.array(materialTransformSchema).max(30),
+ normalConvention: z5.literal("opengl").optional(),
+ channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
procedural: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialLibraryPayloadSchema = z4.object({
- schemaVersion: z4.literal(1),
- records: z4.array(z4.object({
+ materialLibraryPayloadSchema = z5.object({
+ schemaVersion: z5.literal(1),
+ records: z5.array(z5.object({
manifest: materialManifestSchema,
- files: z4.record(z4.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z4.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
+ files: z5.record(z5.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z5.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
}).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
authoringSchemas = makeMaterialAuthoringSchemas(materialProceduralSpecSchema);
@@ -15493,27 +16892,27 @@ var init_material_library = __esm(() => {
v3SpecSchema = authoringSchemas.canonicalProceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, true), afterShape);
atlasSpecSchema = authoringSchemas.canonicalTextureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, true), afterShape);
atlasManifestSchema = authoringSchemas.textureAtlasManifestV1Schema;
- materialMapPinSchema = z4.object({
+ materialMapPinSchema = z5.object({
resourceId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
sha256: materialLibraryHashSchema
}).strict().refine((pin) => pin.sha256 === pin.revisionId, "Material pin hash must match revision");
- materialRecipeV2Schema = z4.discriminatedUnion("kind", [
- z4.object({
- kind: z4.literal("procedural"),
- compilerId: z4.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
- spec: z4.union([materialProceduralSpecSchema, v3SpecSchema]),
+ materialRecipeV2Schema = z5.discriminatedUnion("kind", [
+ z5.object({
+ kind: z5.literal("procedural"),
+ compilerId: z5.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
+ spec: z5.union([materialProceduralSpecSchema, v3SpecSchema]),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text3 }).strict(),
+ encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict(),
derive: materialNormalDerivationSchema.optional()
}).strict(),
- z4.object({
- kind: z4.literal("atlas"),
- compilerId: z4.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ z5.object({
+ kind: z5.literal("atlas"),
+ compilerId: z5.enum(TEXTURE_ATLAS_COMPILER_IDS),
spec: atlasSpecSchema,
manifest: atlasManifestSchema,
- encoder: z4.object({ name: z4.literal("sharp"), version: text3 }).strict()
+ encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict()
}).strict().superRefine((recipe, context) => {
try {
validateTextureAtlasManifestV1(recipe.manifest, recipe.spec);
@@ -15525,38 +16924,38 @@ var init_material_library = __esm(() => {
}, afterShape)
]);
materialManifestV2Schema = materialManifestSchema.omit({ schemaVersion: true, maps: true }).extend({
- schemaVersion: z4.literal(2),
- dependencies: z4.array(materialMapPinSchema).max(16),
- maps: z4.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z5.literal(2),
+ dependencies: z5.array(materialMapPinSchema).max(16),
+ maps: z5.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
pixelHash: materialLibraryHashSchema,
recipe: materialRecipeV2Schema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialManifestAnySchema = z4.discriminatedUnion("schemaVersion", [
+ materialManifestAnySchema = z5.discriminatedUnion("schemaVersion", [
materialManifestSchema,
materialManifestV2Schema
]);
materialLibraryPayloadV2Schema = materialLibraryPayloadSchema.extend({
- schemaVersion: z4.literal(2),
- records: z4.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
+ schemaVersion: z5.literal(2),
+ records: z5.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
- materialLibraryPayloadAnySchema = z4.discriminatedUnion("schemaVersion", [
+ materialLibraryPayloadAnySchema = z5.discriminatedUnion("schemaVersion", [
materialLibraryPayloadSchema,
materialLibraryPayloadV2Schema
]);
proceduralMaterialDraftV2Schema = proceduralMaterialDraftSchema.extend({
- schemaVersion: z4.literal(2),
- maps: z4.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z5.literal(2),
+ maps: z5.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
- procedural: z4.union([
+ procedural: z5.union([
materialProceduralSpecSchema,
authoringSchemas.proceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, false), afterShape)
]).optional(),
atlas: authoringSchemas.textureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, false), afterShape).optional()
}).strict().refine((map) => map.procedural !== undefined !== (map.atlas !== undefined), "Supply exactly one procedural or atlas recipe")).min(1).max(5)
}).strict();
- proceduralMaterialDraftAnySchema = z4.union([
+ proceduralMaterialDraftAnySchema = z5.union([
proceduralMaterialDraftSchema,
proceduralMaterialDraftV2Schema
]);
@@ -16135,7 +17534,7 @@ var init_texture_atlas_pixels = __esm(() => {
});
// src/procedural-texture.ts
-import * as THREE21 from "three";
+import * as THREE23 from "three";
function proceduralTextureSchemaVersion(input) {
if (!input || typeof input !== "object" || Array.isArray(input))
throw new ProceduralTextureError("proceduralTexture requires a plain JSON object.", "PROCEDURAL_TEXTURE_V3_CONTRACT");
@@ -16156,14 +17555,14 @@ function proceduralTexture(spec) {
if (proceduralTextureSchemaVersion(spec) === 3) {
const compiled = compileProceduralTextureSpecV3(spec);
const { width, height, usage, name } = compiled.spec;
- const tex = new THREE21.DataTexture(compiled.pixels, width, height, THREE21.RGBAFormat, THREE21.UnsignedByteType);
+ const tex = new THREE23.DataTexture(compiled.pixels, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE21.SRGBColorSpace : THREE21.NoColorSpace;
- tex.wrapS = THREE21.RepeatWrapping;
- tex.wrapT = THREE21.RepeatWrapping;
- tex.minFilter = THREE21.LinearMipmapLinearFilter;
- tex.magFilter = THREE21.LinearFilter;
+ 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.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -16176,14 +17575,14 @@ function proceduralTexture(spec) {
}
const compiled = compileProceduralTextureSpecV2(spec);
const { size, usage, name, layers } = compiled.spec;
- const tex = new THREE21.DataTexture(compiled.pixels, size, size, THREE21.RGBAFormat, THREE21.UnsignedByteType);
+ const tex = new THREE23.DataTexture(compiled.pixels, size, size, THREE23.RGBAFormat, THREE23.UnsignedByteType);
if (name)
tex.name = name;
- tex.colorSpace = usage === "albedo" || usage === "emissive" ? THREE21.SRGBColorSpace : THREE21.NoColorSpace;
- tex.wrapS = THREE21.RepeatWrapping;
- tex.wrapT = THREE21.RepeatWrapping;
- tex.minFilter = THREE21.LinearMipmapLinearFilter;
- tex.magFilter = THREE21.LinearFilter;
+ 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.generateMipmaps = true;
tex.needsUpdate = true;
tex.userData["kilnProcedural"] = {
@@ -16237,13 +17636,13 @@ function normalMapFromHeight(source, opts = {}) {
out[o + 3] = 255;
}
}
- const tex = new THREE21.DataTexture(out, width, height, THREE21.RGBAFormat, THREE21.UnsignedByteType);
+ const tex = new THREE23.DataTexture(out, width, height, THREE23.RGBAFormat, THREE23.UnsignedByteType);
tex.name = opts.name ?? (source.name ? `${source.name}_Normal` : "");
- tex.colorSpace = THREE21.NoColorSpace;
- tex.wrapS = THREE21.RepeatWrapping;
- tex.wrapT = THREE21.RepeatWrapping;
- tex.minFilter = THREE21.LinearMipmapLinearFilter;
- tex.magFilter = THREE21.LinearFilter;
+ tex.colorSpace = THREE23.NoColorSpace;
+ tex.wrapS = THREE23.RepeatWrapping;
+ tex.wrapT = THREE23.RepeatWrapping;
+ tex.minFilter = THREE23.LinearMipmapLinearFilter;
+ tex.magFilter = THREE23.LinearFilter;
tex.generateMipmaps = true;
tex.needsUpdate = true;
return tex;
@@ -16258,7 +17657,7 @@ var init_procedural_texture = __esm(() => {
});
// src/textures.ts
-import * as THREE22 from "three";
+import * as THREE24 from "three";
async function loadTexture(source, opts = {}) {
let bytes;
if (typeof source === "string") {
@@ -16279,7 +17678,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 THREE24.DataTexture(new Uint8Array(data), meta.width, meta.height, THREE24.RGBAFormat, THREE24.UnsignedByteType);
const usage = opts.usage ?? "albedo";
const colorSpace = usage === "albedo" || usage === "emissive" ? "srgb" : "linear";
let hasAlpha = false;
@@ -16289,14 +17688,14 @@ async function loadTexture(source, opts = {}) {
break;
}
}
- tex.colorSpace = colorSpace === "srgb" ? THREE22.SRGBColorSpace : THREE22.NoColorSpace;
+ tex.colorSpace = colorSpace === "srgb" ? THREE24.SRGBColorSpace : THREE24.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 = THREE24.RepeatWrapping;
+ tex.wrapT = THREE24.RepeatWrapping;
+ tex.minFilter = THREE24.LinearMipmapLinearFilter;
+ tex.magFilter = THREE24.LinearFilter;
tex.generateMipmaps = true;
tex.userData["encoded"] = {
mime,
@@ -16331,17 +17730,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" ? THREE24.SRGBColorSpace : THREE24.NoColorSpace;
}
function pbrMaterial(opts = {}) {
- const mat = new THREE22.MeshStandardMaterial;
+ const mat = new THREE24.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 THREE24.Color(16777215);
} else if (opts.albedo !== undefined) {
- mat.color = new THREE22.Color(opts.albedo);
+ mat.color = new THREE24.Color(opts.albedo);
}
if (opts.normal) {
requireTextureUsage(opts.normal, "normal");
@@ -16379,9 +17778,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 THREE24.Color(16777215);
} else if (opts.emissive !== undefined) {
- mat.emissive = new THREE22.Color(opts.emissive);
+ mat.emissive = new THREE24.Color(opts.emissive);
}
if (opts.emissiveIntensity !== undefined) {
mat.emissiveIntensity = opts.emissiveIntensity;
@@ -16413,7 +17812,7 @@ function pbrMaterial(opts = {}) {
mat.transparent = true;
}
if (opts.doubleSided)
- mat.side = THREE22.DoubleSide;
+ mat.side = THREE24.DoubleSide;
mat.userData["kilnMaterial"] = {
alphaMode,
...alphaMode === "mask" ? { alphaCutoff: mat.alphaTest } : {},
@@ -18587,7 +19986,7 @@ var init_material_resources = __esm(() => {
});
// src/material-recipe-runtime.ts
-import * as THREE23 from "three";
+import * as THREE25 from "three";
async function applyMaterialRecipeV1(request, options = {}) {
const resolved = resolveMaterialRecipeV1(request);
const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;
@@ -18610,9 +20009,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], THREE23.LinearSRGBColorSpace);
+ material.color.setRGB(resolved.baseColorFactor[0], resolved.baseColorFactor[1], resolved.baseColorFactor[2], THREE25.LinearSRGBColorSpace);
material.opacity = resolved.baseColorFactor[3];
- material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE23.LinearSRGBColorSpace);
+ material.emissive.setRGB(resolved.emissiveFactor[0], resolved.emissiveFactor[1], resolved.emissiveFactor[2], THREE25.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,
@@ -19895,7 +21294,8 @@ function resolveRequirementsApplicability(requirements) {
bounds: ["units", "x", "y", "z"],
animation: ["clips"],
representation: ["precomputedTangents"],
- externalSupport: ["supports"]
+ externalSupport: ["supports"],
+ validation: ["version", "profileId", "mode", "checks"]
};
for (const [key, statement] of Object.entries(requirements.requirements)) {
if (statement?.state !== "requested")
@@ -20012,7 +21412,8 @@ var init_requirements_applicability = __esm(() => {
kernel: "connectivity"
},
{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },
- { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" }
+ { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },
+ { id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }
];
});
@@ -20154,103 +21555,21 @@ var init_requirements_report = __esm(() => {
});
// src/rebuild-options.ts
-import { z as z5 } from "zod";
+import { z as z6 } from "zod";
var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
- rebuildOptionsSchema = z5.object({
- indexPolicy: z5.enum(["indexed", "asBuilt"]).optional(),
- gltfExporter: z5.enum(["legacy", "three"]),
- geometryPolicy: z5.enum(["warn", "strict"]),
- optimize: z5.enum(["off", "auto", "palette", "full"]),
- optimizationPipeline: z5.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
- instance: z5.enum(["off", "auto", "on"])
+ rebuildOptionsSchema = z6.object({
+ indexPolicy: z6.enum(["indexed", "asBuilt"]).optional(),
+ gltfExporter: z6.enum(["legacy", "three"]),
+ geometryPolicy: z6.enum(["warn", "strict"]),
+ optimize: z6.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z6.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
+ instance: z6.enum(["off", "auto", "on"])
});
});
-// src/gltf-io.ts
-import {
- Extension,
- ExtensionProperty,
- PropertyType,
- RefList,
- WebIO
-} from "@gltf-transform/core";
-import { ALL_EXTENSIONS } from "@gltf-transform/extensions";
-function createGltfIO() {
- return new WebIO().registerExtensions([...ALL_EXTENSIONS, MSFTLod]);
-}
-var MSFT_LOD = "MSFT_lod", Lod, MSFTLod;
-var init_gltf_io = __esm(() => {
- Lod = class Lod extends ExtensionProperty {
- static EXTENSION_NAME = MSFT_LOD;
- init() {
- this.extensionName = MSFT_LOD;
- this.propertyType = "Lod";
- this.parentTypes = [PropertyType.NODE, PropertyType.MATERIAL];
- }
- getDefaults() {
- return Object.assign(super.getDefaults(), {
- levels: new RefList
- });
- }
- addLevel(level) {
- return this.addRef("levels", level);
- }
- listLevels() {
- return this.listRefs("levels");
- }
- };
- MSFTLod = class MSFTLod extends Extension {
- extensionName = MSFT_LOD;
- static EXTENSION_NAME = MSFT_LOD;
- createLod(name = "") {
- return new Lod(this.document.getGraph(), name);
- }
- read(context) {
- const json = context.jsonDoc.json;
- this.readLevels(json.nodes, context.nodes);
- this.readLevels(json.materials, context.materials);
- return this;
- }
- readLevels(defs, targets) {
- (defs ?? []).forEach((def, index) => {
- const ids = def.extensions?.[MSFT_LOD]?.ids;
- const target = targets[index];
- if (!target || !Array.isArray(ids))
- return;
- const lod = this.createLod();
- for (const id of ids) {
- const level = typeof id === "number" ? targets[id] : undefined;
- if (level && level !== target)
- lod.addLevel(level);
- }
- target.setExtension(MSFT_LOD, lod);
- });
- }
- write(context) {
- const json = context.jsonDoc.json;
- const root = this.document.getRoot();
- for (const node of root.listNodes()) {
- const index = context.nodeIndexMap.get(node);
- const ids = node.getExtension(MSFT_LOD)?.listLevels().filter((level) => level.propertyType === PropertyType.NODE).map((level) => context.nodeIndexMap.get(level)).filter((id) => id !== undefined);
- const def = index === undefined ? undefined : json.nodes?.[index];
- if (def && ids?.length)
- def.extensions = { ...def.extensions, [MSFT_LOD]: { ids } };
- }
- for (const material of root.listMaterials()) {
- const index = context.materialIndexMap.get(material);
- const ids = material.getExtension(MSFT_LOD)?.listLevels().filter((level) => level.propertyType === PropertyType.MATERIAL).map((level) => context.materialIndexMap.get(level)).filter((id) => id !== undefined);
- const def = index === undefined ? undefined : json.materials?.[index];
- if (def && ids?.length)
- def.extensions = { ...def.extensions, [MSFT_LOD]: { ids } };
- }
- return this;
- }
- };
-});
-
// src/qa/breadth-final.ts
-import * as THREE24 from "three";
+import * as THREE26 from "three";
function bytesContainAscii(bytes, value) {
const needle = new TextEncoder().encode(value);
outer:
@@ -20309,7 +21628,7 @@ function finalEffectAxis(nodes, mode) {
if (!(semantic?.roles ?? []).some((role) => /^vfx\.effect\.surface(?:\.|$)/.test(role))) {
continue;
}
- const matrix = new THREE24.Matrix4().fromArray(node.getWorldMatrix());
+ const matrix = new THREE26.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() ?? []) {
@@ -20319,9 +21638,9 @@ function finalEffectAxis(nodes, mode) {
const min = position.getMin([]);
const max = position.getMax([]);
const axes = [
- { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE24.Vector3(1, 0, 0) },
- { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE24.Vector3(0, 1, 0) },
- { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE24.Vector3(0, 0, 1) }
+ { score: (max[0] ?? 0) - (min[0] ?? 0), direction: new THREE26.Vector3(1, 0, 0) },
+ { score: (max[1] ?? 0) - (min[1] ?? 0), direction: new THREE26.Vector3(0, 1, 0) },
+ { score: (max[2] ?? 0) - (min[2] ?? 0), direction: new THREE26.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 = {
@@ -20678,6 +21997,8 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {
}
if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
continue;
+ if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)
+ continue;
if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
continue;
executedRules.push(decision.ruleId);
@@ -20726,14 +22047,17 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {
} : {}
});
}
-function appendRequirementsQa(context, report, findings, metrics = {}) {
+function appendRequirementsQa(context, report, findings, metrics = {}, executedRules = []) {
const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
const merged = { ...priorMetrics };
for (const [dimension, value] of Object.entries(metrics ?? {}))
merged[dimension] = { ...priorMetrics[dimension], ...value };
return createRequirementsQaReport(context, {
findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
- executedRules: report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ executedRules: [
+ ...report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ ...executedRules
+ ],
modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
evaluatedDimensions: [
...new Set([
@@ -20809,6 +22133,16 @@ async function appendRequirementsFinalQa(context, report, gltf, bytes, instancea
exportIntegrity: finalEffectsMetrics(evidence)
});
}
+ const validation = context.requirements.requirements.validation;
+ const hostRule = report.rules.find((r) => r.id === HOST_VALIDATION_QA_RULE.id);
+ if (validation?.state === "requested" && hostRule && hostRule.status !== "notRequested" && hostRule.mode !== "off") {
+ const evaluation = await evaluateValidationProfileGlb(validation.value, bytes);
+ const findings = hostRule.mode === "enforce" ? evaluation.findings : evaluation.findings.map((f) => ({
+ ...f,
+ disposition: f.disposition === "observe" ? f.disposition : hostRule.mode
+ }));
+ result = appendRequirementsQa(context, result, findings, { requirementReadiness: evaluation.metrics }, evaluation.complete ? [HOST_VALIDATION_QA_RULE.id] : []);
+ }
return result;
}
var registry;
@@ -20831,6 +22165,7 @@ var init_requirements_run = __esm(() => {
init_architecture();
init_environment2();
init_requirements_applicability();
+ init_validation_profile2();
init_requirements_report();
init_run();
registry = new QaRegistry([
@@ -20849,12 +22184,13 @@ var init_requirements_run = __esm(() => {
CHARACTER_ADVISORY_QA_RULE,
VFX_EXACT_QA_RULE,
VFX_ADVISORY_QA_RULE,
- ASSET_SCOPE_QA_RULE
+ ASSET_SCOPE_QA_RULE,
+ HOST_VALIDATION_QA_RULE
]);
});
// src/qa/skin-integrity.ts
-import * as THREE25 from "three";
+import * as THREE27 from "three";
function validAttribute(a, count, size) {
if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)
return false;
@@ -20901,9 +22237,9 @@ function inspectSkinIntegrity(root) {
}
while (chain.length) {
const n = chain.pop();
- const local = n.matrixAutoUpdate ? new THREE25.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
+ const local = n.matrixAutoUpdate ? new THREE27.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
const parent = n.parent ? worlds.get(n.parent) : undefined;
- const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE25.Matrix4().multiplyMatrices(parent, local) : local;
+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE27.Matrix4().multiplyMatrices(parent, local) : local;
worlds.set(n, value);
}
return worlds.get(node);
@@ -20953,7 +22289,7 @@ function inspectSkinIntegrity(root) {
if (result.truncated)
break;
}
- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE25.AttachedBindMode, THREE25.DetachedBindMode].includes(mesh.bindMode)) {
+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE27.AttachedBindMode, THREE27.DetachedBindMode].includes(mesh.bindMode)) {
add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");
}
const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;
@@ -21002,7 +22338,7 @@ function inspectSkinIntegrity(root) {
add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");
continue;
}
- const inverse = mesh.bindMode === THREE25.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
+ const inverse = mesh.bindMode === THREE27.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
const matrices = [];
for (let joint = 0;joint < bones.length; joint++) {
const boneWorld = world(bones[joint]);
@@ -21010,13 +22346,13 @@ function inspectSkinIntegrity(root) {
add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);
break;
}
- matrices.push(new THREE25.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
+ matrices.push(new THREE27.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
}
if (result.findings.length !== start)
continue;
- const base = new THREE25.Vector3, posed = new THREE25.Vector3, temp = new THREE25.Vector3, box = new THREE25.Box3;
+ const base = new THREE27.Vector3, posed = new THREE27.Vector3, temp = new THREE27.Vector3, box = new THREE27.Box3;
for (let vertex = 0;vertex < count; vertex++) {
- THREE25.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
+ THREE27.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
posed.set(0, 0, 0);
for (let lane = 0;lane < 4; lane++) {
const weight = weights.getComponent(vertex, lane);
@@ -21038,334 +22374,8 @@ function inspectSkinIntegrity(root) {
var MAX_FINDINGS = 64, WEIGHT_TOLERANCE = 0.00001;
var init_skin_integrity = () => {};
-// src/metrics.ts
-function primTris(prim) {
- const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
- switch (prim.getMode()) {
- case 4:
- return Math.floor(count / 3);
- case 5:
- case 6:
- return Math.max(0, count - 2);
- default:
- return 0;
- }
-}
-function instanceCopies(node) {
- const ext = node.getExtension("EXT_mesh_gpu_instancing");
- if (!ext)
- return 1;
- return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
-}
-function isHiddenGltfNode(node) {
- const visibility = node.getExtension("KHR_node_visibility");
- return visibility?.getVisible?.() === false;
-}
-function nodeTriangles(node) {
- return subtreeTriangles(node, false);
-}
-function drawnNodeTriangles(node) {
- return subtreeTriangles(node, true);
-}
-function subtreeTriangles(node, drawn) {
- if (drawn && isHiddenGltfNode(node))
- return 0;
- let triangles = 0;
- const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- for (const prim of mesh.listPrimitives())
- triangles += primTris(prim) * copies;
- }
- for (const child of node.listChildren())
- triangles += subtreeTriangles(child, drawn);
- return triangles;
-}
-function collectGlbMetrics(doc, triangles) {
- const root = doc.getRoot();
- const geomSet = new Set;
- const matSet = new Set;
- let drawCalls = 0;
- let derivedTris = 0;
- let meshNodes = 0;
- let meshInstances = 0;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- meshNodes += 1;
- meshInstances += copies;
- for (const prim of mesh.listPrimitives()) {
- drawCalls += 1;
- geomSet.add(prim);
- derivedTris += primTris(prim) * copies;
- const mat = prim.getMaterial();
- if (mat)
- matSet.add(mat);
- }
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const scene of root.listScenes()) {
- for (const node of scene.listChildren())
- visit(node);
- }
- const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
- return {
- uniqueGeometries: geomSet.size,
- uniqueMaterials: matSet.size,
- meshNodes,
- meshInstances,
- drawCalls,
- textureCount: root.listTextures().length,
- skinned: root.listSkins().length > 0,
- transparentMaterials,
- triangles: triangles ?? derivedTris
- };
-}
-function rubricGrade(m) {
- const grade = materialBand(m.uniqueMaterials).grade;
- return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
-}
-function textureSlots(m) {
- return [
- [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
- [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
- [m.getNormalTexture(), m.getNormalTextureInfo()],
- [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
- [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
- ];
-}
-function shadingKey(m, textures) {
- const binding = (info) => info && [
- info.getTexCoord(),
- info.getWrapS(),
- info.getWrapT(),
- info.getMagFilter(),
- info.getMinFilter(),
- extensionNames(info)
- ];
- return JSON.stringify([
- m.getAlphaMode(),
- m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
- m.getDoubleSided(),
- textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
- extensionNames(m),
- m.getExtras()
- ]);
-}
-function differingFactors(group) {
- const [first, ...rest] = group;
- const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
- for (const extension of first.listExtensions())
- if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- const slots = textureSlots(first);
- slots.forEach(([, info], slot) => {
- for (const extension of info?.listExtensions() ?? [])
- if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- });
- return [...new Set(differs)];
-}
-function mergeNeeds(differs) {
- const needs = [];
- if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
- needs.push("colours in a shared texture, an atlas region or vertex colours");
- if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
- needs.push("one metallic/roughness value or a shared metallicRoughness texture");
- if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
- needs.push("one normal scale and occlusion strength");
- if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
- needs.push("one setting for each differing extension");
- return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
-}
-function materialMergeCandidates(doc) {
- const root = doc.getRoot();
- const parts = new Map;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
- for (const primitive of mesh?.listPrimitives() ?? []) {
- const material = primitive.getMaterial();
- if (!material)
- continue;
- const list = parts.get(material) ?? [];
- if (!list.includes(name))
- list.push(name);
- parts.set(material, list);
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const scene of root.listScenes())
- for (const node of scene.listChildren())
- visit(node);
- const materials = root.listMaterials();
- const textures = root.listTextures();
- const groups = new Map;
- for (const material of materials) {
- if (!parts.has(material))
- continue;
- const key = shadingKey(material, textures);
- const group = groups.get(key);
- if (group)
- group.push(material);
- else
- groups.set(key, [material]);
- }
- return [...groups.values()].filter((group) => group.length > 1).map((group) => {
- const differs = differingFactors(group);
- return {
- materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
- parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
- alphaMode: group[0].getAlphaMode(),
- differs,
- needs: mergeNeeds(differs)
- };
- });
-}
-function shortList(names, shown, joiner) {
- const head = names.slice(0, shown).join(joiner);
- return names.length > shown ? `${head} and ${names.length - shown} more` : head;
-}
-function mergeAdvice(m, candidates) {
- const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
- const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
- const projected = {
- ...m,
- uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
- transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
- };
- const projectedGrade = rubricGrade(projected);
- const band = materialBand(projected.uniqueMaterials);
- const named = (c) => shortList(c.materials, 4, " + ");
- const groups = candidates.slice(0, 3).map((c) => {
- const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
- return `${named(c)} (${why})`;
- });
- if (candidates.length > 3)
- groups.push(`${candidates.length - 3} more groups`);
- const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
- const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
- const reasons = candidates.map((c) => {
- const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
- return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
- });
- return {
- advice: {
- optional: true,
- materialMerges: [...candidates],
- projectedMaterials: projected.uniqueMaterials,
- projectedGrade
- },
- summary,
- reasons
- };
-}
-function gradeInstanceability(metrics, opts = {}) {
- const m = metrics;
- const band = materialBand(m.uniqueMaterials);
- let grade = band.grade;
- const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
- const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
- const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
- const drivers = [];
- const also = [];
- if ((grade === "A" || grade === "B") && (transparency || textures)) {
- grade = "C";
- if (transparency)
- drivers.push(`${transparency} (lowers A/B to C)`);
- if (textures)
- drivers.push(`${textures} (over 4 lowers A/B to C)`);
- also.push(materials);
- } else {
- drivers.push(materials);
- if (transparency)
- also.push(`${transparency} (lowers only A/B to C)`);
- if (textures)
- also.push(`${textures} (over 4 lowers only A/B to C)`);
- }
- also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
- if (m.skinned)
- also.push("skinned (clone-rendered, not penalized)");
- const setBy = drivers.join(" and ");
- const reasons = [
- `grade ${grade} set by ${setBy}`,
- `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
- ];
- if (transparency)
- reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
- if (textures)
- reasons.push(`${m.textureCount} textures (consider atlasing)`);
- if (m.skinned)
- reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
- if (opts.category)
- reasons.push(`category: ${opts.category}`);
- const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- if (!opts.mergeCandidates?.length)
- return { grade, summary, reasons, metrics: m };
- const merge = mergeAdvice(m, opts.mergeCandidates);
- return {
- grade,
- summary: summary + merge.summary,
- reasons: [...reasons, ...merge.reasons],
- metrics: m,
- advice: merge.advice
- };
-}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
-var init_metrics = __esm(() => {
- MATERIAL_GRADE_BANDS = [
- { grade: "A", max: 1, range: "0-1" },
- { grade: "B", max: 3, range: "2-3" },
- { grade: "C", max: 6, range: "4-6" },
- { grade: "D", max: 12, range: "7-12" },
- { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
- ];
- MERGE_FACTORS = [
- ["baseColorFactor", (m) => m.getBaseColorFactor()],
- ["emissiveFactor", (m) => m.getEmissiveFactor()],
- ["metallicFactor", (m) => m.getMetallicFactor()],
- ["roughnessFactor", (m) => m.getRoughnessFactor()],
- ["normalScale", (m) => m.getNormalScale()],
- ["occlusionStrength", (m) => m.getOcclusionStrength()]
- ];
-});
-
-// src/written-nodes.ts
-function exportedRoot(doc, purpose) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- const top = scene?.listChildren() ?? [];
- if (top.length !== 1)
- throw new Error(`${purpose} expects the exporter to write one root node.`);
- return top[0];
-}
-function writtenNodeResolver(root, doc, purpose) {
- const top = exportedRoot(doc, purpose);
- return (node) => {
- const path = [];
- for (let current = node;current !== root; current = current.parent) {
- if (!current.parent)
- throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
- path.unshift(current.parent.children.indexOf(current));
- }
- let target = top;
- for (const index of path)
- target = target?.listChildren()[index];
- if (!target || (target.getName() || "") !== (node.name || ""))
- throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
- return target;
- };
-}
-
// src/lod-export.ts
-import { PropertyType as PropertyType2 } from "@gltf-transform/core";
+import { PropertyType as PropertyType3 } from "@gltf-transform/core";
function applyLodChains(root, sets, doc) {
if (sets.length === 0)
return;
@@ -21405,9 +22415,9 @@ function listLodChainNodes(doc) {
const chains = [];
const visit = (siblings, parentPath) => {
siblings.forEach((node, index) => {
- const at = (name) => `${parentPath}${segment2(name, occurrence(siblings, index, name))}`;
+ const at = (name) => `${parentPath}${segment4(name, occurrence(siblings, index, name))}`;
const path = at(node.getName());
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
if (lower.length > 0)
chains.push({
levels: [node, ...lower],
@@ -21416,7 +22426,7 @@ function listLodChainNodes(doc) {
visit(node.listChildren(), path);
});
};
- visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
+ visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
return chains;
}
function isImpostorLevel(node) {
@@ -21439,109 +22449,13 @@ function summarizeLodChains(doc) {
};
});
}
-var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
var init_lod_export = __esm(() => {
init_semantic();
init_gltf_io();
init_metrics();
});
-// src/node-visibility.ts
-import { KHRNodeVisibility } from "@gltf-transform/extensions";
-import * as THREE26 from "three";
-function applyNodeVisibility(root, doc) {
- const hidden = [];
- root.traverse((node) => {
- if (node.visible === false)
- hidden.push(node);
- });
- if (hidden.length === 0)
- return;
- const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
- const extension = doc.createExtension(KHRNodeVisibility);
- for (const node of written)
- node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
-}
-function summarizeHiddenNodes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const found = [];
- const visit = (siblings, parentPath) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment3(name, occurrence)}`;
- if (isHiddenGltfNode(node))
- found.push({ path, name, triangles: nodeTriangles(node) });
- else
- visit(node.listChildren(), path);
- }
- };
- visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
- return found;
-}
-function drawnSceneBounds(scene) {
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- if (mesh) {
- const base = new THREE26.Matrix4().fromArray(node.getWorldMatrix());
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < countInstances; i++) {
- const t = translation?.getElement(i, []) ?? [0, 0, 0];
- const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
- const s = scale?.getElement(i, []) ?? [1, 1, 1];
- const localMatrix = new THREE26.Matrix4().compose(new THREE26.Vector3().fromArray(t), new THREE26.Quaternion().fromArray(r), new THREE26.Vector3().fromArray(s));
- matrices.push(base.clone().multiply(localMatrix).toArray());
- }
- const local = [0, 0, 0];
- for (const primitive of mesh.listPrimitives()) {
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const m of matrices)
- for (let i = 0;i < count; i++) {
- position.getElement(indices ? indices.getScalar(i) : i, local);
- const [x, y, z] = local;
- const world = [
- m[0] * x + m[4] * y + m[8] * z + m[12],
- m[1] * x + m[5] * y + m[9] * z + m[13],
- m[2] * x + m[6] * y + m[10] * z + m[14]
- ];
- for (let k = 0;k < 3; k++) {
- if (world[k] < min[k])
- min[k] = world[k];
- if (world[k] > max[k])
- max[k] = world[k];
- }
- }
- }
- }
- for (const child of node.listChildren())
- visit(child);
- };
- for (const node of scene.listChildren())
- visit(node);
- return { min, max };
-}
-var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
-var init_node_visibility = __esm(() => {
- init_metrics();
-});
-
// src/rig-export.ts
function rigExtrasForExport(node) {
const extras = {};
@@ -21585,7 +22499,7 @@ var init_material_export = __esm(() => {
});
// src/community-exporter.ts
-import * as THREE27 from "three";
+import * as THREE28 from "three";
import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
import { GLB_BUFFER } from "@gltf-transform/core";
function resolveGltfExporter(value = typeof process !== "undefined" ? process.env["KILN_GLTF_EXPORTER"] : undefined) {
@@ -21615,7 +22529,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
return found;
const copy = cleanClone(source);
normalizeTextureTransform(copy);
- copy.source = new THREE27.TextureSource(source.image);
+ copy.source = new THREE28.TextureSource(source.image);
textures.set(source, copy);
const bytes = source.userData["encoded"];
if (bytes?.bytes) {
@@ -21624,8 +22538,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
encoded.push((async () => {
copy.image = await platform.decode(bytes.bytes);
Object.defineProperty(copy, "isDataTexture", { value: true });
- copy.format = THREE27.RGBAFormat;
- copy.type = THREE27.UnsignedByteType;
+ copy.format = THREE28.RGBAFormat;
+ copy.type = THREE28.UnsignedByteType;
})());
}
return copy;
@@ -21642,7 +22556,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
physical.sheen = 1;
}
for (const [key, value] of Object.entries(copy)) {
- if (value instanceof THREE27.Texture)
+ if (value instanceof THREE28.Texture)
copy[key] = texture(value);
}
materials.set(source, copy);
@@ -21658,15 +22572,15 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
if (!copy.matrixAutoUpdate)
copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);
if (source.isScene) {
- copy = new THREE27.Group;
+ copy = new THREE28.Group;
copy.copy(shadow, false);
}
if (source.isSprite) {
const sprite = source;
- const geometry = new THREE27.PlaneGeometry(1, 1);
+ const geometry = new THREE28.PlaneGeometry(1, 1);
geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
geometry.rotateZ(sprite.material.rotation);
- const spriteMaterial = new THREE27.MeshBasicMaterial({
+ const spriteMaterial = new THREE28.MeshBasicMaterial({
name: sprite.material.name,
color: sprite.material.color,
opacity: sprite.material.opacity,
@@ -21677,8 +22591,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
});
Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));
originalMaterials.set(spriteMaterial, sprite.material);
- copy = new THREE27.Mesh(geometry, spriteMaterial);
- THREE27.Object3D.prototype.copy.call(copy, shadow, false);
+ copy = new THREE28.Mesh(geometry, spriteMaterial);
+ THREE28.Object3D.prototype.copy.call(copy, shadow, false);
}
Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));
const semantic = source.userData[KILN_SEMANTIC_EXTRAS_KEY];
@@ -21742,8 +22656,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
if (!context)
throw new Error("A 2D canvas is required to prepare export texture channels.");
context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);
- const adapted = new THREE27.Texture().copy(map);
- adapted.source = new THREE27.TextureSource(canvas);
+ const adapted = new THREE28.Texture().copy(map);
+ adapted.source = new THREE28.TextureSource(canvas);
canvasInputs.set(map, adapted);
const direct = directImages.get(map);
if (direct)
@@ -21752,7 +22666,7 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
};
for (const material of materials.values()) {
for (const [key, value] of Object.entries(material)) {
- if (value instanceof THREE27.Texture && value.flipY && value.image?.data)
+ if (value instanceof THREE28.Texture && value.flipY && value.image?.data)
material[key] = canvasInput(value);
}
const standard = material;
@@ -21774,8 +22688,8 @@ async function communitySceneDocument(root, clips, platform = browserPlatform, a
}
cloned.tracks = cloned.tracks.filter((track) => {
try {
- const binding = THREE27.PropertyBinding.parseTrackName(track.name);
- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE27.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ const binding = THREE28.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE28.PropertyBinding.findNode(copy, binding.nodeName) !== null;
} catch {
return false;
}
@@ -21969,443 +22883,6 @@ function applyIndexPolicy(doc, policy) {
}
var init_index_policy = () => {};
-// src/delivery-inspect.ts
-import * as THREE28 from "three";
-import { PropertyType as PropertyType3 } from "@gltf-transform/core";
-function decompose(matrix) {
- const translation = new THREE28.Vector3;
- const rotation = new THREE28.Quaternion;
- const scale = new THREE28.Vector3;
- matrix.decompose(translation, rotation, scale);
- const clean = (value) => Object.is(value, -0) ? 0 : value;
- return {
- translation: translation.toArray().map(clean),
- rotation: rotation.toArray().map(clean),
- scale: scale.toArray().map(clean)
- };
-}
-function drawnTriangles(visited) {
- const values = [];
- const local = [0, 0, 0];
- const point = new THREE28.Vector3;
- for (const { node, roles, hidden } of visited) {
- const mesh = node.getMesh();
- if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
- continue;
- const base = worldMatrix(node);
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < copies; i++) {
- const instance = new THREE28.Matrix4().compose(new THREE28.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE28.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE28.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
- matrices.push(base.clone().multiply(instance));
- }
- for (const primitive of mesh.listPrimitives()) {
- if (primitive.getMode() !== 4)
- continue;
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const matrix of matrices)
- for (let i = 0;i + 2 < count; i += 3)
- for (let k = 0;k < 3; k++) {
- position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
- point.fromArray(local).applyMatrix4(matrix);
- values.push(point.x, point.y, point.z);
- }
- }
- }
- return Float64Array.from(values);
-}
-function triangleOverlapsBox(a, b, c, h, tolerance) {
- const verts = [a, b, c];
- const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
- for (let axis = 0;axis < 3; axis++) {
- const values = verts.map((v) => v.getComponent(axis));
- if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
- return false;
- }
- const e = [
- new THREE28.Vector3().subVectors(b, a),
- new THREE28.Vector3().subVectors(c, b),
- new THREE28.Vector3().subVectors(a, c)
- ];
- const normal = new THREE28.Vector3().crossVectors(e[0], e[1]);
- const axes = [normal];
- const units = [
- new THREE28.Vector3(1, 0, 0),
- new THREE28.Vector3(0, 1, 0),
- new THREE28.Vector3(0, 0, 1)
- ];
- for (const unit of units)
- for (const edge of e)
- axes.push(new THREE28.Vector3().crossVectors(unit, edge));
- for (const axis of axes) {
- if (axis.lengthSq() < 0.000000000000000000000001)
- continue;
- const projections = verts.map((v) => v.dot(axis));
- const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
- if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
- return false;
- }
- return true;
-}
-function closestPointOnTriangle(p, a, b, c) {
- const ab = new THREE28.Vector3().subVectors(b, a);
- const ac = new THREE28.Vector3().subVectors(c, a);
- const ap = new THREE28.Vector3().subVectors(p, a);
- const d1 = ab.dot(ap);
- const d2 = ac.dot(ap);
- if (d1 <= 0 && d2 <= 0)
- return a.clone();
- const bp = new THREE28.Vector3().subVectors(p, b);
- const d3 = ab.dot(bp);
- const d4 = ac.dot(bp);
- if (d3 >= 0 && d4 <= d3)
- return b.clone();
- const vc = d1 * d4 - d3 * d2;
- if (vc <= 0 && d1 >= 0 && d3 <= 0)
- return a.clone().addScaledVector(ab, d1 / (d1 - d3));
- const cp = new THREE28.Vector3().subVectors(p, c);
- const d5 = ab.dot(cp);
- const d6 = ac.dot(cp);
- if (d6 >= 0 && d5 <= d6)
- return c.clone();
- const vb = d5 * d2 - d1 * d6;
- if (vb <= 0 && d2 >= 0 && d6 <= 0)
- return a.clone().addScaledVector(ac, d2 / (d2 - d6));
- const va = d3 * d6 - d5 * d4;
- if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
- return b.clone().addScaledVector(new THREE28.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
- const denominator = 1 / (va + vb + vc);
- return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
-}
-function segmentSegmentDistanceSq(p1, q1, p2, q2) {
- const d1 = new THREE28.Vector3().subVectors(q1, p1);
- const d2 = new THREE28.Vector3().subVectors(q2, p2);
- const r = new THREE28.Vector3().subVectors(p1, p2);
- const a = d1.dot(d1);
- const e = d2.dot(d2);
- const f = d2.dot(r);
- let s = 0;
- let t = 0;
- if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
- return r.lengthSq();
- if (a <= 0.000000000000000000000001)
- t = THREE28.MathUtils.clamp(f / e, 0, 1);
- else {
- const c = d1.dot(r);
- if (e <= 0.000000000000000000000001)
- s = THREE28.MathUtils.clamp(-c / a, 0, 1);
- else {
- const b = d1.dot(d2);
- const denominator = a * e - b * b;
- s = denominator !== 0 ? THREE28.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
- t = (b * s + f) / e;
- if (t < 0) {
- t = 0;
- s = THREE28.MathUtils.clamp(-c / a, 0, 1);
- } else if (t > 1) {
- t = 1;
- s = THREE28.MathUtils.clamp((b - c) / a, 0, 1);
- }
- }
- }
- const c1 = p1.clone().addScaledVector(d1, s);
- const c2 = p2.clone().addScaledVector(d2, t);
- return c1.distanceToSquared(c2);
-}
-function segmentCrossesTriangle(p, q, a, b, c) {
- const hit = new THREE28.Vector3;
- const ray = new THREE28.Ray(p, new THREE28.Vector3().subVectors(q, p));
- const length = ray.direction.length();
- if (length === 0)
- return false;
- ray.direction.divideScalar(length);
- return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
-}
-function triangleTouchesCapsule(a, b, c, p, q, radius) {
- const r2 = radius * radius;
- if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
- return true;
- if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
- return true;
- for (const [s, e] of [
- [a, b],
- [b, c],
- [c, a]
- ])
- if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
- return true;
- return segmentCrossesTriangle(p, q, a, b, c);
-}
-function deliveryNodePaths(doc) {
- const paths = new Map;
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return paths;
- const visit = (siblings, parentPath) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment4(name, occurrence)}`;
- paths.set(node, path);
- visit(node.listChildren(), path);
- }
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
- return paths;
-}
-function summarizeVertexAttributes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const groups = new Map;
- const order = [];
- const record = (node, path) => {
- const mesh = node.getMesh();
- if (!mesh)
- return;
- const bake = mesh.getExtras().kilnSurfaceBakeV1;
- const names = new Set;
- for (const primitive of mesh.listPrimitives())
- for (const semantic of primitive.listSemantics())
- if (semantic.startsWith("_"))
- names.add(semantic);
- for (const name of names) {
- const params = bake && typeof bake === "object" ? bake[name] : undefined;
- const key = `${name}\x00${JSON.stringify(params ?? null)}`;
- let group = groups.get(key);
- if (!group) {
- group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
- groups.set(key, group);
- order.push(key);
- }
- if (!group.meshes.includes(path))
- group.meshes.push(path);
- }
- };
- const visit = (siblings, parentPath) => {
- siblings.forEach((node, index) => {
- const at = (name) => {
- let occurrence = 0;
- for (let i = 0;i < index; i++)
- if (siblings[i].getName() === name)
- occurrence++;
- return `${parentPath}${segment4(name, occurrence)}`;
- };
- const path = at(node.getName());
- record(node, path);
- visit(node.listChildren(), path);
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
- for (const level of lower) {
- const levelPath = at(level.getName());
- record(level, levelPath);
- visit(level.listChildren(), levelPath);
- }
- });
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
- const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
- return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
-}
-function inspectDelivery(doc) {
- const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return summary;
- const visited = [];
- const visit = (siblings, parentPath, hidden, module) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment4(name, occurrence)}`;
- const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
- const nodeHidden = hidden || isHiddenGltfNode(node);
- const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
- visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
- visit(node.listChildren(), path, nodeHidden, nodeModule);
- }
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0), false, undefined);
- const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
- const { min, max } = drawnSceneBounds(scene);
- const bounds = new THREE28.Box3(new THREE28.Vector3(...min), new THREE28.Vector3(...max));
- const finiteBounds = [...min, ...max].every(Number.isFinite);
- const diagonal = finiteBounds ? bounds.getSize(new THREE28.Vector3).length() : 0;
- const tolerance = Math.max(0.0001, diagonal * 0.0001);
- const colliderNodes = [];
- for (const entry of visited) {
- const { node, path, roles } = entry;
- for (const role of roles) {
- const matrix = worldMatrix(node);
- const transform = decompose(matrix);
- for (const shape of ["box", "capsule", "hull"]) {
- const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
- if (id === undefined)
- continue;
- const scale = transform.scale;
- const record = {
- role,
- id,
- path,
- name: node.getName(),
- transform,
- shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
- kind: "hull",
- vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
- }
- };
- summary.colliders.push(record);
- colliderNodes.push({ visit: entry, record });
- }
- const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
- if (anchorTail !== undefined) {
- const [kind, ...rest] = anchorTail.split(".");
- summary.anchors.push({
- role,
- kind,
- id: rest.join("."),
- path,
- name: node.getName(),
- transform
- });
- }
- const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
- if (portId !== undefined)
- summary.ports.push({
- role,
- id: portId,
- path,
- name: node.getName(),
- ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
- transform
- });
- if (role === KILN_SEMANTIC_ROLES.kitModule) {
- const extras = node.getExtras()[KILN_KIT_KEY];
- let spec;
- try {
- const { schemaVersion, ...rest } = extras ?? {};
- spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
- } catch {
- spec = undefined;
- }
- if (!spec)
- finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
- else if (summary.kit)
- finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
- else
- summary.kit = {
- role,
- path,
- name: node.getName(),
- footprint: spec.footprint,
- height: spec.height,
- snapAxis: spec.snapAxis,
- origin: spec.origin,
- transform
- };
- }
- }
- }
- const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
- const triangleCount = triangles.length / 9;
- let overlapTests = 0;
- const a = new THREE28.Vector3;
- const b = new THREE28.Vector3;
- const c = new THREE28.Vector3;
- for (const { visit: entry, record } of colliderNodes) {
- if (!entry.hidden)
- finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
- const matrix = worldMatrix(entry.node);
- const proxyBounds = new THREE28.Box3;
- const mesh = entry.node.getMesh();
- const local = [0, 0, 0];
- for (const primitive of mesh?.listPrimitives() ?? []) {
- const position = primitive.getAttribute("POSITION");
- for (let i = 0;i < (position?.getCount() ?? 0); i++)
- proxyBounds.expandByPoint(new THREE28.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
- }
- if (proxyBounds.isEmpty())
- proxyBounds.expandByPoint(new THREE28.Vector3().setFromMatrixPosition(matrix));
- const expanded = bounds.clone().expandByScalar(tolerance);
- if (!finiteBounds || !expanded.containsBox(proxyBounds))
- finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
- if (record.shape.kind === "hull")
- continue;
- if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
- finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
- continue;
- }
- overlapTests += triangleCount;
- const toLocal = new THREE28.Matrix4;
- let touches = false;
- if (record.shape.kind === "box") {
- toLocal.copy(matrix).invert();
- const half = new THREE28.Vector3(0.5, 0.5, 0.5);
- const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
- }
- } else {
- const { translation, rotation } = record.transform;
- toLocal.compose(new THREE28.Vector3(...translation), new THREE28.Quaternion(...rotation), new THREE28.Vector3(1, 1, 1)).invert();
- const { radius, height } = record.shape;
- const p = new THREE28.Vector3(0, -height / 2 + radius, 0);
- const q = new THREE28.Vector3(0, height / 2 - radius, 0);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
- }
- }
- if (!touches)
- finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
- }
- for (const record of summary.ports) {
- const entry = visited.find((item) => item.path === record.path);
- const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
- const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
- if (!spec) {
- finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
- continue;
- }
- const point = new THREE28.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
- const [width, depth] = spec.footprint;
- const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
- const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
- if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
- finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
- }
- for (const record of summary.anchors) {
- const entry = visited.find((item) => item.path === record.path);
- if (entry.node.listChildren().length > 0)
- finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
- }
- return summary;
-}
-var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE28.Matrix4().fromArray(node.getWorldMatrix());
-var init_delivery_inspect = __esm(() => {
- init_gltf_io();
- init_semantic();
- init_delivery();
- init_metrics();
- init_node_visibility();
-});
-
// src/surface-bake.ts
import * as THREE29 from "three";
function settings(value, label) {
@@ -34647,7 +35124,7 @@ function strict(value, keys, label) {
throw new Error(`${label}.${key} is unknown${hint ? `; use ${KEY_HINTS[key]}` : ""}; accepted keys: ${keys.join(", ")}`);
}
}
-function finite2(n, label) {
+function finite3(n, label) {
if (!Number.isFinite(n))
throw new Error(`${label} must be finite`);
return n;
@@ -34786,7 +35263,7 @@ function validateResolvedAssetCamera(value) {
throw new Error("camera target must differ from position");
if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
throw new Error("camera up must be non-zero and not collinear with view");
- if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
+ if (finite3(camera.aspect, "aspect") <= 0 || finite3(camera.near, "near") <= 0 || finite3(camera.far, "far") <= camera.near)
throw new Error("camera requires positive aspect and 0 < near < far");
if (camera.projection === "orthographic") {
if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
@@ -34816,7 +35293,7 @@ function resolveAssetCamera(root, shot = {}) {
const relative = request.relativeTo ?? "world";
if (!["world", "asset", "part"].includes(relative))
throw new Error("invalid relativeTo");
- const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));
+ const dir = vec(orbitDir(finite3(request.azimuthDeg ?? 45, "azimuthDeg"), finite3(request.elevationDeg ?? 25, "elevationDeg")));
let up;
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
@@ -34894,7 +35371,7 @@ function resolveAssetCamera(root, shot = {}) {
far: request.far ?? fit.far
};
else {
- const fov = finite2(request.fovDeg ?? 50, "fovDeg");
+ const fov = finite3(request.fovDeg ?? 50, "fovDeg");
if (fov <= 0 || fov >= 180)
throw new Error("invalid fovDeg");
const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
@@ -40042,11 +40519,11 @@ var digest4 = (bytes) => createHash12("sha256").update(bytes).digest("hex"), com
var init_runtime_identity = () => {};
// src/projects.ts
-import { z as z6 } from "zod";
+import { z as z7 } from "zod";
function checkContent(data, ctx) {
const unique = (items, path) => {
if (new Set(items).size !== items.length)
- ctx.addIssue({ code: z6.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
+ ctx.addIssue({ code: z7.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
};
unique(data.inventory.map((v) => v.id), "inventory");
unique(data.references.map((v) => v.id), "references");
@@ -40062,20 +40539,20 @@ function checkContent(data, ctx) {
unique(item.references, `inventory.${item.id}.references`);
if (item.references.some((id) => !references.has(id)))
ctx.addIssue({
- code: z6.ZodIssueCode.custom,
+ code: z7.ZodIssueCode.custom,
path: ["inventory"],
message: "Unknown reference"
});
}
if (data.reviews.some((review) => !inventory.has(review.inventoryId)))
ctx.addIssue({
- code: z6.ZodIssueCode.custom,
+ code: z7.ZodIssueCode.custom,
path: ["reviews"],
message: "Unknown inventory item"
});
if (data.design.materialRoles.some((role) => role.resourceId && !resources.has(role.resourceId)))
ctx.addIssue({
- code: z6.ZodIssueCode.custom,
+ code: z7.ZodIssueCode.custom,
path: ["design"],
message: "Material role requires a locked resource"
});
@@ -40083,80 +40560,80 @@ function checkContent(data, ctx) {
var MAX_PROJECT_BYTES, MAX_PROJECT_REVISIONS = 1e4, projectIdSchema, projectRevisionIdSchema, hash3, text5, resourceId2, assetReference, projectDesignSchema, projectMaterialDependencySchema, materialDependenciesSchema, content, projectDraftSchema, projectPatchSchema, projectRevisionSchema, ProjectConflictError, ProjectNotFoundError, ProjectExistsError;
var init_projects = __esm(() => {
MAX_PROJECT_BYTES = 1024 * 1024;
- projectIdSchema = z6.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
- projectRevisionIdSchema = z6.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
- hash3 = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
- text5 = z6.string().max(4000);
- resourceId2 = z6.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
- assetReference = z6.object({
+ projectIdSchema = z7.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
+ projectRevisionIdSchema = z7.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
+ hash3 = z7.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text5 = z7.string().max(4000);
+ resourceId2 = z7.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ assetReference = z7.object({
collectionId: projectIdSchema,
assetId: projectIdSchema,
revisionId: projectIdSchema
}).strict();
- projectDesignSchema = z6.object({
+ projectDesignSchema = z7.object({
style: text5.default(""),
- scale: z6.string().max(1000).default(""),
- palette: z6.array(z6.object({
- role: z6.string().min(1).max(100),
- color: z6.string().regex(/^#[a-fA-F0-9]{6}$/)
+ scale: z7.string().max(1000).default(""),
+ palette: z7.array(z7.object({
+ role: z7.string().min(1).max(100),
+ color: z7.string().regex(/^#[a-fA-F0-9]{6}$/)
}).strict()).max(64).default([]),
- materialRoles: z6.array(z6.object({
- role: z6.string().min(1).max(100),
+ materialRoles: z7.array(z7.object({
+ role: z7.string().min(1).max(100),
description: text5.default(""),
resourceId: resourceId2.optional()
}).strict()).max(128).default([]),
- conventions: z6.array(z6.string().max(1000)).max(100).default([]),
- exceptions: z6.array(z6.string().max(1000)).max(100).default([])
+ conventions: z7.array(z7.string().max(1000)).max(100).default([]),
+ exceptions: z7.array(z7.string().max(1000)).max(100).default([])
}).strict();
- projectMaterialDependencySchema = z6.object({
+ projectMaterialDependencySchema = z7.object({
resourceId: resourceId2,
- revisionId: z6.string().min(1).max(200),
+ revisionId: z7.string().min(1).max(200),
sha256: hash3,
- role: z6.string().max(100).optional()
+ role: z7.string().max(100).optional()
}).strict();
- materialDependenciesSchema = z6.array(projectMaterialDependencySchema).max(512);
+ materialDependenciesSchema = z7.array(projectMaterialDependencySchema).max(512);
content = {
- name: z6.string().trim().min(1).max(200),
- brief: z6.string().max(16000).default(""),
+ name: z7.string().trim().min(1).max(200),
+ brief: z7.string().max(16000).default(""),
design: projectDesignSchema.default(() => projectDesignSchema.parse({})),
- inventory: z6.array(z6.object({
+ inventory: z7.array(z7.object({
id: projectIdSchema,
- name: z6.string().trim().min(1).max(200),
- kind: z6.enum(["asset", "environment"]).default("asset"),
+ name: z7.string().trim().min(1).max(200),
+ kind: z7.enum(["asset", "environment"]).default("asset"),
brief: text5.default(""),
- references: z6.array(projectIdSchema).max(64).default([]),
+ references: z7.array(projectIdSchema).max(64).default([]),
asset: assetReference.optional()
}).strict()).max(1000).default([]),
- deliveryProfiles: z6.array(z6.object({
+ deliveryProfiles: z7.array(z7.object({
id: projectIdSchema,
- target: z6.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
+ target: z7.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
description: text5.default(""),
- performanceIntent: z6.string().max(1000).default(""),
- constraints: z6.array(z6.string().max(1000)).max(100).default([])
+ performanceIntent: z7.string().max(1000).default(""),
+ constraints: z7.array(z7.string().max(1000)).max(100).default([])
}).strict()).max(32).default([]),
materialDependencies: materialDependenciesSchema.default([]),
- references: z6.array(z6.object({
+ references: z7.array(z7.object({
id: projectIdSchema,
- title: z6.string().min(1).max(200),
- uri: z6.string().min(1).max(2048),
+ title: z7.string().min(1).max(200),
+ uri: z7.string().min(1).max(2048),
description: text5.default(""),
sha256: hash3.optional()
}).strict()).max(256).default([]),
- reviews: z6.array(z6.object({
+ reviews: z7.array(z7.object({
id: projectIdSchema,
inventoryId: projectIdSchema,
projectRevisionId: projectRevisionIdSchema,
asset: assetReference,
- reviewer: z6.string().trim().min(1).max(200),
- verdict: z6.enum(["comment", "changes-requested", "accepted"]),
+ reviewer: z7.string().trim().min(1).max(200),
+ verdict: z7.enum(["comment", "changes-requested", "accepted"]),
notes: text5
}).strict()).max(2000).default([])
};
- projectDraftSchema = z6.object({
+ projectDraftSchema = z7.object({
projectId: projectIdSchema.optional(),
...content
}).strict().superRefine(checkContent);
- projectPatchSchema = z6.object({
+ projectPatchSchema = z7.object({
name: content.name.optional(),
brief: content.brief.removeDefault().optional(),
design: content.design.removeDefault().optional(),
@@ -40166,12 +40643,12 @@ var init_projects = __esm(() => {
references: content.references.removeDefault().optional(),
reviews: content.reviews.removeDefault().optional()
}).strict();
- projectRevisionSchema = z6.object({
- version: z6.literal("kiln.project.v1"),
+ projectRevisionSchema = z7.object({
+ version: z7.literal("kiln.project.v1"),
projectId: projectIdSchema,
revisionId: projectRevisionIdSchema,
parentRevision: projectRevisionIdSchema.optional(),
- createdAt: z6.string().datetime(),
+ createdAt: z7.string().datetime(),
...content
}).strict().superRefine(checkContent);
ProjectConflictError = class ProjectConflictError extends Error {
@@ -40425,11 +40902,11 @@ var init_projects_node = __esm(() => {
});
// src/workspace.ts
-import { z as z7 } from "zod";
+import { z as z8 } from "zod";
var workspaceSelectionSchema;
var init_workspace = __esm(() => {
init_projects();
- workspaceSelectionSchema = z7.object({
+ workspaceSelectionSchema = z8.object({
projectId: projectIdSchema.nullable().optional().describe("Project; omit for the configured default, null for standalone."),
projectRevision: projectRevisionIdSchema.optional().describe("Exact project revision."),
materialDependencies: materialDependenciesSchema.optional().describe("Pins for this call; each replaces the project pin of its resourceId.")
@@ -40510,7 +40987,7 @@ var init_workspace_node = __esm(() => {
});
// src/assets.ts
-import { z as z8 } from "zod";
+import { z as z9 } from "zod";
import { zipSync, unzipSync } from "three/addons/libs/fflate.module.js";
function assetMaterialRootManifests(record) {
const roots = new Map;
@@ -40703,38 +41180,38 @@ var init_assets = __esm(() => {
init_background();
init_material_library();
ASSET_LIMIT = 64 * 1024 * 1024;
- assetIdSchema = z8.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- hash4 = z8.string().regex(/^sha256:[a-f0-9]{64}$/);
- assetManifestSchema = z8.object({
- version: z8.literal("kiln.asset.v1"),
+ assetIdSchema = z9.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ hash4 = z9.string().regex(/^sha256:[a-f0-9]{64}$/);
+ assetManifestSchema = z9.object({
+ version: z9.literal("kiln.asset.v1"),
assetId: assetIdSchema,
revisionId: assetIdSchema,
parentRevision: assetIdSchema.optional(),
- name: z8.string().min(1).max(200),
- tags: z8.array(z8.string().max(80)).max(30),
- createdAt: z8.string().datetime(),
- description: z8.string().max(4000).optional(),
- brief: z8.string().max(8000).optional(),
- attribution: z8.object({
- model: z8.string().max(200).optional(),
- harness: z8.string().max(200).optional(),
- author: z8.string().max(200).optional()
+ name: z9.string().min(1).max(200),
+ tags: z9.array(z9.string().max(80)).max(30),
+ createdAt: z9.string().datetime(),
+ description: z9.string().max(4000).optional(),
+ brief: z9.string().max(8000).optional(),
+ attribution: z9.object({
+ model: z9.string().max(200).optional(),
+ harness: z9.string().max(200).optional(),
+ author: z9.string().max(200).optional()
}).optional(),
- editable: z8.boolean(),
- files: z8.record(z8.string(), z8.object({ sha256: hash4, bytes: z8.number().int().nonnegative().max(ASSET_LIMIT) })),
- build: z8.object({
- engine: z8.string(),
- options: z8.record(z8.string(), z8.unknown()),
- warnings: z8.array(z8.string()),
- integration: z8.unknown().optional(),
- qa: z8.unknown().optional(),
- dependencies: z8.array(z8.unknown()).optional(),
- rebuild: z8.enum(["engine-required", "external-dependencies-required"])
+ editable: z9.boolean(),
+ files: z9.record(z9.string(), z9.object({ sha256: hash4, bytes: z9.number().int().nonnegative().max(ASSET_LIMIT) })),
+ build: z9.object({
+ engine: z9.string(),
+ options: z9.record(z9.string(), z9.unknown()),
+ warnings: z9.array(z9.string()),
+ integration: z9.unknown().optional(),
+ qa: z9.unknown().optional(),
+ dependencies: z9.array(z9.unknown()).optional(),
+ rebuild: z9.enum(["engine-required", "external-dependencies-required"])
}).optional(),
- preview: z8.object({
- fidelity: z8.unknown().optional(),
- error: z8.string().optional(),
- backdrop: z8.enum(BACKDROP_IDS).optional()
+ preview: z9.object({
+ fidelity: z9.unknown().optional(),
+ error: z9.string().optional(),
+ backdrop: z9.enum(BACKDROP_IDS).optional()
}).optional()
});
ASSET_MATERIAL_BYTES = 24 * 1024 * 1024;
@@ -40757,7 +41234,7 @@ import {
realpath as realpath5
} from "node:fs/promises";
import { join as join9, resolve as resolve8, relative as relative4, sep as sep3 } from "node:path";
-import { z as z9 } from "zod";
+import { z as z10 } from "zod";
function notify(run) {
try {
Promise.resolve(run()).catch(() => {});
@@ -41023,7 +41500,7 @@ class FileLiveReview {
throw new Error("Live lock generation exhausted");
if (latest) {
try {
- const prior = z9.object({ pid: z9.number().int().positive(), token: z9.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, latest), 1024))));
+ const prior = z10.object({ pid: z10.number().int().positive(), token: z10.string().uuid() }).strict().parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(directory, latest), 1024))));
const released = await lstat7(join9(directory, `${latest}.released`)).then((entry) => {
if (!entry.isFile() || entry.isSymbolicLink() || entry.size !== 0)
throw new Error("Invalid lock release");
@@ -41080,9 +41557,9 @@ class FileLiveReview {
const path = join9(this.directory, "limits.json");
try {
const value = JSON.parse(new TextDecoder().decode(await this.boundedFile(path, 1024)));
- const parsed = z9.object({
- maxOperations: z9.number().int().min(2).max(2000),
- maxBytes: z9.number().int().min(1024).max(1024 ** 3)
+ const parsed = z10.object({
+ maxOperations: z10.number().int().min(2).max(2000),
+ maxBytes: z10.number().int().min(1024).max(1024 ** 3)
}).strict().parse(value);
this.maxOperations = parsed.maxOperations;
this.maxBytes = parsed.maxBytes;
@@ -41406,7 +41883,7 @@ class FileLiveReview {
}
async health() {
try {
- return z9.array(z9.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(this.directory, "health.json"), 16384))));
+ return z10.array(z10.string().max(500)).max(20).parse(JSON.parse(new TextDecoder().decode(await this.boundedFile(join9(this.directory, "health.json"), 16384))));
} catch (error) {
if (missing2(error))
return [];
@@ -41544,41 +42021,41 @@ var init_live_review_node = __esm(() => {
filePattern2 = /^(asset\.glb|source\.kiln\.js|evaluation\.json|capture-\d{1,2}\.png)$/;
metadataLimit = 256 * 1024;
evaluationLimit = 2 * 1024 * 1024;
- descriptorSchema = z9.object({
- name: z9.string().regex(filePattern2),
- bytes: z9.number().int().nonnegative().max(ASSET_LIMIT),
- sha256: z9.string().regex(/^sha256:[a-f0-9]{64}$/),
- url: z9.string().max(200)
+ descriptorSchema = z10.object({
+ name: z10.string().regex(filePattern2),
+ bytes: z10.number().int().nonnegative().max(ASSET_LIMIT),
+ sha256: z10.string().regex(/^sha256:[a-f0-9]{64}$/),
+ url: z10.string().max(200)
}).strict();
- operationSchema = z9.object({
- version: z9.literal("kiln.live.v1"),
- operationId: z9.string().regex(operationPattern),
- revision: z9.number().int().nonnegative(),
- tool: z9.string().min(1).max(120),
- transport: z9.enum(["cli", "mcp", "native", "api"]),
- sessionId: z9.string().uuid(),
- workId: z9.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).optional(),
- startedAt: z9.string().datetime(),
- updatedAt: z9.string().datetime(),
- status: z9.enum(["running", "evaluated", "complete", "failed", "interrupted", "unknown"]),
- projectId: z9.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).optional(),
- projectRevision: z9.string().min(1).max(200).optional(),
- programRef: z9.string().min(1).max(200).optional(),
- runtimeIdentity: z9.string().min(1).max(200).optional(),
+ operationSchema = z10.object({
+ version: z10.literal("kiln.live.v1"),
+ operationId: z10.string().regex(operationPattern),
+ revision: z10.number().int().nonnegative(),
+ tool: z10.string().min(1).max(120),
+ transport: z10.enum(["cli", "mcp", "native", "api"]),
+ sessionId: z10.string().uuid(),
+ workId: z10.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).optional(),
+ startedAt: z10.string().datetime(),
+ updatedAt: z10.string().datetime(),
+ status: z10.enum(["running", "evaluated", "complete", "failed", "interrupted", "unknown"]),
+ projectId: z10.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).optional(),
+ projectRevision: z10.string().min(1).max(200).optional(),
+ programRef: z10.string().min(1).max(200).optional(),
+ runtimeIdentity: z10.string().min(1).max(200).optional(),
artifact: descriptorSchema.optional(),
- captures: z9.array(descriptorSchema).max(100),
- viewFidelity: z9.unknown().optional(),
- result: z9.record(z9.string(), z9.unknown()).optional(),
- error: z9.string().max(4000).optional(),
- pinned: z9.boolean(),
- phases: z9.array(z9.object({ phase: z9.string().max(100), at: z9.string().datetime() }).strict()).max(32),
- observationIssues: z9.array(z9.string().max(500)).max(20).optional()
+ captures: z10.array(descriptorSchema).max(100),
+ viewFidelity: z10.unknown().optional(),
+ result: z10.record(z10.string(), z10.unknown()).optional(),
+ error: z10.string().max(4000).optional(),
+ pinned: z10.boolean(),
+ phases: z10.array(z10.object({ phase: z10.string().max(100), at: z10.string().datetime() }).strict()).max(32),
+ observationIssues: z10.array(z10.string().max(500)).max(20).optional()
}).strict();
- stateSchema = z9.object({
+ stateSchema = z10.object({
operation: operationSchema,
- files: z9.record(z9.string(), descriptorSchema),
- ownerPid: z9.number().int().nonnegative().optional(),
- heartbeatAt: z9.string().datetime().optional()
+ files: z10.record(z10.string(), descriptorSchema),
+ ownerPid: z10.number().int().nonnegative().optional(),
+ heartbeatAt: z10.string().datetime().optional()
}).strict();
});
@@ -42813,7 +43290,7 @@ var init_asset_export = __esm(() => {
});
// src/project-bundle.ts
-import { z as z10 } from "zod";
+import { z as z11 } from "zod";
import { zipSync as zipSync2, unzipSync as unzipSync2 } from "three/addons/libs/fflate.module.js";
async function projectBundleHash(bytes) {
const result = new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));
@@ -43085,7 +43562,7 @@ async function decodeProjectBundle(bytes) {
throw new Error("Unreferenced files in project bundle");
return { manifest, project, materials, assets, runtimeAssets };
}
-var PROJECT_BUNDLE_LIMITS, hashSchema, id = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2, bytesOf2 = (value) => encoder3.encode(JSON.stringify(value)), assetPrefix = (entry) => `assets/${entry.collectionId}/${entry.assetId}/${entry.revisionId}/`, materialPrefix = (entry) => `materials/${entry.materialId}/${entry.revisionId.slice(7)}/`;
+var PROJECT_BUNDLE_LIMITS, hashSchema, id2 = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2, bytesOf2 = (value) => encoder3.encode(JSON.stringify(value)), assetPrefix = (entry) => `assets/${entry.collectionId}/${entry.assetId}/${entry.revisionId}/`, materialPrefix = (entry) => `materials/${entry.materialId}/${entry.revisionId.slice(7)}/`;
var init_project_bundle = __esm(() => {
init_assets();
init_asset_export();
@@ -43097,33 +43574,33 @@ var init_project_bundle = __esm(() => {
maxEntries: 8192,
maxManifestBytes: 2 * 1024 * 1024
});
- hashSchema = z10.string().regex(/^sha256:[a-f0-9]{64}$/);
- pathSchema = z10.string().regex(new RegExp(`^(project\\.json|materials/${id}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id}/${id}/${id}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
- identitySchema = z10.object({
+ hashSchema = z11.string().regex(/^sha256:[a-f0-9]{64}$/);
+ pathSchema = z11.string().regex(new RegExp(`^(project\\.json|materials/${id2}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id2}/${id2}/${id2}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
+ identitySchema = z11.object({
inventoryId: assetIdSchema,
collectionId: assetIdSchema,
assetId: assetIdSchema,
revisionId: assetIdSchema,
canonicalGlbSha256: hashSchema
}).strict();
- projectBundleManifestSchema = z10.object({
- version: z10.literal("kiln.project-bundle.v1"),
- profile: z10.enum(["editable", "runtime"]),
- editable: z10.boolean(),
- resourceClosure: z10.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
- referenceMediaIncluded: z10.literal(false),
- originalAcquisitionFilesIncluded: z10.literal(false),
- assets: z10.array(identitySchema).max(1000),
- materials: z10.array(z10.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
- files: z10.record(pathSchema, z10.object({
+ projectBundleManifestSchema = z11.object({
+ version: z11.literal("kiln.project-bundle.v1"),
+ profile: z11.enum(["editable", "runtime"]),
+ editable: z11.boolean(),
+ resourceClosure: z11.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
+ referenceMediaIncluded: z11.literal(false),
+ originalAcquisitionFilesIncluded: z11.literal(false),
+ assets: z11.array(identitySchema).max(1000),
+ materials: z11.array(z11.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
+ files: z11.record(pathSchema, z11.object({
sha256: hashSchema,
- bytes: z10.number().int().nonnegative().max(64 * 1024 * 1024)
+ bytes: z11.number().int().nonnegative().max(64 * 1024 * 1024)
}).strict())
}).strict();
projectBundleManifestV2Schema = projectBundleManifestSchema.extend({
- version: z10.literal("kiln.project-bundle.v2")
+ version: z11.literal("kiln.project-bundle.v2")
});
- projectBundleManifestAnySchema = z10.union([
+ projectBundleManifestAnySchema = z11.union([
projectBundleManifestSchema,
projectBundleManifestV2Schema
]);
@@ -43661,7 +44138,7 @@ var init_requirements_assets = __esm(() => {
});
// src/tools/review-detail.ts
-import { z as z11 } from "zod";
+import { z as z12 } from "zod";
function requestedDetail(input, fallback = "compact") {
const detail = input?.detail;
return detail === "full" || detail === "lean" || detail === "compact" ? detail : fallback;
@@ -44183,7 +44660,7 @@ function compactEditResult(result, detail = "compact", options = {}) {
}
var COMPACT_PART_PREVIEW = 24, COMPACT_FINDINGS_PER_DIMENSION = 12, LEAD_BLOCKERS = 8, LEAN_WARNINGS = 3, COMPACT_WARNINGS = 12, WARNING_CHARS = 1000, DEFAULT_RESULT_LIMIT = 20000, MAX_RESULT_LIMIT = 40000, COMPACT_DECIMALS = 6, reviewDetailInput, partsHint = (offset) => `For remaining paths use kiln_inspect with image:false and listParts:{offset:${offset}}. listParts.query filters names/paths; follow partListing.nextOffset on the same programRef and query.`, isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value), SEVERITY, severity = (finding) => isRecord7(finding) && typeof finding.disposition === "string" && SEVERITY[finding.disposition] || (isRecord7(finding) && finding.disposition === "block" ? 0 : 3), RECEIPT_IDENTITY, poseFramesHint = (retained) => retained ? `Every frame: read ${retained.path} (pretty-printed), or ask fewer frameTimes or measureParts per call.` : "Every frame: detail: 'full' (inside the 40,000-character limit), or fewer frameTimes or measureParts per call.", LEAN_KEYS, LEAN_DIFF = 2000, COMPACT_COMPARISON_CHANGES = 12, COMPARE_HINT = "Bounds per change and the comparison scope: detail: 'full'. compare.offset pages the changes.";
var init_review_detail = __esm(() => {
- reviewDetailInput = z11.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
+ reviewDetailInput = z12.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
SEVERITY = { block: 0, warn: 1, observe: 2 };
RECEIPT_IDENTITY = new Set([
"version",
@@ -44224,19 +44701,19 @@ var init_review_detail = __esm(() => {
});
// src/tools/programs.ts
-import { z as z12 } from "zod";
+import { z as z13 } from "zod";
function withProgramReferences(def, store, readSourceFile) {
- if (!(def.inputSchema instanceof z12.ZodObject))
+ if (!(def.inputSchema instanceof z13.ZodObject))
throw new Error(`${def.name} must have an object input schema.`);
const sources = readSourceFile ? "code, programRef OR file" : "code OR programRef";
const inputSchema = def.inputSchema.extend({
- code: z12.string().optional().describe("New source."),
+ code: z13.string().optional().describe("New source."),
programRef: refInput.optional(),
...readSourceFile ? {
- file: z12.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
+ file: z13.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
} : {},
...def.name === "kiln_edit" ? {
- includeCode: z12.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
+ includeCode: z13.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
} : {}
}).refine((input) => [input.code, input.programRef, input.file].filter((value) => value !== undefined).length === 1, { message: `Supply exactly one of ${sources.replace(" OR ", " or ")}.` });
const summaries = {
@@ -44289,11 +44766,11 @@ function boundIncludedCode(result, limit) {
};
}
function createKilnSourceDef(store) {
- const inputSchema = z12.object({
+ const inputSchema = z13.object({
programRef: refInput,
- offset: z12.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
- limit: z12.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
- query: z12.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
+ offset: z13.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
+ limit: z13.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
+ query: z13.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
});
return {
name: "kiln_source",
@@ -44322,7 +44799,7 @@ var refInput;
var init_programs = __esm(() => {
init_program_store();
init_review_detail();
- refInput = z12.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
+ refInput = z13.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
});
// src/tools/program-artifacts.ts
@@ -44341,9 +44818,9 @@ var init_engine_identity = __esm(() => {
});
// src/discovery/catalog-schema.ts
-import { z as z13 } from "zod";
+import { z as z14 } from "zod";
function parseCatalog(value) {
- const entries = z13.array(discoveryEntrySchema).parse(value);
+ const entries = z14.array(discoveryEntrySchema).parse(value);
const ids = new Set;
const names = new Set;
for (const entry of entries) {
@@ -44368,35 +44845,35 @@ function parseCatalog(value) {
}
return entries;
}
-var text6, texts, id2, common, operationContractSchema, discoveryEntrySchema;
+var text6, texts, id3, common, operationContractSchema, discoveryEntrySchema;
var init_catalog_schema = __esm(() => {
- text6 = z13.string().trim().min(1);
- texts = z13.array(text6);
- id2 = z13.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
+ text6 = z14.string().trim().min(1);
+ texts = z14.array(text6);
+ id3 = z14.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
common = {
- version: z13.literal("kiln.catalog-entry.v1"),
- id: id2,
+ version: z14.literal("kiln.catalog-entry.v1"),
+ id: id3,
name: text6,
summary: text6.max(500),
family: text6.max(80),
tags: texts,
aliases: texts,
intents: texts,
- stability: z13.enum(["stable", "experimental", "deprecated"]),
- related: z13.array(z13.object({
- id: id2,
- relation: z13.enum(["alternative", "prerequisite", "companion"])
+ stability: z14.enum(["stable", "experimental", "deprecated"]),
+ related: z14.array(z14.object({
+ id: id3,
+ relation: z14.enum(["alternative", "prerequisite", "companion"])
}).strict()),
references: texts,
limitations: texts
};
- operationContractSchema = z13.object({
+ operationContractSchema = z14.object({
signature: text6,
returns: text6,
units: text6,
axes: text6,
origin: text6,
- execution: z13.enum(["sync", "async"]),
+ execution: z14.enum(["sync", "async"]),
ownership: text6,
coordinates: text6,
parameters: texts,
@@ -44406,24 +44883,24 @@ var init_catalog_schema = __esm(() => {
cost: text6,
example: text6
}).strict();
- discoveryEntrySchema = z13.discriminatedUnion("kind", [
- z13.object({ ...common, kind: z13.literal("operation"), contract: operationContractSchema }).strict(),
- z13.object({ ...common, kind: z13.literal("assembly"), contract: operationContractSchema }).strict(),
- z13.object({
+ discoveryEntrySchema = z14.discriminatedUnion("kind", [
+ z14.object({ ...common, kind: z14.literal("operation"), contract: operationContractSchema }).strict(),
+ z14.object({ ...common, kind: z14.literal("assembly"), contract: operationContractSchema }).strict(),
+ z14.object({
...common,
- kind: z13.literal("recipe"),
- recipe: z13.object({
- prerequisites: z13.array(id2),
+ kind: z14.literal("recipe"),
+ recipe: z14.object({
+ prerequisites: z14.array(id3),
steps: texts.min(1),
example: text6,
adaptations: texts,
checks: texts
}).strict()
}).strict(),
- z13.object({
+ z14.object({
...common,
- kind: z13.literal("shape"),
- shape: z13.object({ tool: text6, field: text6, schema: z13.record(z13.string(), z13.unknown()) }).strict()
+ kind: z14.literal("shape"),
+ shape: z14.object({ tool: text6, field: text6, schema: z14.record(z14.string(), z14.unknown()) }).strict()
}).strict()
]).superRefine((entry, ctx) => {
if (!entry.id.startsWith(`${entry.kind}:`)) {
@@ -48025,7 +48502,7 @@ async function build() {
});
// src/tools/capture-input.ts
-import { z as z14 } from "zod";
+import { z as z15 } from "zod";
function taggedCaptureError(issue) {
const input = issue.input;
if (typeof input !== "object" || input === null || !("version" in input) || input.version !== "kiln.capture.v1" && input.version !== "kiln.capture.v2")
@@ -48056,60 +48533,60 @@ var backdropInput, legacyCaptureInput, cameraVec3Input, orbitCameraError = (issu
var init_capture_input = __esm(() => {
init_background();
init_capture_limits();
- backdropInput = z14.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
- legacyCaptureInput = z14.object({
- preset: z14.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
- cells: z14.array(z14.object({
- azimuthDeg: z14.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
- elevationDeg: z14.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
- zoom: z14.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
- name: z14.string().optional().describe("Label; defaults to angles.")
+ backdropInput = z15.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
+ legacyCaptureInput = z15.object({
+ preset: z15.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
+ cells: z15.array(z15.object({
+ azimuthDeg: z15.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
+ elevationDeg: z15.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
+ zoom: z15.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
+ name: z15.string().optional().describe("Label; defaults to angles.")
})).optional().describe("Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9)."),
backdrop: backdropInput
}).optional().describe("Sheet layout and cameras; omit for six views in a 3x2 grid.");
- cameraVec3Input = z14.array(z14.number()).length(3);
- cameraShotInput = z14.object({
- name: z14.string().optional(),
- subject: z14.object({ path: z14.string().optional(), name: z14.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
+ cameraVec3Input = z15.array(z15.number()).length(3);
+ cameraShotInput = z15.object({
+ name: z15.string().optional(),
+ subject: z15.object({ path: z15.string().optional(), name: z15.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
message: "Choose subject path OR exact name."
}).optional(),
- visibility: z14.enum(["context", "isolate"]).optional(),
- hide: z14.array(z14.string().min(1).max(1024)).max(64).optional(),
- camera: z14.discriminatedUnion("type", [
- z14.strictObject({
- type: z14.literal("orbit"),
- azimuthDeg: z14.number().optional(),
- elevationDeg: z14.number().optional(),
- relativeTo: z14.enum(["world", "asset", "part"]).optional(),
- padding: z14.number().positive().max(100).optional()
+ visibility: z15.enum(["context", "isolate"]).optional(),
+ hide: z15.array(z15.string().min(1).max(1024)).max(64).optional(),
+ camera: z15.discriminatedUnion("type", [
+ z15.strictObject({
+ type: z15.literal("orbit"),
+ azimuthDeg: z15.number().optional(),
+ elevationDeg: z15.number().optional(),
+ relativeTo: z15.enum(["world", "asset", "part"]).optional(),
+ padding: z15.number().positive().max(100).optional()
}, { error: orbitCameraError }),
- z14.strictObject({
- type: z14.literal("explicit"),
- projection: z14.enum(["orthographic", "perspective"]),
+ z15.strictObject({
+ type: z15.literal("explicit"),
+ projection: z15.enum(["orthographic", "perspective"]),
position: cameraVec3Input,
target: cameraVec3Input.optional(),
- relativeTo: z14.enum(["world", "asset", "part", "local"]).optional(),
- frame: z14.object({
+ relativeTo: z15.enum(["world", "asset", "part", "local"]).optional(),
+ frame: z15.object({
origin: cameraVec3Input.optional(),
rotation: cameraVec3Input.optional()
}).strict().optional(),
- framing: z14.enum(["explicit", "bounds"]).optional(),
- padding: z14.number().positive().max(100).optional(),
+ framing: z15.enum(["explicit", "bounds"]).optional(),
+ padding: z15.number().positive().max(100).optional(),
targetOffset: cameraVec3Input.optional(),
up: cameraVec3Input.optional(),
- halfHeight: z14.number().positive().optional(),
- fovDeg: z14.number().positive().lt(180).optional(),
- near: z14.number().positive().optional(),
- far: z14.number().positive().optional()
+ halfHeight: z15.number().positive().optional(),
+ fovDeg: z15.number().positive().lt(180).optional(),
+ near: z15.number().positive().optional(),
+ far: z15.number().positive().optional()
}, { error: explicitCameraError })
]).optional()
}).strict();
- advancedCaptureInput = z14.strictObject({
- version: z14.enum(["kiln.capture.v1", "kiln.capture.v2"]),
- shots: z14.array(cameraShotInput).min(1).max(9),
- cols: z14.number().int().min(1).max(3).optional(),
- size: z14.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
- output: z14.enum(["grid", "separate"]).optional(),
+ advancedCaptureInput = z15.strictObject({
+ version: z15.enum(["kiln.capture.v1", "kiln.capture.v2"]),
+ shots: z15.array(cameraShotInput).min(1).max(9),
+ cols: z15.number().int().min(1).max(3).optional(),
+ size: z15.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
+ output: z15.enum(["grid", "separate"]).optional(),
backdrop: backdropInput
}, { error: advancedCaptureError }).superRefine((input, context) => {
if (input.version === "kiln.capture.v1" && input.shots.some((shot) => shot.hide !== undefined))
@@ -48119,21 +48596,21 @@ var init_capture_input = __esm(() => {
message: "shot.hide requires version kiln.capture.v2"
});
});
- captureShapeInput = z14.union([
+ captureShapeInput = z15.union([
advancedCaptureInput,
- z14.strictObject(legacyCaptureInput.unwrap().shape, {
+ z15.strictObject(legacyCaptureInput.unwrap().shape, {
error: taggedCaptureError
})
], { error: taggedCaptureError });
captureInput = captureShapeInput.optional().describe("Omit for six views; preset/cells for orbit sheets. Use kiln.capture.v1 or v2 with 1..9 shots for exact cameras. v2 adds hide: exact paths or unique names. Framing retains subject bounds.");
- captureRecordInput = z14.record(z14.string(), z14.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
- cameraShotRecordInput = z14.record(z14.string(), z14.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
+ captureRecordInput = z15.record(z15.string(), z15.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
+ cameraShotRecordInput = z15.record(z15.string(), z15.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
});
// src/discovery/shapes.ts
-import { z as z15 } from "zod";
+import { z as z16 } from "zod";
var jsonSchema = (schema) => {
- const { $schema: _dialect, ...rest } = z15.toJSONSchema(schema, { io: "input", reused: "ref" });
+ const { $schema: _dialect, ...rest } = z16.toJSONSchema(schema, { io: "input", reused: "ref" });
return rest;
}, shape2 = (name, tool, field, summary, schema, extra = {}) => ({
version: "kiln.catalog-entry.v1",
@@ -48347,7 +48824,7 @@ var init_lexical_index = __esm(() => {
});
// src/discovery/query-schema.ts
-import { z as z16 } from "zod";
+import { z as z17 } from "zod";
function discoverySelectorMigration(keys) {
if (!keys.some((key) => ["category", "name", "names"].includes(key)))
return;
@@ -48369,19 +48846,19 @@ function parseDiscoveryRequest(value) {
}
var selector, discoveryInputSchema;
var init_query_schema = __esm(() => {
- selector = z16.string().trim().min(1).max(120);
- discoveryInputSchema = z16.object({
- query: z16.string().trim().min(1).max(500).optional(),
- ids: z16.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
+ selector = z17.string().trim().min(1).max(120);
+ discoveryInputSchema = z17.object({
+ query: z17.string().trim().min(1).max(500).optional(),
+ ids: z17.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
message: "Exact IDs must be unique."
}).optional(),
- overview: z16.literal(true).optional(),
- capabilities: z16.literal(true).optional(),
+ overview: z17.literal(true).optional(),
+ capabilities: z17.literal(true).optional(),
family: selector.optional(),
- kind: z16.enum(["operation", "assembly", "recipe", "shape"]).optional(),
- tags: z16.array(selector).min(1).max(8).optional(),
- offset: z16.number().int().min(0).max(1e4).optional(),
- limit: z16.number().int().min(1).max(12).optional()
+ kind: z17.enum(["operation", "assembly", "recipe", "shape"]).optional(),
+ tags: z17.array(selector).min(1).max(8).optional(),
+ offset: z17.number().int().min(0).max(1e4).optional(),
+ limit: z17.number().int().min(1).max(12).optional()
}, {
error: (issue) => issue.code === "unrecognized_keys" ? discoverySelectorMigration(issue.keys) : undefined
}).strict().superRefine((input, context) => {
@@ -48661,6 +49138,15 @@ Suggestions: ${structured.suggestions.join(", ")}` : text;
function configuredProject(context) {
return context.workspace?.configured?.() ?? null;
}
+function hostRequirements(context) {
+ const active = resolveRequirementsContext(context.requirements);
+ const validation = active.requirements.requirements.validation;
+ return {
+ bound: active.binding !== undefined,
+ policyHash: active.policyHash,
+ declared: validation?.state === "requested" ? { source: "host-binding", validationProfile: validation.value } : null
+ };
+}
function projectNotes(context) {
const projectId = configuredProject(context);
return projectId ? [
@@ -48702,6 +49188,7 @@ async function currentCapabilities(context, presentation) {
read: 'kiln_project { action: "get", projectId } returns the brief, design, inventory and material pins'
},
renderer,
+ requirements: hostRequirements(context),
execution: context.localExecution ?? (context.evaluatorPort ? { mode: "host-injected", limits: "unspecified by host" } : context.evaluatorProfile === "evaluator-required" ? { mode: "host-required", available: false } : { mode: "trusted-local", terminable: false }),
source: {
...context.programStore?.stats ? { storage: await context.programStore.stats() } : {},
@@ -48774,6 +49261,7 @@ var init_discovery2 = __esm(() => {
init_geometry_export();
init_community_exporter();
init_material_resources();
+ init_requirements_context();
});
// src/tools/actions.ts
@@ -48820,16 +49308,16 @@ function flattenIssuePaths(issues, prefix = []) {
var list = (fields) => fields.length <= 1 ? fields.join("") : `${fields.slice(0, -1).join(", ")} and ${fields.at(-1)}`, nestedRecordDescription = (purpose, shape) => `${purpose} Shape: kiln_discover({ ids: ['${shape}'] }).`, BARE_REFINE_MESSAGE = "Invalid input";
// src/tools/projects.ts
-import { z as z17 } from "zod";
+import { z as z18 } from "zod";
function projectToolInput(actions = PROJECT_ACTIONS) {
- return z17.strictObject({
- action: z17.enum(actions),
+ return z18.strictObject({
+ action: z18.enum(actions),
projectId: projectIdSchema.optional().describe("get, update, export."),
revisionId: projectRevisionIdSchema.optional().describe("get, export: an exact revision; omit for the current one."),
expectedRevision: projectRevisionIdSchema.optional().describe("update: the revision being replaced; a stale value is a conflict."),
draft: record10(nestedRecordDescription("create: name, brief, design, inventory, deliveryProfiles, materialDependencies, references, reviews; optional projectId.", "shape:project-draft")),
patch: record10(nestedRecordDescription("update: the same top-level fields as draft; each supplied field replaces its previous value whole.", "shape:project-patch")),
- profile: z17.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
+ profile: z18.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
});
}
function createKilnProjectDef(store, bundleReader) {
@@ -48890,7 +49378,7 @@ function createKilnProjectDef(store, bundleReader) {
}
}
}
-var PROJECT_ACTIONS, REQUIREMENTS, record10 = (description) => z17.record(z17.string(), z17.unknown()).optional().describe(description);
+var PROJECT_ACTIONS, REQUIREMENTS, record10 = (description) => z18.record(z18.string(), z18.unknown()).optional().describe(description);
var init_projects2 = __esm(() => {
init_projects();
PROJECT_ACTIONS = ["list", "get", "create", "update", "export"];
@@ -48973,7 +49461,7 @@ var init_material_authoring_node = __esm(() => {
});
// src/material-presets.ts
-import { z as z18 } from "zod";
+import { z as z19 } from "zod";
function listMaterialPresets() {
return catalog2.map((item) => ({
...item,
@@ -49312,17 +49800,17 @@ var init_material_presets = __esm(() => {
}
];
RECORD_V2_PRESETS = new Set(["palm-frond"]);
- materialPresetOptionsSchema = z18.object({
- seed: z18.number().int().min(-2147483648).max(2147483647),
- size: z18.union([z18.literal(64), z18.literal(128), z18.literal(256), z18.literal(512)]).default(256),
- creator: z18.string().min(1).max(1000),
+ materialPresetOptionsSchema = z19.object({
+ seed: z19.number().int().min(-2147483648).max(2147483647),
+ size: z19.union([z19.literal(64), z19.literal(128), z19.literal(256), z19.literal(512)]).default(256),
+ creator: z19.string().min(1).max(1000),
license: materialSourceSchema.shape.license,
materialId: materialLibraryIdSchema.optional()
}).strict();
});
// src/tools/materials.ts
-import { z as z19 } from "zod";
+import { z as z20 } from "zod";
async function onlyRevision(library, materialId, listCall) {
const revisions = (await library.list()).filter((material) => material.materialId === materialId).map((material) => material.revisionId).sort();
if (revisions.length === 1)
@@ -49423,7 +49911,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {
}
};
}
-var MATERIAL_ACTIONS, MATERIAL_CONTRACT, record11 = (description) => z19.record(z19.string(), z19.unknown()).optional().describe(description), tag, materialToolInput, materialResult = (material) => ({
+var MATERIAL_ACTIONS, MATERIAL_CONTRACT, record11 = (description) => z20.record(z20.string(), z20.unknown()).optional().describe(description), tag, materialToolInput, materialResult = (material) => ({
ok: true,
material,
portableSpec: materialLibraryPortableSpec(material)
@@ -49475,14 +49963,14 @@ var init_materials = __esm(() => {
description: "Import complete normalized material records and embedded PNGs. Does not fetch URLs or execute source."
}
};
- tag = z19.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
- materialToolInput = z19.strictObject({
- action: z19.enum(MATERIAL_ACTIONS),
+ tag = z20.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
+ materialToolInput = z20.strictObject({
+ action: z20.enum(MATERIAL_ACTIONS),
tag,
- presetId: z19.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
- seed: z19.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
- size: z19.union([z19.literal(64), z19.literal(128), z19.literal(256), z19.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
- creator: z19.string().min(1).max(1000).optional().describe("create-preset."),
+ presetId: z20.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
+ seed: z20.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
+ size: z20.union([z20.literal(64), z20.literal(128), z20.literal(256), z20.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
+ creator: z20.string().min(1).max(1000).optional().describe("create-preset."),
license: materialSourceSchema.shape.license.optional().describe("create-preset: spdx, url and attribution."),
materialId: materialLibraryIdSchema.optional().describe("get: the id a project palette lists as resourceId; create-preset: optional id."),
revisionId: materialLibraryHashSchema.optional().describe("get: the immutable revision; omitted, the material's only revision."),
@@ -49508,7 +49996,7 @@ async function persistedPreviewFidelity(fidelity, glb) {
}
// src/tools/review.ts
-import { z as z20 } from "zod";
+import { z as z21 } from "zod";
function summarizeOperation(operation) {
const fidelity = operation.viewFidelity && typeof operation.viewFidelity === "object" ? operation.viewFidelity : undefined;
return {
@@ -49641,7 +50129,7 @@ function createKilnReviewDef(context) {
}))
];
const preview = operation.captures[0] ? await store.readFile(operation.operationId, operation.captures[0].name) : undefined;
- const capture = z20.object({ backdrop: z20.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
+ const capture = z21.object({ backdrop: z21.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
const asset = await context.assetLibrary.save(collection, {
name: input.name,
assetId: input.assetId,
@@ -49684,8 +50172,8 @@ var init_review = __esm(() => {
init_program_store();
init_background();
init_review_detail();
- operationId = z20.string().regex(/^op_[a-f0-9-]{36}$/);
- assetId = z20.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ operationId = z21.string().regex(/^op_[a-f0-9-]{36}$/);
+ assetId = z21.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
REVIEW_ACTIONS = ["list", "get", "pin", "save"];
REQUIREMENTS2 = {
list: { required: [] },
@@ -49693,25 +50181,25 @@ var init_review = __esm(() => {
pin: { required: ["operationId", "pinned"] },
save: { required: ["operationId", "expectedRevision", "name"] }
};
- reviewToolInput = z20.strictObject({
- action: z20.enum(REVIEW_ACTIONS),
+ reviewToolInput = z21.strictObject({
+ action: z21.enum(REVIEW_ACTIONS),
projectId: assetId.optional().describe("list: only operations bound to this project."),
- offset: z20.number().int().min(0).optional().describe("list: page start; default 0."),
- limit: z20.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
+ offset: z21.number().int().min(0).optional().describe("list: page start; default 0."),
+ limit: z21.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
operationId: operationId.optional().describe("get, pin, save."),
- pinned: z20.boolean().optional().describe("pin: true keeps the operation past normal retention."),
- expectedRevision: z20.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
+ pinned: z21.boolean().optional().describe("pin: true keeps the operation past normal retention."),
+ expectedRevision: z21.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
collection: assetId.optional().describe("save: destination collection; default project."),
- name: z20.string().min(1).max(200).optional().describe("save."),
+ name: z21.string().min(1).max(200).optional().describe("save."),
assetId: assetId.optional().describe("save: revise this asset."),
parentRevision: assetId.optional().describe("save: the revision being revised."),
- description: z20.string().max(4000).optional().describe("save."),
- tags: z20.array(z20.string().max(80)).max(30).optional().describe("save.")
+ description: z21.string().max(4000).optional().describe("save."),
+ tags: z21.array(z21.string().max(80)).max(30).optional().describe("save.")
});
});
// src/tools/workspace.ts
-import { z as z21 } from "zod";
+import { z as z22 } from "zod";
async function observeLiveReview(observer, tool, input, run) {
let authoring;
const invokeOnce = () => authoring ??= Promise.resolve().then(run);
@@ -49751,7 +50239,7 @@ async function observeWorkspaceOperation(context, tool, input, run) {
function withWorkspaceContext(def, context) {
if (!observed.has(def.name))
return def;
- const schema = context.workspace && def.inputSchema instanceof z21.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
+ const schema = context.workspace && def.inputSchema instanceof z22.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
return {
...def,
inputSchema: schema,
@@ -49779,11 +50267,11 @@ var init_workspace2 = __esm(() => {
});
// src/tools/operation-contract.ts
-import { z as z22 } from "zod";
+import { z as z23 } from "zod";
var init_operation_contract = () => {};
// src/tools/operations.ts
-import { z as z23 } from "zod";
+import { z as z24 } from "zod";
var init_operations = __esm(() => {
init_operation_contract();
});
@@ -50278,10 +50766,10 @@ function createPartPlacementReader(root) {
};
};
}
-var round2 = (value) => {
+var round3 = (value) => {
const rounded = Math.round(value * 1e6) / 1e6;
return rounded === 0 ? 0 : rounded;
-}, rounded2 = (values) => values.map(round2);
+}, rounded2 = (values) => values.map(round3);
var init_part_placement = __esm(() => {
init_raster();
});
@@ -51438,7 +51926,7 @@ var init_asset_widget = __esm(() => {
});
// src/tools/registry.ts
-import { z as z24 } from "zod";
+import { z as z25 } from "zod";
import * as THREE58 from "three";
function proceduralTextureMaterialContract(rendered, context) {
const required = [...new Set(context.requiredProceduralTextureUsages ?? [])];
@@ -52691,36 +53179,36 @@ function createKilnAssetDefs(context, presentation = "grouped") {
resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset),
downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId)
});
- const saveInput = z24.object({
+ const saveInput = z25.object({
collection: selector.collection,
- programRef: z24.string(),
- name: z24.string().min(1).max(200),
+ programRef: z25.string(),
+ name: z25.string().min(1).max(200),
assetId: selector.assetId.optional(),
parentRevision: selector.revisionId.optional(),
- tags: z24.array(z24.string().max(80)).max(30).optional(),
- brief: z24.string().max(8000).optional(),
- description: z24.string().max(4000).optional(),
- attribution: z24.object({
- model: z24.string().max(200).optional(),
- harness: z24.string().max(200).optional(),
- author: z24.string().max(200).optional()
+ tags: z25.array(z25.string().max(80)).max(30).optional(),
+ brief: z25.string().max(8000).optional(),
+ description: z25.string().max(4000).optional(),
+ attribution: z25.object({
+ model: z25.string().max(200).optional(),
+ harness: z25.string().max(200).optional(),
+ author: z25.string().max(200).optional()
}).optional(),
- backdrop: z24.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
+ backdrop: z25.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
});
- const assetsInput = z24.object({
- action: z24.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
+ const assetsInput = z25.object({
+ action: z25.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
collection: selector.collection,
assetId: selector.assetId.optional(),
revisionId: selector.revisionId.optional().describe("get, restore: the saved revision; omitted, the newest."),
- query: z24.string().max(200).optional(),
- offset: z24.number().int().min(0).default(0),
- limit: z24.number().int().min(1).max(50).default(20)
+ query: z25.string().max(200).optional(),
+ offset: z25.number().int().min(0).default(0),
+ limit: z25.number().int().min(1).max(50).default(20)
});
- const exportInput = z24.object(selector);
+ const exportInput = z25.object(selector);
const profileExportInput = exportInput.extend({
- profile: z24.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
+ profile: z25.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
});
- const importInput = z24.object({
+ const importInput = z25.object({
...selector,
sourceCollection: selector.collection
});
@@ -52821,9 +53309,9 @@ function createKilnAssetDefs(context, presentation = "grouped") {
name: "kiln_present",
description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",
inputSchema: exportInput,
- outputSchema: z24.object({
- ok: z24.literal(true),
- collection: z24.string(),
+ outputSchema: z25.object({
+ ok: z25.literal(true),
+ collection: z25.string(),
asset: assetManifestSchema.pick({
assetId: true,
revisionId: true,
@@ -52834,25 +53322,25 @@ function createKilnAssetDefs(context, presentation = "grouped") {
editable: true,
files: true
}).extend({
- build: z24.object({
- engine: z24.string(),
- rebuild: z24.enum(["engine-required", "external-dependencies-required"]),
- warningCount: z24.number().int(),
- warnings: z24.array(z24.string())
+ build: z25.object({
+ engine: z25.string(),
+ rebuild: z25.enum(["engine-required", "external-dependencies-required"]),
+ warningCount: z25.number().int(),
+ warnings: z25.array(z25.string())
}).optional()
}),
- resources: z24.array(z24.object({
- type: z24.literal("resource_link"),
- name: z24.string(),
- uri: z24.string(),
- mimeType: z24.string(),
- size: z24.number().int().nonnegative(),
- annotations: z24.object({
- audience: z24.array(z24.enum(["user", "assistant"])),
- priority: z24.number()
+ resources: z25.array(z25.object({
+ type: z25.literal("resource_link"),
+ name: z25.string(),
+ uri: z25.string(),
+ mimeType: z25.string(),
+ size: z25.number().int().nonnegative(),
+ annotations: z25.object({
+ audience: z25.array(z25.enum(["user", "assistant"])),
+ priority: z25.number()
})
})),
- downloadUrls: z24.record(z24.string(), z24.string()).optional()
+ downloadUrls: z25.record(z25.string(), z25.string()).optional()
}),
ui: {
resourceUri: KILN_ASSET_WIDGET_URI,
@@ -52947,41 +53435,41 @@ var init_registry2 = __esm(() => {
init_evidence_history();
init_background();
viewEvidenceHistoryByContext = new WeakMap;
- validateInput = z24.object({
- code: z24.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
+ validateInput = z25.object({
+ code: z25.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
});
- renderInput = z24.object({
- code: z24.string().describe("Kiln source code to execute and render to an in-memory GLB.")
+ renderInput = z25.object({
+ code: z25.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
renderViewsInput = renderInput.extend({ capture: captureInput, detail: reviewDetailInput });
renderViewsBufferInput = renderViewsInput.omit({ code: true });
- screenshotAnimationInput = z24.object({
+ screenshotAnimationInput = z25.object({
shot: cameraShotInput.optional(),
- measureParts: z24.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
- frames: z24.number().int().min(2).max(6).optional(),
- frameTimes: z24.array(z24.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
- framing: z24.enum(["locked", "follow"]).optional(),
- size: z24.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
+ measureParts: z25.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
+ frames: z25.number().int().min(2).max(6).optional(),
+ frameTimes: z25.array(z25.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
+ framing: z25.enum(["locked", "follow"]).optional(),
+ size: z25.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
detail: reviewDetailInput,
- code: z24.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
- clip: z24.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
- camera: z24.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
- perFrame: z24.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
+ code: z25.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
+ clip: z25.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
+ camera: z25.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
+ perFrame: z25.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
});
screenshotAnimationAdvertisedInput = screenshotAnimationInput.extend({
shot: cameraShotRecordInput
});
- viewInteriorInput = z24.object({
+ viewInteriorInput = z25.object({
capture: advancedCaptureInput.optional(),
- code: z24.string().describe("Kiln source code to execute and render with the roof hidden."),
- nodeName: z24.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
+ code: z25.string().describe("Kiln source code to execute and render with the roof hidden."),
+ nodeName: z25.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
});
viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureRecordInput });
- partListInput = z24.object({
- query: z24.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
- offset: z24.number().int().min(0).optional(),
- limit: z24.number().int().min(1).max(100).optional(),
- placement: z24.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
+ partListInput = z25.object({
+ query: z25.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
+ offset: z25.number().int().min(0).optional(),
+ limit: z25.number().int().min(1).max(100).optional(),
+ placement: z25.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
}).strict();
KILN_RENDER_VIEWS_DESCRIPTION = "Build the current asset and return geometry metrics, exact part paths and images. Omit capture for six orthographic views. Choose preset/cells for a smaller orbit sheet, or version kiln.capture.v1 with shots for per-part framing, local axes, perspective and separate images. +X is forward, +Y up, +Z right. Review silhouette, attachments, proportion and ground contact. GPU PBR shading supports textured or metallic materials; a flat-shaded CPU render supports geometry review. Read viewFidelity; do not judge material fidelity from CPU views. Failed builds return errors without images." + VIEW_EVIDENCE_GUIDANCE;
kilnRenderViewsDef = createKilnRenderViewsDef();
@@ -52989,49 +53477,49 @@ var init_registry2 = __esm(() => {
kilnScreenshotAnimationDef = createKilnScreenshotAnimationDef();
KILN_VIEW_INTERIOR_DESCRIPTION = "SEE INSIDE an enterable building: renders it with the roof lifted off, as a " + "three-view grid. (1) Floor plan: top-down — check the interior is open and walkable and the footprint " + "is right. (2) Dollhouse: a 3/4 cutaway — check built-in fixtures (hearth, counter, shelves) rest ON the " + "floor, not floating or sunk, and the walls enclose a real volume with headroom. (3) Eye-level: a low " + "angle looking in through the doorway with the near walls also removed — confirm the doorway is a REAL " + "gap you could walk through (not a panel) and no wall or glass is buried inside a solid mass. Call this before finalizing any building. Take no argument: the roof is found from its semantic role, so any roof built with createRoofPlanes/createGableRoof lifts whatever it is named. If " + "roofsHidden comes back 0 no roof was resolvable and the interior stays hidden — build the roof " + 'with a roof primitive (or name the group "Roof"). Each cell is rendered from deterministic cutaway GLB bytes: GPU PBR when available, otherwise a GLB-native geometry-flat fallback. Read viewFidelity before judging materials; writes no files.' + VIEW_EVIDENCE_GUIDANCE;
kilnViewInteriorDef = createKilnViewInteriorDef();
- attachmentEndpointInput = z24.object({
- subject: z24.object({ path: z24.string().optional(), name: z24.string().optional() }).strict(),
+ attachmentEndpointInput = z25.object({
+ subject: z25.object({ path: z25.string().optional(), name: z25.string().optional() }).strict(),
point: cameraVec3Input.optional()
}).strict();
- surfacePairInput = z24.array(z24.string().max(4096)).length(2);
- inspectInput = z24.object({
- image: z24.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
+ surfacePairInput = z25.array(z25.string().max(4096)).length(2);
+ inspectInput = z25.object({
+ image: z25.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
detail: reviewDetailInput,
listParts: partListInput.optional().describe("List exported-scene paths, including nested parts. Default 80, max 100 per page. Follow partListing.nextOffset with the same programRef/query. image:false avoids rendering."),
- surfacePairs: z24.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
- compare: z24.object({
- programRef: z24.string().regex(programRefPattern),
- offset: z24.number().int().min(0).optional(),
- limit: z24.number().int().min(1).max(100).optional(),
- paths: z24.array(z24.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
+ surfacePairs: z25.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
+ compare: z25.object({
+ programRef: z25.string().regex(programRefPattern),
+ offset: z25.number().int().min(0).optional(),
+ limit: z25.number().int().min(1).max(100).optional(),
+ paths: z25.array(z25.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
}).strict().optional().describe("Static geometry/material/transform/bounds under current host settings. Follow nextOffset; paths adds complete subtrees."),
- measure: z24.object({
- mode: z24.enum(["anchors", "surface"]).optional(),
+ measure: z25.object({
+ mode: z25.enum(["anchors", "surface"]).optional(),
from: attachmentEndpointInput,
to: attachmentEndpointInput
}).strict().optional().describe("Default anchors: origin/local-point distance. Surface: disjoint mesh triangles, omit points. Rest pose, asset units. Check status/bounds; no solid clearance/attachment proof."),
shot: cameraShotInput.optional().describe("Exact shot; omit part/view/orbit controls."),
- code: z24.string().describe("Kiln source code to execute and inspect."),
- part: z24.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
- view: z24.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
- azimuthDeg: z24.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
- elevationDeg: z24.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
- zoom: z24.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
- isolate: z24.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
+ code: z25.string().describe("Kiln source code to execute and inspect."),
+ part: z25.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
+ view: z25.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
+ azimuthDeg: z25.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
+ elevationDeg: z25.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
+ zoom: z25.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
+ isolate: z25.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
});
inspectBufferInput = inspectInput.omit({ code: true });
inspectAdvertisedInput = inspectInput.extend({ shot: cameraShotRecordInput });
KILN_INSPECT_DESCRIPTION = "List complete part paths with listParts and image:false; query filters names/paths, offset/limit paginate. Follow partListing.nextOffset. ZOOM IN on one part: renders a single 512x512 close-up framed to the named part (the node name you gave createPart, matched case-insensitively with a substring fallback) and its descendants, " + "from one camera. Use it after kiln_render reveals a suspect region — a floating part, a bad " + "joint, a wrong proportion — to see fine detail one grid cell cannot show. args: part (omit to " + "frame the whole asset in one large view), view (front/right/back/left/top/three-quarter, default three-quarter), azimuthDeg + elevationDeg (orbit to ANY angle instead of a named view: azimuth 0 = front, 90 = right, 180 = back, 270 = left; elevation 0 = eye level, positive looks down, clamped to -89..89), zoom (padding multiplier around the part bounds, 1 = tight crop up to 4 = wide context, default 1.2), isolate (hide everything except that part, default false). Reach for the orbit angles when a named view puts the thing you need to judge edge-on or " + "behind something — the reply always tells you the azimuth/elevation it used, so you can step " + "from there. " + "If the part name does not resolve you get the list of available part names back — pick one and " + "retry. By default surrounding geometry stays visible for context and can occlude the part: either pick a different view, or set isolate:true to hide everything else and see the part unobstructed (use it for anything buried inside or behind other geometry). The view is rendered from deterministic derivative GLB bytes; GPU PBR is used only when it can preserve the requested framing, otherwise the GLB-native geometry-flat fallback reports why in viewFidelity. Writes no files." + VIEW_EVIDENCE_GUIDANCE;
kilnInspectDef = createKilnInspectDef();
- editOperationInput = z24.object({
- oldString: z24.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
- newString: z24.string().describe("The replacement text. Use an empty string to delete."),
- replaceAll: z24.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
- });
- editInput = z24.object({
- code: z24.string().describe("The Kiln program to patch. The full current source."),
- edits: z24.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
- render: z24.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
+ editOperationInput = z25.object({
+ oldString: z25.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
+ newString: z25.string().describe("The replacement text. Use an empty string to delete."),
+ replaceAll: z25.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
+ });
+ editInput = z25.object({
+ code: z25.string().describe("The Kiln program to patch. The full current source."),
+ edits: z25.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
+ render: z25.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
capture: captureInput,
detail: reviewDetailInput
});
@@ -53041,14 +53529,14 @@ var init_registry2 = __esm(() => {
shot: "shape:camera-shot",
capture: "shape:capture"
};
- rendererInput = z24.strictObject({
- action: z24.enum(["status", "reprobe"]).default("status")
+ rendererInput = z25.strictObject({
+ action: z25.enum(["status", "reprobe"]).default("status")
});
- rendererStatusInput = z24.strictObject({});
+ rendererStatusInput = z25.strictObject({});
assetSelector = {
- collection: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
- assetId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
- revisionId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
+ collection: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
+ assetId: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
+ revisionId: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
};
ASSET_CONTRACT = {
collections: {
@@ -53872,7 +54360,7 @@ var init_loopback = __esm(() => {
});
// src/workspace-http.ts
-import { z as z25 } from "zod";
+import { z as z26 } from "zod";
async function readJson(req, origin) {
if (req.headers.origin !== origin)
throw new WorkspaceHttpError(403, "Same-origin writes only");
@@ -54041,11 +54529,11 @@ var init_workspace_http = __esm(() => {
this.status = status;
}
};
- updateSchema = z25.strictObject({
+ updateSchema = z26.strictObject({
expectedRevision: projectRevisionIdSchema,
patch: projectPatchSchema
});
- pinSchema = z25.strictObject({ pinned: z25.boolean() });
+ pinSchema = z26.strictObject({ pinned: z26.boolean() });
filePattern3 = /^(asset\.glb|source\.kiln\.js|evaluation\.json|capture-\d{1,2}\.png)$/;
});
diff --git a/dist/evaluator-worker.mjs b/dist/evaluator-worker.mjs
index f9addfc4..d729b379 100644
--- a/dist/evaluator-worker.mjs
+++ b/dist/evaluator-worker.mjs
@@ -693,14 +693,115 @@ var init_asset = __esm(() => {
THREE_DEGREES = Math.PI / 180;
});
-// src/contracts/requirements.ts
+// src/contracts/validation-profile.ts
import { z } from "zod";
+var VALIDATION_PROFILE_VERSION = "kiln.validation-profile.v1", MAX_VALIDATION_PROFILE_BYTES, MAX_VALIDATION_CHECKS = 16, MAX_VALIDATION_PATTERN_CHARS = 128, MAX_VALIDATION_PATTERN_STARS = 4, MAX_VALIDATION_MATCHES = 512, VALIDATION_SEMANTICS, VALIDATION_SEMANTIC_SIZE, VALIDATION_AXES, finite, id = (max) => z.string().min(1).max(max).regex(/^[A-Za-z0-9._-]+$/, 'Use letters, digits, ".", "_" or "-".'), pattern, componentFits = (value) => value.component < VALIDATION_SEMANTIC_SIZE[value.attribute], componentMessage, gradient, range, check, ValidationProfileV1Schema;
+var init_validation_profile = __esm(() => {
+ MAX_VALIDATION_PROFILE_BYTES = 8 * 1024;
+ VALIDATION_SEMANTICS = [
+ "POSITION",
+ "NORMAL",
+ "TANGENT",
+ "TEXCOORD_0",
+ "TEXCOORD_1",
+ "COLOR_0",
+ "JOINTS_0",
+ "WEIGHTS_0"
+ ];
+ VALIDATION_SEMANTIC_SIZE = {
+ POSITION: 3,
+ NORMAL: 3,
+ TANGENT: 4,
+ TEXCOORD_0: 2,
+ TEXCOORD_1: 2,
+ COLOR_0: 4,
+ JOINTS_0: 4,
+ WEIGHTS_0: 4
+ };
+ VALIDATION_AXES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
+ finite = z.number().finite();
+ pattern = z.string().min(1).refine((value) => Array.from(value).length <= MAX_VALIDATION_PATTERN_CHARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_CHARS} characters.`
+ }).refine((value) => value.split("*").length - 1 <= MAX_VALIDATION_PATTERN_STARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_STARS} "*".`
+ });
+ componentMessage = {
+ message: "component is outside the attribute.",
+ path: ["component"]
+ };
+ gradient = z.strictObject({
+ attribute: z.enum(["TEXCOORD_0", "TEXCOORD_1", "COLOR_0"]),
+ component: z.number().int().min(0).max(3),
+ axis: z.enum(VALIDATION_AXES),
+ from: finite,
+ to: finite,
+ tolerance: finite.positive().max(0.5),
+ monotonic: z.boolean()
+ }).refine((value) => value.from !== value.to, {
+ message: "from and to must differ."
+ }).refine(componentFits, componentMessage);
+ range = z.strictObject({
+ attribute: z.enum(VALIDATION_SEMANTICS),
+ component: z.number().int().min(0).max(3),
+ min: finite,
+ max: finite,
+ tolerance: finite.nonnegative()
+ }).refine((value) => value.min <= value.max, {
+ message: "min must not exceed max."
+ }).refine(componentFits, componentMessage);
+ check = z.strictObject({
+ id: id(48),
+ select: z.strictObject({
+ names: z.array(pattern).min(1).max(8),
+ minMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ maxMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional()
+ }).refine((value) => value.maxMatches === undefined || (value.minMatches ?? 1) <= value.maxMatches, { message: "minMatches must not exceed maxMatches." }),
+ primitives: z.union([
+ z.strictObject({ exactly: z.number().int().min(1).max(64) }),
+ z.strictObject({ max: z.number().int().min(1).max(64) })
+ ]).optional(),
+ attributes: z.array(z.enum(VALIDATION_SEMANTICS)).min(1).max(8).refine((values) => new Set(values).size === values.length, {
+ message: "Attributes must be unique."
+ }).optional(),
+ gradient: gradient.optional(),
+ range: range.optional(),
+ material: z.strictObject({
+ alphaMode: z.enum(["OPAQUE", "MASK", "BLEND"]).optional(),
+ doubleSided: z.boolean().optional()
+ }).refine((value) => value.alphaMode !== undefined || value.doubleSided !== undefined, {
+ message: "A material check needs alphaMode or doubleSided."
+ }).optional()
+ }).refine((value) => value.primitives !== undefined || value.attributes !== undefined || value.gradient !== undefined || value.range !== undefined || value.material !== undefined, { message: "A check needs at least one assertion." });
+ ValidationProfileV1Schema = z.strictObject({
+ version: z.literal(VALIDATION_PROFILE_VERSION),
+ profileId: id(64).regex(/^[a-z0-9._-]+$/, 'Use lowercase letters, digits, ".", "_" or "-".'),
+ mode: z.enum(["warn", "enforce"]),
+ checks: z.array(check).min(1).max(MAX_VALIDATION_CHECKS)
+ }).superRefine((value, context) => {
+ const ids = value.checks.map((item) => item.id);
+ if (new Set(ids).size !== ids.length)
+ context.addIssue({
+ code: "custom",
+ path: ["checks"],
+ message: "Check ids must be unique."
+ });
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_VALIDATION_PROFILE_BYTES)
+ context.addIssue({
+ code: "custom",
+ message: `A validation profile serializes to at most ${MAX_VALIDATION_PROFILE_BYTES} bytes (got ${bytes}).`
+ });
+ });
+});
+
+// src/contracts/requirements.ts
+import { z as z2 } from "zod";
function statement(value) {
- return z.discriminatedUnion("state", [
- z.strictObject({ state: z.literal("requested"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("inferred"), value, reason: text.optional() }),
- z.strictObject({ state: z.literal("unknown"), reason: text.optional() }),
- z.strictObject({ state: z.literal("inapplicable"), reason: text.optional() })
+ return z2.discriminatedUnion("state", [
+ z2.strictObject({ state: z2.literal("requested"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inferred"), value, reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("unknown"), reason: text.optional() }),
+ z2.strictObject({ state: z2.literal("inapplicable"), reason: text.optional() })
]);
}
function validateAssetRequirementsV1(value) {
@@ -730,157 +831,159 @@ var text, positive, nonnegative, count2, names, marker, supportParts, roof, stru
var init_requirements = __esm(() => {
init_asset();
init_breadth();
- text = z.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
- positive = z.number().finite().positive();
- nonnegative = z.number().finite().nonnegative();
- count2 = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
- names = z.array(text).refine((values) => new Set(values).size === values.length, {
+ init_validation_profile();
+ text = z2.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
+ positive = z2.number().finite().positive();
+ nonnegative = z2.number().finite().nonnegative();
+ count2 = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+ names = z2.array(text).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- marker = z.strictObject({});
- supportParts = z.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
+ marker = z2.strictObject({});
+ supportParts = z2.array(text).min(1).max(256).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- roof = z.strictObject({
+ roof = z2.strictObject({
type: text.optional(),
- ridgeAxis: z.enum(["x", "z"]).optional(),
+ ridgeAxis: z2.enum(["x", "z"]).optional(),
rise: nonnegative.optional(),
- pitchDegrees: z.number().min(0).max(90).optional(),
+ pitchDegrees: z2.number().min(0).max(90).optional(),
overhang: nonnegative.optional(),
- closedEnds: z.boolean().optional()
+ closedEnds: z2.boolean().optional()
});
- structure = z.strictObject({
+ structure = z2.strictObject({
subtype: text.optional(),
- enterable: z.boolean().optional(),
+ enterable: z2.boolean().optional(),
storeyCount: count2.min(1).optional(),
- interiorMode: z.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
- roofMode: z.enum(ARCHITECTURE_ROOF_MODES).optional(),
- footprint: z.strictObject({ spanX: positive, spanZ: positive, units: z.literal("m") }).optional(),
+ interiorMode: z2.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
+ roofMode: z2.enum(ARCHITECTURE_ROOF_MODES).optional(),
+ footprint: z2.strictObject({ spanX: positive, spanZ: positive, units: z2.literal("m") }).optional(),
wallHeight: positive.optional(),
- scaleMode: z.enum(ARCHITECTURE_SCALE_MODES).optional(),
+ scaleMode: z2.enum(ARCHITECTURE_SCALE_MODES).optional(),
roof: roof.optional(),
- portal: z.strictObject({ width: positive, height: positive, depth: positive }).optional()
+ portal: z2.strictObject({ width: positive, height: positive, depth: positive }).optional()
}).refine((value) => value.enterable === undefined || value.interiorMode === undefined || value.enterable === (value.interiorMode === "navigable"), {
message: "enterable and interiorMode must agree when both are specified."
});
- effects = z.strictObject({
- schemaVersion: z.literal(1),
- subtype: z.enum(VFX_SUBTYPES),
- portability: z.enum(VFX_PORTABILITY_MODES),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES),
- doubleSided: z.boolean(),
- facing: z.strictObject({
- source: z.enum(["explicit", "inferred"]),
- mode: z.enum(VFX_FACING_MODES),
- normalAxis: z.enum(VFX_AXIS_DIRECTIONS).optional(),
- directionAxis: z.enum(VFX_AXIS_DIRECTIONS).optional()
+ effects = z2.strictObject({
+ schemaVersion: z2.literal(1),
+ subtype: z2.enum(VFX_SUBTYPES),
+ portability: z2.enum(VFX_PORTABILITY_MODES),
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES),
+ doubleSided: z2.boolean(),
+ facing: z2.strictObject({
+ source: z2.enum(["explicit", "inferred"]),
+ mode: z2.enum(VFX_FACING_MODES),
+ normalAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional(),
+ directionAxis: z2.enum(VFX_AXIS_DIRECTIONS).optional()
}),
- animation: z.strictObject({
- playback: z.enum(VFX_PLAYBACK_POLICIES),
+ animation: z2.strictObject({
+ playback: z2.enum(VFX_PLAYBACK_POLICIES),
durationSeconds: nonnegative,
- endpointBehavior: z.enum(VFX_ENDPOINT_BEHAVIORS),
- driver: z.enum(VFX_RUNTIME_DRIVERS),
+ endpointBehavior: z2.enum(VFX_ENDPOINT_BEHAVIORS),
+ driver: z2.enum(VFX_RUNTIME_DRIVERS),
clipName: text.optional(),
timeUniformName: text.optional()
}),
- sidecar: z.strictObject({ kind: z.literal("tsl"), id: text, version: text }).optional()
+ sidecar: z2.strictObject({ kind: z2.literal("tsl"), id: text, version: text }).optional()
}).superRefine((value, context) => {
for (const issue of validateVfxIntentV1(value).issues) {
context.addIssue({ code: "custom", path: issue.path.split("."), message: issue.message });
}
});
- requirements = z.strictObject({
- grounding: statement(z.strictObject({ planeY: z.number().finite().optional() })).optional(),
+ requirements = z2.strictObject({
+ grounding: statement(z2.strictObject({ planeY: z2.number().finite().optional() })).optional(),
articulation: statement(marker).optional(),
opening: statement(marker).optional(),
- navigation: statement(z.strictObject({ minWidth: positive.optional(), minHeight: positive.optional() })).optional(),
+ navigation: statement(z2.strictObject({ minWidth: positive.optional(), minHeight: positive.optional() })).optional(),
tiling: statement(marker).optional(),
- mobility: statement(z.strictObject({
+ mobility: statement(z2.strictObject({
subtype: text.optional(),
supportAssemblies: names.optional(),
propulsionAssemblies: names.optional(),
- frontFrame: z.literal("+X").optional(),
+ frontFrame: z2.literal("+X").optional(),
wheelCount: count2.optional(),
axleCount: count2.optional(),
- steering: z.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
- supportPolicy: z.enum(VEHICLE_SUPPORT_POLICIES).optional(),
+ steering: z2.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
+ supportPolicy: z2.enum(VEHICLE_SUPPORT_POLICIES).optional(),
animationAssemblies: names.optional()
})).optional(),
structure: statement(structure).optional(),
- rig: statement(z.strictObject({
- bodyPlan: z.enum(CHARACTER_BODY_PLANS).optional(),
- grounded: z.boolean().optional(),
- locomotion: z.enum(CHARACTER_LOCOMOTION_MODES).optional(),
+ rig: statement(z2.strictObject({
+ bodyPlan: z2.enum(CHARACTER_BODY_PLANS).optional(),
+ grounded: z2.boolean().optional(),
+ locomotion: z2.enum(CHARACTER_LOCOMOTION_MODES).optional(),
gait: text.optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- clips: z.array(z.strictObject({ name: text, playback: z.enum(["loop", "oneShot"]) })).optional(),
- heldItem: z.strictObject({ required: z.boolean(), attachmentRole: text }).optional()
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ clips: z2.array(z2.strictObject({ name: text, playback: z2.enum(["loop", "oneShot"]) })).optional(),
+ heldItem: z2.strictObject({ required: z2.boolean(), attachmentRole: text }).optional()
})).optional(),
- foliage: statement(z.strictObject({
+ foliage: statement(z2.strictObject({
subtype: text.optional(),
- growthState: z.enum(VEGETATION_GROWTH_STATES).optional(),
- canopyProfile: z.enum(VEGETATION_CANOPY_PROFILES).optional(),
- standalone: z.boolean().optional(),
- grounded: z.boolean().optional()
+ growthState: z2.enum(VEGETATION_GROWTH_STATES).optional(),
+ canopyProfile: z2.enum(VEGETATION_CANOPY_PROFILES).optional(),
+ standalone: z2.boolean().optional(),
+ grounded: z2.boolean().optional()
})).optional(),
- spatialLayout: statement(z.strictObject({
+ spatialLayout: statement(z2.strictObject({
subtype: text.optional(),
- tileable: z.boolean().optional(),
- navigable: z.boolean().optional()
+ tileable: z2.boolean().optional(),
+ navigable: z2.boolean().optional()
})).optional(),
effects: statement(effects).optional(),
- material: statement(z.strictObject({
- mode: z.enum(MATERIAL_INTENT_MODES).optional(),
+ material: statement(z2.strictObject({
+ mode: z2.enum(MATERIAL_INTENT_MODES).optional(),
recipeId: text.optional(),
paletteId: text.optional(),
- transparency: z.enum(MATERIAL_TRANSPARENCY_MODES).optional()
+ transparency: z2.enum(MATERIAL_TRANSPARENCY_MODES).optional()
})).optional(),
- animation: statement(z.strictObject({
+ animation: statement(z2.strictObject({
clips: names,
- locomotionDirection: z.literal("+X").optional(),
- rootMotion: z.enum(["inPlace", "forward"]).optional(),
- loop: z.boolean().optional(),
+ locomotionDirection: z2.literal("+X").optional(),
+ rootMotion: z2.enum(["inPlace", "forward"]).optional(),
+ loop: z2.boolean().optional(),
gait: text.optional()
})).optional(),
- bounds: statement(z.strictObject({
- units: z.literal("m"),
+ bounds: statement(z2.strictObject({
+ units: z2.literal("m"),
x: positive.optional(),
y: positive.optional(),
z: positive.optional()
})).optional(),
- parts: statement(z.strictObject({ required: names, forbiddenExtras: names })).optional(),
- modular: statement(z.strictObject({
- schemaVersion: z.literal(1),
- units: z.literal("m"),
- grid: z.tuple([positive, positive, positive])
+ parts: statement(z2.strictObject({ required: names, forbiddenExtras: names })).optional(),
+ modular: statement(z2.strictObject({
+ schemaVersion: z2.literal(1),
+ units: z2.literal("m"),
+ grid: z2.tuple([positive, positive, positive])
})).optional(),
- representation: statement(z.strictObject({
- transparentSurface: z.boolean().optional(),
- runtimeShader: z.boolean().optional(),
- precomputedTangents: z.boolean().optional(),
- skinned: z.boolean().optional()
+ representation: statement(z2.strictObject({
+ transparentSurface: z2.boolean().optional(),
+ runtimeShader: z2.boolean().optional(),
+ precomputedTangents: z2.boolean().optional(),
+ skinned: z2.boolean().optional()
})).optional(),
- externalSupport: statement(z.strictObject({
- supports: z.array(z.strictObject({
+ externalSupport: statement(z2.strictObject({
+ supports: z2.array(z2.strictObject({
parts: supportParts,
- planeY: z.number().finite(),
+ planeY: z2.number().finite(),
tolerance: nonnegative.max(0.5).optional()
})).min(1).max(32)
})).optional(),
- access: statement(z.strictObject({ enterable: z.boolean().optional(), driveable: z.boolean().optional() })).optional()
+ access: statement(z2.strictObject({ enterable: z2.boolean().optional(), driveable: z2.boolean().optional() })).optional(),
+ validation: statement(ValidationProfileV1Schema).optional()
});
- AssetRequirementsV1Schema = z.strictObject({
- kind: z.literal("kiln.asset-requirements"),
- schemaVersion: z.literal(1),
+ AssetRequirementsV1Schema = z2.strictObject({
+ kind: z2.literal("kiln.asset-requirements"),
+ schemaVersion: z2.literal(1),
labels: names,
- frame: z.strictObject({
- units: z.literal("m"),
- forward: z.literal("+X"),
- up: z.literal("+Y"),
- right: z.literal("+Z"),
- groundY: z.literal(0)
+ frame: z2.strictObject({
+ units: z2.literal("m"),
+ forward: z2.literal("+X"),
+ up: z2.literal("+Y"),
+ right: z2.literal("+Z"),
+ groundY: z2.literal(0)
}),
- scope: statement(z.enum(ASSET_SCOPES)).optional(),
+ scope: statement(z2.enum(ASSET_SCOPES)).optional(),
requirements
}).superRefine((record, context) => {
const requests = record.requirements;
@@ -997,7 +1100,7 @@ var init_requirements_json = __esm(() => {
// src/requirements-context.ts
import { createHash as createHash2 } from "node:crypto";
-import { z as z2 } from "zod";
+import { z as z3 } from "zod";
function canonical2(value) {
if (Array.isArray(value))
return `[${value.map(canonical2).join(",")}]`;
@@ -1040,26 +1143,26 @@ var init_requirements_context = __esm(() => {
init_requirements();
init_requirements_identity();
init_requirements_json();
- text2 = z2.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
- hash = z2.string().regex(/^[a-f0-9]{64}$/);
- revision = z2.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
- change = z2.strictObject({
+ text2 = z3.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
+ hash = z3.string().regex(/^[a-f0-9]{64}$/);
+ revision = z3.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
+ change = z3.strictObject({
actor: text2,
reason: text2,
- source: z2.enum(["brief", "automation", "migration", "restore"]),
+ source: z3.enum(["brief", "automation", "migration", "restore"]),
revision,
policyHash: hash,
previousPolicyHash: hash.optional()
});
- RequirementsBindingSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-binding"),
- schemaVersion: z2.literal(1),
+ RequirementsBindingSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-binding"),
+ schemaVersion: z3.literal(1),
taskId: text2,
lineageId: text2,
revision,
policyHash: hash,
requirements: AssetRequirementsV1Schema,
- history: z2.array(change).min(1)
+ history: z3.array(change).min(1)
}).superRefine((binding, context) => {
const issue = (message) => context.addIssue({ code: "custom", message });
if (binding.policyHash !== assetRequirementsPolicyHash(binding.requirements))
@@ -1074,9 +1177,9 @@ var init_requirements_context = __esm(() => {
if (binding.history.at(-1)?.policyHash !== binding.policyHash)
issue("Requirements binding history does not end at its current policy.");
});
- CheckpointSchema = z2.strictObject({
- kind: z2.literal("kiln.requirements-checkpoint.v1"),
- programRef: z2.string().regex(/^sha256:[a-f0-9]{64}$/),
+ CheckpointSchema = z3.strictObject({
+ kind: z3.literal("kiln.requirements-checkpoint.v1"),
+ programRef: z3.string().regex(/^sha256:[a-f0-9]{64}$/),
binding: RequirementsBindingSchema
});
});
@@ -3623,7 +3726,7 @@ function integer(value, path, fallback, min, max) {
}
return value;
}
-function finite(value, path, fallback, min, max, diagnostic) {
+function finite2(value, path, fallback, min, max, diagnostic) {
if (value === undefined)
return fallback;
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
@@ -3632,7 +3735,7 @@ function finite(value, path, fallback, min, max, diagnostic) {
return value;
}
function unit(value, path, fallback) {
- return finite(value, path, fallback, 0, 1, "MATERIAL_FRACTION_RANGE");
+ return finite2(value, path, fallback, 0, 1, "MATERIAL_FRACTION_RANGE");
}
function optionalName(value, path) {
if (value === undefined)
@@ -3655,7 +3758,7 @@ function usage(value, path, fallback) {
return value;
}
function angle(value, path) {
- const bounded = finite(value, path, 0, -36000, 36000);
+ const bounded = finite2(value, path, 0, -36000, 36000);
const normalized = (bounded % 360 + 360) % 360;
return Object.is(normalized, -0) ? 0 : normalized;
}
@@ -3934,7 +4037,7 @@ function canonicalizePortableMaterialSpecV2(input) {
...record["emissive"] !== undefined ? {
emissive: color(record["emissive"], "portableMaterial.emissive", "PORTABLE_COLOR_ARGUMENT")
} : {},
- emissiveIntensity: finite(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),
+ emissiveIntensity: finite2(record["emissiveIntensity"], "portableMaterial.emissiveIntensity", 1, 0, 64),
alphaMode,
alphaCutoff: unit(record["alphaCutoff"], "portableMaterial.alphaCutoff", 0.5),
doubleSided: record["doubleSided"] === true,
@@ -13790,7 +13893,8 @@ function resolveRequirementsApplicability(requirements) {
bounds: ["units", "x", "y", "z"],
animation: ["clips"],
representation: ["precomputedTangents"],
- externalSupport: ["supports"]
+ externalSupport: ["supports"],
+ validation: ["version", "profileId", "mode", "checks"]
};
for (const [key, statement] of Object.entries(requirements.requirements)) {
if (statement?.state !== "requested")
@@ -13907,2039 +14011,2431 @@ var init_requirements_applicability = __esm(() => {
kernel: "connectivity"
},
{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },
- { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" }
+ { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },
+ { id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }
];
});
-// src/qa/requirements-report.ts
-function createRequirementsQaReport(context, options) {
- const applicability = resolveRequirementsApplicability(context.requirements);
- const unevaluatedRequirements = [
- ...applicability.unevaluatedRequirements,
- ...sceneMeasurementGaps(context.requirements, options.findings ?? [])
- ];
- const executed = new Set(options.executedRules);
- const rules = applicability.rules.map((rule) => ({
- id: rule.id,
- mode: options.modes?.[rule.id] ?? rule.mode,
- status: rule.status === "evaluate" ? executed.has(rule.id) ? "evaluated" : "notEvaluated" : rule.status,
- ...rule.reason ? { reason: rule.reason } : {}
- }));
- const incomplete = unevaluatedRequirements.length > 0 || applicability.rules.some((rule) => rule.status === "evaluate" && !(rule.mode === "observe" && rule.keys.length === 0) && (!executed.has(rule.id) || (options.modes?.[rule.id] ?? rule.mode) === "off" || rule.mode === "enforce" && (options.modes?.[rule.id] ?? rule.mode) !== "enforce"));
- const findings = (options.findings ?? []).map((finding) => ({
- ...finding,
- dimension: finding.dimension === "categoryReadiness" ? "requirementReadiness" : finding.dimension
- }));
- const evaluated = new Set(options.evaluatedDimensions ?? ["exportIntegrity", "requirementReadiness"]);
- for (const finding of findings)
- evaluated.add(finding.dimension);
- const dimensions = Object.fromEntries(REQUIREMENTS_QA_DIMENSIONS.map((dimension) => {
- const selected = findings.filter((finding) => finding.dimension === dimension);
- const partialObservation = selected.some((finding) => finding.code === "GEO_PART_SELF_INTERSECTION_UNMEASURED" || finding.code === "GEO_PART_SELF_INTERSECTION_TRUNCATED" || finding.code === "GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED");
- const status = selected.some((f) => f.disposition === "block") ? "block" : partialObservation || !evaluated.has(dimension) || dimension === "requirementReadiness" && incomplete ? "notEvaluated" : selected.some((f) => f.disposition === "warn") ? "warn" : "pass";
- return [
- dimension,
- {
- status,
- findings: selected,
- ...options.metrics?.[dimension] ? { metrics: options.metrics[dimension] } : {}
- }
- ];
- }));
- const blocked = findings.some((f) => f.disposition === "block");
- const warned = findings.some((f) => f.disposition === "warn");
- return {
- kind: "kiln.asset-qa-report",
- schemaVersion: 2,
- qaProfile: "asset.requirements.v1",
- policyHash: context.policyHash,
- adviceHash: context.adviceHash,
- acceptance: blocked ? "blocked" : incomplete ? "incomplete" : "accepted",
- disposition: blocked ? "block" : incomplete ? "notEvaluated" : warned ? "warn" : "pass",
- dimensions,
- rules,
- unevaluatedRequirements
- };
+// src/metrics.ts
+function primTris(prim) {
+ const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
+ switch (prim.getMode()) {
+ case 4:
+ return Math.floor(count / 3);
+ case 5:
+ case 6:
+ return Math.max(0, count - 2);
+ default:
+ return 0;
+ }
}
-var REQUIREMENTS_QA_DIMENSIONS;
-var init_requirements_report = __esm(() => {
- init_requirements_applicability();
- init_types();
- REQUIREMENTS_QA_DIMENSIONS = [
- "exportIntegrity",
- "requirementReadiness",
- "promptAlignment",
- "visualQuality",
- "runtimeCost"
- ];
-});
-
-// src/qa/reference-comparison.ts
-function isEvidence(value) {
- if (typeof value !== "object" || value === null)
- return false;
- const candidate = value;
- return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";
+function instanceCopies(node) {
+ const ext = node.getExtension("EXT_mesh_gpu_instancing");
+ if (!ext)
+ return 1;
+ return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
}
-function referenceComparisonFindings(evidence, profile) {
- if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)
- return [];
- const findings = [];
- if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {
- findings.push({
- code: "REF_SILHOUETTE_AGREEMENT",
- disposition: "observe",
- dimension: "promptAlignment",
- profile,
- message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,
- measurement: {
- name: "silhouetteIoU",
- actual: evidence.silhouetteIoU,
- threshold: SILHOUETTE_IOU_OBSERVE
- },
- repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."
- });
- }
- if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {
- findings.push({
- code: "REF_COLOR_AGREEMENT",
- disposition: "observe",
- dimension: "promptAlignment",
- profile,
- message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,
- measurement: {
- name: "colorAgreement",
- actual: evidence.colorAgreement,
- threshold: COLOR_AGREEMENT_OBSERVE
- },
- repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."
- });
+function isHiddenGltfNode(node) {
+ const visibility = node.getExtension("KHR_node_visibility");
+ return visibility?.getVisible?.() === false;
+}
+function nodeTriangles(node) {
+ return subtreeTriangles(node, false);
+}
+function drawnNodeTriangles(node) {
+ return subtreeTriangles(node, true);
+}
+function subtreeTriangles(node, drawn) {
+ if (drawn && isHiddenGltfNode(node))
+ return 0;
+ let triangles = 0;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ for (const prim of mesh.listPrimitives())
+ triangles += primTris(prim) * copies;
}
- return findings;
+ for (const child of node.listChildren())
+ triangles += subtreeTriangles(child, drawn);
+ return triangles;
}
-var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;
-var init_reference_comparison = __esm(() => {
- init_registry();
- REFERENCE_COMPARISON_QA_RULE = Object.freeze({
- id: "REF_COMPARISON",
- profile: "reference.comparison",
- scope: { kind: "universal" },
- ruleClass: "heuristic",
- owner: KILN_ENGINE_QA_OWNER,
- defaultMode: "observe",
- evaluate(context) {
- const evidence = context.derivedEvidence?.["referenceComparison"];
- if (!isEvidence(evidence))
- return [];
- return referenceComparisonFindings(evidence, "reference.comparison");
+function collectGlbMetrics(doc, triangles) {
+ const root = doc.getRoot();
+ const geomSet = new Set;
+ const matSet = new Set;
+ let drawCalls = 0;
+ let derivedTris = 0;
+ let meshNodes = 0;
+ let meshInstances = 0;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const copies = instanceCopies(node);
+ meshNodes += 1;
+ meshInstances += copies;
+ for (const prim of mesh.listPrimitives()) {
+ drawCalls += 1;
+ geomSet.add(prim);
+ derivedTris += primTris(prim) * copies;
+ const mat = prim.getMaterial();
+ if (mat)
+ matSet.add(mat);
+ }
}
- });
-});
-
-// src/qa/run.ts
-function gltfReportFindings(report, profile) {
- return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
- code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),
- disposition: issue.severity === 0 ? "block" : "warn",
- dimension: "exportIntegrity",
- profile,
- message: issue.message,
- ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}
- }));
-}
-function isExpectedKtx2ValidatorLimitation(report, issue) {
- const required = report.info?.["extensionsRequired"];
- if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))
- return false;
- if (issue.code === "VALUE_NOT_IN_LIST") {
- return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const scene of root.listScenes()) {
+ for (const node of scene.listChildren())
+ visit(node);
}
- return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";
+ const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
+ return {
+ uniqueGeometries: geomSet.size,
+ uniqueMaterials: matSet.size,
+ meshNodes,
+ meshInstances,
+ drawCalls,
+ textureCount: root.listTextures().length,
+ skinned: root.listSkins().length > 0,
+ transparentMaterials,
+ triangles: triangles ?? derivedTris
+ };
}
-function qaPolicyFromEnv(env = process.env) {
- const mode = env["KILN_QA_MODE"];
- return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};
+function rubricGrade(m) {
+ const grade = materialBand(m.uniqueMaterials).grade;
+ return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
}
-function qaBlockingEnabled(env = process.env) {
- const mode = env["KILN_QA_MODE"];
- return mode !== "observe" && mode !== "off";
+function textureSlots(m) {
+ return [
+ [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
+ [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
+ [m.getNormalTexture(), m.getNormalTextureInfo()],
+ [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
+ [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
+ ];
}
-var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;
-var init_run = __esm(() => {
- init_material();
- init_architecture();
- init_character2();
- init_character_advisory();
- init_vehicle2();
- init_vegetation();
- init_prop();
- init_part_connectivity();
- init_reference_comparison();
- init_self_intersection();
- init_sweep();
- init_environment2();
- init_breadth2();
- init_breadth_evidence();
- init_registry();
- init_types();
- init_universal();
- DETERMINISTIC_QA_REGISTRY = new QaRegistry([
- ...UNIVERSAL_QA_RULES,
- MATERIAL_QA_RULE,
- ...ARCHITECTURE_QA_RULES,
- CHARACTER_QA_RULE,
- CHARACTER_ADVISORY_QA_RULE,
- ...VEHICLE_QA_RULES,
- ...VEGETATION_QA_RULES,
- ...PROP_QA_RULES,
- ...ENVIRONMENT_QA_RULES,
- ...W7_BREADTH_QA_RULES,
- SELF_INTERSECTION_QA_RULE,
- SWEEP_QA_RULE,
- PART_CONNECTIVITY_QA_RULE,
- REFERENCE_COMPARISON_QA_RULE
+function shadingKey(m, textures) {
+ const binding = (info) => info && [
+ info.getTexCoord(),
+ info.getWrapS(),
+ info.getWrapT(),
+ info.getMagFilter(),
+ info.getMinFilter(),
+ extensionNames(info)
+ ];
+ return JSON.stringify([
+ m.getAlphaMode(),
+ m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
+ m.getDoubleSided(),
+ textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
+ extensionNames(m),
+ m.getExtras()
]);
- AssetQaBlockedError = class AssetQaBlockedError extends Error {
- report;
- stage;
- gltfValidation;
- constructor(report, stage, gltfValidation) {
- const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");
- const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.affected ? ` AFFECTED: ${JSON.stringify(finding.affected)}` : ""}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);
- const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";
- super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);
- this.name = "AssetQaBlockedError";
- this.report = report;
- this.stage = stage;
- this.gltfValidation = gltfValidation;
+}
+function differingFactors(group) {
+ const [first, ...rest] = group;
+ const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
+ for (const extension of first.listExtensions())
+ if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ const slots = textureSlots(first);
+ slots.forEach(([, info], slot) => {
+ for (const extension of info?.listExtensions() ?? [])
+ if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
+ differs.push(extension.extensionName);
+ });
+ return [...new Set(differs)];
+}
+function mergeNeeds(differs) {
+ const needs = [];
+ if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
+ needs.push("colours in a shared texture, an atlas region or vertex colours");
+ if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
+ needs.push("one metallic/roughness value or a shared metallicRoughness texture");
+ if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
+ needs.push("one normal scale and occlusion strength");
+ if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
+ needs.push("one setting for each differing extension");
+ return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
+}
+function materialMergeCandidates(doc) {
+ const root = doc.getRoot();
+ const parts = new Map;
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+ for (const primitive of mesh?.listPrimitives() ?? []) {
+ const material = primitive.getMaterial();
+ if (!material)
+ continue;
+ const list = parts.get(material) ?? [];
+ if (!list.includes(name))
+ list.push(name);
+ parts.set(material, list);
}
+ for (const child of node.listChildren())
+ visit(child);
};
-});
-
-// src/qa/requirements-run.ts
-import { Object3D as Object3D15 } from "three";
-function sceneDecisions(context, policy) {
- const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));
- return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);
-}
-async function collectRequirementsSceneEvidence(context, scene, policy = {}) {
- if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))
- return {};
- try {
- return { partPenetration: await analyzePartPenetration(scene) };
- } catch {
- return { partPenetrationFailed: true };
+ for (const scene of root.listScenes())
+ for (const node of scene.listChildren())
+ visit(node);
+ const materials = root.listMaterials();
+ const textures = root.listTextures();
+ const groups = new Map;
+ for (const material of materials) {
+ if (!parts.has(material))
+ continue;
+ const key = shadingKey(material, textures);
+ const group = groups.get(key);
+ if (group)
+ group.push(material);
+ else
+ groups.set(key, [material]);
}
+ return [...groups.values()].filter((group) => group.length > 1).map((group) => {
+ const differs = differingFactors(group);
+ return {
+ materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
+ parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
+ alphaMode: group[0].getAlphaMode(),
+ differs,
+ needs: mergeNeeds(differs)
+ };
+ });
}
-function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {
- const needs = context.requirements.requirements;
- const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];
- const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;
- const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;
- const requiredClips = [
- ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])
- ];
- const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;
- const findings = [];
- const decisions = sceneDecisions(context, policy);
- const geometryMetrics = {};
- const mobilityInput = {
- scene,
- mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];
- const executedRules = [];
- const rigInput = {
- scene,
- clips,
- rig,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const foliageInput = {
- scene,
- foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,
- materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
- };
- const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;
- const scope = context.requirements.scope;
- const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;
- const effectsInput = {
- effects,
- derivedEvidence: {
- source: "engine-scene-analysis",
- ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}
- }
+function shortList(names, shown, joiner) {
+ const head = names.slice(0, shown).join(joiner);
+ return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+}
+function mergeAdvice(m, candidates) {
+ const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
+ const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
+ const projected = {
+ ...m,
+ uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
+ transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
};
- const spatialInput = {
- scene,
- tileable: needs.tiling?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.tileable === true,
- navigable: needs.navigation?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.navigable === true,
- navigation: needs.navigation?.state === "requested" ? needs.navigation.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
+ const projectedGrade = rubricGrade(projected);
+ const band = materialBand(projected.uniqueMaterials);
+ const named = (c) => shortList(c.materials, 4, " + ");
+ const groups = candidates.slice(0, 3).map((c) => {
+ const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
+ return `${named(c)} (${why})`;
+ });
+ if (candidates.length > 3)
+ groups.push(`${candidates.length - 3} more groups`);
+ const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
+ const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
+ const reasons = candidates.map((c) => {
+ const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
+ return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
+ });
+ return {
+ advice: {
+ optional: true,
+ materialMerges: [...candidates],
+ projectedMaterials: projected.uniqueMaterials,
+ projectedGrade
+ },
+ summary,
+ reasons
};
- const spatialFindings = decisions.some((d) => d.ruleId.startsWith("ENVIRONMENT_") && d.mode !== "off") ? [
- ...inspectPlacementSockets(spatialInput),
- ...inspectTileEdges(spatialInput),
- ...inspectNavigationClearance(spatialInput),
- ...inspectSpatialSupport(spatialInput)
- ] : [];
- const structureFindings = needs.structure?.state === "requested" && decisions.some((d) => d.ruleId.startsWith("ARCHITECTURE_") && d.mode !== "off") ? inspectStructure({
- scene,
- structure: needs.structure.value,
- opening: needs.opening?.state === "requested"
- }) : [];
- for (const decision of decisions) {
- if (decision.mode === "off")
- continue;
- if (decision.ruleId === SELF_INTERSECTION_QA_RULE.id) {
- const volume = evidence.partPenetration;
- if (volume) {
- const acknowledged = volume.acknowledged?.length ?? 0;
- const partial = volume.truncated || volume.skipped.length > 0 || acknowledged > 0;
- if (!partial)
- executedRules.push(decision.ruleId);
- findings.push(...inspectPartPenetration(volume));
- Object.assign(geometryMetrics, {
- partVolumeCoverage: partial ? "partial" : "complete-static-pairs",
- partVolumeScope: "Visible static closed mesh pairs, except alternates on different LOD levels; excludes intra-mesh intersections, motion, open surfaces and usable passage space. Positive overlap may be intentional.",
- partVolumeEligibleParts: volume.partsAnalyzed,
- partVolumeCandidatePairs: volume.candidatePairs,
- partVolumeCandidatesLowerBound: volume.broadPhaseTruncated === true,
- partVolumePairsTested: volume.pairsTested,
- partVolumeUnmeasurablePairs: volume.pairsUnmeasurable,
- partVolumePairsNotReached: volume.pairsNotReached,
- partVolumeLodAlternatePairs: volume.pairsLodAlternates,
- partVolumeSkipped: volume.skipped.length,
- ...acknowledged > 0 ? {
- partVolumeAcknowledgedParts: acknowledged,
- partVolumeAcknowledgedPairs: volume.pairsUnmeasurableAcknowledged ?? 0
- } : {}
- });
- } else if (evidence.partPenetrationFailed) {
- findings.push({
- code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",
- disposition: "observe",
- dimension: "visualQuality",
- profile: "geometry.selfIntersection",
- message: "Part-volume analysis could not complete. Overlap and clearance remain unmeasured."
- });
- geometryMetrics.partVolumeCoverage = "unavailable";
- }
- continue;
- }
- if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
- continue;
- if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
- continue;
- executedRules.push(decision.ruleId);
- if (decision.ruleId === PROP_EXACT_QA_RULE.id) {
- const measured = [
- ...needs.articulation?.state === "requested" ? inspectArticulation({ scene }) : [],
- ...needs.opening?.state === "requested" ? inspectContainerOpening({ scene }) : []
- ];
- for (const finding of measured)
- findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
- continue;
- }
- const measured = decision.ruleId === SWEEP_QA_RULE.id ? inspectSweepGeometry(scene) : decision.ruleId === PART_CONNECTIVITY_QA_RULE.id ? inspectPartConnectivity(scene, needs.externalSupport?.state === "requested" ? needs.externalSupport.value.supports : undefined) : decision.ruleId === ASSET_SCOPE_QA_RULE.id && scope?.state === "requested" ? inspectAssetScope({
- profile: "asset.requirements.v1",
- scope: { schemaVersion: 1, scope: scope.value, explicit: true },
- derivedEvidence: { source: "engine-scene-analysis", assetScope: scopeObservation }
- }) : decision.ruleId === "CHARACTER_PROFILE" ? inspectRig(rigInput) : decision.ruleId === "CHARACTER_ADVISORY_PROFILE" ? inspectRigAdvisory(rigInput) : decision.ruleId === "VEGETATION_CONTACT_PROFILE" ? inspectFoliageContact(foliageInput) : decision.ruleId === "VEGETATION_ADVISORY_PROFILE" ? inspectFoliageAdvisory(foliageInput) : decision.ruleId === MATERIAL_QA_RULE.id ? inspectPortableSceneMaterials(scene, tangents) : decision.ruleId === "VFX_EXACT_PROFILE" ? inspectEffectsExact(effectsInput) : decision.ruleId === "VFX_ADVISORY_PROFILE" ? inspectEffectsAdvisory(effectsInput) : decision.ruleId === "ARCHITECTURE_PROFILE" ? structureFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ARCHITECTURE_ADVISORY_PROFILE" ? structureFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "ENVIRONMENT_EXACT_PROFILE" ? spatialFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ENVIRONMENT_ADVISORY_PROFILE" ? spatialFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_PROFILE" ? mobilityFindings.filter((f) => f.disposition === "block") : decision.ruleId === "VEHICLE_ADVISORY_PROFILE" ? mobilityFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_W6_ADVISORY_PROFILE" ? inspectMobilityAdvisory(mobilityInput) : decision.ruleId === PROP_ADVISORY_QA_RULE.id ? inspectPlacement({
- scene,
- bounds: needs.bounds?.state === "requested" ? needs.bounds.value : undefined,
- groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
- }) : UNIVERSAL_QA_KERNELS[decision.ruleId]({
- scene,
- clips,
- requiredParts: parts,
- animation: { clips: requiredClips }
- });
- for (const finding of measured)
- findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
- }
- return createRequirementsQaReport(context, {
- findings,
- executedRules,
- modes: Object.fromEntries(decisions.map((x) => [x.ruleId, x.mode])),
- metrics: {
- ...Object.keys(geometryMetrics).length ? { visualQuality: geometryMetrics } : {},
- ...scopeObservation ? {
- promptAlignment: {
- scopeTopLevelAssetRoots: scopeObservation.topLevelAssetRoots,
- scopeReusableMemberCount: scopeObservation.reusableMemberCount,
- scopeDressingSignalCount: scopeObservation.sceneDressingRoles.length
- }
- } : {}
- },
- ...scopeObservation ? {
- evaluatedDimensions: ["exportIntegrity", "requirementReadiness", "promptAlignment"]
- } : {}
- });
-}
-function appendRequirementsQa(context, report, findings, metrics = {}) {
- const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
- const merged = { ...priorMetrics };
- for (const [dimension, value] of Object.entries(metrics ?? {}))
- merged[dimension] = { ...priorMetrics[dimension], ...value };
- return createRequirementsQaReport(context, {
- findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
- executedRules: report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
- modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
- evaluatedDimensions: [
- ...new Set([
- ...Object.entries(report.dimensions).filter(([, value]) => value.status !== "notEvaluated").map(([key]) => key),
- ...Object.keys(metrics ?? {})
- ])
- ],
- metrics: merged
- });
}
-async function appendRequirementsFinalQa(context, report, gltf, bytes, instanceability, metricsError, material, warnings = []) {
- const gltfFindings = gltfReportFindings(gltf, report.qaProfile);
- const findings = [
- ...gltfFindings,
- ...warnings.map((w) => ({
- code: w.code,
- disposition: "warn",
- dimension: "runtimeCost",
- profile: `${w.profile}.${w.tier}`,
- message: `${w.message} ${w.advice}`,
- measurement: w.measurement
- }))
- ];
- if (metricsError)
- findings.push({
- code: "RUNTIME_COST_METRICS_FAILED",
- disposition: "warn",
- dimension: "runtimeCost",
- profile: report.qaProfile,
- message: `Runtime-cost metrics could not be computed: ${metricsError}`
- });
- const cost = {};
- if (instanceability)
- Object.assign(cost, {
- instanceabilityGrade: instanceability.grade,
- instanceabilitySummary: instanceability.summary,
- ...instanceability.metrics
- });
- if (material)
- Object.assign(cost, {
- materialCount: material.materialCount,
- opaqueMaterials: material.opaqueMaterials,
- maskedMaterials: material.maskedMaterials,
- blendedMaterials: material.blendedMaterials,
- singleSidedMaterials: material.singleSidedMaterials,
- doubleSidedMaterials: material.doubleSidedMaterials,
- texturedMaterials: material.texturedMaterials,
- materialExtensionCount: material.materialExtensionCount,
- materialExtensionsUsed: material.materialExtensionsUsed.join(","),
- imageCount: material.imageCount,
- maxImageDimension: material.maxImageDimension,
- decodedImageBytesRgba8: material.decodedImageBytesRgba8,
- estimatedGpuBytesWithMipmaps: material.estimatedGpuBytesWithMipmaps,
- blendedSurfaceAreaRatio: material.blendedSurfaceAreaRatio
- });
- let result = appendRequirementsQa(context, report, findings, {
- exportIntegrity: {
- gltfErrors: gltf.issues.numErrors,
- gltfWarnings: gltfFindings.filter((x) => x.disposition === "warn").length
- },
- runtimeCost: cost
- });
- const effects = context.requirements.requirements.effects;
- const rule = report.rules.find((r) => r.id === "VFX_EXACT_PROFILE");
- if (effects?.state === "requested" && rule?.status === "evaluated" && rule.mode !== "off") {
- const evidence = await analyzeFinalVfxGlbBytesV1(bytes);
- const measured = inspectFinalEffects(effects.value, evidence);
- const findings = rule.mode === "enforce" ? measured : measured.map((f) => ({
- ...f,
- disposition: rule.mode
- }));
- result = appendRequirementsQa(context, result, findings, {
- exportIntegrity: finalEffectsMetrics(evidence)
- });
+function gradeInstanceability(metrics, opts = {}) {
+ const m = metrics;
+ const band = materialBand(m.uniqueMaterials);
+ let grade = band.grade;
+ const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
+ const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
+ const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
+ const drivers = [];
+ const also = [];
+ if ((grade === "A" || grade === "B") && (transparency || textures)) {
+ grade = "C";
+ if (transparency)
+ drivers.push(`${transparency} (lowers A/B to C)`);
+ if (textures)
+ drivers.push(`${textures} (over 4 lowers A/B to C)`);
+ also.push(materials);
+ } else {
+ drivers.push(materials);
+ if (transparency)
+ also.push(`${transparency} (lowers only A/B to C)`);
+ if (textures)
+ also.push(`${textures} (over 4 lowers only A/B to C)`);
}
- return result;
+ also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
+ if (m.skinned)
+ also.push("skinned (clone-rendered, not penalized)");
+ const setBy = drivers.join(" and ");
+ const reasons = [
+ `grade ${grade} set by ${setBy}`,
+ `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
+ ];
+ if (transparency)
+ reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
+ if (textures)
+ reasons.push(`${m.textureCount} textures (consider atlasing)`);
+ if (m.skinned)
+ reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
+ if (opts.category)
+ reasons.push(`category: ${opts.category}`);
+ const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
+ if (!opts.mergeCandidates?.length)
+ return { grade, summary, reasons, metrics: m };
+ const merge = mergeAdvice(m, opts.mergeCandidates);
+ return {
+ grade,
+ summary: summary + merge.summary,
+ reasons: [...reasons, ...merge.reasons],
+ metrics: m,
+ advice: merge.advice
+ };
}
-var registry;
-var init_requirements_run = __esm(() => {
- init_breadth_evidence();
- init_breadth2();
- init_breadth_final();
- init_registry();
- init_universal();
- init_material();
- init_prop();
- init_part_connectivity();
- init_sweep();
- init_self_intersection();
- init_vehicle2();
- init_vehicle_advisory();
- init_vegetation();
- init_character2();
- init_character_advisory();
- init_architecture();
- init_environment2();
- init_requirements_applicability();
- init_requirements_report();
- init_run();
- registry = new QaRegistry([
- ...UNIVERSAL_QA_RULES,
- MATERIAL_QA_RULE,
- PROP_EXACT_QA_RULE,
- PROP_ADVISORY_QA_RULE,
- PART_CONNECTIVITY_QA_RULE,
- SELF_INTERSECTION_QA_RULE,
- SWEEP_QA_RULE,
- ...VEHICLE_QA_RULES,
- ...ARCHITECTURE_QA_RULES,
- ...ENVIRONMENT_QA_RULES,
- ...VEGETATION_QA_RULES,
- CHARACTER_QA_RULE,
- CHARACTER_ADVISORY_QA_RULE,
- VFX_EXACT_QA_RULE,
- VFX_ADVISORY_QA_RULE,
- ASSET_SCOPE_QA_RULE
- ]);
+var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
+var init_metrics = __esm(() => {
+ MATERIAL_GRADE_BANDS = [
+ { grade: "A", max: 1, range: "0-1" },
+ { grade: "B", max: 3, range: "2-3" },
+ { grade: "C", max: 6, range: "4-6" },
+ { grade: "D", max: 12, range: "7-12" },
+ { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
+ ];
+ MERGE_FACTORS = [
+ ["baseColorFactor", (m) => m.getBaseColorFactor()],
+ ["emissiveFactor", (m) => m.getEmissiveFactor()],
+ ["metallicFactor", (m) => m.getMetallicFactor()],
+ ["roughnessFactor", (m) => m.getRoughnessFactor()],
+ ["normalScale", (m) => m.getNormalScale()],
+ ["occlusionStrength", (m) => m.getOcclusionStrength()]
+ ];
});
-// src/qa/skin-integrity.ts
-import * as THREE22 from "three";
-function validAttribute(a, count, size) {
- if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)
- return false;
- if ("isInterleavedBufferAttribute" in a) {
- return Number.isSafeInteger(a.data.stride) && a.data.stride >= size && Number.isSafeInteger(a.offset) && a.offset >= 0 && a.offset + size <= a.data.stride && (count - 1) * a.data.stride + a.offset + size <= a.array.length;
- }
- return count * size <= a.array.length;
-}
-function finiteAffine(matrix) {
- const e = matrix?.elements;
- return !!e && e.length === 16 && [...e].every((v) => Number.isFinite(v) && Number.isFinite(Math.fround(v))) && Math.fround(e[3]) === 0 && Math.fround(e[7]) === 0 && Math.fround(e[11]) === 0 && Math.fround(e[15]) === 1;
+// src/written-nodes.ts
+function exportedRoot(doc, purpose) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ const top = scene?.listChildren() ?? [];
+ if (top.length !== 1)
+ throw new Error(`${purpose} expects the exporter to write one root node.`);
+ return top[0];
}
-function inspectSkinIntegrity(root) {
- const result = {
- schemaVersion: 1,
- findings: [],
- meshesChecked: 0,
- verticesChecked: 0,
- truncated: false,
- bounds: []
- };
- const paths = new Map;
- const pending = [[root, "", 0]];
- while (pending.length) {
- const [node, parent, sibling] = pending.pop();
- if (paths.has(node))
- continue;
- const segment = `${(node.name || node.type).slice(0, 80)}[${sibling}]`;
- const path = (parent ? `${parent}/${segment}` : segment).slice(-800);
- paths.set(node, path);
- for (let i = node.children.length - 1;i >= 0; i--)
- pending.push([node.children[i], path, i]);
- }
- const worlds = new Map;
- function world(node) {
- const chain = [], seen = new Set;
- let cursor = node;
- while (cursor && !worlds.has(cursor)) {
- if (seen.has(cursor))
- return;
- seen.add(cursor);
- chain.push(cursor);
- cursor = cursor.parent;
- }
- while (chain.length) {
- const n = chain.pop();
- const local = n.matrixAutoUpdate ? new THREE22.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
- const parent = n.parent ? worlds.get(n.parent) : undefined;
- const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE22.Matrix4().multiplyMatrices(parent, local) : local;
- worlds.set(n, value);
- }
- return worlds.get(node);
- }
- for (const [node, nodePath] of paths) {
- const mesh = node;
- if (!mesh.isSkinnedMesh)
- continue;
- if (result.findings.length >= MAX_FINDINGS) {
- result.truncated = true;
- break;
- }
- result.meshesChecked++;
- const start = result.findings.length;
- const add = (code, message, attribute, measurement) => {
- if (result.findings.length >= MAX_FINDINGS) {
- result.truncated = true;
- return;
- }
- result.findings.push({
- code,
- disposition: "block",
- dimension: "exportIntegrity",
- profile: "skin.source-integrity.v1",
- message,
- affected: { node: mesh.name.slice(0, 160), nodePath, ...attribute ? { attribute } : {} },
- ...measurement ? { measurement } : {},
- repairText: "Rebuild the named binding at its intended rest pose. Keep bone order, inverse bind matrices and four influence lanes aligned with every final vertex; unwrap or change topology before binding. Do not repair invalid indices by normalizing weights."
- });
- };
- const skeleton = mesh.skeleton, bones = skeleton?.bones;
- if (!bones?.length || !Array.isArray(bones)) {
- add("SKIN_SKELETON", "Skinned mesh requires a nonempty skeleton in the exported hierarchy.");
- continue;
- }
- const unique = new Set;
- for (let joint = 0;joint < bones.length; joint++) {
- const bone = bones[joint];
- if (!bone?.isObject3D || !paths.has(bone) || unique.has(bone)) {
- add("SKIN_JOINT_MEMBERSHIP", `Joint ${joint} (${JSON.stringify(bone?.name?.slice(0, 160) ?? "missing")}) must be a distinct node inside the exported hierarchy.`, `joints[${joint}]`);
- }
- if (bone)
- unique.add(bone);
- if (!finiteAffine(skeleton.boneInverses?.[joint])) {
- add("SKIN_INVERSE_BIND", `Joint ${joint} (${JSON.stringify(bone?.name?.slice(0, 160) ?? "missing")}) requires a finite affine inverse bind matrix.`, `boneInverses[${joint}]`);
- }
- if (result.truncated)
- break;
- }
- if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE22.AttachedBindMode, THREE22.DetachedBindMode].includes(mesh.bindMode)) {
- add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");
+function writtenNodeResolver(root, doc, purpose) {
+ const top = exportedRoot(doc, purpose);
+ return (node) => {
+ const path = [];
+ for (let current = node;current !== root; current = current.parent) {
+ if (!current.parent)
+ throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
+ path.unshift(current.parent.children.indexOf(current));
}
- const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;
- const indices = mesh.geometry?.getAttribute("skinIndex"), weights = mesh.geometry?.getAttribute("skinWeight");
- if (!validAttribute(position, count, 3) || !validAttribute(indices, count, 4) || indices.normalized || !validAttribute(weights, count, 4)) {
- add("SKIN_ATTRIBUTES", "Skin requires xyz positions and four non-normalized joint indices and four weights per final vertex, backed by complete buffers.", "skinIndex/skinWeight");
- continue;
+ let target = top;
+ for (const index of path)
+ target = target?.listChildren()[index];
+ if (!target || (target.getName() || "") !== (node.name || ""))
+ throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
+ return target;
+ };
+}
+
+// src/node-visibility.ts
+import { KHRNodeVisibility } from "@gltf-transform/extensions";
+import * as THREE22 from "three";
+function applyNodeVisibility(root, doc) {
+ const hidden = [];
+ root.traverse((node) => {
+ if (node.visible === false)
+ hidden.push(node);
+ });
+ if (hidden.length === 0)
+ return;
+ const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
+ const extension = doc.createExtension(KHRNodeVisibility);
+ for (const node of written)
+ node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
+}
+function summarizeHiddenNodes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const found = [];
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment2(name, occurrence)}`;
+ if (isHiddenGltfNode(node))
+ found.push({ path, name, triangles: nodeTriangles(node) });
+ else
+ visit(node.listChildren(), path);
}
- const invalid = new Map;
- const bad = (code, vertex, attribute) => {
- const row = invalid.get(code);
- if (row) {
- if (row.last !== vertex)
- row.count++;
- row.last = vertex;
- } else
- invalid.set(code, { count: 1, first: vertex, last: vertex, attribute });
- };
- for (let vertex = 0;vertex < count; vertex++) {
- let sum = 0;
- for (let lane = 0;lane < 4; lane++) {
- const index = indices.getComponent(vertex, lane), weight = weights.getComponent(vertex, lane);
- if (!Number.isInteger(index) || index < 0 || index >= bones.length)
- bad("SKIN_JOINT_INDEX", vertex, "skinIndex");
- if (!Number.isFinite(weight) || weight < 0 || weight > 1)
- bad("SKIN_WEIGHT_VALUE", vertex, "skinWeight");
- sum += weight;
+ };
+ visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
+ return found;
+}
+function drawnSceneBounds(scene) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ const visit = (node) => {
+ if (isHiddenGltfNode(node))
+ return;
+ const mesh = node.getMesh();
+ if (mesh) {
+ const base = new THREE22.Matrix4().fromArray(node.getWorldMatrix());
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
+ const matrices = [];
+ for (let i = 0;i < countInstances; i++) {
+ const t = translation?.getElement(i, []) ?? [0, 0, 0];
+ const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
+ const s = scale?.getElement(i, []) ?? [1, 1, 1];
+ const localMatrix = new THREE22.Matrix4().compose(new THREE22.Vector3().fromArray(t), new THREE22.Quaternion().fromArray(r), new THREE22.Vector3().fromArray(s));
+ matrices.push(base.clone().multiply(localMatrix).toArray());
+ }
+ const local = [0, 0, 0];
+ for (const primitive of mesh.listPrimitives()) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const m of matrices)
+ for (let i = 0;i < count; i++) {
+ position.getElement(indices ? indices.getScalar(i) : i, local);
+ const [x, y, z] = local;
+ const world = [
+ m[0] * x + m[4] * y + m[8] * z + m[12],
+ m[1] * x + m[5] * y + m[9] * z + m[13],
+ m[2] * x + m[6] * y + m[10] * z + m[14]
+ ];
+ for (let k = 0;k < 3; k++) {
+ if (world[k] < min[k])
+ min[k] = world[k];
+ if (world[k] > max[k])
+ max[k] = world[k];
+ }
+ }
}
- if (!Number.isFinite(sum) || Math.abs(sum - 1) > WEIGHT_TOLERANCE)
- bad("SKIN_WEIGHT_SUM", vertex, "skinWeight");
- }
- result.verticesChecked += count;
- for (const [code, row] of invalid) {
- const why = code === "SKIN_JOINT_INDEX" ? "indices must address the skeleton, including zero-weight lanes" : code === "SKIN_WEIGHT_SUM" ? `weights must sum to one within ${WEIGHT_TOLERANCE}` : "weights must be finite values in [0,1]";
- add(code, `Invalid ${row.attribute} at vertex range ${row.first}..${row.last} (${row.count} affected vertices): ${why}.`, row.attribute, {
- name: "invalidSkinVertices",
- actual: row.count,
- expected: 0,
- breakdown: { firstVertex: row.first, lastVertex: row.last }
- });
}
- if (result.findings.length !== start)
- continue;
- const meshWorld = world(mesh);
- if (!finiteAffine(meshWorld)) {
- add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");
+ for (const child of node.listChildren())
+ visit(child);
+ };
+ for (const node of scene.listChildren())
+ visit(node);
+ return { min, max };
+}
+var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var init_node_visibility = __esm(() => {
+ init_metrics();
+});
+
+// src/delivery-inspect.ts
+import * as THREE23 from "three";
+import { PropertyType as PropertyType2 } from "@gltf-transform/core";
+function decompose(matrix) {
+ const translation = new THREE23.Vector3;
+ const rotation = new THREE23.Quaternion;
+ const scale = new THREE23.Vector3;
+ matrix.decompose(translation, rotation, scale);
+ const clean = (value) => Object.is(value, -0) ? 0 : value;
+ return {
+ translation: translation.toArray().map(clean),
+ rotation: rotation.toArray().map(clean),
+ scale: scale.toArray().map(clean)
+ };
+}
+function drawnTriangles(visited) {
+ const values = [];
+ const local = [0, 0, 0];
+ const point = new THREE23.Vector3;
+ for (const { node, roles, hidden } of visited) {
+ const mesh = node.getMesh();
+ if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
continue;
- }
- const inverse = mesh.bindMode === THREE22.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
+ const base = worldMatrix(node);
+ const instances = node.getExtension("EXT_mesh_gpu_instancing");
+ const translation = instances?.getAttribute("TRANSLATION");
+ const rotation = instances?.getAttribute("ROTATION");
+ const scale = instances?.getAttribute("SCALE");
+ const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
const matrices = [];
- for (let joint = 0;joint < bones.length; joint++) {
- const boneWorld = world(bones[joint]);
- if (!finiteAffine(boneWorld)) {
- add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);
- break;
- }
- matrices.push(new THREE22.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
+ for (let i = 0;i < copies; i++) {
+ const instance = new THREE23.Matrix4().compose(new THREE23.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE23.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE23.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
+ matrices.push(base.clone().multiply(instance));
}
- if (result.findings.length !== start)
- continue;
- const base = new THREE22.Vector3, posed = new THREE22.Vector3, temp = new THREE22.Vector3, box = new THREE22.Box3;
- for (let vertex = 0;vertex < count; vertex++) {
- THREE22.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
- posed.set(0, 0, 0);
- for (let lane = 0;lane < 4; lane++) {
- const weight = weights.getComponent(vertex, lane);
- if (weight !== 0)
- posed.addScaledVector(temp.copy(base).applyMatrix4(matrices[indices.getComponent(vertex, lane)]), weight);
- }
- posed.applyMatrix4(inverse).applyMatrix4(meshWorld);
- if (!Number.isFinite(Math.fround(posed.x)) || !Number.isFinite(Math.fround(posed.y)) || !Number.isFinite(Math.fround(posed.z))) {
- add("SKIN_POSED_VERTEX", `Current deformed vertex ${vertex} is not finite and Float32-representable. Check positions, morphs and weighted joint transforms.`, `position[${vertex}]`);
- break;
- }
- box.expandByPoint(posed);
+ for (const primitive of mesh.listPrimitives()) {
+ if (primitive.getMode() !== 4)
+ continue;
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ continue;
+ const indices = primitive.getIndices();
+ const count = indices ? indices.getCount() : position.getCount();
+ for (const matrix of matrices)
+ for (let i = 0;i + 2 < count; i += 3)
+ for (let k = 0;k < 3; k++) {
+ position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
+ point.fromArray(local).applyMatrix4(matrix);
+ values.push(point.x, point.y, point.z);
+ }
}
- if (result.findings.length === start)
- result.bounds.push({ nodePath, min: box.min.toArray(), max: box.max.toArray() });
}
- return result;
+ return Float64Array.from(values);
}
-var MAX_FINDINGS = 64, WEIGHT_TOLERANCE = 0.00001;
-var init_skin_integrity = () => {};
-
-// src/metrics.ts
-function primTris(prim) {
- const count = prim.getIndices()?.getCount() ?? prim.getAttribute("POSITION")?.getCount() ?? 0;
- switch (prim.getMode()) {
- case 4:
- return Math.floor(count / 3);
- case 5:
- case 6:
- return Math.max(0, count - 2);
- default:
- return 0;
+function triangleOverlapsBox(a, b, c, h, tolerance) {
+ const verts = [a, b, c];
+ const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
+ for (let axis = 0;axis < 3; axis++) {
+ const values = verts.map((v) => v.getComponent(axis));
+ if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
+ return false;
}
+ const e = [
+ new THREE23.Vector3().subVectors(b, a),
+ new THREE23.Vector3().subVectors(c, b),
+ new THREE23.Vector3().subVectors(a, c)
+ ];
+ const normal = new THREE23.Vector3().crossVectors(e[0], e[1]);
+ const axes = [normal];
+ const units = [
+ new THREE23.Vector3(1, 0, 0),
+ new THREE23.Vector3(0, 1, 0),
+ new THREE23.Vector3(0, 0, 1)
+ ];
+ for (const unit of units)
+ for (const edge of e)
+ axes.push(new THREE23.Vector3().crossVectors(unit, edge));
+ for (const axis of axes) {
+ if (axis.lengthSq() < 0.000000000000000000000001)
+ continue;
+ const projections = verts.map((v) => v.dot(axis));
+ const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
+ if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
+ return false;
+ }
+ return true;
}
-function instanceCopies(node) {
- const ext = node.getExtension("EXT_mesh_gpu_instancing");
- if (!ext)
- return 1;
- return ext.getAttribute?.("TRANSLATION")?.getCount() ?? ext.getAttribute?.("ROTATION")?.getCount() ?? ext.getAttribute?.("SCALE")?.getCount() ?? 1;
-}
-function isHiddenGltfNode(node) {
- const visibility = node.getExtension("KHR_node_visibility");
- return visibility?.getVisible?.() === false;
+function closestPointOnTriangle(p, a, b, c) {
+ const ab = new THREE23.Vector3().subVectors(b, a);
+ const ac = new THREE23.Vector3().subVectors(c, a);
+ const ap = new THREE23.Vector3().subVectors(p, a);
+ const d1 = ab.dot(ap);
+ const d2 = ac.dot(ap);
+ if (d1 <= 0 && d2 <= 0)
+ return a.clone();
+ const bp = new THREE23.Vector3().subVectors(p, b);
+ const d3 = ab.dot(bp);
+ const d4 = ac.dot(bp);
+ if (d3 >= 0 && d4 <= d3)
+ return b.clone();
+ const vc = d1 * d4 - d3 * d2;
+ if (vc <= 0 && d1 >= 0 && d3 <= 0)
+ return a.clone().addScaledVector(ab, d1 / (d1 - d3));
+ const cp = new THREE23.Vector3().subVectors(p, c);
+ const d5 = ab.dot(cp);
+ const d6 = ac.dot(cp);
+ if (d6 >= 0 && d5 <= d6)
+ return c.clone();
+ const vb = d5 * d2 - d1 * d6;
+ if (vb <= 0 && d2 >= 0 && d6 <= 0)
+ return a.clone().addScaledVector(ac, d2 / (d2 - d6));
+ const va = d3 * d6 - d5 * d4;
+ if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
+ return b.clone().addScaledVector(new THREE23.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
+ const denominator = 1 / (va + vb + vc);
+ return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
}
-function nodeTriangles(node) {
- return subtreeTriangles(node, false);
+function segmentSegmentDistanceSq(p1, q1, p2, q2) {
+ const d1 = new THREE23.Vector3().subVectors(q1, p1);
+ const d2 = new THREE23.Vector3().subVectors(q2, p2);
+ const r = new THREE23.Vector3().subVectors(p1, p2);
+ const a = d1.dot(d1);
+ const e = d2.dot(d2);
+ const f = d2.dot(r);
+ let s = 0;
+ let t = 0;
+ if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
+ return r.lengthSq();
+ if (a <= 0.000000000000000000000001)
+ t = THREE23.MathUtils.clamp(f / e, 0, 1);
+ else {
+ const c = d1.dot(r);
+ if (e <= 0.000000000000000000000001)
+ s = THREE23.MathUtils.clamp(-c / a, 0, 1);
+ else {
+ const b = d1.dot(d2);
+ const denominator = a * e - b * b;
+ s = denominator !== 0 ? THREE23.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
+ t = (b * s + f) / e;
+ if (t < 0) {
+ t = 0;
+ s = THREE23.MathUtils.clamp(-c / a, 0, 1);
+ } else if (t > 1) {
+ t = 1;
+ s = THREE23.MathUtils.clamp((b - c) / a, 0, 1);
+ }
+ }
+ }
+ const c1 = p1.clone().addScaledVector(d1, s);
+ const c2 = p2.clone().addScaledVector(d2, t);
+ return c1.distanceToSquared(c2);
}
-function drawnNodeTriangles(node) {
- return subtreeTriangles(node, true);
+function segmentCrossesTriangle(p, q, a, b, c) {
+ const hit = new THREE23.Vector3;
+ const ray = new THREE23.Ray(p, new THREE23.Vector3().subVectors(q, p));
+ const length = ray.direction.length();
+ if (length === 0)
+ return false;
+ ray.direction.divideScalar(length);
+ return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
}
-function subtreeTriangles(node, drawn) {
- if (drawn && isHiddenGltfNode(node))
- return 0;
- let triangles = 0;
- const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- for (const prim of mesh.listPrimitives())
- triangles += primTris(prim) * copies;
- }
- for (const child of node.listChildren())
- triangles += subtreeTriangles(child, drawn);
- return triangles;
+function triangleTouchesCapsule(a, b, c, p, q, radius) {
+ const r2 = radius * radius;
+ if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
+ return true;
+ if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
+ return true;
+ for (const [s, e] of [
+ [a, b],
+ [b, c],
+ [c, a]
+ ])
+ if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
+ return true;
+ return segmentCrossesTriangle(p, q, a, b, c);
}
-function collectGlbMetrics(doc, triangles) {
- const root = doc.getRoot();
- const geomSet = new Set;
- const matSet = new Set;
- let drawCalls = 0;
- let derivedTris = 0;
- let meshNodes = 0;
- let meshInstances = 0;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
+function deliveryNodePaths(doc) {
+ const paths = new Map;
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return paths;
+ const visit = (siblings, parentPath) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ paths.set(node, path);
+ visit(node.listChildren(), path);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ return paths;
+}
+function summarizeVertexAttributes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const groups = new Map;
+ const order = [];
+ const record = (node, path) => {
const mesh = node.getMesh();
- if (mesh) {
- const copies = instanceCopies(node);
- meshNodes += 1;
- meshInstances += copies;
- for (const prim of mesh.listPrimitives()) {
- drawCalls += 1;
- geomSet.add(prim);
- derivedTris += primTris(prim) * copies;
- const mat = prim.getMaterial();
- if (mat)
- matSet.add(mat);
+ if (!mesh)
+ return;
+ const bake = mesh.getExtras().kilnSurfaceBakeV1;
+ const names = new Set;
+ for (const primitive of mesh.listPrimitives())
+ for (const semantic of primitive.listSemantics())
+ if (semantic.startsWith("_"))
+ names.add(semantic);
+ for (const name of names) {
+ const params = bake && typeof bake === "object" ? bake[name] : undefined;
+ const key = `${name}\x00${JSON.stringify(params ?? null)}`;
+ let group = groups.get(key);
+ if (!group) {
+ group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
+ groups.set(key, group);
+ order.push(key);
}
+ if (!group.meshes.includes(path))
+ group.meshes.push(path);
}
- for (const child of node.listChildren())
- visit(child);
};
- for (const scene of root.listScenes()) {
- for (const node of scene.listChildren())
- visit(node);
- }
- const transparentMaterials = root.listMaterials().filter((m) => m.getAlphaMode() === "BLEND").length;
- return {
- uniqueGeometries: geomSet.size,
- uniqueMaterials: matSet.size,
- meshNodes,
- meshInstances,
- drawCalls,
- textureCount: root.listTextures().length,
- skinned: root.listSkins().length > 0,
- transparentMaterials,
- triangles: triangles ?? derivedTris
+ const visit = (siblings, parentPath) => {
+ siblings.forEach((node, index) => {
+ const at = (name) => {
+ let occurrence = 0;
+ for (let i = 0;i < index; i++)
+ if (siblings[i].getName() === name)
+ occurrence++;
+ return `${parentPath}${segment3(name, occurrence)}`;
+ };
+ const path = at(node.getName());
+ record(node, path);
+ visit(node.listChildren(), path);
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
+ for (const level of lower) {
+ const levelPath = at(level.getName());
+ record(level, levelPath);
+ visit(level.listChildren(), levelPath);
+ }
+ });
};
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
+ const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
+ return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
}
-function rubricGrade(m) {
- const grade = materialBand(m.uniqueMaterials).grade;
- return (grade === "A" || grade === "B") && lowersToC(m) ? "C" : grade;
-}
-function textureSlots(m) {
- return [
- [m.getBaseColorTexture(), m.getBaseColorTextureInfo()],
- [m.getEmissiveTexture(), m.getEmissiveTextureInfo()],
- [m.getNormalTexture(), m.getNormalTextureInfo()],
- [m.getOcclusionTexture(), m.getOcclusionTextureInfo()],
- [m.getMetallicRoughnessTexture(), m.getMetallicRoughnessTextureInfo()]
- ];
-}
-function shadingKey(m, textures) {
- const binding = (info) => info && [
- info.getTexCoord(),
- info.getWrapS(),
- info.getWrapT(),
- info.getMagFilter(),
- info.getMinFilter(),
- extensionNames(info)
- ];
- return JSON.stringify([
- m.getAlphaMode(),
- m.getAlphaMode() === "MASK" ? m.getAlphaCutoff() : null,
- m.getDoubleSided(),
- textureSlots(m).map(([texture, info]) => texture && [textures.indexOf(texture), binding(info)]),
- extensionNames(m),
- m.getExtras()
- ]);
-}
-function differingFactors(group) {
- const [first, ...rest] = group;
- const differs = MERGE_FACTORS.filter(([, read]) => rest.some((m) => JSON.stringify(read(m)) !== JSON.stringify(read(first)))).map(([name]) => name);
- for (const extension of first.listExtensions())
- if (rest.some((m) => !m.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- const slots = textureSlots(first);
- slots.forEach(([, info], slot) => {
- for (const extension of info?.listExtensions() ?? [])
- if (rest.some((m) => !textureSlots(m)[slot]?.[1]?.getExtension(extension.extensionName)?.equals(extension)))
- differs.push(extension.extensionName);
- });
- return [...new Set(differs)];
-}
-function mergeNeeds(differs) {
- const needs = [];
- if (differs.some((d) => d === "baseColorFactor" || d === "emissiveFactor"))
- needs.push("colours in a shared texture, an atlas region or vertex colours");
- if (differs.some((d) => d === "metallicFactor" || d === "roughnessFactor"))
- needs.push("one metallic/roughness value or a shared metallicRoughness texture");
- if (differs.some((d) => d === "normalScale" || d === "occlusionStrength"))
- needs.push("one normal scale and occlusion strength");
- if (differs.some((d) => d.startsWith("KHR_") || d.startsWith("EXT_")))
- needs.push("one setting for each differing extension");
- return needs.length ? needs.join("; ") : "only reusing one material; the members already match";
-}
-function materialMergeCandidates(doc) {
- const root = doc.getRoot();
- const parts = new Map;
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- const name = node.getName() || mesh?.getName() || `node ${root.listNodes().indexOf(node)}`;
+function inspectDelivery(doc) {
+ const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return summary;
+ const visited = [];
+ const visit = (siblings, parentPath, hidden, module) => {
+ const seen = new Map;
+ for (const node of siblings) {
+ const name = node.getName();
+ const occurrence = seen.get(name) ?? 0;
+ seen.set(name, occurrence + 1);
+ const path = `${parentPath}${segment3(name, occurrence)}`;
+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
+ const nodeHidden = hidden || isHiddenGltfNode(node);
+ const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
+ visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
+ visit(node.listChildren(), path, nodeHidden, nodeModule);
+ }
+ };
+ visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0), false, undefined);
+ const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
+ const { min, max } = drawnSceneBounds(scene);
+ const bounds = new THREE23.Box3(new THREE23.Vector3(...min), new THREE23.Vector3(...max));
+ const finiteBounds = [...min, ...max].every(Number.isFinite);
+ const diagonal = finiteBounds ? bounds.getSize(new THREE23.Vector3).length() : 0;
+ const tolerance = Math.max(0.0001, diagonal * 0.0001);
+ const colliderNodes = [];
+ for (const entry of visited) {
+ const { node, path, roles } = entry;
+ for (const role of roles) {
+ const matrix = worldMatrix(node);
+ const transform = decompose(matrix);
+ for (const shape of ["box", "capsule", "hull"]) {
+ const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
+ if (id === undefined)
+ continue;
+ const scale = transform.scale;
+ const record = {
+ role,
+ id,
+ path,
+ name: node.getName(),
+ transform,
+ shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
+ kind: "hull",
+ vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
+ }
+ };
+ summary.colliders.push(record);
+ colliderNodes.push({ visit: entry, record });
+ }
+ const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
+ if (anchorTail !== undefined) {
+ const [kind, ...rest] = anchorTail.split(".");
+ summary.anchors.push({
+ role,
+ kind,
+ id: rest.join("."),
+ path,
+ name: node.getName(),
+ transform
+ });
+ }
+ const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
+ if (portId !== undefined)
+ summary.ports.push({
+ role,
+ id: portId,
+ path,
+ name: node.getName(),
+ ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
+ transform
+ });
+ if (role === KILN_SEMANTIC_ROLES.kitModule) {
+ const extras = node.getExtras()[KILN_KIT_KEY];
+ let spec;
+ try {
+ const { schemaVersion, ...rest } = extras ?? {};
+ spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
+ } catch {
+ spec = undefined;
+ }
+ if (!spec)
+ finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
+ else if (summary.kit)
+ finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
+ else
+ summary.kit = {
+ role,
+ path,
+ name: node.getName(),
+ footprint: spec.footprint,
+ height: spec.height,
+ snapAxis: spec.snapAxis,
+ origin: spec.origin,
+ transform
+ };
+ }
+ }
+ }
+ const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
+ const triangleCount = triangles.length / 9;
+ let overlapTests = 0;
+ const a = new THREE23.Vector3;
+ const b = new THREE23.Vector3;
+ const c = new THREE23.Vector3;
+ for (const { visit: entry, record } of colliderNodes) {
+ if (!entry.hidden)
+ finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
+ const matrix = worldMatrix(entry.node);
+ const proxyBounds = new THREE23.Box3;
+ const mesh = entry.node.getMesh();
+ const local = [0, 0, 0];
for (const primitive of mesh?.listPrimitives() ?? []) {
- const material = primitive.getMaterial();
- if (!material)
- continue;
- const list = parts.get(material) ?? [];
- if (!list.includes(name))
- list.push(name);
- parts.set(material, list);
+ const position = primitive.getAttribute("POSITION");
+ for (let i = 0;i < (position?.getCount() ?? 0); i++)
+ proxyBounds.expandByPoint(new THREE23.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
}
- for (const child of node.listChildren())
- visit(child);
- };
- for (const scene of root.listScenes())
- for (const node of scene.listChildren())
- visit(node);
- const materials = root.listMaterials();
- const textures = root.listTextures();
- const groups = new Map;
- for (const material of materials) {
- if (!parts.has(material))
+ if (proxyBounds.isEmpty())
+ proxyBounds.expandByPoint(new THREE23.Vector3().setFromMatrixPosition(matrix));
+ const expanded = bounds.clone().expandByScalar(tolerance);
+ if (!finiteBounds || !expanded.containsBox(proxyBounds))
+ finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
+ if (record.shape.kind === "hull")
continue;
- const key = shadingKey(material, textures);
- const group = groups.get(key);
- if (group)
- group.push(material);
- else
- groups.set(key, [material]);
+ if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
+ finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
+ continue;
+ }
+ overlapTests += triangleCount;
+ const toLocal = new THREE23.Matrix4;
+ let touches = false;
+ if (record.shape.kind === "box") {
+ toLocal.copy(matrix).invert();
+ const half = new THREE23.Vector3(0.5, 0.5, 0.5);
+ const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
+ }
+ } else {
+ const { translation, rotation } = record.transform;
+ toLocal.compose(new THREE23.Vector3(...translation), new THREE23.Quaternion(...rotation), new THREE23.Vector3(1, 1, 1)).invert();
+ const { radius, height } = record.shape;
+ const p = new THREE23.Vector3(0, -height / 2 + radius, 0);
+ const q = new THREE23.Vector3(0, height / 2 - radius, 0);
+ for (let t = 0;t < triangleCount && !touches; t++) {
+ a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
+ b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
+ c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
+ touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
+ }
+ }
+ if (!touches)
+ finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
}
- return [...groups.values()].filter((group) => group.length > 1).map((group) => {
- const differs = differingFactors(group);
- return {
- materials: group.map((m) => m.getName() || `${parts.get(m)[0]} material`),
- parts: group.map((m) => parts.get(m).slice(0, MERGE_PARTS_KEPT)),
- alphaMode: group[0].getAlphaMode(),
- differs,
- needs: mergeNeeds(differs)
- };
- });
+ for (const record of summary.ports) {
+ const entry = visited.find((item) => item.path === record.path);
+ const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
+ const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
+ if (!spec) {
+ finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
+ continue;
+ }
+ const point = new THREE23.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
+ const [width, depth] = spec.footprint;
+ const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
+ const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
+ if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
+ finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
+ }
+ for (const record of summary.anchors) {
+ const entry = visited.find((item) => item.path === record.path);
+ if (entry.node.listChildren().length > 0)
+ finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
+ }
+ return summary;
}
-function shortList(names, shown, joiner) {
- const head = names.slice(0, shown).join(joiner);
- return names.length > shown ? `${head} and ${names.length - shown} more` : head;
+var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE23.Matrix4().fromArray(node.getWorldMatrix());
+var init_delivery_inspect = __esm(() => {
+ init_gltf_io();
+ init_semantic();
+ init_delivery();
+ init_metrics();
+ init_node_visibility();
+});
+
+// src/qa/validation-profile.ts
+function matchValidationPattern(pattern, name) {
+ const p = Array.from(pattern);
+ const s = Array.from(name);
+ let pi = 0;
+ let si = 0;
+ let star = -1;
+ let resume = 0;
+ while (si < s.length) {
+ if (pi < p.length && (p[pi] === "?" || p[pi] !== "*" && p[pi] === s[si])) {
+ pi++;
+ si++;
+ } else if (pi < p.length && p[pi] === "*") {
+ star = pi++;
+ resume = si;
+ } else if (star >= 0) {
+ pi = star + 1;
+ si = ++resume;
+ } else
+ return false;
+ }
+ while (pi < p.length && p[pi] === "*")
+ pi++;
+ return pi === p.length;
}
-function mergeAdvice(m, candidates) {
- const merged = candidates.reduce((n, c) => n + c.materials.length - 1, 0);
- const blendMerged = candidates.filter((c) => c.alphaMode === "BLEND").reduce((n, c) => n + c.materials.length - 1, 0);
- const projected = {
- ...m,
- uniqueMaterials: Math.max(1, m.uniqueMaterials - merged),
- transparentMaterials: Math.max(0, m.transparentMaterials - blendMerged)
- };
- const projectedGrade = rubricGrade(projected);
- const band = materialBand(projected.uniqueMaterials);
- const named = (c) => shortList(c.materials, 4, " + ");
- const groups = candidates.slice(0, 3).map((c) => {
- const why = c.differs.length ? `differ in ${c.differs.join(", ")}` : "identical shading";
- return `${named(c)} (${why})`;
- });
- if (candidates.length > 3)
- groups.push(`${candidates.length - 3} more groups`);
- const otherFactors = projectedGrade === band.grade ? "" : `; other factors give ${projectedGrade}`;
- const summary = ` Optional advice, not a requirement: merging ${groups.join("; ")} would leave ` + `${counted(projected.uniqueMaterials, "material", "materials")} (${band.grade} at ${band.range}${otherFactors}).`;
- const reasons = candidates.map((c) => {
- const why = c.differs.length ? ` and differ in ${c.differs.join(", ")}` : "";
- return `optional advice: ${named(c)} share shading${why}; a merge needs ${c.needs}; parts: ${shortList(c.parts.flat(), 3, ", ")}`;
- });
+function component(accessor, index, slot, element) {
+ accessor.getElement(index, element);
+ return element[slot];
+}
+function evaluateValidationProfileDocument(profile, doc, options = {}) {
+ const disposition = profile.mode === "enforce" ? "block" : "warn";
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ const budget = options.maxAttributeReads ?? MAX_VALIDATION_ATTRIBUTE_READS;
+ const paths = deliveryNodePaths(doc);
+ const candidates = [...paths.entries()].filter(([node]) => node.getMesh() !== null);
+ const findings = [];
+ let complete = true;
+ let reads = 0;
+ let matchedNodes = 0;
+ let notMeasured = 0;
+ for (const check of profile.checks) {
+ const kept = new Map;
+ const omitted = new Map;
+ const push = (code, assertion, message, measurement, affected, findingDisposition) => findings.push({
+ code,
+ disposition: findingDisposition,
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation check ${check.id}: ${message}`,
+ ...affected ? { affected } : {},
+ measurement: {
+ name: `checks.${check.id}.${assertion}`,
+ ...measurement
+ }
+ });
+ const report = (code, assertion, message, { affected, measurement }, findingDisposition = disposition) => {
+ const used = kept.get(code) ?? 0;
+ if (used < MAX_VALIDATION_FINDINGS_PER_CODE) {
+ kept.set(code, used + 1);
+ push(code, assertion, message, measurement, affected, findingDisposition);
+ return;
+ }
+ const entry = omitted.get(code) ?? {
+ count: 0,
+ assertion,
+ disposition: findingDisposition
+ };
+ entry.count++;
+ omitted.set(code, entry);
+ };
+ const matched = candidates.filter(([node]) => check.select.names.some((pattern) => matchValidationPattern(pattern, node.getName())));
+ const minMatches = check.select.minMatches ?? 1;
+ if (matched.length < minMatches || check.select.maxMatches !== undefined && matched.length > check.select.maxMatches) {
+ const expected = check.select.maxMatches === undefined ? `>= ${minMatches}` : minMatches === check.select.maxMatches ? `${minMatches}` : `${minMatches}..${check.select.maxMatches}`;
+ report("HOST_VALIDATION_SELECTOR_UNMATCHED", "select", `${matched.length} default-scene mesh node(s) match ${JSON.stringify(check.select.names)}; the host expects ${expected}. Node names come from the final GLB.`, { measurement: { actual: matched.length, expected } });
+ }
+ const measured = matched.slice(0, MAX_VALIDATION_MATCHES);
+ if (matched.length > measured.length) {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "select", `${matched.length - measured.length} matched node(s) beyond the ${MAX_VALIDATION_MATCHES}-node limit were not measured.`, {
+ measurement: {
+ actual: matched.length,
+ threshold: MAX_VALIDATION_MATCHES,
+ breakdown: { nodesNotMeasured: matched.length - measured.length }
+ }
+ }, "observe");
+ }
+ for (const [node, nodePath] of measured) {
+ const primitives = node.getMesh().listPrimitives();
+ const cost = primitives.reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0) * ((check.gradient ? 2 : 0) + (check.range ? 1 : 0)), 0);
+ if (notMeasured > 0 || reads + cost > budget) {
+ notMeasured++;
+ continue;
+ }
+ reads += cost;
+ matchedNodes++;
+ const affected = { node: node.getName(), nodePath };
+ if (check.primitives) {
+ const limit = "exactly" in check.primitives ? check.primitives.exactly : check.primitives.max;
+ const fails = "exactly" in check.primitives ? primitives.length !== limit : primitives.length > limit;
+ if (fails)
+ report("HOST_VALIDATION_PRIMITIVE_COUNT", "primitives", `${node.getName()} has ${primitives.length} primitive(s) in the final GLB; the host expects ${"exactly" in check.primitives ? "exactly" : "at most"} ${limit}. Each material group exports as its own primitive.`, {
+ affected,
+ measurement: {
+ actual: primitives.length,
+ expected: limit
+ }
+ });
+ }
+ primitives.forEach((primitive, index) => {
+ const where = `${node.getName()} primitive ${index}`;
+ for (const semantic of check.attributes ?? []) {
+ if (primitive.getAttribute(semantic))
+ continue;
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "attributes", `${where} has no ${semantic} attribute.`, {
+ affected: { ...affected, attribute: semantic },
+ measurement: { actual: false, expected: true }
+ });
+ }
+ if (check.gradient) {
+ const outcome = measureGradient(primitive, check.gradient);
+ if (outcome.kind === "missing")
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "gradient", `${where} cannot be measured: ${outcome.reason}.`, {
+ affected: { ...affected, attribute: outcome.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else if (outcome.kind === "unmeasured") {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "gradient", `${where} has no extent along ${check.gradient.axis}; the gradient is unmeasured.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: { actual: null }
+ }, "observe");
+ } else if (outcome.failures.length > 0)
+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: {
+ actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,
+ expected: `${check.gradient.from}..${check.gradient.to}`,
+ threshold: check.gradient.tolerance,
+ breakdown: {
+ fromMean: round2(outcome.fromMean),
+ toMean: round2(outcome.toMean),
+ worstRegression: round2(outcome.worstRegression)
+ }
+ }
+ });
+ }
+ if (check.range) {
+ const accessor = primitive.getAttribute(check.range.attribute);
+ if (!accessor || check.range.component >= accessor.getElementSize())
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "range", `${where} has no ${check.range.attribute}[${check.range.component}].`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else {
+ const element = [];
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0;i < accessor.getCount(); i++) {
+ const value = component(accessor, i, check.range.component, element);
+ if (value < min)
+ min = value;
+ if (value > max)
+ max = value;
+ }
+ const { tolerance } = check.range;
+ if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))
+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: {
+ actual: `${round2(min)}..${round2(max)}`,
+ expected: `${check.range.min}..${check.range.max}`,
+ threshold: tolerance
+ }
+ });
+ }
+ }
+ if (check.material) {
+ const material = primitive.getMaterial();
+ const label = material?.getName() || (material ? `materials[${doc.getRoot().listMaterials().indexOf(material)}]` : "(glTF default)");
+ const alphaMode = material?.getAlphaMode() ?? "OPAQUE";
+ const doubleSided = material?.getDoubleSided() ?? false;
+ if (check.material.alphaMode !== undefined && alphaMode !== check.material.alphaMode)
+ report("HOST_VALIDATION_MATERIAL_ALPHA_MODE", "material", `${where} uses alphaMode ${alphaMode}; the host expects ${check.material.alphaMode}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: alphaMode,
+ expected: check.material.alphaMode
+ }
+ });
+ if (check.material.doubleSided !== undefined && doubleSided !== check.material.doubleSided)
+ report("HOST_VALIDATION_MATERIAL_DOUBLE_SIDED", "material", `${where} is ${doubleSided ? "double-sided" : "single-sided"}; the host expects ${check.material.doubleSided ? "double-sided" : "single-sided"}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: doubleSided,
+ expected: check.material.doubleSided
+ }
+ });
+ }
+ });
+ }
+ for (const [code, entry] of omitted)
+ push(code, entry.assertion, `${entry.count} more ${code} finding(s) omitted after the first ${MAX_VALIDATION_FINDINGS_PER_CODE}.`, { actual: entry.count, breakdown: { omitted: entry.count } }, undefined, entry.disposition);
+ }
+ if (notMeasured > 0) {
+ complete = false;
+ findings.push({
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation stopped at its ${budget} attribute-read budget; ${notMeasured} matched node(s) were not measured.`,
+ measurement: {
+ name: "checks.*.budget",
+ actual: reads,
+ threshold: budget,
+ breakdown: { nodesNotMeasured: notMeasured }
+ }
+ });
+ }
return {
- advice: {
- optional: true,
- materialMerges: [...candidates],
- projectedMaterials: projected.uniqueMaterials,
- projectedGrade
- },
- summary,
- reasons
+ findings,
+ complete,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: matchedNodes,
+ hostValidationAttributeReads: reads,
+ hostValidationComplete: complete
+ }
};
}
-function gradeInstanceability(metrics, opts = {}) {
- const m = metrics;
- const band = materialBand(m.uniqueMaterials);
- let grade = band.grade;
- const materials = `${counted(m.uniqueMaterials, "distinct material", "distinct materials")} (${band.grade} at ${band.range})`;
- const transparency = m.transparentMaterials > 0 ? counted(m.transparentMaterials, "transparent material", "transparent materials") : undefined;
- const textures = m.textureCount > 4 ? `${m.textureCount} textures` : undefined;
- const drivers = [];
- const also = [];
- if ((grade === "A" || grade === "B") && (transparency || textures)) {
- grade = "C";
- if (transparency)
- drivers.push(`${transparency} (lowers A/B to C)`);
- if (textures)
- drivers.push(`${textures} (over 4 lowers A/B to C)`);
- also.push(materials);
- } else {
- drivers.push(materials);
- if (transparency)
- also.push(`${transparency} (lowers only A/B to C)`);
- if (textures)
- also.push(`${textures} (over 4 lowers only A/B to C)`);
+function measureGradient(primitive, gradient) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ return {
+ kind: "missing",
+ attribute: "POSITION",
+ reason: "no POSITION attribute"
+ };
+ const values = primitive.getAttribute(gradient.attribute);
+ if (!values || gradient.component >= values.getElementSize())
+ return {
+ kind: "missing",
+ attribute: gradient.attribute,
+ reason: `no ${gradient.attribute}[${gradient.component}]`
+ };
+ const count = Math.min(position.getCount(), values.getCount());
+ const axis = AXIS_INDEX[gradient.axis[1]];
+ const sign = gradient.axis[0] === "-" ? -1 : 1;
+ const t = new Float64Array(count);
+ const v = new Float64Array(count);
+ const element = [];
+ let tMin = Infinity;
+ let tMax = -Infinity;
+ for (let i = 0;i < count; i++) {
+ t[i] = sign * component(position, i, axis, element);
+ v[i] = component(values, i, gradient.component, element);
+ if (t[i] < tMin)
+ tMin = t[i];
+ if (t[i] > tMax)
+ tMax = t[i];
+ }
+ if (!(tMax - tMin >= MIN_AXIS_EXTENT))
+ return { kind: "unmeasured" };
+ const sums = new Float64Array(GRADIENT_BINS);
+ const counts = new Uint32Array(GRADIENT_BINS);
+ let fromSum = 0;
+ let fromCount = 0;
+ let toSum = 0;
+ let toCount = 0;
+ for (let i = 0;i < count; i++) {
+ const s = (t[i] - tMin) / (tMax - tMin);
+ if (s <= ENDPOINT_BAND) {
+ fromSum += v[i];
+ fromCount++;
+ }
+ if (s >= 1 - ENDPOINT_BAND) {
+ toSum += v[i];
+ toCount++;
+ }
+ const bin = Math.min(GRADIENT_BINS - 1, Math.floor(s * GRADIENT_BINS));
+ sums[bin] = sums[bin] + v[i];
+ counts[bin] = counts[bin] + 1;
+ }
+ const fromMean = fromSum / fromCount;
+ const toMean = toSum / toCount;
+ const direction = Math.sign(gradient.to - gradient.from);
+ let worstRegression = 0;
+ let previous;
+ for (let bin = 0;bin < GRADIENT_BINS; bin++) {
+ if (counts[bin] === 0)
+ continue;
+ const mean = sums[bin] / counts[bin];
+ if (previous !== undefined)
+ worstRegression = Math.max(worstRegression, (previous - mean) * direction);
+ previous = mean;
}
- also.push(counted(m.uniqueGeometries, "geometry", "geometries"), counted(m.drawCalls, "draw call", "draw calls"));
- if (m.skinned)
- also.push("skinned (clone-rendered, not penalized)");
- const setBy = drivers.join(" and ");
- const reasons = [
- `grade ${grade} set by ${setBy}`,
- `${m.uniqueMaterials} material${m.uniqueMaterials === 1 ? "" : "s"}, ` + `${m.uniqueGeometries} geometr${m.uniqueGeometries === 1 ? "y" : "ies"}, ` + `${m.drawCalls} draw call${m.drawCalls === 1 ? "" : "s"}`
+ const failures = [];
+ if (Math.abs(fromMean - gradient.from) > gradient.tolerance || Math.abs(toMean - gradient.to) > gradient.tolerance)
+ failures.push("endpoints");
+ if (gradient.monotonic && worstRegression > gradient.tolerance)
+ failures.push("monotonic");
+ return { kind: "measured", fromMean, toMean, worstRegression, failures };
+}
+async function evaluateValidationProfileGlb(profile, bytes, options = {}) {
+ let doc;
+ try {
+ doc = await createGltfIO().readBinary(bytes);
+ } catch (error) {
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ return {
+ findings: [
+ {
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation could not read the final GLB: ${error instanceof Error ? error.message : String(error)}`,
+ measurement: { name: "checks.*.read", actual: null }
+ }
+ ],
+ complete: false,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: 0,
+ hostValidationAttributeReads: 0,
+ hostValidationComplete: false
+ }
+ };
+ }
+ return evaluateValidationProfileDocument(profile, doc, options);
+}
+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;
+var init_validation_profile2 = __esm(() => {
+ init_gltf_io();
+ init_delivery_inspect();
+ init_validation_profile();
+ init_registry();
+ HOST_VALIDATION_QA_RULE = Object.freeze({
+ id: HOST_VALIDATION_RULE_ID,
+ profile: "host.validation-profile",
+ scope: { kind: "universal" },
+ ruleClass: "exact",
+ owner: KILN_ENGINE_QA_OWNER,
+ promotion: conformancePromotionAuthorization("host-validation-profile-v1", "src/qa/validation-profile.test.ts", "b6b60fcbba0238688cb0d3ef497fa3ed837757422b43207f18fc8cbe0a412ffc", KILN_ENGINE_QA_OWNER, "2026-10-22T00:00:00.000Z", "enforce", "cpu-raster:1.3.1"),
+ defaultMode: "enforce",
+ evaluate: () => []
+ });
+ AXIS_INDEX = { X: 0, Y: 1, Z: 2 };
+});
+
+// src/qa/requirements-report.ts
+function createRequirementsQaReport(context, options) {
+ const applicability = resolveRequirementsApplicability(context.requirements);
+ const unevaluatedRequirements = [
+ ...applicability.unevaluatedRequirements,
+ ...sceneMeasurementGaps(context.requirements, options.findings ?? [])
];
- if (transparency)
- reasons.push(`${m.transparentMaterials} transparent material(s) force per-object sort`);
- if (textures)
- reasons.push(`${m.textureCount} textures (consider atlasing)`);
- if (m.skinned)
- reasons.push("skinned/animated — clone-rendered (not statically GPU-instanced); fine at low counts");
- if (opts.category)
- reasons.push(`category: ${opts.category}`);
- const summary = `${grade} (informational, not a QA verdict), set by ${setBy}. Also: ${also.join("; ")}.`;
- if (!opts.mergeCandidates?.length)
- return { grade, summary, reasons, metrics: m };
- const merge = mergeAdvice(m, opts.mergeCandidates);
+ const executed = new Set(options.executedRules);
+ const rules = applicability.rules.map((rule) => ({
+ id: rule.id,
+ mode: options.modes?.[rule.id] ?? rule.mode,
+ status: rule.status === "evaluate" ? executed.has(rule.id) ? "evaluated" : "notEvaluated" : rule.status,
+ ...rule.reason ? { reason: rule.reason } : {}
+ }));
+ const incomplete = unevaluatedRequirements.length > 0 || applicability.rules.some((rule) => rule.status === "evaluate" && !(rule.mode === "observe" && rule.keys.length === 0) && (!executed.has(rule.id) || (options.modes?.[rule.id] ?? rule.mode) === "off" || rule.mode === "enforce" && (options.modes?.[rule.id] ?? rule.mode) !== "enforce"));
+ const findings = (options.findings ?? []).map((finding) => ({
+ ...finding,
+ dimension: finding.dimension === "categoryReadiness" ? "requirementReadiness" : finding.dimension
+ }));
+ const evaluated = new Set(options.evaluatedDimensions ?? ["exportIntegrity", "requirementReadiness"]);
+ for (const finding of findings)
+ evaluated.add(finding.dimension);
+ const dimensions = Object.fromEntries(REQUIREMENTS_QA_DIMENSIONS.map((dimension) => {
+ const selected = findings.filter((finding) => finding.dimension === dimension);
+ const partialObservation = selected.some((finding) => finding.code === "GEO_PART_SELF_INTERSECTION_UNMEASURED" || finding.code === "GEO_PART_SELF_INTERSECTION_TRUNCATED" || finding.code === "GEO_PART_SELF_INTERSECTION_ACKNOWLEDGED");
+ const status = selected.some((f) => f.disposition === "block") ? "block" : partialObservation || !evaluated.has(dimension) || dimension === "requirementReadiness" && incomplete ? "notEvaluated" : selected.some((f) => f.disposition === "warn") ? "warn" : "pass";
+ return [
+ dimension,
+ {
+ status,
+ findings: selected,
+ ...options.metrics?.[dimension] ? { metrics: options.metrics[dimension] } : {}
+ }
+ ];
+ }));
+ const blocked = findings.some((f) => f.disposition === "block");
+ const warned = findings.some((f) => f.disposition === "warn");
return {
- grade,
- summary: summary + merge.summary,
- reasons: [...reasons, ...merge.reasons],
- metrics: m,
- advice: merge.advice
+ kind: "kiln.asset-qa-report",
+ schemaVersion: 2,
+ qaProfile: "asset.requirements.v1",
+ policyHash: context.policyHash,
+ adviceHash: context.adviceHash,
+ acceptance: blocked ? "blocked" : incomplete ? "incomplete" : "accepted",
+ disposition: blocked ? "block" : incomplete ? "notEvaluated" : warned ? "warn" : "pass",
+ dimensions,
+ rules,
+ unevaluatedRequirements
};
}
-var MATERIAL_GRADE_BANDS, counted = (n, one, many) => `${n} ${n === 1 ? one : many}`, materialBand = (materials) => MATERIAL_GRADE_BANDS.find((b) => materials <= b.max), lowersToC = (m) => m.transparentMaterials > 0 || m.textureCount > 4, MERGE_PARTS_KEPT = 8, MERGE_FACTORS, extensionNames = (property) => property.listExtensions().map((extension) => extension.extensionName).sort();
-var init_metrics = __esm(() => {
- MATERIAL_GRADE_BANDS = [
- { grade: "A", max: 1, range: "0-1" },
- { grade: "B", max: 3, range: "2-3" },
- { grade: "C", max: 6, range: "4-6" },
- { grade: "D", max: 12, range: "7-12" },
- { grade: "F", max: Number.POSITIVE_INFINITY, range: "13+" }
- ];
- MERGE_FACTORS = [
- ["baseColorFactor", (m) => m.getBaseColorFactor()],
- ["emissiveFactor", (m) => m.getEmissiveFactor()],
- ["metallicFactor", (m) => m.getMetallicFactor()],
- ["roughnessFactor", (m) => m.getRoughnessFactor()],
- ["normalScale", (m) => m.getNormalScale()],
- ["occlusionStrength", (m) => m.getOcclusionStrength()]
+var REQUIREMENTS_QA_DIMENSIONS;
+var init_requirements_report = __esm(() => {
+ init_requirements_applicability();
+ init_types();
+ REQUIREMENTS_QA_DIMENSIONS = [
+ "exportIntegrity",
+ "requirementReadiness",
+ "promptAlignment",
+ "visualQuality",
+ "runtimeCost"
];
});
-// src/written-nodes.ts
-function exportedRoot(doc, purpose) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- const top = scene?.listChildren() ?? [];
- if (top.length !== 1)
- throw new Error(`${purpose} expects the exporter to write one root node.`);
- return top[0];
+// src/qa/reference-comparison.ts
+function isEvidence(value) {
+ if (typeof value !== "object" || value === null)
+ return false;
+ const candidate = value;
+ return candidate.schemaVersion === 1 && typeof candidate.silhouetteIoU === "number" && typeof candidate.colorAgreement === "number" && typeof candidate.reference === "object" && typeof candidate.rendered === "object";
}
-function writtenNodeResolver(root, doc, purpose) {
- const top = exportedRoot(doc, purpose);
- return (node) => {
- const path = [];
- for (let current = node;current !== root; current = current.parent) {
- if (!current.parent)
- throw new Error(`${purpose}: ${node.name} is outside the asset root.`);
- path.unshift(current.parent.children.indexOf(current));
- }
- let target = top;
- for (const index of path)
- target = target?.listChildren()[index];
- if (!target || (target.getName() || "") !== (node.name || ""))
- throw new Error(`${purpose} could not find the written node for ${JSON.stringify(node.name)}.`);
- return target;
- };
+function referenceComparisonFindings(evidence, profile) {
+ if (evidence.reference.coverage <= 0 || evidence.rendered.coverage <= 0)
+ return [];
+ const findings = [];
+ if (evidence.silhouetteIoU < SILHOUETTE_IOU_OBSERVE) {
+ findings.push({
+ code: "REF_SILHOUETTE_AGREEMENT",
+ disposition: "observe",
+ dimension: "promptAlignment",
+ profile,
+ message: `The asset's outline agrees with the reference image on ${(evidence.silhouetteIoU * 100).toFixed(0)}% of ` + `its normalised silhouette. Shapes are compared after cropping each to its own bounding box, so this is ` + `about proportion and outline, not about framing or distance.`,
+ measurement: {
+ name: "silhouetteIoU",
+ actual: evidence.silhouetteIoU,
+ threshold: SILHOUETTE_IOU_OBSERVE
+ },
+ repairText: "Compare the reference against the rendered views and adjust the overall proportions — the outline is the part that disagrees, not the detail."
+ });
+ }
+ if (evidence.colorAgreement < COLOR_AGREEMENT_OBSERVE) {
+ findings.push({
+ code: "REF_COLOR_AGREEMENT",
+ disposition: "observe",
+ dimension: "promptAlignment",
+ profile,
+ message: `The asset's average colour is far from the reference image's ` + `(agreement ${(evidence.colorAgreement * 100).toFixed(0)}%). This is a coarse whole-subject average, so it ` + `catches a wrong palette rather than a wrong detail.`,
+ measurement: {
+ name: "colorAgreement",
+ actual: evidence.colorAgreement,
+ threshold: COLOR_AGREEMENT_OBSERVE
+ },
+ repairText: "Set the base colours from the reference image rather than from the prompt wording, then re-render."
+ });
+ }
+ return findings;
}
+var SILHOUETTE_IOU_OBSERVE = 0.55, COLOR_AGREEMENT_OBSERVE = 0.5, REFERENCE_COMPARISON_QA_RULE;
+var init_reference_comparison = __esm(() => {
+ init_registry();
+ REFERENCE_COMPARISON_QA_RULE = Object.freeze({
+ id: "REF_COMPARISON",
+ profile: "reference.comparison",
+ scope: { kind: "universal" },
+ ruleClass: "heuristic",
+ owner: KILN_ENGINE_QA_OWNER,
+ defaultMode: "observe",
+ evaluate(context) {
+ const evidence = context.derivedEvidence?.["referenceComparison"];
+ if (!isEvidence(evidence))
+ return [];
+ return referenceComparisonFindings(evidence, "reference.comparison");
+ }
+ });
+});
-// src/lod-export.ts
-import { PropertyType as PropertyType2 } from "@gltf-transform/core";
-function applyLodChains(root, sets, doc) {
- if (sets.length === 0)
- return;
- const exported = writtenNodeResolver(root, doc, "LOD export");
- const chains = sets.map((set) => ({
- set,
- parent: exported(set.parent),
- levels: set.levels.map(exported)
+// src/qa/run.ts
+function gltfReportFindings(report, profile) {
+ return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
+ code: `GLTF_${issue.code}`.replace(/[^A-Z0-9_]/g, "_"),
+ disposition: issue.severity === 0 ? "block" : "warn",
+ dimension: "exportIntegrity",
+ profile,
+ message: issue.message,
+ ...issue.pointer ? { affected: { nodePath: issue.pointer } } : {}
}));
- const extension = doc.createExtension(MSFTLod);
- for (const { set, parent, levels } of chains) {
- const [base, ...lower] = levels;
- const lod = extension.createLod();
- for (const level of lower) {
- parent.removeChild(level);
- lod.addLevel(level);
- }
- base.setExtension(MSFT_LOD, lod);
- base.setExtras({ ...base.getExtras(), [MSFT_SCREENCOVERAGE]: [...set.screenCoverage] });
- }
-}
-function occurrence(siblings, index, name) {
- let count = 0;
- for (let i = 0;i < index; i++)
- if (siblings[i].getName() === name)
- count++;
- return count;
-}
-function screenCoverageOf(node) {
- const value = node.getExtras()[MSFT_SCREENCOVERAGE];
- return Array.isArray(value) && value.every((item) => typeof item === "number") ? [...value] : undefined;
}
-function listLodChainNodes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const chains = [];
- const visit = (siblings, parentPath) => {
- siblings.forEach((node, index) => {
- const at = (name) => `${parentPath}${segment2(name, occurrence(siblings, index, name))}`;
- const path = at(node.getName());
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType2.NODE);
- if (lower.length > 0)
- chains.push({
- levels: [node, ...lower],
- paths: [path, ...lower.map((level) => at(level.getName()))]
- });
- visit(node.listChildren(), path);
- });
- };
- visit(scene.listChildren(), segment2(scene.getName() || "Scene", 0));
- return chains;
+function isExpectedKtx2ValidatorLimitation(report, issue) {
+ const required = report.info?.["extensionsRequired"];
+ if (!Array.isArray(required) || !required.includes("KHR_texture_basisu"))
+ return false;
+ if (issue.code === "VALUE_NOT_IN_LIST") {
+ return /^\/images\/\d+\/mimeType$/.test(issue.pointer ?? "") && issue.message === "Invalid value 'image/ktx2'. Valid values are ('image/jpeg', 'image/png').";
+ }
+ return issue.code === "IMAGE_UNRECOGNIZED_FORMAT" && /^\/images\/\d+$/.test(issue.pointer ?? "") && issue.message === "Image format not recognized.";
}
-function isImpostorLevel(node) {
- const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
- return roles.includes(KILN_SEMANTIC_ROLES.lodImpostor);
+function qaPolicyFromEnv(env = process.env) {
+ const mode = env["KILN_QA_MODE"];
+ return mode === "observe" || mode === "off" ? { defaultMode: mode } : {};
}
-function summarizeLodChains(doc) {
- return listLodChainNodes(doc).map(({ levels, paths }) => {
- const screenCoverage = screenCoverageOf(levels[0]);
- return {
- path: paths[0],
- ...screenCoverage ? { screenCoverage } : {},
- levels: levels.map((level, number) => ({
- level: number,
- name: level.getName(),
- path: paths[number],
- triangles: drawnNodeTriangles(level),
- ...number > 0 && isImpostorLevel(level) ? { impostor: true } : {}
- }))
- };
- });
+function qaBlockingEnabled(env = process.env) {
+ const mode = env["KILN_QA_MODE"];
+ return mode !== "observe" && mode !== "off";
}
-var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment2 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
-var init_lod_export = __esm(() => {
- init_semantic();
- init_gltf_io();
- init_metrics();
+var DETERMINISTIC_QA_REGISTRY, MAX_DETAILED_BLOCKERS = 6, AssetQaBlockedError;
+var init_run = __esm(() => {
+ init_material();
+ init_architecture();
+ init_character2();
+ init_character_advisory();
+ init_vehicle2();
+ init_vegetation();
+ init_prop();
+ init_part_connectivity();
+ init_reference_comparison();
+ init_self_intersection();
+ init_sweep();
+ init_environment2();
+ init_breadth2();
+ init_breadth_evidence();
+ init_registry();
+ init_types();
+ init_universal();
+ init_validation_profile2();
+ DETERMINISTIC_QA_REGISTRY = new QaRegistry([
+ ...UNIVERSAL_QA_RULES,
+ MATERIAL_QA_RULE,
+ ...ARCHITECTURE_QA_RULES,
+ CHARACTER_QA_RULE,
+ CHARACTER_ADVISORY_QA_RULE,
+ ...VEHICLE_QA_RULES,
+ ...VEGETATION_QA_RULES,
+ ...PROP_QA_RULES,
+ ...ENVIRONMENT_QA_RULES,
+ ...W7_BREADTH_QA_RULES,
+ SELF_INTERSECTION_QA_RULE,
+ SWEEP_QA_RULE,
+ PART_CONNECTIVITY_QA_RULE,
+ REFERENCE_COMPARISON_QA_RULE,
+ HOST_VALIDATION_QA_RULE
+ ]);
+ AssetQaBlockedError = class AssetQaBlockedError extends Error {
+ report;
+ stage;
+ gltfValidation;
+ constructor(report, stage, gltfValidation) {
+ const blockers = Object.values(report.dimensions).flatMap((dimension) => dimension.findings).filter((finding) => finding.disposition === "block");
+ const detailed = blockers.slice(0, MAX_DETAILED_BLOCKERS).map((finding) => `${finding.code}: ${finding.message}${finding.affected ? ` AFFECTED: ${JSON.stringify(finding.affected)}` : ""}${finding.repairText ? ` FIX: ${finding.repairText}` : ""}`);
+ const overflow = blockers.length > MAX_DETAILED_BLOCKERS ? ` (+${blockers.length - MAX_DETAILED_BLOCKERS} more blockers)` : "";
+ super(`Asset QA blocked at ${stage}: ${detailed.join(" | ") || "unknown blocker"}${overflow}`);
+ this.name = "AssetQaBlockedError";
+ this.report = report;
+ this.stage = stage;
+ this.gltfValidation = gltfValidation;
+ }
+ };
});
-// src/node-visibility.ts
-import { KHRNodeVisibility } from "@gltf-transform/extensions";
-import * as THREE23 from "three";
-function applyNodeVisibility(root, doc) {
- const hidden = [];
- root.traverse((node) => {
- if (node.visible === false)
- hidden.push(node);
- });
- if (hidden.length === 0)
- return;
- const written = hidden.map(writtenNodeResolver(root, doc, "Visibility export"));
- const extension = doc.createExtension(KHRNodeVisibility);
- for (const node of written)
- node.setExtension(KHR_NODE_VISIBILITY, extension.createVisibility().setVisible(false));
+// src/qa/requirements-run.ts
+import { Object3D as Object3D15 } from "three";
+function sceneDecisions(context, policy) {
+ const applicable = new Set(resolveRequirementsApplicability(context.requirements).rules.filter((rule) => rule.status === "evaluate").map((rule) => rule.id));
+ return new QaRegistry(registry.list().filter((rule) => applicable.has(rule.id))).describePolicy(policy);
}
-function summarizeHiddenNodes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const found = [];
- const visit = (siblings, parentPath) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment3(name, occurrence)}`;
- if (isHiddenGltfNode(node))
- found.push({ path, name, triangles: nodeTriangles(node) });
- else
- visit(node.listChildren(), path);
+async function collectRequirementsSceneEvidence(context, scene, policy = {}) {
+ if (!(scene instanceof Object3D15) || !sceneDecisions(context, policy).some((d) => d.ruleId === SELF_INTERSECTION_QA_RULE.id && d.mode !== "off"))
+ return {};
+ try {
+ return { partPenetration: await analyzePartPenetration(scene) };
+ } catch {
+ return { partPenetrationFailed: true };
+ }
+}
+function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {}) {
+ const needs = context.requirements.requirements;
+ const parts = needs.parts?.state === "requested" ? needs.parts.value.required : [];
+ const animation = needs.animation?.state === "requested" ? needs.animation.value : undefined;
+ const rig = needs.rig?.state === "requested" ? needs.rig.value : undefined;
+ const requiredClips = [
+ ...new Set([...animation?.clips ?? [], ...rig?.clips?.map((clip) => clip.name) ?? []])
+ ];
+ const tangents = needs.representation?.state === "requested" && needs.representation.value.precomputedTangents === true;
+ const findings = [];
+ const decisions = sceneDecisions(context, policy);
+ const geometryMetrics = {};
+ const mobilityInput = {
+ scene,
+ mobility: needs.mobility?.state === "requested" ? needs.mobility.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const mobilityFindings = mobilityInput.mobility && decisions.some((d) => (d.ruleId === "VEHICLE_PROFILE" || d.ruleId === "VEHICLE_ADVISORY_PROFILE") && d.mode !== "off") ? inspectMobility(mobilityInput) : [];
+ const executedRules = [];
+ const rigInput = {
+ scene,
+ clips,
+ rig,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const foliageInput = {
+ scene,
+ foliage: needs.foliage?.state === "requested" ? needs.foliage.value : undefined,
+ materialMode: needs.material?.state === "requested" ? needs.material.value.mode : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY : undefined
+ };
+ const effects = needs.effects?.state === "requested" ? needs.effects.value : undefined;
+ const scope = context.requirements.scope;
+ const scopeObservation = scope?.state === "requested" && scene instanceof Object3D15 && decisions.some((d) => d.ruleId === ASSET_SCOPE_QA_RULE.id && d.mode !== "off") ? analyzeAssetScopeObservationV1(scene) : undefined;
+ const effectsInput = {
+ effects,
+ derivedEvidence: {
+ source: "engine-scene-analysis",
+ ...effects && scene instanceof Object3D15 && decisions.some((d) => d.ruleId.startsWith("VFX_") && d.mode !== "off") ? { vfxArtifact: analyzeVfxArtifactEvidenceV1(effects, scene, clips) } : {}
}
};
- visit(scene.listChildren(), segment3(scene.getName() || "Scene", 0));
- return found;
-}
-function drawnSceneBounds(scene) {
- const min = [Infinity, Infinity, Infinity];
- const max = [-Infinity, -Infinity, -Infinity];
- const visit = (node) => {
- if (isHiddenGltfNode(node))
- return;
- const mesh = node.getMesh();
- if (mesh) {
- const base = new THREE23.Matrix4().fromArray(node.getWorldMatrix());
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const countInstances = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < countInstances; i++) {
- const t = translation?.getElement(i, []) ?? [0, 0, 0];
- const r = rotation?.getElement(i, []) ?? [0, 0, 0, 1];
- const s = scale?.getElement(i, []) ?? [1, 1, 1];
- const localMatrix = new THREE23.Matrix4().compose(new THREE23.Vector3().fromArray(t), new THREE23.Quaternion().fromArray(r), new THREE23.Vector3().fromArray(s));
- matrices.push(base.clone().multiply(localMatrix).toArray());
- }
- const local = [0, 0, 0];
- for (const primitive of mesh.listPrimitives()) {
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const m of matrices)
- for (let i = 0;i < count; i++) {
- position.getElement(indices ? indices.getScalar(i) : i, local);
- const [x, y, z] = local;
- const world = [
- m[0] * x + m[4] * y + m[8] * z + m[12],
- m[1] * x + m[5] * y + m[9] * z + m[13],
- m[2] * x + m[6] * y + m[10] * z + m[14]
- ];
- for (let k = 0;k < 3; k++) {
- if (world[k] < min[k])
- min[k] = world[k];
- if (world[k] > max[k])
- max[k] = world[k];
- }
- }
+ const spatialInput = {
+ scene,
+ tileable: needs.tiling?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.tileable === true,
+ navigable: needs.navigation?.state === "requested" || needs.spatialLayout?.state === "requested" && needs.spatialLayout.value.navigable === true,
+ navigation: needs.navigation?.state === "requested" ? needs.navigation.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
+ };
+ const spatialFindings = decisions.some((d) => d.ruleId.startsWith("ENVIRONMENT_") && d.mode !== "off") ? [
+ ...inspectPlacementSockets(spatialInput),
+ ...inspectTileEdges(spatialInput),
+ ...inspectNavigationClearance(spatialInput),
+ ...inspectSpatialSupport(spatialInput)
+ ] : [];
+ const structureFindings = needs.structure?.state === "requested" && decisions.some((d) => d.ruleId.startsWith("ARCHITECTURE_") && d.mode !== "off") ? inspectStructure({
+ scene,
+ structure: needs.structure.value,
+ opening: needs.opening?.state === "requested"
+ }) : [];
+ for (const decision of decisions) {
+ if (decision.mode === "off")
+ continue;
+ if (decision.ruleId === SELF_INTERSECTION_QA_RULE.id) {
+ const volume = evidence.partPenetration;
+ if (volume) {
+ const acknowledged = volume.acknowledged?.length ?? 0;
+ const partial = volume.truncated || volume.skipped.length > 0 || acknowledged > 0;
+ if (!partial)
+ executedRules.push(decision.ruleId);
+ findings.push(...inspectPartPenetration(volume));
+ Object.assign(geometryMetrics, {
+ partVolumeCoverage: partial ? "partial" : "complete-static-pairs",
+ partVolumeScope: "Visible static closed mesh pairs, except alternates on different LOD levels; excludes intra-mesh intersections, motion, open surfaces and usable passage space. Positive overlap may be intentional.",
+ partVolumeEligibleParts: volume.partsAnalyzed,
+ partVolumeCandidatePairs: volume.candidatePairs,
+ partVolumeCandidatesLowerBound: volume.broadPhaseTruncated === true,
+ partVolumePairsTested: volume.pairsTested,
+ partVolumeUnmeasurablePairs: volume.pairsUnmeasurable,
+ partVolumePairsNotReached: volume.pairsNotReached,
+ partVolumeLodAlternatePairs: volume.pairsLodAlternates,
+ partVolumeSkipped: volume.skipped.length,
+ ...acknowledged > 0 ? {
+ partVolumeAcknowledgedParts: acknowledged,
+ partVolumeAcknowledgedPairs: volume.pairsUnmeasurableAcknowledged ?? 0
+ } : {}
+ });
+ } else if (evidence.partPenetrationFailed) {
+ findings.push({
+ code: "GEO_PART_SELF_INTERSECTION_UNMEASURED",
+ disposition: "observe",
+ dimension: "visualQuality",
+ profile: "geometry.selfIntersection",
+ message: "Part-volume analysis could not complete. Overlap and clearance remain unmeasured."
+ });
+ geometryMetrics.partVolumeCoverage = "unavailable";
}
+ continue;
}
- for (const child of node.listChildren())
- visit(child);
- };
- for (const node of scene.listChildren())
- visit(node);
- return { min, max };
-}
-var KHR_NODE_VISIBILITY = "KHR_node_visibility", segment3 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
-var init_node_visibility = __esm(() => {
- init_metrics();
-});
-
-// src/rig-export.ts
-function rigExtrasForExport(node) {
- const extras = {};
- for (const [key, validate] of [
- [KILN_CHARACTER_JOINT_EXTRAS_KEY, validateCharacterJointDescriptorV1],
- [KILN_CHARACTER_RIG_EXTRAS_KEY, validateCharacterRigGraphV1]
- ]) {
- const value = node.userData[key];
- if (value === undefined)
+ if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
+ continue;
+ if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)
+ continue;
+ if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
+ continue;
+ executedRules.push(decision.ruleId);
+ if (decision.ruleId === PROP_EXACT_QA_RULE.id) {
+ const measured = [
+ ...needs.articulation?.state === "requested" ? inspectArticulation({ scene }) : [],
+ ...needs.opening?.state === "requested" ? inspectContainerOpening({ scene }) : []
+ ];
+ for (const finding of measured)
+ findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
continue;
- const result = validate(value);
- if (!result.valid || !result.value) {
- throw new TypeError(`Invalid ${key} on node ${node.name || "<unnamed>"}: ${result.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ")}`);
}
- extras[key] = result.value;
+ const measured = decision.ruleId === SWEEP_QA_RULE.id ? inspectSweepGeometry(scene) : decision.ruleId === PART_CONNECTIVITY_QA_RULE.id ? inspectPartConnectivity(scene, needs.externalSupport?.state === "requested" ? needs.externalSupport.value.supports : undefined) : decision.ruleId === ASSET_SCOPE_QA_RULE.id && scope?.state === "requested" ? inspectAssetScope({
+ profile: "asset.requirements.v1",
+ scope: { schemaVersion: 1, scope: scope.value, explicit: true },
+ derivedEvidence: { source: "engine-scene-analysis", assetScope: scopeObservation }
+ }) : decision.ruleId === "CHARACTER_PROFILE" ? inspectRig(rigInput) : decision.ruleId === "CHARACTER_ADVISORY_PROFILE" ? inspectRigAdvisory(rigInput) : decision.ruleId === "VEGETATION_CONTACT_PROFILE" ? inspectFoliageContact(foliageInput) : decision.ruleId === "VEGETATION_ADVISORY_PROFILE" ? inspectFoliageAdvisory(foliageInput) : decision.ruleId === MATERIAL_QA_RULE.id ? inspectPortableSceneMaterials(scene, tangents) : decision.ruleId === "VFX_EXACT_PROFILE" ? inspectEffectsExact(effectsInput) : decision.ruleId === "VFX_ADVISORY_PROFILE" ? inspectEffectsAdvisory(effectsInput) : decision.ruleId === "ARCHITECTURE_PROFILE" ? structureFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ARCHITECTURE_ADVISORY_PROFILE" ? structureFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "ENVIRONMENT_EXACT_PROFILE" ? spatialFindings.filter((f) => f.disposition === "block") : decision.ruleId === "ENVIRONMENT_ADVISORY_PROFILE" ? spatialFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_PROFILE" ? mobilityFindings.filter((f) => f.disposition === "block") : decision.ruleId === "VEHICLE_ADVISORY_PROFILE" ? mobilityFindings.filter((f) => f.disposition !== "block") : decision.ruleId === "VEHICLE_W6_ADVISORY_PROFILE" ? inspectMobilityAdvisory(mobilityInput) : decision.ruleId === PROP_ADVISORY_QA_RULE.id ? inspectPlacement({
+ scene,
+ bounds: needs.bounds?.state === "requested" ? needs.bounds.value : undefined,
+ groundPlaneY: needs.grounding?.state === "requested" ? needs.grounding.value.planeY ?? 0 : undefined
+ }) : UNIVERSAL_QA_KERNELS[decision.ruleId]({
+ scene,
+ clips,
+ requiredParts: parts,
+ animation: { clips: requiredClips }
+ });
+ for (const finding of measured)
+ findings.push(decision.mode === "observe" || decision.mode === "warn" ? { ...finding, disposition: decision.mode } : finding);
}
- return extras;
-}
-var init_rig_export = __esm(() => {
- init_character();
-});
-
-// src/material-export.ts
-import { BackSide } from "three";
-function assertPortableMaterialSides(root) {
- root.traverse((node) => {
- const mesh = node;
- if (!mesh.isMesh && !node.isSprite)
- return;
- const materials = mesh.material;
- const used = Array.isArray(materials) ? [...new Set(mesh.geometry.groups.map((group) => group.materialIndex ?? 0))].map((index) => ({ material: materials[index], index })) : [{ material: materials, index: 0 }];
- for (const { material, index } of used) {
- if (!material || material.side !== BackSide)
- continue;
- throw new AuthoringDiagnosticError("EXPORT_MATERIAL_SIDE_UNSUPPORTED", `EXPORT_MATERIAL_SIDE_UNSUPPORTED ${node.name || "<unnamed part>"}: material ${material.name || `<slot ${index}>`} uses BackSide, which glTF cannot encode directly. Author inward-facing geometry with FrontSide, or choose DoubleSide when both faces are intended.`);
- }
+ return createRequirementsQaReport(context, {
+ findings,
+ executedRules,
+ modes: Object.fromEntries(decisions.map((x) => [x.ruleId, x.mode])),
+ metrics: {
+ ...Object.keys(geometryMetrics).length ? { visualQuality: geometryMetrics } : {},
+ ...scopeObservation ? {
+ promptAlignment: {
+ scopeTopLevelAssetRoots: scopeObservation.topLevelAssetRoots,
+ scopeReusableMemberCount: scopeObservation.reusableMemberCount,
+ scopeDressingSignalCount: scopeObservation.sceneDressingRoles.length
+ }
+ } : {}
+ },
+ ...scopeObservation ? {
+ evaluatedDimensions: ["exportIntegrity", "requirementReadiness", "promptAlignment"]
+ } : {}
});
}
-var init_material_export = __esm(() => {
- init_authoring_diagnostic();
-});
-
-// src/community-exporter.ts
-import * as THREE24 from "three";
-import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
-import { GLB_BUFFER } from "@gltf-transform/core";
-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 appendRequirementsQa(context, report, findings, metrics = {}, executedRules = []) {
+ const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
+ const merged = { ...priorMetrics };
+ for (const [dimension, value] of Object.entries(metrics ?? {}))
+ merged[dimension] = { ...priorMetrics[dimension], ...value };
+ return createRequirementsQaReport(context, {
+ findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
+ executedRules: [
+ ...report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ ...executedRules
+ ],
+ modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
+ evaluatedDimensions: [
+ ...new Set([
+ ...Object.entries(report.dimensions).filter(([, value]) => value.status !== "notEvaluated").map(([key]) => key),
+ ...Object.keys(metrics ?? {})
+ ])
+ ],
+ metrics: merged
+ });
}
-function cleanClone(source) {
- const shadow = Object.create(source);
- shadow.userData = {};
- return shadow.clone();
+async function appendRequirementsFinalQa(context, report, gltf, bytes, instanceability, metricsError, material, warnings = []) {
+ const gltfFindings = gltfReportFindings(gltf, report.qaProfile);
+ const findings = [
+ ...gltfFindings,
+ ...warnings.map((w) => ({
+ code: w.code,
+ disposition: "warn",
+ dimension: "runtimeCost",
+ profile: `${w.profile}.${w.tier}`,
+ message: `${w.message} ${w.advice}`,
+ measurement: w.measurement
+ }))
+ ];
+ if (metricsError)
+ findings.push({
+ code: "RUNTIME_COST_METRICS_FAILED",
+ disposition: "warn",
+ dimension: "runtimeCost",
+ profile: report.qaProfile,
+ message: `Runtime-cost metrics could not be computed: ${metricsError}`
+ });
+ const cost = {};
+ if (instanceability)
+ Object.assign(cost, {
+ instanceabilityGrade: instanceability.grade,
+ instanceabilitySummary: instanceability.summary,
+ ...instanceability.metrics
+ });
+ if (material)
+ Object.assign(cost, {
+ materialCount: material.materialCount,
+ opaqueMaterials: material.opaqueMaterials,
+ maskedMaterials: material.maskedMaterials,
+ blendedMaterials: material.blendedMaterials,
+ singleSidedMaterials: material.singleSidedMaterials,
+ doubleSidedMaterials: material.doubleSidedMaterials,
+ texturedMaterials: material.texturedMaterials,
+ materialExtensionCount: material.materialExtensionCount,
+ materialExtensionsUsed: material.materialExtensionsUsed.join(","),
+ imageCount: material.imageCount,
+ maxImageDimension: material.maxImageDimension,
+ decodedImageBytesRgba8: material.decodedImageBytesRgba8,
+ estimatedGpuBytesWithMipmaps: material.estimatedGpuBytesWithMipmaps,
+ blendedSurfaceAreaRatio: material.blendedSurfaceAreaRatio
+ });
+ let result = appendRequirementsQa(context, report, findings, {
+ exportIntegrity: {
+ gltfErrors: gltf.issues.numErrors,
+ gltfWarnings: gltfFindings.filter((x) => x.disposition === "warn").length
+ },
+ runtimeCost: cost
+ });
+ const effects = context.requirements.requirements.effects;
+ const rule = report.rules.find((r) => r.id === "VFX_EXACT_PROFILE");
+ if (effects?.state === "requested" && rule?.status === "evaluated" && rule.mode !== "off") {
+ const evidence = await analyzeFinalVfxGlbBytesV1(bytes);
+ const measured = inspectFinalEffects(effects.value, evidence);
+ const findings = rule.mode === "enforce" ? measured : measured.map((f) => ({
+ ...f,
+ disposition: rule.mode
+ }));
+ result = appendRequirementsQa(context, result, findings, {
+ exportIntegrity: finalEffectsMetrics(evidence)
+ });
+ }
+ const validation = context.requirements.requirements.validation;
+ const hostRule = report.rules.find((r) => r.id === HOST_VALIDATION_QA_RULE.id);
+ if (validation?.state === "requested" && hostRule && hostRule.status !== "notRequested" && hostRule.mode !== "off") {
+ const evaluation = await evaluateValidationProfileGlb(validation.value, bytes);
+ const findings = hostRule.mode === "enforce" ? evaluation.findings : evaluation.findings.map((f) => ({
+ ...f,
+ disposition: f.disposition === "observe" ? f.disposition : hostRule.mode
+ }));
+ result = appendRequirementsQa(context, result, findings, { requirementReadiness: evaluation.metrics }, evaluation.complete ? [HOST_VALIDATION_QA_RULE.id] : []);
+ }
+ return result;
}
-async function communitySceneDocument(root, clips, platform = browserPlatform, authorExtras, atlas = collectAtlasProvenance(root)) {
- assertPortableMaterialSides(root);
- const materials = new Map;
- const originalMaterials = new Map;
- const originalGeometries = new Map;
- const textures = new Map;
- const directImages = 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 THREE24.TextureSource(source.image);
- textures.set(source, copy);
- const bytes = source.userData["encoded"];
- if (bytes?.bytes) {
- if (!copy.flipY && (bytes.mime === "image/png" || bytes.mime === "image/jpeg"))
- directImages.set(copy, { bytes: bytes.bytes, mime: bytes.mime });
- encoded.push((async () => {
- copy.image = await platform.decode(bytes.bytes);
- Object.defineProperty(copy, "isDataTexture", { value: true });
- copy.format = THREE24.RGBAFormat;
- copy.type = THREE24.UnsignedByteType;
- })());
- }
- return copy;
+var registry;
+var init_requirements_run = __esm(() => {
+ init_breadth_evidence();
+ init_breadth2();
+ init_breadth_final();
+ init_registry();
+ init_universal();
+ init_material();
+ init_prop();
+ init_part_connectivity();
+ init_sweep();
+ init_self_intersection();
+ init_vehicle2();
+ init_vehicle_advisory();
+ init_vegetation();
+ init_character2();
+ init_character_advisory();
+ init_architecture();
+ init_environment2();
+ init_requirements_applicability();
+ init_validation_profile2();
+ init_requirements_report();
+ init_run();
+ registry = new QaRegistry([
+ ...UNIVERSAL_QA_RULES,
+ MATERIAL_QA_RULE,
+ PROP_EXACT_QA_RULE,
+ PROP_ADVISORY_QA_RULE,
+ PART_CONNECTIVITY_QA_RULE,
+ SELF_INTERSECTION_QA_RULE,
+ SWEEP_QA_RULE,
+ ...VEHICLE_QA_RULES,
+ ...ARCHITECTURE_QA_RULES,
+ ...ENVIRONMENT_QA_RULES,
+ ...VEGETATION_QA_RULES,
+ CHARACTER_QA_RULE,
+ CHARACTER_ADVISORY_QA_RULE,
+ VFX_EXACT_QA_RULE,
+ VFX_ADVISORY_QA_RULE,
+ ASSET_SCOPE_QA_RULE,
+ HOST_VALIDATION_QA_RULE
+ ]);
+});
+
+// src/qa/skin-integrity.ts
+import * as THREE24 from "three";
+function validAttribute(a, count, size) {
+ if (!a || a.itemSize !== size || a.count !== count || !Number.isSafeInteger(count) || count < 1)
+ return false;
+ if ("isInterleavedBufferAttribute" in a) {
+ return Number.isSafeInteger(a.data.stride) && a.data.stride >= size && Number.isSafeInteger(a.offset) && a.offset >= 0 && a.offset + size <= a.data.stride && (count - 1) * a.data.stride + a.offset + size <= a.array.length;
}
- function material(source) {
- const found = materials.get(source);
- if (found)
- return found;
- const copy = cleanClone(source);
- Object.assign(copy.userData, authorExtras?.material(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 THREE24.Texture)
- copy[key] = texture(value);
- }
- materials.set(source, copy);
- originalMaterials.set(copy, source);
- return copy;
+ return count * size <= a.array.length;
+}
+function finiteAffine(matrix) {
+ const e = matrix?.elements;
+ return !!e && e.length === 16 && [...e].every((v) => Number.isFinite(v) && Number.isFinite(Math.fround(v))) && Math.fround(e[3]) === 0 && Math.fround(e[7]) === 0 && Math.fround(e[11]) === 0 && Math.fround(e[15]) === 1;
+}
+function inspectSkinIntegrity(root) {
+ const result = {
+ schemaVersion: 1,
+ findings: [],
+ meshesChecked: 0,
+ verticesChecked: 0,
+ truncated: false,
+ bounds: []
+ };
+ const paths = new Map;
+ const pending = [[root, "", 0]];
+ while (pending.length) {
+ const [node, parent, sibling] = pending.pop();
+ if (paths.has(node))
+ continue;
+ const segment = `${(node.name || node.type).slice(0, 80)}[${sibling}]`;
+ const path = (parent ? `${parent}/${segment}` : segment).slice(-800);
+ paths.set(node, path);
+ for (let i = node.children.length - 1;i >= 0; i--)
+ pending.push([node.children[i], path, i]);
}
- 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 (!copy.matrixAutoUpdate)
- copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);
- if (source.isScene) {
- copy = new THREE24.Group;
- copy.copy(shadow, false);
- }
- if (source.isSprite) {
- const sprite = source;
- const geometry = new THREE24.PlaneGeometry(1, 1);
- geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
- geometry.rotateZ(sprite.material.rotation);
- const spriteMaterial = new THREE24.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
- });
- Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));
- originalMaterials.set(spriteMaterial, sprite.material);
- copy = new THREE24.Mesh(geometry, spriteMaterial);
- THREE24.Object3D.prototype.copy.call(copy, shadow, false);
- }
- Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));
- 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"]
- ]
- });
+ const worlds = new Map;
+ function world(node) {
+ const chain = [], seen = new Set;
+ let cursor = node;
+ while (cursor && !worlds.has(cursor)) {
+ if (seen.has(cursor))
+ return;
+ seen.add(cursor);
+ chain.push(cursor);
+ cursor = cursor.parent;
}
- if (source.isMesh) {
- const original = source;
- const mesh = copy;
- mesh.geometry = cleanClone(original.geometry);
- originalGeometries.set(mesh, original.geometry);
- mesh.material = Array.isArray(original.material) ? original.material.map(material) : material(original.material);
+ while (chain.length) {
+ const n = chain.pop();
+ const local = n.matrixAutoUpdate ? new THREE24.Matrix4().compose(n.position, n.quaternion, n.scale) : n.matrix.clone();
+ const parent = n.parent ? worlds.get(n.parent) : undefined;
+ const value = n.matrixWorldAutoUpdate === false ? n.matrixWorld.clone() : parent ? new THREE24.Matrix4().multiplyMatrices(parent, local) : local;
+ worlds.set(n, value);
}
- nodes.set(source, copy);
- for (const child of source.children)
- copy.add(node(child));
- return copy;
+ return worlds.get(node);
}
- const copy = node(root);
- for (const [source, target] of nodes) {
- if (!source.isSkinnedMesh)
+ for (const [node, nodePath] of paths) {
+ const mesh = node;
+ if (!mesh.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 canvasInputs = new Map;
- const canvasInput = (map) => {
- const raw = map?.image;
- if (!map || !raw?.data)
- return map;
- const found = canvasInputs.get(map);
- if (found)
- return found;
- const { data, width, height } = raw;
- const canvas = new OffscreenCanvas(width, height);
- const context = canvas.getContext("2d");
- if (!context)
- throw new Error("A 2D canvas is required to prepare export texture channels.");
- context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);
- const adapted = new THREE24.Texture().copy(map);
- adapted.source = new THREE24.TextureSource(canvas);
- canvasInputs.set(map, adapted);
- const direct = directImages.get(map);
- if (direct)
- directImages.set(adapted, direct);
- return adapted;
- };
- for (const material of materials.values()) {
- for (const [key, value] of Object.entries(material)) {
- if (value instanceof THREE24.Texture && value.flipY && value.image?.data)
- material[key] = canvasInput(value);
+ if (result.findings.length >= MAX_FINDINGS) {
+ result.truncated = true;
+ break;
}
- const standard = material;
- if (!standard.isMeshStandardMaterial)
+ result.meshesChecked++;
+ const start = result.findings.length;
+ const add = (code, message, attribute, measurement) => {
+ if (result.findings.length >= MAX_FINDINGS) {
+ result.truncated = true;
+ return;
+ }
+ result.findings.push({
+ code,
+ disposition: "block",
+ dimension: "exportIntegrity",
+ profile: "skin.source-integrity.v1",
+ message,
+ affected: { node: mesh.name.slice(0, 160), nodePath, ...attribute ? { attribute } : {} },
+ ...measurement ? { measurement } : {},
+ repairText: "Rebuild the named binding at its intended rest pose. Keep bone order, inverse bind matrices and four influence lanes aligned with every final vertex; unwrap or change topology before binding. Do not repair invalid indices by normalizing weights."
+ });
+ };
+ const skeleton = mesh.skeleton, bones = skeleton?.bones;
+ if (!bones?.length || !Array.isArray(bones)) {
+ add("SKIN_SKELETON", "Skinned mesh requires a nonempty skeleton in the exported hierarchy.");
continue;
- if (standard.metalnessMap !== standard.roughnessMap) {
- standard.metalnessMap = canvasInput(standard.metalnessMap);
- standard.roughnessMap = canvasInput(standard.roughnessMap);
}
- standard.normalMap = canvasInput(standard.normalMap);
- }
- 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);
+ const unique = new Set;
+ for (let joint = 0;joint < bones.length; joint++) {
+ const bone = bones[joint];
+ if (!bone?.isObject3D || !paths.has(bone) || unique.has(bone)) {
+ add("SKIN_JOINT_MEMBERSHIP", `Joint ${joint} (${JSON.stringify(bone?.name?.slice(0, 160) ?? "missing")}) must be a distinct node inside the exported hierarchy.`, `joints[${joint}]`);
}
- }
- cloned.tracks = cloned.tracks.filter((track) => {
- try {
- const binding = THREE24.PropertyBinding.parseTrackName(track.name);
- return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE24.PropertyBinding.findNode(copy, binding.nodeName) !== null;
- } catch {
- return false;
+ if (bone)
+ unique.add(bone);
+ if (!finiteAffine(skeleton.boneInverses?.[joint])) {
+ add("SKIN_INVERSE_BIND", `Joint ${joint} (${JSON.stringify(bone?.name?.slice(0, 160) ?? "missing")}) requires a finite affine inverse bind matrix.`, `boneInverses[${joint}]`);
}
- });
- return cloned;
- });
- const preservedImages = new Map;
- const exporter = new GLTFExporter().register(() => ({
- writeMesh(mesh, definition) {
- const geometry = originalGeometries.get(mesh);
- const binding = geometry && atlas.binding(geometry);
- if (binding)
- for (const primitive of definition.primitives)
- primitive.extras = { ...primitive.extras, kilnAtlasBinding: binding };
- },
- async writeMaterialAsync(material, definition) {
- const source = originalMaterials.get(material);
- if (!source)
- return;
- const bag = source;
- const pbr = definition.pbrMetallicRoughness;
- for (const [slot, info] of [
- ["map", pbr?.baseColorTexture],
- ["normalMap", definition.normalTexture],
- ["metalnessMap", pbr?.metallicRoughnessTexture],
- ["roughnessMap", pbr?.metallicRoughnessTexture],
- [
- "emissiveMap",
- definition.emissiveTexture
- ],
- ["aoMap", definition.occlusionTexture]
- ]) {
- const texture = bag[slot], ref = texture && atlas.texture(texture);
- if (ref && info) {
- const prior = info.extras?.["kilnAtlasReference"];
- if (prior && prior.id !== ref.id)
- throw new TypeError("Atlas channel packing requires one exact source identity.");
- info.extras = { ...info.extras, kilnAtlasReference: ref };
- }
+ if (result.truncated)
+ break;
+ }
+ if (!finiteAffine(mesh.bindMatrix) || !Number.isFinite(mesh.bindMatrix.determinant()) || mesh.bindMatrix.determinant() === 0 || ![THREE24.AttachedBindMode, THREE24.DetachedBindMode].includes(mesh.bindMode)) {
+ add("SKIN_BIND_MATRIX", "Mesh requires a finite invertible affine bind matrix and an attached or detached bind mode.", "bindMatrix");
+ }
+ const position = mesh.geometry?.getAttribute("position"), count = position?.count ?? 0;
+ const indices = mesh.geometry?.getAttribute("skinIndex"), weights = mesh.geometry?.getAttribute("skinWeight");
+ if (!validAttribute(position, count, 3) || !validAttribute(indices, count, 4) || indices.normalized || !validAttribute(weights, count, 4)) {
+ add("SKIN_ATTRIBUTES", "Skin requires xyz positions and four non-normalized joint indices and four weights per final vertex, backed by complete buffers.", "skinIndex/skinWeight");
+ continue;
+ }
+ const invalid = new Map;
+ const bad = (code, vertex, attribute) => {
+ const row = invalid.get(code);
+ if (row) {
+ if (row.last !== vertex)
+ row.count++;
+ row.last = vertex;
+ } else
+ invalid.set(code, { count: 1, first: vertex, last: vertex, attribute });
+ };
+ for (let vertex = 0;vertex < count; vertex++) {
+ let sum = 0;
+ for (let lane = 0;lane < 4; lane++) {
+ const index = indices.getComponent(vertex, lane), weight = weights.getComponent(vertex, lane);
+ if (!Number.isInteger(index) || index < 0 || index >= bones.length)
+ bad("SKIN_JOINT_INDEX", vertex, "skinIndex");
+ if (!Number.isFinite(weight) || weight < 0 || weight > 1)
+ bad("SKIN_WEIGHT_VALUE", vertex, "skinWeight");
+ sum += weight;
}
- },
- writeTexture(map, definition) {
- const direct = directImages.get(map);
- if (direct && typeof definition["source"] === "number")
- preservedImages.set(definition["source"], direct);
+ if (!Number.isFinite(sum) || Math.abs(sum - 1) > WEIGHT_TOLERANCE)
+ bad("SKIN_WEIGHT_SUM", vertex, "skinWeight");
}
- }));
- const bytes = await exporter.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 [index, original] of preservedImages) {
- const image = json.json.images?.[index];
- if (!image)
- throw new Error("The glTF converter lost a direct texture image.");
- const uri = `kiln-direct-image-${index}`;
- image.uri = uri;
- image.mimeType = original.mime;
- delete image.bufferView;
- json.resources[uri] = new Uint8Array(original.bytes);
- }
- for (const image of json.json.images ?? []) {
- if (image.mimeType !== "image/png" || image.bufferView === undefined)
+ result.verticesChecked += count;
+ for (const [code, row] of invalid) {
+ const why = code === "SKIN_JOINT_INDEX" ? "indices must address the skeleton, including zero-weight lanes" : code === "SKIN_WEIGHT_SUM" ? `weights must sum to one within ${WEIGHT_TOLERANCE}` : "weights must be finite values in [0,1]";
+ add(code, `Invalid ${row.attribute} at vertex range ${row.first}..${row.last} (${row.count} affected vertices): ${why}.`, row.attribute, {
+ name: "invalidSkinVertices",
+ actual: row.count,
+ expected: 0,
+ breakdown: { firstVertex: row.first, lastVertex: row.last }
+ });
+ }
+ if (result.findings.length !== start)
continue;
- const view = json.json.bufferViews[image.bufferView];
- const buffer = json.resources[json.json.buffers?.[view.buffer]?.uri ?? GLB_BUFFER];
- const start = view.byteOffset ?? 0;
- const png = buffer.subarray(start, start + view.byteLength);
- const data = new DataView(png.buffer, png.byteOffset, png.byteLength);
- for (let offset = 8;offset + 12 <= png.length; ) {
- const length = data.getUint32(offset), end = offset + length + 12;
- if (end > png.length)
- break;
- if (data.getUint32(offset + 4) === 1229278788 && length === 0) {
- if (png.length - end <= 3 && png.subarray(end).every((byte) => byte === 0))
- view.byteLength = end;
+ const meshWorld = world(mesh);
+ if (!finiteAffine(meshWorld)) {
+ add("SKIN_POSE_TRANSFORM", "Current mesh world transform must be finite and affine.");
+ continue;
+ }
+ const inverse = mesh.bindMode === THREE24.AttachedBindMode ? meshWorld.clone().invert() : mesh.bindMatrix.clone().invert();
+ const matrices = [];
+ for (let joint = 0;joint < bones.length; joint++) {
+ const boneWorld = world(bones[joint]);
+ if (!finiteAffine(boneWorld)) {
+ add("SKIN_POSE_TRANSFORM", `Current transform for joint ${joint} must be finite and affine.`, `joints[${joint}]`);
break;
}
- offset = end;
+ matrices.push(new THREE24.Matrix4().multiplyMatrices(boneWorld, skeleton.boneInverses[joint]).multiply(mesh.bindMatrix));
}
- }
- for (const binding of json.json.textures ?? []) {
- if (binding.source === undefined || !binding.name)
+ if (result.findings.length !== start)
continue;
- const image = json.json.images?.[binding.source];
- if (image && !image.name)
- image.name = binding.name;
- }
- const document = await io.readJSON(json);
- if (atlas.table) {
- const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
- scene.setExtras({ ...scene.getExtras(), kilnAtlasProvenance: atlas.table });
- await refreshAtlasDocumentProvenance(document);
+ const base = new THREE24.Vector3, posed = new THREE24.Vector3, temp = new THREE24.Vector3, box = new THREE24.Box3;
+ for (let vertex = 0;vertex < count; vertex++) {
+ THREE24.Mesh.prototype.getVertexPosition.call(mesh, vertex, base);
+ posed.set(0, 0, 0);
+ for (let lane = 0;lane < 4; lane++) {
+ const weight = weights.getComponent(vertex, lane);
+ if (weight !== 0)
+ posed.addScaledVector(temp.copy(base).applyMatrix4(matrices[indices.getComponent(vertex, lane)]), weight);
+ }
+ posed.applyMatrix4(inverse).applyMatrix4(meshWorld);
+ if (!Number.isFinite(Math.fround(posed.x)) || !Number.isFinite(Math.fround(posed.y)) || !Number.isFinite(Math.fround(posed.z))) {
+ add("SKIN_POSED_VERTEX", `Current deformed vertex ${vertex} is not finite and Float32-representable. Check positions, morphs and weighted joint transforms.`, `position[${vertex}]`);
+ break;
+ }
+ box.expandByPoint(posed);
+ }
+ if (result.findings.length === start)
+ result.bounds.push({ nodePath, min: box.min.toArray(), max: box.max.toArray() });
}
- return document;
+ return result;
}
-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.`);
+var MAX_FINDINGS = 64, WEIGHT_TOLERANCE = 0.00001;
+var init_skin_integrity = () => {};
+
+// src/lod-export.ts
+import { PropertyType as PropertyType3 } from "@gltf-transform/core";
+function applyLodChains(root, sets, doc) {
+ if (sets.length === 0)
+ return;
+ const exported = writtenNodeResolver(root, doc, "LOD export");
+ const chains = sets.map((set) => ({
+ set,
+ parent: exported(set.parent),
+ levels: set.levels.map(exported)
+ }));
+ const extension = doc.createExtension(MSFTLod);
+ for (const { set, parent, levels } of chains) {
+ const [base, ...lower] = levels;
+ const lod = extension.createLod();
+ for (const level of lower) {
+ parent.removeChild(level);
+ lod.addLevel(level);
+ }
+ base.setExtension(MSFT_LOD, lod);
+ base.setExtras({ ...base.getExtras(), [MSFT_SCREENCOVERAGE]: [...set.screenCoverage] });
}
- 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(() => {
+function occurrence(siblings, index, name) {
+ let count = 0;
+ for (let i = 0;i < index; i++)
+ if (siblings[i].getName() === name)
+ count++;
+ return count;
+}
+function screenCoverageOf(node) {
+ const value = node.getExtras()[MSFT_SCREENCOVERAGE];
+ return Array.isArray(value) && value.every((item) => typeof item === "number") ? [...value] : undefined;
+}
+function listLodChainNodes(doc) {
+ const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
+ if (!scene)
+ return [];
+ const chains = [];
+ const visit = (siblings, parentPath) => {
+ siblings.forEach((node, index) => {
+ const at = (name) => `${parentPath}${segment4(name, occurrence(siblings, index, name))}`;
+ const path = at(node.getName());
+ const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
+ if (lower.length > 0)
+ chains.push({
+ levels: [node, ...lower],
+ paths: [path, ...lower.map((level) => at(level.getName()))]
+ });
+ visit(node.listChildren(), path);
+ });
+ };
+ visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
+ return chains;
+}
+function isImpostorLevel(node) {
+ const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
+ return roles.includes(KILN_SEMANTIC_ROLES.lodImpostor);
+}
+function summarizeLodChains(doc) {
+ return listLodChainNodes(doc).map(({ levels, paths }) => {
+ const screenCoverage = screenCoverageOf(levels[0]);
+ return {
+ path: paths[0],
+ ...screenCoverage ? { screenCoverage } : {},
+ levels: levels.map((level, number) => ({
+ level: number,
+ name: level.getName(),
+ path: paths[number],
+ triangles: drawnNodeTriangles(level),
+ ...number > 0 && isImpostorLevel(level) ? { impostor: true } : {}
+ }))
+ };
+ });
+}
+var MSFT_SCREENCOVERAGE = "MSFT_screencoverage", segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`;
+var init_lod_export = __esm(() => {
+ init_semantic();
init_gltf_io();
- init_open_shell();
- init_delivery();
- init_rig_export();
- init_material_export();
- init_atlas_provenance();
- 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();
- }
+ init_metrics();
+});
+
+// src/rig-export.ts
+function rigExtrasForExport(node) {
+ const extras = {};
+ for (const [key, validate] of [
+ [KILN_CHARACTER_JOINT_EXTRAS_KEY, validateCharacterJointDescriptorV1],
+ [KILN_CHARACTER_RIG_EXTRAS_KEY, validateCharacterRigGraphV1]
+ ]) {
+ const value = node.userData[key];
+ if (value === undefined)
+ continue;
+ const result = validate(value);
+ if (!result.valid || !result.value) {
+ throw new TypeError(`Invalid ${key} on node ${node.name || "<unnamed>"}: ${result.issues.map((issue) => `${issue.path || "<root>"}: ${issue.message}`).join("; ")}`);
}
- };
+ extras[key] = result.value;
+ }
+ return extras;
+}
+var init_rig_export = __esm(() => {
+ init_character();
});
-// src/index-policy.ts
-import { weldPrimitive } from "@gltf-transform/functions";
-function resolveIndexPolicy(value = "indexed") {
- if (value !== "indexed" && value !== "asBuilt")
- throw new Error("indexPolicy must be indexed or asBuilt");
- return value;
-}
-function geometryBytes(doc) {
- const accessors = new Set;
- for (const mesh of doc.getRoot().listMeshes())
- for (const primitive of mesh.listPrimitives()) {
- for (const accessor of primitive.listAttributes())
- accessors.add(accessor);
- const index = primitive.getIndices();
- if (index)
- accessors.add(index);
- for (const target of primitive.listTargets())
- for (const accessor of target.listAttributes())
- accessors.add(accessor);
+// src/material-export.ts
+import { BackSide } from "three";
+function assertPortableMaterialSides(root) {
+ root.traverse((node) => {
+ const mesh = node;
+ if (!mesh.isMesh && !node.isSprite)
+ return;
+ const materials = mesh.material;
+ const used = Array.isArray(materials) ? [...new Set(mesh.geometry.groups.map((group) => group.materialIndex ?? 0))].map((index) => ({ material: materials[index], index })) : [{ material: materials, index: 0 }];
+ for (const { material, index } of used) {
+ if (!material || material.side !== BackSide)
+ continue;
+ throw new AuthoringDiagnosticError("EXPORT_MATERIAL_SIDE_UNSUPPORTED", `EXPORT_MATERIAL_SIDE_UNSUPPORTED ${node.name || "<unnamed part>"}: material ${material.name || `<slot ${index}>`} uses BackSide, which glTF cannot encode directly. Author inward-facing geometry with FrontSide, or choose DoubleSide when both faces are intended.`);
}
- return [...accessors].reduce((bytes, accessor) => bytes + (accessor.getArray()?.byteLength ?? 0), 0);
-}
-function applyIndexPolicy(doc, policy) {
- const bufferBytesBefore = geometryBytes(doc);
- let primitivesConverted = 0;
- if (policy === "indexed")
- for (const mesh of doc.getRoot().listMeshes())
- for (const primitive of mesh.listPrimitives()) {
- if (!primitive.getIndices()) {
- weldPrimitive(primitive, { overwrite: false });
- primitivesConverted++;
- }
- }
- return {
- version: "kiln.index-buffers.v1",
- policy,
- primitivesConverted,
- bufferBytesBefore,
- bufferBytesAfter: geometryBytes(doc)
- };
+ });
}
-var init_index_policy = () => {};
+var init_material_export = __esm(() => {
+ init_authoring_diagnostic();
+});
-// src/delivery-inspect.ts
+// src/community-exporter.ts
import * as THREE25 from "three";
-import { PropertyType as PropertyType3 } from "@gltf-transform/core";
-function decompose(matrix) {
- const translation = new THREE25.Vector3;
- const rotation = new THREE25.Quaternion;
- const scale = new THREE25.Vector3;
- matrix.decompose(translation, rotation, scale);
- const clean = (value) => Object.is(value, -0) ? 0 : value;
- return {
- translation: translation.toArray().map(clean),
- rotation: rotation.toArray().map(clean),
- scale: scale.toArray().map(clean)
- };
+import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
+import { GLB_BUFFER } from "@gltf-transform/core";
+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 drawnTriangles(visited) {
- const values = [];
- const local = [0, 0, 0];
- const point = new THREE25.Vector3;
- for (const { node, roles, hidden } of visited) {
- const mesh = node.getMesh();
- if (!mesh || hidden || roles.some((role) => role.startsWith("collider.")))
- continue;
- const base = worldMatrix(node);
- const instances = node.getExtension("EXT_mesh_gpu_instancing");
- const translation = instances?.getAttribute("TRANSLATION");
- const rotation = instances?.getAttribute("ROTATION");
- const scale = instances?.getAttribute("SCALE");
- const copies = translation?.getCount() ?? rotation?.getCount() ?? scale?.getCount() ?? 1;
- const matrices = [];
- for (let i = 0;i < copies; i++) {
- const instance = new THREE25.Matrix4().compose(new THREE25.Vector3().fromArray(translation?.getElement(i, []) ?? [0, 0, 0]), new THREE25.Quaternion().fromArray(rotation?.getElement(i, []) ?? [0, 0, 0, 1]), new THREE25.Vector3().fromArray(scale?.getElement(i, []) ?? [1, 1, 1]));
- matrices.push(base.clone().multiply(instance));
+function cleanClone(source) {
+ const shadow = Object.create(source);
+ shadow.userData = {};
+ return shadow.clone();
+}
+async function communitySceneDocument(root, clips, platform = browserPlatform, authorExtras, atlas = collectAtlasProvenance(root)) {
+ assertPortableMaterialSides(root);
+ const materials = new Map;
+ const originalMaterials = new Map;
+ const originalGeometries = new Map;
+ const textures = new Map;
+ const directImages = 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 THREE25.TextureSource(source.image);
+ textures.set(source, copy);
+ const bytes = source.userData["encoded"];
+ if (bytes?.bytes) {
+ if (!copy.flipY && (bytes.mime === "image/png" || bytes.mime === "image/jpeg"))
+ directImages.set(copy, { bytes: bytes.bytes, mime: bytes.mime });
+ encoded.push((async () => {
+ copy.image = await platform.decode(bytes.bytes);
+ Object.defineProperty(copy, "isDataTexture", { value: true });
+ copy.format = THREE25.RGBAFormat;
+ copy.type = THREE25.UnsignedByteType;
+ })());
}
- for (const primitive of mesh.listPrimitives()) {
- if (primitive.getMode() !== 4)
- continue;
- const position = primitive.getAttribute("POSITION");
- if (!position)
- continue;
- const indices = primitive.getIndices();
- const count = indices ? indices.getCount() : position.getCount();
- for (const matrix of matrices)
- for (let i = 0;i + 2 < count; i += 3)
- for (let k = 0;k < 3; k++) {
- position.getElement(indices ? indices.getScalar(i + k) : i + k, local);
- point.fromArray(local).applyMatrix4(matrix);
- values.push(point.x, point.y, point.z);
- }
+ return copy;
+ }
+ function material(source) {
+ const found = materials.get(source);
+ if (found)
+ return found;
+ const copy = cleanClone(source);
+ Object.assign(copy.userData, authorExtras?.material(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 THREE25.Texture)
+ copy[key] = texture(value);
+ }
+ materials.set(source, copy);
+ originalMaterials.set(copy, source);
+ 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 (!copy.matrixAutoUpdate)
+ copy.matrix.decompose(copy.position, copy.quaternion, copy.scale);
+ if (source.isScene) {
+ copy = new THREE25.Group;
+ copy.copy(shadow, false);
+ }
+ if (source.isSprite) {
+ const sprite = source;
+ const geometry = new THREE25.PlaneGeometry(1, 1);
+ geometry.translate(0.5 - sprite.center.x, 0.5 - sprite.center.y, 0);
+ geometry.rotateZ(sprite.material.rotation);
+ const spriteMaterial = new THREE25.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
+ });
+ Object.assign(spriteMaterial.userData, authorExtras?.material(sprite.material));
+ originalMaterials.set(spriteMaterial, sprite.material);
+ copy = new THREE25.Mesh(geometry, spriteMaterial);
+ THREE25.Object3D.prototype.copy.call(copy, shadow, false);
+ }
+ Object.assign(copy.userData, authorExtras?.node(source), rigExtrasForExport(source), openShellExtras(source), kitExtras(source), repeatInstancesExtras(source));
+ 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);
+ originalGeometries.set(mesh, 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 canvasInputs = new Map;
+ const canvasInput = (map) => {
+ const raw = map?.image;
+ if (!map || !raw?.data)
+ return map;
+ const found = canvasInputs.get(map);
+ if (found)
+ return found;
+ const { data, width, height } = raw;
+ const canvas = new OffscreenCanvas(width, height);
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("A 2D canvas is required to prepare export texture channels.");
+ context.putImageData(new ImageData(new Uint8ClampedArray(data), width, height), 0, 0);
+ const adapted = new THREE25.Texture().copy(map);
+ adapted.source = new THREE25.TextureSource(canvas);
+ canvasInputs.set(map, adapted);
+ const direct = directImages.get(map);
+ if (direct)
+ directImages.set(adapted, direct);
+ return adapted;
+ };
+ for (const material of materials.values()) {
+ for (const [key, value] of Object.entries(material)) {
+ if (value instanceof THREE25.Texture && value.flipY && value.image?.data)
+ material[key] = canvasInput(value);
}
- }
- return Float64Array.from(values);
-}
-function triangleOverlapsBox(a, b, c, h, tolerance) {
- const verts = [a, b, c];
- const he = [h.x + tolerance, h.y + tolerance, h.z + tolerance];
- for (let axis = 0;axis < 3; axis++) {
- const values = verts.map((v) => v.getComponent(axis));
- if (Math.min(...values) > he[axis] || Math.max(...values) < -he[axis])
- return false;
- }
- const e = [
- new THREE25.Vector3().subVectors(b, a),
- new THREE25.Vector3().subVectors(c, b),
- new THREE25.Vector3().subVectors(a, c)
- ];
- const normal = new THREE25.Vector3().crossVectors(e[0], e[1]);
- const axes = [normal];
- const units = [
- new THREE25.Vector3(1, 0, 0),
- new THREE25.Vector3(0, 1, 0),
- new THREE25.Vector3(0, 0, 1)
- ];
- for (const unit of units)
- for (const edge of e)
- axes.push(new THREE25.Vector3().crossVectors(unit, edge));
- for (const axis of axes) {
- if (axis.lengthSq() < 0.000000000000000000000001)
+ const standard = material;
+ if (!standard.isMeshStandardMaterial)
continue;
- const projections = verts.map((v) => v.dot(axis));
- const radius = he[0] * Math.abs(axis.x) + he[1] * Math.abs(axis.y) + he[2] * Math.abs(axis.z);
- if (Math.min(...projections) > radius || Math.max(...projections) < -radius)
- return false;
- }
- return true;
-}
-function closestPointOnTriangle(p, a, b, c) {
- const ab = new THREE25.Vector3().subVectors(b, a);
- const ac = new THREE25.Vector3().subVectors(c, a);
- const ap = new THREE25.Vector3().subVectors(p, a);
- const d1 = ab.dot(ap);
- const d2 = ac.dot(ap);
- if (d1 <= 0 && d2 <= 0)
- return a.clone();
- const bp = new THREE25.Vector3().subVectors(p, b);
- const d3 = ab.dot(bp);
- const d4 = ac.dot(bp);
- if (d3 >= 0 && d4 <= d3)
- return b.clone();
- const vc = d1 * d4 - d3 * d2;
- if (vc <= 0 && d1 >= 0 && d3 <= 0)
- return a.clone().addScaledVector(ab, d1 / (d1 - d3));
- const cp = new THREE25.Vector3().subVectors(p, c);
- const d5 = ab.dot(cp);
- const d6 = ac.dot(cp);
- if (d6 >= 0 && d5 <= d6)
- return c.clone();
- const vb = d5 * d2 - d1 * d6;
- if (vb <= 0 && d2 >= 0 && d6 <= 0)
- return a.clone().addScaledVector(ac, d2 / (d2 - d6));
- const va = d3 * d6 - d5 * d4;
- if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0)
- return b.clone().addScaledVector(new THREE25.Vector3().subVectors(c, b), (d4 - d3) / (d4 - d3 + (d5 - d6)));
- const denominator = 1 / (va + vb + vc);
- return a.clone().addScaledVector(ab, vb * denominator).addScaledVector(ac, vc * denominator);
-}
-function segmentSegmentDistanceSq(p1, q1, p2, q2) {
- const d1 = new THREE25.Vector3().subVectors(q1, p1);
- const d2 = new THREE25.Vector3().subVectors(q2, p2);
- const r = new THREE25.Vector3().subVectors(p1, p2);
- const a = d1.dot(d1);
- const e = d2.dot(d2);
- const f = d2.dot(r);
- let s = 0;
- let t = 0;
- if (a <= 0.000000000000000000000001 && e <= 0.000000000000000000000001)
- return r.lengthSq();
- if (a <= 0.000000000000000000000001)
- t = THREE25.MathUtils.clamp(f / e, 0, 1);
- else {
- const c = d1.dot(r);
- if (e <= 0.000000000000000000000001)
- s = THREE25.MathUtils.clamp(-c / a, 0, 1);
- else {
- const b = d1.dot(d2);
- const denominator = a * e - b * b;
- s = denominator !== 0 ? THREE25.MathUtils.clamp((b * f - c * e) / denominator, 0, 1) : 0;
- t = (b * s + f) / e;
- if (t < 0) {
- t = 0;
- s = THREE25.MathUtils.clamp(-c / a, 0, 1);
- } else if (t > 1) {
- t = 1;
- s = THREE25.MathUtils.clamp((b - c) / a, 0, 1);
- }
+ if (standard.metalnessMap !== standard.roughnessMap) {
+ standard.metalnessMap = canvasInput(standard.metalnessMap);
+ standard.roughnessMap = canvasInput(standard.roughnessMap);
}
+ standard.normalMap = canvasInput(standard.normalMap);
}
- const c1 = p1.clone().addScaledVector(d1, s);
- const c2 = p2.clone().addScaledVector(d2, t);
- return c1.distanceToSquared(c2);
-}
-function segmentCrossesTriangle(p, q, a, b, c) {
- const hit = new THREE25.Vector3;
- const ray = new THREE25.Ray(p, new THREE25.Vector3().subVectors(q, p));
- const length = ray.direction.length();
- if (length === 0)
- return false;
- ray.direction.divideScalar(length);
- return ray.intersectTriangle(a, b, c, false, hit) !== null && hit.distanceTo(p) <= length;
-}
-function triangleTouchesCapsule(a, b, c, p, q, radius) {
- const r2 = radius * radius;
- if (closestPointOnTriangle(p, a, b, c).distanceToSquared(p) <= r2)
- return true;
- if (closestPointOnTriangle(q, a, b, c).distanceToSquared(q) <= r2)
- return true;
- for (const [s, e] of [
- [a, b],
- [b, c],
- [c, a]
- ])
- if (segmentSegmentDistanceSq(p, q, s, e) <= r2)
- return true;
- return segmentCrossesTriangle(p, q, a, b, c);
-}
-function summarizeVertexAttributes(doc) {
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return [];
- const groups = new Map;
- const order = [];
- const record = (node, path) => {
- const mesh = node.getMesh();
- if (!mesh)
- return;
- const bake = mesh.getExtras().kilnSurfaceBakeV1;
- const names = new Set;
- for (const primitive of mesh.listPrimitives())
- for (const semantic of primitive.listSemantics())
- if (semantic.startsWith("_"))
- names.add(semantic);
- for (const name of names) {
- const params = bake && typeof bake === "object" ? bake[name] : undefined;
- const key = `${name}\x00${JSON.stringify(params ?? null)}`;
- let group = groups.get(key);
- if (!group) {
- group = { name, meshes: [], ...params ? { params: { ...params } } : {} };
- groups.set(key, group);
- order.push(key);
+ 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);
}
- if (!group.meshes.includes(path))
- group.meshes.push(path);
}
- };
- const visit = (siblings, parentPath) => {
- siblings.forEach((node, index) => {
- const at = (name) => {
- let occurrence = 0;
- for (let i = 0;i < index; i++)
- if (siblings[i].getName() === name)
- occurrence++;
- return `${parentPath}${segment4(name, occurrence)}`;
- };
- const path = at(node.getName());
- record(node, path);
- visit(node.listChildren(), path);
- const lower = (node.getExtension(MSFT_LOD)?.listLevels() ?? []).filter((level) => level.propertyType === PropertyType3.NODE);
- for (const level of lower) {
- const levelPath = at(level.getName());
- record(level, levelPath);
- visit(level.listChildren(), levelPath);
+ cloned.tracks = cloned.tracks.filter((track) => {
+ try {
+ const binding = THREE25.PropertyBinding.parseTrackName(track.name);
+ return ["position", "quaternion", "scale", "morphTargetInfluences"].includes(binding.propertyName) && THREE25.PropertyBinding.findNode(copy, binding.nodeName) !== null;
+ } catch {
+ return false;
}
});
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0));
- const rank = (name) => name === "_EDGE" ? 0 : name === "_CAVITY" ? 1 : 2;
- return order.map((key, position) => ({ group: groups.get(key), position })).sort((a, b) => rank(a.group.name) - rank(b.group.name) || (rank(a.group.name) === 2 ? a.group.name.localeCompare(b.group.name) : 0) || a.position - b.position).map(({ group }) => group);
-}
-function inspectDelivery(doc) {
- const summary = { colliders: [], anchors: [], ports: [], diagnostics: [] };
- const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
- if (!scene)
- return summary;
- const visited = [];
- const visit = (siblings, parentPath, hidden, module) => {
- const seen = new Map;
- for (const node of siblings) {
- const name = node.getName();
- const occurrence = seen.get(name) ?? 0;
- seen.set(name, occurrence + 1);
- const path = `${parentPath}${segment4(name, occurrence)}`;
- const roles = readSemanticMetadataV1FromExtras(node.getExtras())?.roles ?? [];
- const nodeHidden = hidden || isHiddenGltfNode(node);
- const nodeModule = roles.includes(KILN_SEMANTIC_ROLES.kitModule) ? { node, path } : module;
- visited.push({ node, path, roles, hidden: nodeHidden, module: nodeModule });
- visit(node.listChildren(), path, nodeHidden, nodeModule);
- }
- };
- visit(scene.listChildren(), segment4(scene.getName() || "Scene", 0), false, undefined);
- const finding = (code, path, message) => summary.diagnostics.push({ code, path, message });
- const { min, max } = drawnSceneBounds(scene);
- const bounds = new THREE25.Box3(new THREE25.Vector3(...min), new THREE25.Vector3(...max));
- const finiteBounds = [...min, ...max].every(Number.isFinite);
- const diagonal = finiteBounds ? bounds.getSize(new THREE25.Vector3).length() : 0;
- const tolerance = Math.max(0.0001, diagonal * 0.0001);
- const colliderNodes = [];
- for (const entry of visited) {
- const { node, path, roles } = entry;
- for (const role of roles) {
- const matrix = worldMatrix(node);
- const transform = decompose(matrix);
- for (const shape of ["box", "capsule", "hull"]) {
- const id = roleTail(role, `${KILN_SEMANTIC_ROLES.collider}.${shape}`);
- if (id === undefined)
- continue;
- const scale = transform.scale;
- const record = {
- role,
- id,
- path,
- name: node.getName(),
- transform,
- shape: shape === "box" ? { kind: "box", size: [...scale] } : shape === "capsule" ? { kind: "capsule", radius: scale[0] / 2, height: scale[1] } : {
- kind: "hull",
- vertices: node.getMesh()?.listPrimitives().reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0), 0) ?? 0
- }
- };
- summary.colliders.push(record);
- colliderNodes.push({ visit: entry, record });
- }
- const anchorTail = roleTail(role, KILN_SEMANTIC_ROLES.anchor);
- if (anchorTail !== undefined) {
- const [kind, ...rest] = anchorTail.split(".");
- summary.anchors.push({
- role,
- kind,
- id: rest.join("."),
- path,
- name: node.getName(),
- transform
- });
- }
- const portId = roleTail(role, KILN_SEMANTIC_ROLES.kitPort);
- if (portId !== undefined)
- summary.ports.push({
- role,
- id: portId,
- path,
- name: node.getName(),
- ...entry.module && entry.module.node !== node ? { module: entry.module.path } : {},
- transform
- });
- if (role === KILN_SEMANTIC_ROLES.kitModule) {
- const extras = node.getExtras()[KILN_KIT_KEY];
- let spec;
- try {
- const { schemaVersion, ...rest } = extras ?? {};
- spec = schemaVersion === 1 ? kitModuleExtras(rest) : undefined;
- } catch {
- spec = undefined;
+ return cloned;
+ });
+ const preservedImages = new Map;
+ const exporter = new GLTFExporter().register(() => ({
+ writeMesh(mesh, definition) {
+ const geometry = originalGeometries.get(mesh);
+ const binding = geometry && atlas.binding(geometry);
+ if (binding)
+ for (const primitive of definition.primitives)
+ primitive.extras = { ...primitive.extras, kilnAtlasBinding: binding };
+ },
+ async writeMaterialAsync(material, definition) {
+ const source = originalMaterials.get(material);
+ if (!source)
+ return;
+ const bag = source;
+ const pbr = definition.pbrMetallicRoughness;
+ for (const [slot, info] of [
+ ["map", pbr?.baseColorTexture],
+ ["normalMap", definition.normalTexture],
+ ["metalnessMap", pbr?.metallicRoughnessTexture],
+ ["roughnessMap", pbr?.metallicRoughnessTexture],
+ [
+ "emissiveMap",
+ definition.emissiveTexture
+ ],
+ ["aoMap", definition.occlusionTexture]
+ ]) {
+ const texture = bag[slot], ref = texture && atlas.texture(texture);
+ if (ref && info) {
+ const prior = info.extras?.["kilnAtlasReference"];
+ if (prior && prior.id !== ref.id)
+ throw new TypeError("Atlas channel packing requires one exact source identity.");
+ info.extras = { ...info.extras, kilnAtlasReference: ref };
}
- if (!spec)
- finding("DELIVERY_KIT_INVALID", path, `kit module has no valid ${KILN_KIT_KEY} extras; mark it with defineModule.`);
- else if (summary.kit)
- finding("DELIVERY_KIT_MULTIPLE", path, `a GLB delivers one kit module; ${summary.kit.path} is listed and this one is not.`);
- else
- summary.kit = {
- role,
- path,
- name: node.getName(),
- footprint: spec.footprint,
- height: spec.height,
- snapAxis: spec.snapAxis,
- origin: spec.origin,
- transform
- };
}
+ },
+ writeTexture(map, definition) {
+ const direct = directImages.get(map);
+ if (direct && typeof definition["source"] === "number")
+ preservedImages.set(definition["source"], direct);
}
+ }));
+ const bytes = await exporter.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 [index, original] of preservedImages) {
+ const image = json.json.images?.[index];
+ if (!image)
+ throw new Error("The glTF converter lost a direct texture image.");
+ const uri = `kiln-direct-image-${index}`;
+ image.uri = uri;
+ image.mimeType = original.mime;
+ delete image.bufferView;
+ json.resources[uri] = new Uint8Array(original.bytes);
}
- const triangles = colliderNodes.some(({ record }) => record.shape.kind !== "hull") ? drawnTriangles(visited) : new Float64Array;
- const triangleCount = triangles.length / 9;
- let overlapTests = 0;
- const a = new THREE25.Vector3;
- const b = new THREE25.Vector3;
- const c = new THREE25.Vector3;
- for (const { visit: entry, record } of colliderNodes) {
- if (!entry.hidden)
- finding("DELIVERY_COLLIDER_NOT_HIDDEN", record.path, "collider proxy draws; hide it (the delivery helpers do) so importers that ignore roles draw only the asset.");
- const matrix = worldMatrix(entry.node);
- const proxyBounds = new THREE25.Box3;
- const mesh = entry.node.getMesh();
- const local = [0, 0, 0];
- for (const primitive of mesh?.listPrimitives() ?? []) {
- const position = primitive.getAttribute("POSITION");
- for (let i = 0;i < (position?.getCount() ?? 0); i++)
- proxyBounds.expandByPoint(new THREE25.Vector3().fromArray(position.getElement(i, local)).applyMatrix4(matrix));
- }
- if (proxyBounds.isEmpty())
- proxyBounds.expandByPoint(new THREE25.Vector3().setFromMatrixPosition(matrix));
- const expanded = bounds.clone().expandByScalar(tolerance);
- if (!finiteBounds || !expanded.containsBox(proxyBounds))
- finding("DELIVERY_COLLIDER_OUTSIDE_BOUNDS", record.path, "collider proxy reaches outside the bounds of the drawn asset.");
- if (record.shape.kind === "hull")
- continue;
- if (overlapTests + triangleCount > DELIVERY_OVERLAP_TEST_LIMIT) {
- finding("DELIVERY_COLLIDER_OVERLAP_UNMEASURED", record.path, `overlap with drawn triangles was not measured: the check stops at ${DELIVERY_OVERLAP_TEST_LIMIT} collider-triangle tests.`);
+ for (const image of json.json.images ?? []) {
+ if (image.mimeType !== "image/png" || image.bufferView === undefined)
continue;
- }
- overlapTests += triangleCount;
- const toLocal = new THREE25.Matrix4;
- let touches = false;
- if (record.shape.kind === "box") {
- toLocal.copy(matrix).invert();
- const half = new THREE25.Vector3(0.5, 0.5, 0.5);
- const scale = Math.max(...record.transform.scale.map(Math.abs), 0.000000001);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleOverlapsBox(a, b, c, half, tolerance / scale);
- }
- } else {
- const { translation, rotation } = record.transform;
- toLocal.compose(new THREE25.Vector3(...translation), new THREE25.Quaternion(...rotation), new THREE25.Vector3(1, 1, 1)).invert();
- const { radius, height } = record.shape;
- const p = new THREE25.Vector3(0, -height / 2 + radius, 0);
- const q = new THREE25.Vector3(0, height / 2 - radius, 0);
- for (let t = 0;t < triangleCount && !touches; t++) {
- a.fromArray(triangles, t * 9).applyMatrix4(toLocal);
- b.fromArray(triangles, t * 9 + 3).applyMatrix4(toLocal);
- c.fromArray(triangles, t * 9 + 6).applyMatrix4(toLocal);
- touches = triangleTouchesCapsule(a, b, c, p, q, radius + tolerance);
+ const view = json.json.bufferViews[image.bufferView];
+ const buffer = json.resources[json.json.buffers?.[view.buffer]?.uri ?? GLB_BUFFER];
+ const start = view.byteOffset ?? 0;
+ const png = buffer.subarray(start, start + view.byteLength);
+ const data = new DataView(png.buffer, png.byteOffset, png.byteLength);
+ for (let offset = 8;offset + 12 <= png.length; ) {
+ const length = data.getUint32(offset), end = offset + length + 12;
+ if (end > png.length)
+ break;
+ if (data.getUint32(offset + 4) === 1229278788 && length === 0) {
+ if (png.length - end <= 3 && png.subarray(end).every((byte) => byte === 0))
+ view.byteLength = end;
+ break;
}
+ offset = end;
}
- if (!touches)
- finding("DELIVERY_COLLIDER_NO_OVERLAP", record.path, "collider proxy overlaps no drawn triangle; a box or capsule normally wraps or crosses the surface it stands for.");
}
- for (const record of summary.ports) {
- const entry = visited.find((item) => item.path === record.path);
- const moduleEntry = entry.module && entry.module.node !== entry.node ? entry.module : undefined;
- const spec = moduleEntry && summary.kit?.path === moduleEntry.path ? summary.kit : undefined;
- if (!spec) {
- finding("DELIVERY_PORT_WITHOUT_MODULE", record.path, "port is not under a valid kit module; place ports under the root defineModule marked.");
+ for (const binding of json.json.textures ?? []) {
+ if (binding.source === undefined || !binding.name)
continue;
- }
- const point = new THREE25.Vector3(...record.transform.translation).applyMatrix4(worldMatrix(moduleEntry.node).invert());
- const [width, depth] = spec.footprint;
- const [x0, x1, z0, z1] = spec.origin === "corner" ? [0, width, 0, depth] : [-width / 2, width / 2, -depth / 2, depth / 2];
- const slack = Math.max(0.0001, Math.max(width, depth, spec.height) * 0.00001);
- if (point.x < x0 - slack || point.x > x1 + slack || point.z < z0 - slack || point.z > z1 + slack || point.y < -slack || point.y > spec.height + slack)
- finding("DELIVERY_PORT_OUTSIDE_FOOTPRINT", record.path, `port lies outside its module footprint (${width} x ${depth} m from the ${spec.origin}, 0..${spec.height} m high).`);
+ const image = json.json.images?.[binding.source];
+ if (image && !image.name)
+ image.name = binding.name;
}
- for (const record of summary.anchors) {
- const entry = visited.find((item) => item.path === record.path);
- if (entry.node.listChildren().length > 0)
- finding("DELIVERY_ANCHOR_NOT_LEAF", record.path, "anchor has children; an anchor is an empty leaf node, so attach parts beside it instead.");
+ const document = await io.readJSON(json);
+ if (atlas.table) {
+ const scene = document.getRoot().getDefaultScene() ?? document.getRoot().listScenes()[0];
+ scene.setExtras({ ...scene.getExtras(), kilnAtlasProvenance: atlas.table });
+ await refreshAtlasDocumentProvenance(document);
}
- return summary;
+ return document;
}
-var DELIVERY_OVERLAP_TEST_LIMIT = 50000000, segment4 = (name, occurrence) => `/${encodeURIComponent(name)}[${occurrence}]`, roleTail = (role, base) => role.startsWith(`${base}.`) ? role.slice(base.length + 1) : undefined, worldMatrix = (node) => new THREE25.Matrix4().fromArray(node.getWorldMatrix());
-var init_delivery_inspect = __esm(() => {
+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_semantic();
+ init_open_shell();
init_delivery();
- init_metrics();
- init_node_visibility();
+ init_rig_export();
+ init_material_export();
+ init_atlas_provenance();
+ 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/index-policy.ts
+import { weldPrimitive } from "@gltf-transform/functions";
+function resolveIndexPolicy(value = "indexed") {
+ if (value !== "indexed" && value !== "asBuilt")
+ throw new Error("indexPolicy must be indexed or asBuilt");
+ return value;
+}
+function geometryBytes(doc) {
+ const accessors = new Set;
+ for (const mesh of doc.getRoot().listMeshes())
+ for (const primitive of mesh.listPrimitives()) {
+ for (const accessor of primitive.listAttributes())
+ accessors.add(accessor);
+ const index = primitive.getIndices();
+ if (index)
+ accessors.add(index);
+ for (const target of primitive.listTargets())
+ for (const accessor of target.listAttributes())
+ accessors.add(accessor);
+ }
+ return [...accessors].reduce((bytes, accessor) => bytes + (accessor.getArray()?.byteLength ?? 0), 0);
+}
+function applyIndexPolicy(doc, policy) {
+ const bufferBytesBefore = geometryBytes(doc);
+ let primitivesConverted = 0;
+ if (policy === "indexed")
+ for (const mesh of doc.getRoot().listMeshes())
+ for (const primitive of mesh.listPrimitives()) {
+ if (!primitive.getIndices()) {
+ weldPrimitive(primitive, { overwrite: false });
+ primitivesConverted++;
+ }
+ }
+ return {
+ version: "kiln.index-buffers.v1",
+ policy,
+ primitivesConverted,
+ bufferBytesBefore,
+ bufferBytesAfter: geometryBytes(doc)
+ };
+}
+var init_index_policy = () => {};
+
// src/surface-bake.ts
import * as THREE26 from "three";
function settings(value, label) {
@@ -26081,16 +26577,16 @@ var init_material_metrics = __esm(() => {
});
// src/rebuild-options.ts
-import { z as z3 } from "zod";
+import { z as z4 } from "zod";
var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
- rebuildOptionsSchema = z3.object({
- indexPolicy: z3.enum(["indexed", "asBuilt"]).optional(),
- gltfExporter: z3.enum(["legacy", "three"]),
- geometryPolicy: z3.enum(["warn", "strict"]),
- optimize: z3.enum(["off", "auto", "palette", "full"]),
- optimizationPipeline: z3.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
- instance: z3.enum(["off", "auto", "on"])
+ rebuildOptionsSchema = z4.object({
+ indexPolicy: z4.enum(["indexed", "asBuilt"]).optional(),
+ gltfExporter: z4.enum(["legacy", "three"]),
+ geometryPolicy: z4.enum(["warn", "strict"]),
+ optimize: z4.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z4.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
+ instance: z4.enum(["off", "auto", "on"])
});
});
@@ -30262,7 +30758,7 @@ function strict(value, keys, label) {
throw new Error(`${label}.${key} is unknown${hint ? `; use ${KEY_HINTS[key]}` : ""}; accepted keys: ${keys.join(", ")}`);
}
}
-function finite2(n, label) {
+function finite3(n, label) {
if (!Number.isFinite(n))
throw new Error(`${label} must be finite`);
return n;
@@ -30401,7 +30897,7 @@ function validateResolvedAssetCamera(value) {
throw new Error("camera target must differ from position");
if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
throw new Error("camera up must be non-zero and not collinear with view");
- if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
+ if (finite3(camera.aspect, "aspect") <= 0 || finite3(camera.near, "near") <= 0 || finite3(camera.far, "far") <= camera.near)
throw new Error("camera requires positive aspect and 0 < near < far");
if (camera.projection === "orthographic") {
if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
@@ -30431,7 +30927,7 @@ function resolveAssetCamera(root, shot = {}) {
const relative = request.relativeTo ?? "world";
if (!["world", "asset", "part"].includes(relative))
throw new Error("invalid relativeTo");
- const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));
+ const dir = vec(orbitDir(finite3(request.azimuthDeg ?? 45, "azimuthDeg"), finite3(request.elevationDeg ?? 25, "elevationDeg")));
let up;
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
@@ -30509,7 +31005,7 @@ function resolveAssetCamera(root, shot = {}) {
far: request.far ?? fit.far
};
else {
- const fov = finite2(request.fovDeg ?? 50, "fovDeg");
+ const fov = finite3(request.fovDeg ?? 50, "fovDeg");
if (fov <= 0 || fov >= 180)
throw new Error("invalid fovDeg");
const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
@@ -30788,58 +31284,58 @@ var init_glb = __esm(() => {
var init_atomic_directory = () => {};
// src/material-authoring-schema.ts
-import { z as z4 } from "zod";
+import { z as z5 } from "zod";
function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema = canonicalLegacyV2FieldSchema) {
- const integer = (min, max) => z4.number().int().min(min).max(max);
+ const integer = (min, max) => z5.number().int().min(min).max(max);
const byte = integer(0, 255);
const coordinate = integer(-4096, 4096);
- const point = z4.tuple([coordinate, coordinate]);
- const rgba = z4.tuple([byte, byte, byte, byte]);
- const usage = z4.enum(TEXTURE_USAGES);
- const hash = z4.templateLiteral(["sha256:", z4.string().regex(/^[a-f0-9]{64}$/)]);
- const name = z4.string().min(1).max(80);
- const stableId = z4.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- const mapId = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ const point = z5.tuple([coordinate, coordinate]);
+ const rgba = z5.tuple([byte, byte, byte, byte]);
+ const usage = z5.enum(TEXTURE_USAGES);
+ const hash = z5.templateLiteral(["sha256:", z5.string().regex(/^[a-f0-9]{64}$/)]);
+ const name = z5.string().min(1).max(80);
+ const stableId = z5.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ const mapId = z5.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
const dimensions = { width: integer(1, 4096), height: integer(1, 4096) };
- const pixelRectangleSchema = z4.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
- const atlasRectangleSchema = z4.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
- const shape = z4.discriminatedUnion("kind", [
- pixelRectangleSchema.extend({ kind: z4.literal("rectangle") }).strict(),
- pixelRectangleSchema.extend({ kind: z4.literal("ellipse") }).strict(),
- z4.object({
- kind: z4.literal("polygon"),
- points: z4.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
+ const pixelRectangleSchema = z5.object({ x: coordinate, y: coordinate, width: integer(1, 2048), height: integer(1, 2048) }).strict();
+ const atlasRectangleSchema = z5.object({ x: integer(0, 4096), y: integer(0, 4096), ...dimensions }).strict();
+ const shape = z5.discriminatedUnion("kind", [
+ pixelRectangleSchema.extend({ kind: z5.literal("rectangle") }).strict(),
+ pixelRectangleSchema.extend({ kind: z5.literal("ellipse") }).strict(),
+ z5.object({
+ kind: z5.literal("polygon"),
+ points: z5.array(point).min(3).max(MAX_PROCEDURAL_V3_VERTICES)
}).strict(),
- z4.object({ kind: z4.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
+ z5.object({ kind: z5.literal("line"), from: point, to: point, width: integer(1, 2048) }).strict()
]);
- const paint = z4.object({ op: z4.literal("paint"), shape, rgba, opacity: byte }).strict();
- const mask = z4.object({ op: z4.literal("mask"), shape, alpha: byte, invert: z4.boolean() }).strict();
- const stamps = z4.object({
- op: z4.literal("stamps"),
+ const paint = z5.object({ op: z5.literal("paint"), shape, rgba, opacity: byte }).strict();
+ const mask = z5.object({ op: z5.literal("mask"), shape, alpha: byte, invert: z5.boolean() }).strict();
+ const stamps = z5.object({
+ op: z5.literal("stamps"),
shape,
rgba,
opacity: byte,
count: integer(1, MAX_PROCEDURAL_V3_STAMPS),
seed: integer(0, 4294967295),
area: pixelRectangleSchema,
- periodic: z4.boolean()
+ periodic: z5.boolean()
}).strict();
- const legacy = z4.object({ op: z4.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
- const palette = z4.object({
- colors: z4.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
- dither: z4.enum(["none", "bayer4"])
+ const legacy = z5.object({ op: z5.literal("legacy-v2"), spec: legacyV2Schema, alpha: byte, opacity: byte }).strict();
+ const palette = z5.object({
+ colors: z5.array(integer(0, 16777215)).min(1).max(MAX_PROCEDURAL_V3_PALETTE),
+ dither: z5.enum(["none", "bayer4"])
}).strict();
const proceduralBase = {
- schemaVersion: z4.literal(3),
+ schemaVersion: z5.literal(3),
width: integer(4, MAX_PROCEDURAL_V3_EDGE),
height: integer(4, MAX_PROCEDURAL_V3_EDGE),
usage,
name: name.optional(),
background: rgba
};
- const canonicalProceduralTextureSpecV3Schema = z4.object({
+ const canonicalProceduralTextureSpecV3Schema = z5.object({
...proceduralBase,
- operations: z4.array(z4.discriminatedUnion("op", [
+ operations: z5.array(z5.discriminatedUnion("op", [
paint,
mask,
stamps,
@@ -30847,11 +31343,11 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.optional()
}).strict();
- const proceduralTextureSpecV3Schema = z4.object({
+ const proceduralTextureSpecV3Schema = z5.object({
...proceduralBase,
usage: usage.optional(),
background: rgba.optional(),
- operations: z4.array(z4.discriminatedUnion("op", [
+ operations: z5.array(z5.discriminatedUnion("op", [
paint.partial({ opacity: true }),
mask.partial({ alpha: true, invert: true }),
stamps.partial({ opacity: true, periodic: true }),
@@ -30859,110 +31355,110 @@ function makeMaterialAuthoringSchemas(legacyV2Schema, canonicalLegacyV2Schema =
])).max(MAX_PROCEDURAL_V3_OPERATIONS),
palette: palette.partial({ dither: true }).optional()
}).strict();
- const portableSamplerSchema = z4.object({
- minFilter: z4.enum(PORTABLE_MIN_FILTERS_V1),
- magFilter: z4.enum(PORTABLE_MAG_FILTERS_V1),
- wrapS: z4.enum(PORTABLE_WRAPS_V1),
- wrapT: z4.enum(PORTABLE_WRAPS_V1)
+ const portableSamplerSchema = z5.object({
+ minFilter: z5.enum(PORTABLE_MIN_FILTERS_V1),
+ magFilter: z5.enum(PORTABLE_MAG_FILTERS_V1),
+ wrapS: z5.enum(PORTABLE_WRAPS_V1),
+ wrapT: z5.enum(PORTABLE_WRAPS_V1)
}).strict();
- const materialMapPinSchema = z4.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
- const resourceSource = z4.object({
- kind: z4.literal("resource"),
+ const materialMapPinSchema = z5.object({ resourceId: stableId, revisionId: hash, sha256: hash }).strict();
+ const resourceSource = z5.object({
+ kind: z5.literal("resource"),
resourceId: mapId,
pin: materialMapPinSchema,
- expected: z4.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
+ expected: z5.object({ ...dimensions, imageSha256: hash, decodedPixelHash: hash }).partial().strict().optional()
}).strict();
- const region = z4.object({
+ const region = z5.object({
name: stableId,
content: atlasRectangleSchema,
gutter: integer(0, 32),
- edgeMode: z4.enum(["copy-edge", "mask-rgb-dilate"]),
- source: z4.discriminatedUnion("kind", [
- z4.object({ kind: z4.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
+ edgeMode: z5.enum(["copy-edge", "mask-rgb-dilate"]),
+ source: z5.discriminatedUnion("kind", [
+ z5.object({ kind: z5.literal("procedural"), spec: canonicalProceduralTextureSpecV3Schema }).strict(),
resourceSource
]),
crop: atlasRectangleSchema.optional(),
- packed: z4.literal(true).optional()
+ packed: z5.literal(true).optional()
}).strict();
const atlasBase = {
- schemaVersion: z4.literal(1),
+ schemaVersion: z5.literal(1),
width: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
height: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
usage,
sampler: portableSamplerSchema
};
- const packEdge = z4.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z4.literal(edge)));
- const canonicalTextureAtlasSpecV1Schema = z4.object({
+ const packEdge = z5.union(TEXTURE_ATLAS_PACK_EDGES.map((edge) => z5.literal(edge)));
+ const canonicalTextureAtlasSpecV1Schema = z5.object({
...atlasBase,
- regions: z4.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
- pack: z4.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z4.literal("maxrects") }).strict().optional()
+ regions: z5.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
+ pack: z5.object({ edge: packEdge, gutter: integer(0, 32), algorithm: z5.literal("maxrects") }).strict().optional()
}).strict();
- const textureAtlasSpecV1Schema = z4.object({
+ const textureAtlasSpecV1Schema = z5.object({
...atlasBase,
width: atlasBase.width.optional(),
height: atlasBase.height.optional(),
- pack: z4.object({
+ pack: z5.object({
edge: packEdge,
gutter: integer(0, 32).optional(),
- algorithm: z4.literal("maxrects").optional()
+ algorithm: z5.literal("maxrects").optional()
}).strict().optional(),
sampler: portableSamplerSchema.optional(),
- regions: z4.array(region.extend({
- source: z4.discriminatedUnion("kind", [
- z4.object({ kind: z4.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
+ regions: z5.array(region.extend({
+ source: z5.discriminatedUnion("kind", [
+ z5.object({ kind: z5.literal("procedural"), spec: proceduralTextureSpecV3Schema }).strict(),
resourceSource
])
}).partial({ content: true, gutter: true, edgeMode: true })).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions)
}).strict();
- const verifiedPinnedMaterialMapDescriptorSchema = z4.object({
+ const verifiedPinnedMaterialMapDescriptorSchema = z5.object({
materialId: stableId,
revisionId: hash,
resourceId: mapId,
- slot: z4.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ slot: z5.enum(["baseColor", "normal", "metallicRoughness", "emissive", "occlusion"]),
usage,
- colorSpace: z4.enum(["srgb", "linear"]),
+ colorSpace: z5.enum(["srgb", "linear"]),
...dimensions,
encodedByteLength: integer(1, TEXTURE_ATLAS_LIMITS.encodedSourceBytes),
imageSha256: hash,
decodedPixelHash: hash.optional()
}).strict();
const sourceManifestBase = {
- id: z4.string().min(1).max(1024),
+ id: z5.string().min(1).max(1024),
...dimensions,
decodedPixelHash: hash
};
- const sourceManifest = z4.discriminatedUnion("kind", [
- z4.object({
+ const sourceManifest = z5.discriminatedUnion("kind", [
+ z5.object({
...sourceManifestBase,
- kind: z4.literal("procedural"),
+ kind: z5.literal("procedural"),
recipeHash: hash,
- compilerId: z4.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
+ compilerId: z5.literal(PROCEDURAL_TEXTURE_V3_COMPILER_ID)
}).strict(),
- z4.object({
+ z5.object({
...sourceManifestBase,
- kind: z4.literal("resource"),
+ kind: z5.literal("resource"),
descriptor: verifiedPinnedMaterialMapDescriptorSchema
}).strict()
]);
- const textureAtlasManifestV1Schema = z4.object({
- version: z4.literal("kiln.atlas-manifest.v1"),
- compilerId: z4.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ const textureAtlasManifestV1Schema = z5.object({
+ version: z5.literal("kiln.atlas-manifest.v1"),
+ compilerId: z5.enum(TEXTURE_ATLAS_COMPILER_IDS),
width: atlasBase.width,
height: atlasBase.height,
usage,
- origin: z4.literal("top-left"),
+ origin: z5.literal("top-left"),
sampler: portableSamplerSchema,
specHash: hash,
layoutHash: hash,
decodedPixelHash: hash,
atlasPixelHash: hash,
- sources: z4.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
- regions: z4.array(z4.object({
+ sources: z5.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
+ regions: z5.array(z5.object({
name: stableId,
content: atlasRectangleSchema,
allocation: atlasRectangleSchema,
crop: atlasRectangleSchema,
- sourceId: z4.string().min(1).max(1024)
+ sourceId: z5.string().min(1).max(1024)
}).strict()).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
manifestHash: hash
}).strict();
@@ -30985,36 +31481,36 @@ var init_material_authoring_schema = __esm(() => {
init_portable_sampler();
init_texture_contract();
canonicalLegacyV2FieldSchema = (() => {
- const color = z4.number().int().min(0).max(16777215);
- const count = z4.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
- const angleDeg = z4.number().min(-36000).max(36000);
- const unit = z4.number().min(0).max(1);
- const common = { blend: z4.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
- return z4.object({
- schemaVersion: z4.literal(2),
- size: z4.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
- usage: z4.enum(TEXTURE_USAGES),
- name: z4.string().min(1).max(80).optional(),
- layers: z4.array(z4.discriminatedUnion("op", [
- z4.object({ op: z4.literal("solid"), color, ...common }).strict(),
- z4.object({
- op: z4.literal("checker"),
+ const color = z5.number().int().min(0).max(16777215);
+ const count = z5.number().int().min(1).max(MAX_PROCEDURAL_PATTERN_COUNT);
+ const angleDeg = z5.number().min(-36000).max(36000);
+ const unit = z5.number().min(0).max(1);
+ const common = { blend: z5.enum(["normal", "multiply", "screen", "overlay"]), opacity: unit };
+ return z5.object({
+ schemaVersion: z5.literal(2),
+ size: z5.number().int().min(MIN_PROCEDURAL_SIZE).max(MAX_PROCEDURAL_SIZE),
+ usage: z5.enum(TEXTURE_USAGES),
+ name: z5.string().min(1).max(80).optional(),
+ layers: z5.array(z5.discriminatedUnion("op", [
+ z5.object({ op: z5.literal("solid"), color, ...common }).strict(),
+ z5.object({
+ op: z5.literal("checker"),
colorA: color,
colorB: color,
squares: count,
...common
}).strict(),
- z4.object({
- op: z4.literal("stripes"),
+ z5.object({
+ op: z5.literal("stripes"),
colorA: color,
colorB: color,
count,
angleDeg,
...common
}).strict(),
- z4.object({ op: z4.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
- z4.object({
- op: z4.literal("bricks"),
+ z5.object({ op: z5.literal("gradient"), from: color, to: color, angleDeg, ...common }).strict(),
+ z5.object({
+ op: z5.literal("bricks"),
brick: color,
mortar: color,
rows: count,
@@ -31023,13 +31519,13 @@ var init_material_authoring_schema = __esm(() => {
stagger: unit,
...common
}).strict(),
- z4.object({
- op: z4.literal("noise"),
+ z5.object({
+ op: z5.literal("noise"),
colorA: color,
colorB: color,
scale: count,
- octaves: z4.number().int().min(1).max(MAX_NOISE_OCTAVES),
- seed: z4.number().int().min(-2147483648).max(2147483647),
+ octaves: z5.number().int().min(1).max(MAX_NOISE_OCTAVES),
+ seed: z5.number().int().min(-2147483648).max(2147483647),
...common
}).strict()
])).min(1).max(MAX_PROCEDURAL_LAYERS)
@@ -31038,7 +31534,7 @@ var init_material_authoring_schema = __esm(() => {
});
// src/material-library.ts
-import { z as z5 } from "zod";
+import { z as z6 } from "zod";
function assertMaterialJson(value, allowBytes = false, depth = 0) {
if (depth > 30)
throw new Error("Material JSON exceeds nesting limit");
@@ -31265,23 +31761,23 @@ var init_material_library = __esm(() => {
emissive: "emissive",
occlusion: "occlusion"
};
- materialLibraryIdSchema = z5.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
- materialLibraryHashSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
- text3 = z5.string().min(1).max(1000);
- url = z5.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
- materialSourceSchema = z5.object({
+ materialLibraryIdSchema = z6.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+ materialLibraryHashSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text3 = z6.string().min(1).max(1000);
+ url = z6.string().max(2000).url().refine((value) => /^https?:\/\//.test(value), "Provenance URL must be HTTP(S)");
+ materialSourceSchema = z6.object({
id: materialLibraryIdSchema,
- kind: z5.enum(["external", "procedural"]),
+ kind: z6.enum(["external", "procedural"]),
provider: text3,
creator: text3,
assetId: text3.optional(),
assetUrl: url.optional(),
- accessedAt: z5.string().datetime().optional(),
- license: z5.object({ spdx: text3, url, attribution: z5.string().max(4000) }).strict(),
- originalFiles: z5.array(z5.object({
- name: z5.string().min(1).max(200),
+ accessedAt: z6.string().datetime().optional(),
+ license: z6.object({ spdx: text3, url, attribution: z6.string().max(4000) }).strict(),
+ originalFiles: z6.array(z6.object({
+ name: z6.string().min(1).max(200),
sha256: materialLibraryHashSchema,
- bytes: z5.number().int().positive().max(1024 * 1024 * 1024)
+ bytes: z6.number().int().positive().max(1024 * 1024 * 1024)
}).strict()).max(20)
}).strict().superRefine((source, context) => {
if (source.kind === "external" && (!source.assetUrl || !source.originalFiles.length))
@@ -31292,22 +31788,22 @@ var init_material_library = __esm(() => {
if (new Set(source.originalFiles.map((file) => file.name)).size !== source.originalFiles.length)
context.addIssue({ code: "custom", message: "Duplicate original filename" });
});
- materialTransformSchema = z5.object({
+ materialTransformSchema = z6.object({
operation: text3,
tool: text3,
version: text3,
- parameters: z5.record(z5.string().max(100), z5.union([z5.string().max(2000), z5.number().finite(), z5.boolean()])).optional()
+ parameters: z6.record(z6.string().max(100), z6.union([z6.string().max(2000), z6.number().finite(), z6.boolean()])).optional()
}).strict();
- color2 = z5.number().int().min(0).max(16777215);
- count4 = z5.number().int().min(1).max(256);
+ color2 = z6.number().int().min(0).max(16777215);
+ count4 = z6.number().int().min(1).max(256);
layerCommon = {
- blend: z5.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
- opacity: z5.number().min(0).max(1).default(1)
+ blend: z6.enum(["normal", "multiply", "screen", "overlay"]).default("normal"),
+ opacity: z6.number().min(0).max(1).default(1)
};
- materialProceduralSpecSchema = z5.object({
- schemaVersion: z5.literal(2),
- size: z5.number().int().min(4).max(1024).default(256),
- usage: z5.enum([
+ materialProceduralSpecSchema = z6.object({
+ schemaVersion: z6.literal(2),
+ size: z6.number().int().min(4).max(1024).default(256),
+ usage: z6.enum([
"albedo",
"normal",
"roughness",
@@ -31316,90 +31812,90 @@ var init_material_library = __esm(() => {
"emissive",
"occlusion"
]).default("albedo"),
- name: z5.string().min(1).max(80).optional(),
- layers: z5.array(z5.discriminatedUnion("op", [
- z5.object({ op: z5.literal("solid"), color: color2, ...layerCommon }).strict(),
- z5.object({
- op: z5.literal("checker"),
+ name: z6.string().min(1).max(80).optional(),
+ layers: z6.array(z6.discriminatedUnion("op", [
+ z6.object({ op: z6.literal("solid"), color: color2, ...layerCommon }).strict(),
+ z6.object({
+ op: z6.literal("checker"),
colorA: color2,
colorB: color2,
squares: count4.default(8),
...layerCommon
}).strict(),
- z5.object({
- op: z5.literal("stripes"),
+ z6.object({
+ op: z6.literal("stripes"),
colorA: color2,
colorB: color2,
count: count4.default(8),
- angleDeg: z5.number().min(-36000).max(36000).default(0),
+ angleDeg: z6.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z5.object({
- op: z5.literal("gradient"),
+ z6.object({
+ op: z6.literal("gradient"),
from: color2,
to: color2,
- angleDeg: z5.number().min(-36000).max(36000).default(0),
+ angleDeg: z6.number().min(-36000).max(36000).default(0),
...layerCommon
}).strict(),
- z5.object({
- op: z5.literal("bricks"),
+ z6.object({
+ op: z6.literal("bricks"),
brick: color2,
mortar: color2,
rows: count4.default(8),
cols: count4.default(4),
- mortarWidth: z5.number().min(0).max(1).default(0.06),
- stagger: z5.number().min(0).max(1).default(0.5),
+ mortarWidth: z6.number().min(0).max(1).default(0.06),
+ stagger: z6.number().min(0).max(1).default(0.5),
...layerCommon
}).strict(),
- z5.object({
- op: z5.literal("noise"),
+ z6.object({
+ op: z6.literal("noise"),
colorA: color2,
colorB: color2,
scale: count4.default(8),
- octaves: z5.number().int().min(1).max(6).default(3),
- seed: z5.number().int().min(-2147483648).max(2147483647).default(0),
+ octaves: z6.number().int().min(1).max(6).default(3),
+ seed: z6.number().int().min(-2147483648).max(2147483647).default(0),
...layerCommon
}).strict()
])).min(1).max(8)
}).strict();
- materialNormalDerivationSchema = z5.object({
- kind: z5.literal("normal-from-height"),
- strength: z5.number().finite().positive().max(64)
+ materialNormalDerivationSchema = z6.object({
+ kind: z6.literal("normal-from-height"),
+ strength: z6.number().finite().positive().max(64)
}).strict();
- proceduralSchema = z5.object({
- compiler: z5.literal("kiln.procedural-texture.v2"),
+ proceduralSchema = z6.object({
+ compiler: z6.literal("kiln.procedural-texture.v2"),
spec: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional(),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict()
+ encoder: z6.object({ name: z6.literal("sharp"), version: text3 }).strict()
}).strict();
- parametersSchema = z5.object({
- baseColor: z5.number().int().min(0).max(16777215).optional(),
- roughness: z5.number().min(0).max(1).default(1),
- metalness: z5.number().min(0).max(1).default(0),
- emissive: z5.number().int().min(0).max(16777215).optional(),
- emissiveIntensity: z5.number().min(0).max(64).default(1),
- alphaMode: z5.enum(["opaque", "mask", "blend"]).default("opaque"),
- alphaCutoff: z5.number().min(0).max(1).default(0.5),
- doubleSided: z5.boolean().default(false)
+ parametersSchema = z6.object({
+ baseColor: z6.number().int().min(0).max(16777215).optional(),
+ roughness: z6.number().min(0).max(1).default(1),
+ metalness: z6.number().min(0).max(1).default(0),
+ emissive: z6.number().int().min(0).max(16777215).optional(),
+ emissiveIntensity: z6.number().min(0).max(64).default(1),
+ alphaMode: z6.enum(["opaque", "mask", "blend"]).default("opaque"),
+ alphaCutoff: z6.number().min(0).max(1).default(0.5),
+ doubleSided: z6.boolean().default(false)
}).strict();
- materialManifestSchema = z5.object({
- schemaVersion: z5.literal(1),
+ materialManifestSchema = z6.object({
+ schemaVersion: z6.literal(1),
materialId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
- name: z5.string().min(1).max(200),
- tags: z5.array(z5.string().min(1).max(80)).max(30),
- tileable: z5.boolean(),
- physicalSizeMeters: z5.object({
- width: z5.number().finite().positive().max(1e5),
- height: z5.number().finite().positive().max(1e5)
+ name: z6.string().min(1).max(200),
+ tags: z6.array(z6.string().min(1).max(80)).max(30),
+ tileable: z6.boolean(),
+ physicalSizeMeters: z6.object({
+ width: z6.number().finite().positive().max(1e5),
+ height: z6.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema,
- sources: z5.array(materialSourceSchema).min(1).max(20),
- maps: z5.array(z5.object({
- slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
- file: z5.enum([
+ sources: z6.array(materialSourceSchema).min(1).max(20),
+ maps: z6.array(z6.object({
+ slot: z6.enum(MATERIAL_LIBRARY_SLOTS),
+ file: z6.enum([
"baseColor.png",
"normal.png",
"metallicRoughness.png",
@@ -31407,45 +31903,45 @@ var init_material_library = __esm(() => {
"occlusion.png"
]),
sha256: materialLibraryHashSchema,
- bytes: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
- width: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- height: z5.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
- usage: z5.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
- colorSpace: z5.enum(["srgb", "linear"]),
- normalConvention: z5.literal("opengl").optional(),
- channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ bytes: z6.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapBytes),
+ width: z6.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ height: z6.number().int().positive().max(MATERIAL_LIBRARY_LIMITS.maxMapEdge),
+ usage: z6.enum(["albedo", "normal", "metallicRoughness", "emissive", "occlusion"]),
+ colorSpace: z6.enum(["srgb", "linear"]),
+ normalConvention: z6.literal("opengl").optional(),
+ channelPacking: z6.literal("r-occlusion-g-roughness-b-metallic").optional(),
sourceId: materialLibraryIdSchema,
- originalFile: z5.string().min(1).max(200).optional(),
- transforms: z5.array(materialTransformSchema).max(30),
+ originalFile: z6.string().min(1).max(200).optional(),
+ transforms: z6.array(materialTransformSchema).max(30),
procedural: proceduralSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- proceduralMaterialDraftSchema = z5.object({
+ proceduralMaterialDraftSchema = z6.object({
materialId: materialLibraryIdSchema,
- name: z5.string().min(1).max(200),
- tags: z5.array(z5.string().min(1).max(80)).max(30).optional(),
- tileable: z5.boolean(),
- physicalSizeMeters: z5.object({
- width: z5.number().finite().positive().max(1e5),
- height: z5.number().finite().positive().max(1e5)
+ name: z6.string().min(1).max(200),
+ tags: z6.array(z6.string().min(1).max(80)).max(30).optional(),
+ tileable: z6.boolean(),
+ physicalSizeMeters: z6.object({
+ width: z6.number().finite().positive().max(1e5),
+ height: z6.number().finite().positive().max(1e5)
}).strict().optional(),
parameters: parametersSchema.partial().optional(),
- sources: z5.array(materialSourceSchema).min(1).max(20),
- maps: z5.array(z5.object({
- slot: z5.enum(MATERIAL_LIBRARY_SLOTS),
+ sources: z6.array(materialSourceSchema).min(1).max(20),
+ maps: z6.array(z6.object({
+ slot: z6.enum(MATERIAL_LIBRARY_SLOTS),
sourceId: materialLibraryIdSchema,
- transforms: z5.array(materialTransformSchema).max(30),
- normalConvention: z5.literal("opengl").optional(),
- channelPacking: z5.literal("r-occlusion-g-roughness-b-metallic").optional(),
+ transforms: z6.array(materialTransformSchema).max(30),
+ normalConvention: z6.literal("opengl").optional(),
+ channelPacking: z6.literal("r-occlusion-g-roughness-b-metallic").optional(),
procedural: materialProceduralSpecSchema,
derive: materialNormalDerivationSchema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialLibraryPayloadSchema = z5.object({
- schemaVersion: z5.literal(1),
- records: z5.array(z5.object({
+ materialLibraryPayloadSchema = z6.object({
+ schemaVersion: z6.literal(1),
+ records: z6.array(z6.object({
manifest: materialManifestSchema,
- files: z5.record(z5.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z5.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
+ files: z6.record(z6.string().regex(/^(baseColor|normal|metallicRoughness|emissive|occlusion)\.png$/), z6.string().max(Math.ceil(MATERIAL_LIBRARY_LIMITS.maxMapBytes / 3) * 4))
}).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
authoringSchemas = makeMaterialAuthoringSchemas(materialProceduralSpecSchema);
@@ -31454,27 +31950,27 @@ var init_material_library = __esm(() => {
v3SpecSchema = authoringSchemas.canonicalProceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, true), afterShape);
atlasSpecSchema = authoringSchemas.canonicalTextureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, true), afterShape);
atlasManifestSchema = authoringSchemas.textureAtlasManifestV1Schema;
- materialMapPinSchema = z5.object({
+ materialMapPinSchema = z6.object({
resourceId: materialLibraryIdSchema,
revisionId: materialLibraryHashSchema,
sha256: materialLibraryHashSchema
}).strict().refine((pin) => pin.sha256 === pin.revisionId, "Material pin hash must match revision");
- materialRecipeV2Schema = z5.discriminatedUnion("kind", [
- z5.object({
- kind: z5.literal("procedural"),
- compilerId: z5.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
- spec: z5.union([materialProceduralSpecSchema, v3SpecSchema]),
+ materialRecipeV2Schema = z6.discriminatedUnion("kind", [
+ z6.object({
+ kind: z6.literal("procedural"),
+ compilerId: z6.enum(["kiln.procedural-texture.v2", PROCEDURAL_TEXTURE_V3_COMPILER_ID]),
+ spec: z6.union([materialProceduralSpecSchema, v3SpecSchema]),
recipeHash: materialLibraryHashSchema,
pixelHash: materialLibraryHashSchema,
- encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict(),
+ encoder: z6.object({ name: z6.literal("sharp"), version: text3 }).strict(),
derive: materialNormalDerivationSchema.optional()
}).strict(),
- z5.object({
- kind: z5.literal("atlas"),
- compilerId: z5.enum(TEXTURE_ATLAS_COMPILER_IDS),
+ z6.object({
+ kind: z6.literal("atlas"),
+ compilerId: z6.enum(TEXTURE_ATLAS_COMPILER_IDS),
spec: atlasSpecSchema,
manifest: atlasManifestSchema,
- encoder: z5.object({ name: z5.literal("sharp"), version: text3 }).strict()
+ encoder: z6.object({ name: z6.literal("sharp"), version: text3 }).strict()
}).strict().superRefine((recipe, context) => {
try {
validateTextureAtlasManifestV1(recipe.manifest, recipe.spec);
@@ -31486,38 +31982,38 @@ var init_material_library = __esm(() => {
}, afterShape)
]);
materialManifestV2Schema = materialManifestSchema.omit({ schemaVersion: true, maps: true }).extend({
- schemaVersion: z5.literal(2),
- dependencies: z5.array(materialMapPinSchema).max(16),
- maps: z5.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z6.literal(2),
+ dependencies: z6.array(materialMapPinSchema).max(16),
+ maps: z6.array(materialManifestSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
pixelHash: materialLibraryHashSchema,
recipe: materialRecipeV2Schema.optional()
}).strict()).min(1).max(5)
}).strict();
- materialManifestAnySchema = z5.discriminatedUnion("schemaVersion", [
+ materialManifestAnySchema = z6.discriminatedUnion("schemaVersion", [
materialManifestSchema,
materialManifestV2Schema
]);
materialLibraryPayloadV2Schema = materialLibraryPayloadSchema.extend({
- schemaVersion: z5.literal(2),
- records: z5.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
+ schemaVersion: z6.literal(2),
+ records: z6.array(materialLibraryPayloadSchema.shape.records.element.extend({ manifest: materialManifestAnySchema }).strict()).max(MATERIAL_LIBRARY_LIMITS.maxPayloadRecords)
}).strict();
- materialLibraryPayloadAnySchema = z5.discriminatedUnion("schemaVersion", [
+ materialLibraryPayloadAnySchema = z6.discriminatedUnion("schemaVersion", [
materialLibraryPayloadSchema,
materialLibraryPayloadV2Schema
]);
proceduralMaterialDraftV2Schema = proceduralMaterialDraftSchema.extend({
- schemaVersion: z5.literal(2),
- maps: z5.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
+ schemaVersion: z6.literal(2),
+ maps: z6.array(proceduralMaterialDraftSchema.shape.maps.element.omit({ procedural: true }).extend({
sampler: samplerSchema,
- procedural: z5.union([
+ procedural: z6.union([
materialProceduralSpecSchema,
authoringSchemas.proceduralTextureSpecV3Schema.superRefine(admittedBy("procedural V3 spec", canonicalizeProceduralTextureSpecV3, false), afterShape)
]).optional(),
atlas: authoringSchemas.textureAtlasSpecV1Schema.superRefine(admittedBy("atlas spec", canonicalizeTextureAtlasSpecV1, false), afterShape).optional()
}).strict().refine((map) => map.procedural !== undefined !== (map.atlas !== undefined), "Supply exactly one procedural or atlas recipe")).min(1).max(5)
}).strict();
- proceduralMaterialDraftAnySchema = z5.union([
+ proceduralMaterialDraftAnySchema = z6.union([
proceduralMaterialDraftSchema,
proceduralMaterialDraftV2Schema
]);
diff --git a/dist/mcp-engine.mjs b/dist/mcp-engine.mjs
index 139f7c79..573bf15b 100644
--- a/dist/mcp-engine.mjs
+++ b/dist/mcp-engine.mjs
@@ -20113,6 +20113,460 @@ var init_universal = __esm(() => {
};
});
+// src/contracts/validation-profile.ts
+import { z as z5 } from "zod";
+var VALIDATION_PROFILE_VERSION = "kiln.validation-profile.v1", MAX_VALIDATION_PROFILE_BYTES, MAX_VALIDATION_CHECKS = 16, MAX_VALIDATION_PATTERN_CHARS = 128, MAX_VALIDATION_PATTERN_STARS = 4, MAX_VALIDATION_MATCHES = 512, VALIDATION_SEMANTICS, VALIDATION_SEMANTIC_SIZE, VALIDATION_AXES, finite2, id = (max) => z5.string().min(1).max(max).regex(/^[A-Za-z0-9._-]+$/, 'Use letters, digits, ".", "_" or "-".'), pattern, componentFits = (value) => value.component < VALIDATION_SEMANTIC_SIZE[value.attribute], componentMessage, gradient, range, check, ValidationProfileV1Schema;
+var init_validation_profile = __esm(() => {
+ MAX_VALIDATION_PROFILE_BYTES = 8 * 1024;
+ VALIDATION_SEMANTICS = [
+ "POSITION",
+ "NORMAL",
+ "TANGENT",
+ "TEXCOORD_0",
+ "TEXCOORD_1",
+ "COLOR_0",
+ "JOINTS_0",
+ "WEIGHTS_0"
+ ];
+ VALIDATION_SEMANTIC_SIZE = {
+ POSITION: 3,
+ NORMAL: 3,
+ TANGENT: 4,
+ TEXCOORD_0: 2,
+ TEXCOORD_1: 2,
+ COLOR_0: 4,
+ JOINTS_0: 4,
+ WEIGHTS_0: 4
+ };
+ VALIDATION_AXES = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
+ finite2 = z5.number().finite();
+ pattern = z5.string().min(1).refine((value) => Array.from(value).length <= MAX_VALIDATION_PATTERN_CHARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_CHARS} characters.`
+ }).refine((value) => value.split("*").length - 1 <= MAX_VALIDATION_PATTERN_STARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_STARS} "*".`
+ });
+ componentMessage = {
+ message: "component is outside the attribute.",
+ path: ["component"]
+ };
+ gradient = z5.strictObject({
+ attribute: z5.enum(["TEXCOORD_0", "TEXCOORD_1", "COLOR_0"]),
+ component: z5.number().int().min(0).max(3),
+ axis: z5.enum(VALIDATION_AXES),
+ from: finite2,
+ to: finite2,
+ tolerance: finite2.positive().max(0.5),
+ monotonic: z5.boolean()
+ }).refine((value) => value.from !== value.to, {
+ message: "from and to must differ."
+ }).refine(componentFits, componentMessage);
+ range = z5.strictObject({
+ attribute: z5.enum(VALIDATION_SEMANTICS),
+ component: z5.number().int().min(0).max(3),
+ min: finite2,
+ max: finite2,
+ tolerance: finite2.nonnegative()
+ }).refine((value) => value.min <= value.max, {
+ message: "min must not exceed max."
+ }).refine(componentFits, componentMessage);
+ check = z5.strictObject({
+ id: id(48),
+ select: z5.strictObject({
+ names: z5.array(pattern).min(1).max(8),
+ minMatches: z5.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ maxMatches: z5.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional()
+ }).refine((value) => value.maxMatches === undefined || (value.minMatches ?? 1) <= value.maxMatches, { message: "minMatches must not exceed maxMatches." }),
+ primitives: z5.union([
+ z5.strictObject({ exactly: z5.number().int().min(1).max(64) }),
+ z5.strictObject({ max: z5.number().int().min(1).max(64) })
+ ]).optional(),
+ attributes: z5.array(z5.enum(VALIDATION_SEMANTICS)).min(1).max(8).refine((values) => new Set(values).size === values.length, {
+ message: "Attributes must be unique."
+ }).optional(),
+ gradient: gradient.optional(),
+ range: range.optional(),
+ material: z5.strictObject({
+ alphaMode: z5.enum(["OPAQUE", "MASK", "BLEND"]).optional(),
+ doubleSided: z5.boolean().optional()
+ }).refine((value) => value.alphaMode !== undefined || value.doubleSided !== undefined, {
+ message: "A material check needs alphaMode or doubleSided."
+ }).optional()
+ }).refine((value) => value.primitives !== undefined || value.attributes !== undefined || value.gradient !== undefined || value.range !== undefined || value.material !== undefined, { message: "A check needs at least one assertion." });
+ ValidationProfileV1Schema = z5.strictObject({
+ version: z5.literal(VALIDATION_PROFILE_VERSION),
+ profileId: id(64).regex(/^[a-z0-9._-]+$/, 'Use lowercase letters, digits, ".", "_" or "-".'),
+ mode: z5.enum(["warn", "enforce"]),
+ checks: z5.array(check).min(1).max(MAX_VALIDATION_CHECKS)
+ }).superRefine((value, context) => {
+ const ids = value.checks.map((item) => item.id);
+ if (new Set(ids).size !== ids.length)
+ context.addIssue({
+ code: "custom",
+ path: ["checks"],
+ message: "Check ids must be unique."
+ });
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_VALIDATION_PROFILE_BYTES)
+ context.addIssue({
+ code: "custom",
+ message: `A validation profile serializes to at most ${MAX_VALIDATION_PROFILE_BYTES} bytes (got ${bytes}).`
+ });
+ });
+});
+
+// src/qa/validation-profile.ts
+function matchValidationPattern(pattern, name) {
+ const p = Array.from(pattern);
+ const s = Array.from(name);
+ let pi = 0;
+ let si = 0;
+ let star = -1;
+ let resume = 0;
+ while (si < s.length) {
+ if (pi < p.length && (p[pi] === "?" || p[pi] !== "*" && p[pi] === s[si])) {
+ pi++;
+ si++;
+ } else if (pi < p.length && p[pi] === "*") {
+ star = pi++;
+ resume = si;
+ } else if (star >= 0) {
+ pi = star + 1;
+ si = ++resume;
+ } else
+ return false;
+ }
+ while (pi < p.length && p[pi] === "*")
+ pi++;
+ return pi === p.length;
+}
+function component(accessor, index, slot, element) {
+ accessor.getElement(index, element);
+ return element[slot];
+}
+function evaluateValidationProfileDocument(profile, doc, options = {}) {
+ const disposition = profile.mode === "enforce" ? "block" : "warn";
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ const budget = options.maxAttributeReads ?? MAX_VALIDATION_ATTRIBUTE_READS;
+ const paths = deliveryNodePaths(doc);
+ const candidates = [...paths.entries()].filter(([node]) => node.getMesh() !== null);
+ const findings = [];
+ let complete = true;
+ let reads = 0;
+ let matchedNodes = 0;
+ let notMeasured = 0;
+ for (const check of profile.checks) {
+ const kept = new Map;
+ const omitted = new Map;
+ const push = (code, assertion, message, measurement, affected, findingDisposition) => findings.push({
+ code,
+ disposition: findingDisposition,
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation check ${check.id}: ${message}`,
+ ...affected ? { affected } : {},
+ measurement: {
+ name: `checks.${check.id}.${assertion}`,
+ ...measurement
+ }
+ });
+ const report = (code, assertion, message, { affected, measurement }, findingDisposition = disposition) => {
+ const used = kept.get(code) ?? 0;
+ if (used < MAX_VALIDATION_FINDINGS_PER_CODE) {
+ kept.set(code, used + 1);
+ push(code, assertion, message, measurement, affected, findingDisposition);
+ return;
+ }
+ const entry = omitted.get(code) ?? {
+ count: 0,
+ assertion,
+ disposition: findingDisposition
+ };
+ entry.count++;
+ omitted.set(code, entry);
+ };
+ const matched = candidates.filter(([node]) => check.select.names.some((pattern) => matchValidationPattern(pattern, node.getName())));
+ const minMatches = check.select.minMatches ?? 1;
+ if (matched.length < minMatches || check.select.maxMatches !== undefined && matched.length > check.select.maxMatches) {
+ const expected = check.select.maxMatches === undefined ? `>= ${minMatches}` : minMatches === check.select.maxMatches ? `${minMatches}` : `${minMatches}..${check.select.maxMatches}`;
+ report("HOST_VALIDATION_SELECTOR_UNMATCHED", "select", `${matched.length} default-scene mesh node(s) match ${JSON.stringify(check.select.names)}; the host expects ${expected}. Node names come from the final GLB.`, { measurement: { actual: matched.length, expected } });
+ }
+ const measured = matched.slice(0, MAX_VALIDATION_MATCHES);
+ if (matched.length > measured.length) {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "select", `${matched.length - measured.length} matched node(s) beyond the ${MAX_VALIDATION_MATCHES}-node limit were not measured.`, {
+ measurement: {
+ actual: matched.length,
+ threshold: MAX_VALIDATION_MATCHES,
+ breakdown: { nodesNotMeasured: matched.length - measured.length }
+ }
+ }, "observe");
+ }
+ for (const [node, nodePath] of measured) {
+ const primitives = node.getMesh().listPrimitives();
+ const cost = primitives.reduce((sum, primitive) => sum + (primitive.getAttribute("POSITION")?.getCount() ?? 0) * ((check.gradient ? 2 : 0) + (check.range ? 1 : 0)), 0);
+ if (notMeasured > 0 || reads + cost > budget) {
+ notMeasured++;
+ continue;
+ }
+ reads += cost;
+ matchedNodes++;
+ const affected = { node: node.getName(), nodePath };
+ if (check.primitives) {
+ const limit = "exactly" in check.primitives ? check.primitives.exactly : check.primitives.max;
+ const fails = "exactly" in check.primitives ? primitives.length !== limit : primitives.length > limit;
+ if (fails)
+ report("HOST_VALIDATION_PRIMITIVE_COUNT", "primitives", `${node.getName()} has ${primitives.length} primitive(s) in the final GLB; the host expects ${"exactly" in check.primitives ? "exactly" : "at most"} ${limit}. Each material group exports as its own primitive.`, {
+ affected,
+ measurement: {
+ actual: primitives.length,
+ expected: limit
+ }
+ });
+ }
+ primitives.forEach((primitive, index) => {
+ const where = `${node.getName()} primitive ${index}`;
+ for (const semantic of check.attributes ?? []) {
+ if (primitive.getAttribute(semantic))
+ continue;
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "attributes", `${where} has no ${semantic} attribute.`, {
+ affected: { ...affected, attribute: semantic },
+ measurement: { actual: false, expected: true }
+ });
+ }
+ if (check.gradient) {
+ const outcome = measureGradient(primitive, check.gradient);
+ if (outcome.kind === "missing")
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "gradient", `${where} cannot be measured: ${outcome.reason}.`, {
+ affected: { ...affected, attribute: outcome.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else if (outcome.kind === "unmeasured") {
+ complete = false;
+ report("HOST_VALIDATION_UNMEASURED", "gradient", `${where} has no extent along ${check.gradient.axis}; the gradient is unmeasured.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: { actual: null }
+ }, "observe");
+ } else if (outcome.failures.length > 0)
+ report("HOST_VALIDATION_ATTRIBUTE_GRADIENT", "gradient", `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(" and ")} test along local ${check.gradient.axis}: ${round2(outcome.fromMean)} to ${round2(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`, {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: {
+ actual: `${round2(outcome.fromMean)}..${round2(outcome.toMean)}`,
+ expected: `${check.gradient.from}..${check.gradient.to}`,
+ threshold: check.gradient.tolerance,
+ breakdown: {
+ fromMean: round2(outcome.fromMean),
+ toMean: round2(outcome.toMean),
+ worstRegression: round2(outcome.worstRegression)
+ }
+ }
+ });
+ }
+ if (check.range) {
+ const accessor = primitive.getAttribute(check.range.attribute);
+ if (!accessor || check.range.component >= accessor.getElementSize())
+ report("HOST_VALIDATION_ATTRIBUTE_MISSING", "range", `${where} has no ${check.range.attribute}[${check.range.component}].`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: { actual: false, expected: true }
+ });
+ else {
+ const element = [];
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0;i < accessor.getCount(); i++) {
+ const value = component(accessor, i, check.range.component, element);
+ if (value < min)
+ min = value;
+ if (value > max)
+ max = value;
+ }
+ const { tolerance } = check.range;
+ if (accessor.getCount() > 0 && (min < check.range.min - tolerance || max > check.range.max + tolerance))
+ report("HOST_VALIDATION_ATTRIBUTE_RANGE", "range", `${where} ${check.range.attribute}[${check.range.component}] spans ${round2(min)}..${round2(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`, {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: {
+ actual: `${round2(min)}..${round2(max)}`,
+ expected: `${check.range.min}..${check.range.max}`,
+ threshold: tolerance
+ }
+ });
+ }
+ }
+ if (check.material) {
+ const material = primitive.getMaterial();
+ const label = material?.getName() || (material ? `materials[${doc.getRoot().listMaterials().indexOf(material)}]` : "(glTF default)");
+ const alphaMode = material?.getAlphaMode() ?? "OPAQUE";
+ const doubleSided = material?.getDoubleSided() ?? false;
+ if (check.material.alphaMode !== undefined && alphaMode !== check.material.alphaMode)
+ report("HOST_VALIDATION_MATERIAL_ALPHA_MODE", "material", `${where} uses alphaMode ${alphaMode}; the host expects ${check.material.alphaMode}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: alphaMode,
+ expected: check.material.alphaMode
+ }
+ });
+ if (check.material.doubleSided !== undefined && doubleSided !== check.material.doubleSided)
+ report("HOST_VALIDATION_MATERIAL_DOUBLE_SIDED", "material", `${where} is ${doubleSided ? "double-sided" : "single-sided"}; the host expects ${check.material.doubleSided ? "double-sided" : "single-sided"}.`, {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: doubleSided,
+ expected: check.material.doubleSided
+ }
+ });
+ }
+ });
+ }
+ for (const [code, entry] of omitted)
+ push(code, entry.assertion, `${entry.count} more ${code} finding(s) omitted after the first ${MAX_VALIDATION_FINDINGS_PER_CODE}.`, { actual: entry.count, breakdown: { omitted: entry.count } }, undefined, entry.disposition);
+ }
+ if (notMeasured > 0) {
+ complete = false;
+ findings.push({
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation stopped at its ${budget} attribute-read budget; ${notMeasured} matched node(s) were not measured.`,
+ measurement: {
+ name: "checks.*.budget",
+ actual: reads,
+ threshold: budget,
+ breakdown: { nodesNotMeasured: notMeasured }
+ }
+ });
+ }
+ return {
+ findings,
+ complete,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: matchedNodes,
+ hostValidationAttributeReads: reads,
+ hostValidationComplete: complete
+ }
+ };
+}
+function measureGradient(primitive, gradient) {
+ const position = primitive.getAttribute("POSITION");
+ if (!position)
+ return {
+ kind: "missing",
+ attribute: "POSITION",
+ reason: "no POSITION attribute"
+ };
+ const values = primitive.getAttribute(gradient.attribute);
+ if (!values || gradient.component >= values.getElementSize())
+ return {
+ kind: "missing",
+ attribute: gradient.attribute,
+ reason: `no ${gradient.attribute}[${gradient.component}]`
+ };
+ const count = Math.min(position.getCount(), values.getCount());
+ const axis = AXIS_INDEX[gradient.axis[1]];
+ const sign = gradient.axis[0] === "-" ? -1 : 1;
+ const t = new Float64Array(count);
+ const v = new Float64Array(count);
+ const element = [];
+ let tMin = Infinity;
+ let tMax = -Infinity;
+ for (let i = 0;i < count; i++) {
+ t[i] = sign * component(position, i, axis, element);
+ v[i] = component(values, i, gradient.component, element);
+ if (t[i] < tMin)
+ tMin = t[i];
+ if (t[i] > tMax)
+ tMax = t[i];
+ }
+ if (!(tMax - tMin >= MIN_AXIS_EXTENT))
+ return { kind: "unmeasured" };
+ const sums = new Float64Array(GRADIENT_BINS);
+ const counts = new Uint32Array(GRADIENT_BINS);
+ let fromSum = 0;
+ let fromCount = 0;
+ let toSum = 0;
+ let toCount = 0;
+ for (let i = 0;i < count; i++) {
+ const s = (t[i] - tMin) / (tMax - tMin);
+ if (s <= ENDPOINT_BAND) {
+ fromSum += v[i];
+ fromCount++;
+ }
+ if (s >= 1 - ENDPOINT_BAND) {
+ toSum += v[i];
+ toCount++;
+ }
+ const bin = Math.min(GRADIENT_BINS - 1, Math.floor(s * GRADIENT_BINS));
+ sums[bin] = sums[bin] + v[i];
+ counts[bin] = counts[bin] + 1;
+ }
+ const fromMean = fromSum / fromCount;
+ const toMean = toSum / toCount;
+ const direction = Math.sign(gradient.to - gradient.from);
+ let worstRegression = 0;
+ let previous;
+ for (let bin = 0;bin < GRADIENT_BINS; bin++) {
+ if (counts[bin] === 0)
+ continue;
+ const mean = sums[bin] / counts[bin];
+ if (previous !== undefined)
+ worstRegression = Math.max(worstRegression, (previous - mean) * direction);
+ previous = mean;
+ }
+ const failures = [];
+ if (Math.abs(fromMean - gradient.from) > gradient.tolerance || Math.abs(toMean - gradient.to) > gradient.tolerance)
+ failures.push("endpoints");
+ if (gradient.monotonic && worstRegression > gradient.tolerance)
+ failures.push("monotonic");
+ return { kind: "measured", fromMean, toMean, worstRegression, failures };
+}
+async function evaluateValidationProfileGlb(profile, bytes, options = {}) {
+ let doc;
+ try {
+ doc = await createGltfIO().readBinary(bytes);
+ } catch (error) {
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ return {
+ findings: [
+ {
+ code: "HOST_VALIDATION_UNMEASURED",
+ disposition: "observe",
+ dimension: "categoryReadiness",
+ profile: profileName,
+ message: `Host validation could not read the final GLB: ${error instanceof Error ? error.message : String(error)}`,
+ measurement: { name: "checks.*.read", actual: null }
+ }
+ ],
+ complete: false,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: 0,
+ hostValidationAttributeReads: 0,
+ hostValidationComplete: false
+ }
+ };
+ }
+ return evaluateValidationProfileDocument(profile, doc, options);
+}
+var HOST_VALIDATION_RULE_ID = "HOST_VALIDATION_PROFILE", MAX_VALIDATION_ATTRIBUTE_READS = 4000000, MAX_VALIDATION_FINDINGS_PER_CODE = 32, ENDPOINT_BAND = 0.05, GRADIENT_BINS = 16, MIN_AXIS_EXTENT = 0.000001, HOST_VALIDATION_QA_RULE, round2 = (value) => Math.round(value * 1e6) / 1e6, AXIS_INDEX;
+var init_validation_profile2 = __esm(() => {
+ init_gltf_io();
+ init_delivery_inspect();
+ init_validation_profile();
+ init_registry();
+ HOST_VALIDATION_QA_RULE = Object.freeze({
+ id: HOST_VALIDATION_RULE_ID,
+ profile: "host.validation-profile",
+ scope: { kind: "universal" },
+ ruleClass: "exact",
+ owner: KILN_ENGINE_QA_OWNER,
+ promotion: conformancePromotionAuthorization("host-validation-profile-v1", "src/qa/validation-profile.test.ts", "b6b60fcbba0238688cb0d3ef497fa3ed837757422b43207f18fc8cbe0a412ffc", KILN_ENGINE_QA_OWNER, "2026-10-22T00:00:00.000Z", "enforce", "cpu-raster:1.3.1"),
+ defaultMode: "enforce",
+ evaluate: () => []
+ });
+ AXIS_INDEX = { X: 0, Y: 1, Z: 2 };
+});
+
// src/qa/run.ts
function gltfReportFindings(report, profile) {
return report.issues.messages.filter((issue) => issue.severity === 0 || issue.severity === 1).filter((issue) => !isExpectedKtx2ValidatorLimitation(report, issue)).map((issue) => ({
@@ -20160,6 +20614,7 @@ var init_run = __esm(() => {
init_registry();
init_types();
init_universal();
+ init_validation_profile2();
DETERMINISTIC_QA_REGISTRY = new QaRegistry([
...UNIVERSAL_QA_RULES,
MATERIAL_QA_RULE,
@@ -20174,7 +20629,8 @@ var init_run = __esm(() => {
SELF_INTERSECTION_QA_RULE,
SWEEP_QA_RULE,
PART_CONNECTIVITY_QA_RULE,
- REFERENCE_COMPARISON_QA_RULE
+ REFERENCE_COMPARISON_QA_RULE,
+ HOST_VALIDATION_QA_RULE
]);
AssetQaBlockedError = class AssetQaBlockedError extends Error {
report;
@@ -20194,13 +20650,13 @@ var init_run = __esm(() => {
});
// src/contracts/requirements.ts
-import { z as z5 } from "zod";
+import { z as z6 } from "zod";
function statement(value) {
- return z5.discriminatedUnion("state", [
- z5.strictObject({ state: z5.literal("requested"), value, reason: text2.optional() }),
- z5.strictObject({ state: z5.literal("inferred"), value, reason: text2.optional() }),
- z5.strictObject({ state: z5.literal("unknown"), reason: text2.optional() }),
- z5.strictObject({ state: z5.literal("inapplicable"), reason: text2.optional() })
+ return z6.discriminatedUnion("state", [
+ z6.strictObject({ state: z6.literal("requested"), value, reason: text2.optional() }),
+ z6.strictObject({ state: z6.literal("inferred"), value, reason: text2.optional() }),
+ z6.strictObject({ state: z6.literal("unknown"), reason: text2.optional() }),
+ z6.strictObject({ state: z6.literal("inapplicable"), reason: text2.optional() })
]);
}
function validateAssetRequirementsV1(value) {
@@ -20230,157 +20686,159 @@ var text2, positive2, nonnegative, count3, names, marker, supportParts, roof, st
var init_requirements = __esm(() => {
init_asset();
init_breadth();
- text2 = z5.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
- positive2 = z5.number().finite().positive();
- nonnegative = z5.number().finite().nonnegative();
- count3 = z5.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
- names = z5.array(text2).refine((values) => new Set(values).size === values.length, {
+ init_validation_profile();
+ text2 = z6.string().refine((value) => value.trim().length > 0, { message: "Must be non-empty." });
+ positive2 = z6.number().finite().positive();
+ nonnegative = z6.number().finite().nonnegative();
+ count3 = z6.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
+ names = z6.array(text2).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- marker = z5.strictObject({});
- supportParts = z5.array(text2).min(1).max(256).refine((values) => new Set(values).size === values.length, {
+ marker = z6.strictObject({});
+ supportParts = z6.array(text2).min(1).max(256).refine((values) => new Set(values).size === values.length, {
message: "Values must be unique."
});
- roof = z5.strictObject({
+ roof = z6.strictObject({
type: text2.optional(),
- ridgeAxis: z5.enum(["x", "z"]).optional(),
+ ridgeAxis: z6.enum(["x", "z"]).optional(),
rise: nonnegative.optional(),
- pitchDegrees: z5.number().min(0).max(90).optional(),
+ pitchDegrees: z6.number().min(0).max(90).optional(),
overhang: nonnegative.optional(),
- closedEnds: z5.boolean().optional()
+ closedEnds: z6.boolean().optional()
});
- structure = z5.strictObject({
+ structure = z6.strictObject({
subtype: text2.optional(),
- enterable: z5.boolean().optional(),
+ enterable: z6.boolean().optional(),
storeyCount: count3.min(1).optional(),
- interiorMode: z5.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
- roofMode: z5.enum(ARCHITECTURE_ROOF_MODES).optional(),
- footprint: z5.strictObject({ spanX: positive2, spanZ: positive2, units: z5.literal("m") }).optional(),
+ interiorMode: z6.enum(ARCHITECTURE_INTERIOR_MODES).optional(),
+ roofMode: z6.enum(ARCHITECTURE_ROOF_MODES).optional(),
+ footprint: z6.strictObject({ spanX: positive2, spanZ: positive2, units: z6.literal("m") }).optional(),
wallHeight: positive2.optional(),
- scaleMode: z5.enum(ARCHITECTURE_SCALE_MODES).optional(),
+ scaleMode: z6.enum(ARCHITECTURE_SCALE_MODES).optional(),
roof: roof.optional(),
- portal: z5.strictObject({ width: positive2, height: positive2, depth: positive2 }).optional()
+ portal: z6.strictObject({ width: positive2, height: positive2, depth: positive2 }).optional()
}).refine((value) => value.enterable === undefined || value.interiorMode === undefined || value.enterable === (value.interiorMode === "navigable"), {
message: "enterable and interiorMode must agree when both are specified."
});
- effects = z5.strictObject({
- schemaVersion: z5.literal(1),
- subtype: z5.enum(VFX_SUBTYPES),
- portability: z5.enum(VFX_PORTABILITY_MODES),
- transparency: z5.enum(MATERIAL_TRANSPARENCY_MODES),
- doubleSided: z5.boolean(),
- facing: z5.strictObject({
- source: z5.enum(["explicit", "inferred"]),
- mode: z5.enum(VFX_FACING_MODES),
- normalAxis: z5.enum(VFX_AXIS_DIRECTIONS).optional(),
- directionAxis: z5.enum(VFX_AXIS_DIRECTIONS).optional()
+ effects = z6.strictObject({
+ schemaVersion: z6.literal(1),
+ subtype: z6.enum(VFX_SUBTYPES),
+ portability: z6.enum(VFX_PORTABILITY_MODES),
+ transparency: z6.enum(MATERIAL_TRANSPARENCY_MODES),
+ doubleSided: z6.boolean(),
+ facing: z6.strictObject({
+ source: z6.enum(["explicit", "inferred"]),
+ mode: z6.enum(VFX_FACING_MODES),
+ normalAxis: z6.enum(VFX_AXIS_DIRECTIONS).optional(),
+ directionAxis: z6.enum(VFX_AXIS_DIRECTIONS).optional()
}),
- animation: z5.strictObject({
- playback: z5.enum(VFX_PLAYBACK_POLICIES),
+ animation: z6.strictObject({
+ playback: z6.enum(VFX_PLAYBACK_POLICIES),
durationSeconds: nonnegative,
- endpointBehavior: z5.enum(VFX_ENDPOINT_BEHAVIORS),
- driver: z5.enum(VFX_RUNTIME_DRIVERS),
+ endpointBehavior: z6.enum(VFX_ENDPOINT_BEHAVIORS),
+ driver: z6.enum(VFX_RUNTIME_DRIVERS),
clipName: text2.optional(),
timeUniformName: text2.optional()
}),
- sidecar: z5.strictObject({ kind: z5.literal("tsl"), id: text2, version: text2 }).optional()
+ sidecar: z6.strictObject({ kind: z6.literal("tsl"), id: text2, version: text2 }).optional()
}).superRefine((value, context) => {
for (const issue of validateVfxIntentV1(value).issues) {
context.addIssue({ code: "custom", path: issue.path.split("."), message: issue.message });
}
});
- requirements = z5.strictObject({
- grounding: statement(z5.strictObject({ planeY: z5.number().finite().optional() })).optional(),
+ requirements = z6.strictObject({
+ grounding: statement(z6.strictObject({ planeY: z6.number().finite().optional() })).optional(),
articulation: statement(marker).optional(),
opening: statement(marker).optional(),
- navigation: statement(z5.strictObject({ minWidth: positive2.optional(), minHeight: positive2.optional() })).optional(),
+ navigation: statement(z6.strictObject({ minWidth: positive2.optional(), minHeight: positive2.optional() })).optional(),
tiling: statement(marker).optional(),
- mobility: statement(z5.strictObject({
+ mobility: statement(z6.strictObject({
subtype: text2.optional(),
supportAssemblies: names.optional(),
propulsionAssemblies: names.optional(),
- frontFrame: z5.literal("+X").optional(),
+ frontFrame: z6.literal("+X").optional(),
wheelCount: count3.optional(),
axleCount: count3.optional(),
- steering: z5.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
- supportPolicy: z5.enum(VEHICLE_SUPPORT_POLICIES).optional(),
+ steering: z6.enum(VEHICLE_STEERING_ARRANGEMENTS).optional(),
+ supportPolicy: z6.enum(VEHICLE_SUPPORT_POLICIES).optional(),
animationAssemblies: names.optional()
})).optional(),
structure: statement(structure).optional(),
- rig: statement(z5.strictObject({
- bodyPlan: z5.enum(CHARACTER_BODY_PLANS).optional(),
- grounded: z5.boolean().optional(),
- locomotion: z5.enum(CHARACTER_LOCOMOTION_MODES).optional(),
+ rig: statement(z6.strictObject({
+ bodyPlan: z6.enum(CHARACTER_BODY_PLANS).optional(),
+ grounded: z6.boolean().optional(),
+ locomotion: z6.enum(CHARACTER_LOCOMOTION_MODES).optional(),
gait: text2.optional(),
- rootMotion: z5.enum(["inPlace", "forward"]).optional(),
- clips: z5.array(z5.strictObject({ name: text2, playback: z5.enum(["loop", "oneShot"]) })).optional(),
- heldItem: z5.strictObject({ required: z5.boolean(), attachmentRole: text2 }).optional()
+ rootMotion: z6.enum(["inPlace", "forward"]).optional(),
+ clips: z6.array(z6.strictObject({ name: text2, playback: z6.enum(["loop", "oneShot"]) })).optional(),
+ heldItem: z6.strictObject({ required: z6.boolean(), attachmentRole: text2 }).optional()
})).optional(),
- foliage: statement(z5.strictObject({
+ foliage: statement(z6.strictObject({
subtype: text2.optional(),
- growthState: z5.enum(VEGETATION_GROWTH_STATES).optional(),
- canopyProfile: z5.enum(VEGETATION_CANOPY_PROFILES).optional(),
- standalone: z5.boolean().optional(),
- grounded: z5.boolean().optional()
+ growthState: z6.enum(VEGETATION_GROWTH_STATES).optional(),
+ canopyProfile: z6.enum(VEGETATION_CANOPY_PROFILES).optional(),
+ standalone: z6.boolean().optional(),
+ grounded: z6.boolean().optional()
})).optional(),
- spatialLayout: statement(z5.strictObject({
+ spatialLayout: statement(z6.strictObject({
subtype: text2.optional(),
- tileable: z5.boolean().optional(),
- navigable: z5.boolean().optional()
+ tileable: z6.boolean().optional(),
+ navigable: z6.boolean().optional()
})).optional(),
effects: statement(effects).optional(),
- material: statement(z5.strictObject({
- mode: z5.enum(MATERIAL_INTENT_MODES).optional(),
+ material: statement(z6.strictObject({
+ mode: z6.enum(MATERIAL_INTENT_MODES).optional(),
recipeId: text2.optional(),
paletteId: text2.optional(),
- transparency: z5.enum(MATERIAL_TRANSPARENCY_MODES).optional()
+ transparency: z6.enum(MATERIAL_TRANSPARENCY_MODES).optional()
})).optional(),
- animation: statement(z5.strictObject({
+ animation: statement(z6.strictObject({
clips: names,
- locomotionDirection: z5.literal("+X").optional(),
- rootMotion: z5.enum(["inPlace", "forward"]).optional(),
- loop: z5.boolean().optional(),
+ locomotionDirection: z6.literal("+X").optional(),
+ rootMotion: z6.enum(["inPlace", "forward"]).optional(),
+ loop: z6.boolean().optional(),
gait: text2.optional()
})).optional(),
- bounds: statement(z5.strictObject({
- units: z5.literal("m"),
+ bounds: statement(z6.strictObject({
+ units: z6.literal("m"),
x: positive2.optional(),
y: positive2.optional(),
z: positive2.optional()
})).optional(),
- parts: statement(z5.strictObject({ required: names, forbiddenExtras: names })).optional(),
- modular: statement(z5.strictObject({
- schemaVersion: z5.literal(1),
- units: z5.literal("m"),
- grid: z5.tuple([positive2, positive2, positive2])
+ parts: statement(z6.strictObject({ required: names, forbiddenExtras: names })).optional(),
+ modular: statement(z6.strictObject({
+ schemaVersion: z6.literal(1),
+ units: z6.literal("m"),
+ grid: z6.tuple([positive2, positive2, positive2])
})).optional(),
- representation: statement(z5.strictObject({
- transparentSurface: z5.boolean().optional(),
- runtimeShader: z5.boolean().optional(),
- precomputedTangents: z5.boolean().optional(),
- skinned: z5.boolean().optional()
+ representation: statement(z6.strictObject({
+ transparentSurface: z6.boolean().optional(),
+ runtimeShader: z6.boolean().optional(),
+ precomputedTangents: z6.boolean().optional(),
+ skinned: z6.boolean().optional()
})).optional(),
- externalSupport: statement(z5.strictObject({
- supports: z5.array(z5.strictObject({
+ externalSupport: statement(z6.strictObject({
+ supports: z6.array(z6.strictObject({
parts: supportParts,
- planeY: z5.number().finite(),
+ planeY: z6.number().finite(),
tolerance: nonnegative.max(0.5).optional()
})).min(1).max(32)
})).optional(),
- access: statement(z5.strictObject({ enterable: z5.boolean().optional(), driveable: z5.boolean().optional() })).optional()
+ access: statement(z6.strictObject({ enterable: z6.boolean().optional(), driveable: z6.boolean().optional() })).optional(),
+ validation: statement(ValidationProfileV1Schema).optional()
});
- AssetRequirementsV1Schema = z5.strictObject({
- kind: z5.literal("kiln.asset-requirements"),
- schemaVersion: z5.literal(1),
+ AssetRequirementsV1Schema = z6.strictObject({
+ kind: z6.literal("kiln.asset-requirements"),
+ schemaVersion: z6.literal(1),
labels: names,
- frame: z5.strictObject({
- units: z5.literal("m"),
- forward: z5.literal("+X"),
- up: z5.literal("+Y"),
- right: z5.literal("+Z"),
- groundY: z5.literal(0)
+ frame: z6.strictObject({
+ units: z6.literal("m"),
+ forward: z6.literal("+X"),
+ up: z6.literal("+Y"),
+ right: z6.literal("+Z"),
+ groundY: z6.literal(0)
}),
- scope: statement(z5.enum(ASSET_SCOPES)).optional(),
+ scope: statement(z6.enum(ASSET_SCOPES)).optional(),
requirements
}).superRefine((record, context) => {
const requests = record.requirements;
@@ -20497,7 +20955,7 @@ var init_requirements_json = __esm(() => {
// src/requirements-context.ts
import { createHash as createHash10 } from "node:crypto";
-import { z as z6 } from "zod";
+import { z as z7 } from "zod";
function canonical2(value) {
if (Array.isArray(value))
return `[${value.map(canonical2).join(",")}]`;
@@ -20565,26 +21023,26 @@ var init_requirements_context = __esm(() => {
init_requirements();
init_requirements_identity();
init_requirements_json();
- text3 = z6.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
- hash4 = z6.string().regex(/^[a-f0-9]{64}$/);
- revision = z6.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
- change = z6.strictObject({
+ text3 = z7.string().refine((value) => value.trim().length > 0, "Must be non-empty.");
+ hash4 = z7.string().regex(/^[a-f0-9]{64}$/);
+ revision = z7.number().int().min(1).max(Number.MAX_SAFE_INTEGER);
+ change = z7.strictObject({
actor: text3,
reason: text3,
- source: z6.enum(["brief", "automation", "migration", "restore"]),
+ source: z7.enum(["brief", "automation", "migration", "restore"]),
revision,
policyHash: hash4,
previousPolicyHash: hash4.optional()
});
- RequirementsBindingSchema = z6.strictObject({
- kind: z6.literal("kiln.requirements-binding"),
- schemaVersion: z6.literal(1),
+ RequirementsBindingSchema = z7.strictObject({
+ kind: z7.literal("kiln.requirements-binding"),
+ schemaVersion: z7.literal(1),
taskId: text3,
lineageId: text3,
revision,
policyHash: hash4,
requirements: AssetRequirementsV1Schema,
- history: z6.array(change).min(1)
+ history: z7.array(change).min(1)
}).superRefine((binding, context) => {
const issue = (message) => context.addIssue({ code: "custom", message });
if (binding.policyHash !== assetRequirementsPolicyHash(binding.requirements))
@@ -20599,9 +21057,9 @@ var init_requirements_context = __esm(() => {
if (binding.history.at(-1)?.policyHash !== binding.policyHash)
issue("Requirements binding history does not end at its current policy.");
});
- CheckpointSchema = z6.strictObject({
- kind: z6.literal("kiln.requirements-checkpoint.v1"),
- programRef: z6.string().regex(/^sha256:[a-f0-9]{64}$/),
+ CheckpointSchema = z7.strictObject({
+ kind: z7.literal("kiln.requirements-checkpoint.v1"),
+ programRef: z7.string().regex(/^sha256:[a-f0-9]{64}$/),
binding: RequirementsBindingSchema
});
});
@@ -20664,7 +21122,8 @@ function resolveRequirementsApplicability(requirements) {
bounds: ["units", "x", "y", "z"],
animation: ["clips"],
representation: ["precomputedTangents"],
- externalSupport: ["supports"]
+ externalSupport: ["supports"],
+ validation: ["version", "profileId", "mode", "checks"]
};
for (const [key, statement] of Object.entries(requirements.requirements)) {
if (statement?.state !== "requested")
@@ -20781,7 +21240,8 @@ var init_requirements_applicability = __esm(() => {
kernel: "connectivity"
},
{ id: "REF_COMPARISON", mode: "observe", keys: [], observation: true },
- { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" }
+ { id: "SWEEP_SELF_INTERSECTION", mode: "observe", keys: [], observation: true, kernel: "sweep" },
+ { id: "HOST_VALIDATION_PROFILE", mode: "enforce", keys: ["validation"], kernel: "validation" }
];
});
@@ -20923,16 +21383,16 @@ var init_requirements_report = __esm(() => {
});
// src/rebuild-options.ts
-import { z as z7 } from "zod";
+import { z as z8 } from "zod";
var FULL_OPTIMIZATION_PIPELINE = "rigid-v1", rebuildOptionsSchema;
var init_rebuild_options = __esm(() => {
- rebuildOptionsSchema = z7.object({
- indexPolicy: z7.enum(["indexed", "asBuilt"]).optional(),
- gltfExporter: z7.enum(["legacy", "three"]),
- geometryPolicy: z7.enum(["warn", "strict"]),
- optimize: z7.enum(["off", "auto", "palette", "full"]),
- optimizationPipeline: z7.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
- instance: z7.enum(["off", "auto", "on"])
+ rebuildOptionsSchema = z8.object({
+ indexPolicy: z8.enum(["indexed", "asBuilt"]).optional(),
+ gltfExporter: z8.enum(["legacy", "three"]),
+ geometryPolicy: z8.enum(["warn", "strict"]),
+ optimize: z8.enum(["off", "auto", "palette", "full"]),
+ optimizationPipeline: z8.literal(FULL_OPTIMIZATION_PIPELINE).optional(),
+ instance: z8.enum(["off", "auto", "on"])
});
});
@@ -21365,6 +21825,8 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {
}
if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation)
continue;
+ if (decision.ruleId === HOST_VALIDATION_QA_RULE.id)
+ continue;
if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D15))
continue;
executedRules.push(decision.ruleId);
@@ -21413,14 +21875,17 @@ function runRequirementsSceneQa(context, scene, clips, policy = {}, evidence = {
} : {}
});
}
-function appendRequirementsQa(context, report, findings, metrics = {}) {
+function appendRequirementsQa(context, report, findings, metrics = {}, executedRules = []) {
const priorMetrics = Object.fromEntries(Object.entries(report.dimensions).flatMap(([dimension, value]) => value.metrics ? [[dimension, value.metrics]] : []));
const merged = { ...priorMetrics };
for (const [dimension, value] of Object.entries(metrics ?? {}))
merged[dimension] = { ...priorMetrics[dimension], ...value };
return createRequirementsQaReport(context, {
findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
- executedRules: report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ executedRules: [
+ ...report.rules.filter((x) => x.status === "evaluated").map((x) => x.id),
+ ...executedRules
+ ],
modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
evaluatedDimensions: [
...new Set([
@@ -21496,6 +21961,16 @@ async function appendRequirementsFinalQa(context, report, gltf, bytes, instancea
exportIntegrity: finalEffectsMetrics(evidence)
});
}
+ const validation = context.requirements.requirements.validation;
+ const hostRule = report.rules.find((r) => r.id === HOST_VALIDATION_QA_RULE.id);
+ if (validation?.state === "requested" && hostRule && hostRule.status !== "notRequested" && hostRule.mode !== "off") {
+ const evaluation = await evaluateValidationProfileGlb(validation.value, bytes);
+ const findings = hostRule.mode === "enforce" ? evaluation.findings : evaluation.findings.map((f) => ({
+ ...f,
+ disposition: f.disposition === "observe" ? f.disposition : hostRule.mode
+ }));
+ result = appendRequirementsQa(context, result, findings, { requirementReadiness: evaluation.metrics }, evaluation.complete ? [HOST_VALIDATION_QA_RULE.id] : []);
+ }
return result;
}
var registry;
@@ -21518,6 +21993,7 @@ var init_requirements_run = __esm(() => {
init_architecture();
init_environment2();
init_requirements_applicability();
+ init_validation_profile2();
init_requirements_report();
init_run();
registry = new QaRegistry([
@@ -21536,7 +22012,8 @@ var init_requirements_run = __esm(() => {
CHARACTER_ADVISORY_QA_RULE,
VFX_EXACT_QA_RULE,
VFX_ADVISORY_QA_RULE,
- ASSET_SCOPE_QA_RULE
+ ASSET_SCOPE_QA_RULE,
+ HOST_VALIDATION_QA_RULE
]);
});
@@ -34448,7 +34925,7 @@ function strict(value, keys, label) {
throw new Error(`${label}.${key} is unknown${hint ? `; use ${KEY_HINTS[key]}` : ""}; accepted keys: ${keys.join(", ")}`);
}
}
-function finite2(n, label) {
+function finite3(n, label) {
if (!Number.isFinite(n))
throw new Error(`${label} must be finite`);
return n;
@@ -34587,7 +35064,7 @@ function validateResolvedAssetCamera(value) {
throw new Error("camera target must differ from position");
if (up.length() < 0.000000001 || view.clone().cross(up).length() <= view.length() * up.length() * 0.000000001)
throw new Error("camera up must be non-zero and not collinear with view");
- if (finite2(camera.aspect, "aspect") <= 0 || finite2(camera.near, "near") <= 0 || finite2(camera.far, "far") <= camera.near)
+ if (finite3(camera.aspect, "aspect") <= 0 || finite3(camera.near, "near") <= 0 || finite3(camera.far, "far") <= camera.near)
throw new Error("camera requires positive aspect and 0 < near < far");
if (camera.projection === "orthographic") {
if (!Number.isFinite(camera.halfHeight) || camera.halfHeight <= 0 || camera.fovDeg !== undefined)
@@ -34617,7 +35094,7 @@ function resolveAssetCamera(root, shot = {}) {
const relative = request.relativeTo ?? "world";
if (!["world", "asset", "part"].includes(relative))
throw new Error("invalid relativeTo");
- const dir = vec(orbitDir(finite2(request.azimuthDeg ?? 45, "azimuthDeg"), finite2(request.elevationDeg ?? 25, "elevationDeg")));
+ const dir = vec(orbitDir(finite3(request.azimuthDeg ?? 45, "azimuthDeg"), finite3(request.elevationDeg ?? 25, "elevationDeg")));
let up;
if (relative !== "world") {
const node = relative === "part" ? selected.node : rootNode;
@@ -34695,7 +35172,7 @@ function resolveAssetCamera(root, shot = {}) {
far: request.far ?? fit.far
};
else {
- const fov = finite2(request.fovDeg ?? 50, "fovDeg");
+ const fov = finite3(request.fovDeg ?? 50, "fovDeg");
if (fov <= 0 || fov >= 180)
throw new Error("invalid fovDeg");
const distance = Math.max(radius / 2, 0.000001) * padding / Math.sin(fov * Math.PI / 360);
@@ -39157,11 +39634,11 @@ var init_subprocess = __esm(() => {
});
// src/projects.ts
-import { z as z8 } from "zod";
+import { z as z9 } from "zod";
function checkContent(data, ctx) {
const unique = (items, path) => {
if (new Set(items).size !== items.length)
- ctx.addIssue({ code: z8.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
+ ctx.addIssue({ code: z9.ZodIssueCode.custom, path: [path], message: "Duplicate identity" });
};
unique(data.inventory.map((v) => v.id), "inventory");
unique(data.references.map((v) => v.id), "references");
@@ -39177,20 +39654,20 @@ function checkContent(data, ctx) {
unique(item.references, `inventory.${item.id}.references`);
if (item.references.some((id) => !references.has(id)))
ctx.addIssue({
- code: z8.ZodIssueCode.custom,
+ code: z9.ZodIssueCode.custom,
path: ["inventory"],
message: "Unknown reference"
});
}
if (data.reviews.some((review) => !inventory.has(review.inventoryId)))
ctx.addIssue({
- code: z8.ZodIssueCode.custom,
+ code: z9.ZodIssueCode.custom,
path: ["reviews"],
message: "Unknown inventory item"
});
if (data.design.materialRoles.some((role) => role.resourceId && !resources.has(role.resourceId)))
ctx.addIssue({
- code: z8.ZodIssueCode.custom,
+ code: z9.ZodIssueCode.custom,
path: ["design"],
message: "Material role requires a locked resource"
});
@@ -39198,80 +39675,80 @@ function checkContent(data, ctx) {
var MAX_PROJECT_BYTES, MAX_PROJECT_REVISIONS = 1e4, projectIdSchema, projectRevisionIdSchema, hash5, text5, resourceId2, assetReference, projectDesignSchema, projectMaterialDependencySchema, materialDependenciesSchema, content, projectDraftSchema, projectPatchSchema, projectRevisionSchema, ProjectConflictError, ProjectNotFoundError, ProjectExistsError;
var init_projects = __esm(() => {
MAX_PROJECT_BYTES = 1024 * 1024;
- projectIdSchema = z8.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
- projectRevisionIdSchema = z8.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
- hash5 = z8.string().regex(/^sha256:[a-f0-9]{64}$/);
- text5 = z8.string().max(4000);
- resourceId2 = z8.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
- assetReference = z8.object({
+ projectIdSchema = z9.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).refine((value) => !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(value), "Reserved filesystem name");
+ projectRevisionIdSchema = z9.string().regex(/^r_[0-9]{10}_[a-f0-9]{64}$/);
+ hash5 = z9.string().regex(/^sha256:[a-f0-9]{64}$/);
+ text5 = z9.string().max(4000);
+ resourceId2 = z9.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:/-]{0,199}$/);
+ assetReference = z9.object({
collectionId: projectIdSchema,
assetId: projectIdSchema,
revisionId: projectIdSchema
}).strict();
- projectDesignSchema = z8.object({
+ projectDesignSchema = z9.object({
style: text5.default(""),
- scale: z8.string().max(1000).default(""),
- palette: z8.array(z8.object({
- role: z8.string().min(1).max(100),
- color: z8.string().regex(/^#[a-fA-F0-9]{6}$/)
+ scale: z9.string().max(1000).default(""),
+ palette: z9.array(z9.object({
+ role: z9.string().min(1).max(100),
+ color: z9.string().regex(/^#[a-fA-F0-9]{6}$/)
}).strict()).max(64).default([]),
- materialRoles: z8.array(z8.object({
- role: z8.string().min(1).max(100),
+ materialRoles: z9.array(z9.object({
+ role: z9.string().min(1).max(100),
description: text5.default(""),
resourceId: resourceId2.optional()
}).strict()).max(128).default([]),
- conventions: z8.array(z8.string().max(1000)).max(100).default([]),
- exceptions: z8.array(z8.string().max(1000)).max(100).default([])
+ conventions: z9.array(z9.string().max(1000)).max(100).default([]),
+ exceptions: z9.array(z9.string().max(1000)).max(100).default([])
}).strict();
- projectMaterialDependencySchema = z8.object({
+ projectMaterialDependencySchema = z9.object({
resourceId: resourceId2,
- revisionId: z8.string().min(1).max(200),
+ revisionId: z9.string().min(1).max(200),
sha256: hash5,
- role: z8.string().max(100).optional()
+ role: z9.string().max(100).optional()
}).strict();
- materialDependenciesSchema = z8.array(projectMaterialDependencySchema).max(512);
+ materialDependenciesSchema = z9.array(projectMaterialDependencySchema).max(512);
content = {
- name: z8.string().trim().min(1).max(200),
- brief: z8.string().max(16000).default(""),
+ name: z9.string().trim().min(1).max(200),
+ brief: z9.string().max(16000).default(""),
design: projectDesignSchema.default(() => projectDesignSchema.parse({})),
- inventory: z8.array(z8.object({
+ inventory: z9.array(z9.object({
id: projectIdSchema,
- name: z8.string().trim().min(1).max(200),
- kind: z8.enum(["asset", "environment"]).default("asset"),
+ name: z9.string().trim().min(1).max(200),
+ kind: z9.enum(["asset", "environment"]).default("asset"),
brief: text5.default(""),
- references: z8.array(projectIdSchema).max(64).default([]),
+ references: z9.array(projectIdSchema).max(64).default([]),
asset: assetReference.optional()
}).strict()).max(1000).default([]),
- deliveryProfiles: z8.array(z8.object({
+ deliveryProfiles: z9.array(z9.object({
id: projectIdSchema,
- target: z8.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
+ target: z9.enum(["three", "godot", "unity", "unreal", "roblox", "sbox", "usdz", "custom"]),
description: text5.default(""),
- performanceIntent: z8.string().max(1000).default(""),
- constraints: z8.array(z8.string().max(1000)).max(100).default([])
+ performanceIntent: z9.string().max(1000).default(""),
+ constraints: z9.array(z9.string().max(1000)).max(100).default([])
}).strict()).max(32).default([]),
materialDependencies: materialDependenciesSchema.default([]),
- references: z8.array(z8.object({
+ references: z9.array(z9.object({
id: projectIdSchema,
- title: z8.string().min(1).max(200),
- uri: z8.string().min(1).max(2048),
+ title: z9.string().min(1).max(200),
+ uri: z9.string().min(1).max(2048),
description: text5.default(""),
sha256: hash5.optional()
}).strict()).max(256).default([]),
- reviews: z8.array(z8.object({
+ reviews: z9.array(z9.object({
id: projectIdSchema,
inventoryId: projectIdSchema,
projectRevisionId: projectRevisionIdSchema,
asset: assetReference,
- reviewer: z8.string().trim().min(1).max(200),
- verdict: z8.enum(["comment", "changes-requested", "accepted"]),
+ reviewer: z9.string().trim().min(1).max(200),
+ verdict: z9.enum(["comment", "changes-requested", "accepted"]),
notes: text5
}).strict()).max(2000).default([])
};
- projectDraftSchema = z8.object({
+ projectDraftSchema = z9.object({
projectId: projectIdSchema.optional(),
...content
}).strict().superRefine(checkContent);
- projectPatchSchema = z8.object({
+ projectPatchSchema = z9.object({
name: content.name.optional(),
brief: content.brief.removeDefault().optional(),
design: content.design.removeDefault().optional(),
@@ -39281,12 +39758,12 @@ var init_projects = __esm(() => {
references: content.references.removeDefault().optional(),
reviews: content.reviews.removeDefault().optional()
}).strict();
- projectRevisionSchema = z8.object({
- version: z8.literal("kiln.project.v1"),
+ projectRevisionSchema = z9.object({
+ version: z9.literal("kiln.project.v1"),
projectId: projectIdSchema,
revisionId: projectRevisionIdSchema,
parentRevision: projectRevisionIdSchema.optional(),
- createdAt: z8.string().datetime(),
+ createdAt: z9.string().datetime(),
...content
}).strict().superRefine(checkContent);
ProjectConflictError = class ProjectConflictError extends Error {
@@ -39325,7 +39802,7 @@ var init_projects = __esm(() => {
});
// src/project-bundle.ts
-import { z as z10 } from "zod";
+import { z as z11 } from "zod";
import { zipSync as zipSync2, unzipSync as unzipSync2 } from "three/addons/libs/fflate.module.js";
async function projectBundleHash(bytes) {
const result = new Uint8Array(await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes)));
@@ -39486,7 +39963,7 @@ async function encodeProjectBundle(input, profile = "editable") {
files["bundle.json"] = manifestBytes;
return zipSync2(files, { level: 0, mtime: new Date(1980, 0, 1) });
}
-var PROJECT_BUNDLE_LIMITS, hashSchema, id = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2, bytesOf2 = (value) => encoder3.encode(JSON.stringify(value)), assetPrefix = (entry) => `assets/${entry.collectionId}/${entry.assetId}/${entry.revisionId}/`, materialPrefix = (entry) => `materials/${entry.materialId}/${entry.revisionId.slice(7)}/`;
+var PROJECT_BUNDLE_LIMITS, hashSchema, id2 = "[a-z][a-z0-9_-]{0,79}", pathSchema, identitySchema, projectBundleManifestSchema, projectBundleManifestV2Schema, projectBundleManifestAnySchema, encoder3, decoder2, bytesOf2 = (value) => encoder3.encode(JSON.stringify(value)), assetPrefix = (entry) => `assets/${entry.collectionId}/${entry.assetId}/${entry.revisionId}/`, materialPrefix = (entry) => `materials/${entry.materialId}/${entry.revisionId.slice(7)}/`;
var init_project_bundle = __esm(() => {
init_assets();
init_asset_export();
@@ -39498,33 +39975,33 @@ var init_project_bundle = __esm(() => {
maxEntries: 8192,
maxManifestBytes: 2 * 1024 * 1024
});
- hashSchema = z10.string().regex(/^sha256:[a-f0-9]{64}$/);
- pathSchema = z10.string().regex(new RegExp(`^(project\\.json|materials/${id}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id}/${id}/${id}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
- identitySchema = z10.object({
+ hashSchema = z11.string().regex(/^sha256:[a-f0-9]{64}$/);
+ pathSchema = z11.string().regex(new RegExp(`^(project\\.json|materials/${id2}/[a-f0-9]{64}/(manifest\\.json|baseColor\\.png|normal\\.png|metallicRoughness\\.png|emissive\\.png|occlusion\\.png)|assets/${id2}/${id2}/${id2}/(manifest\\.json|asset\\.glb|source\\.kiln\\.js|preview\\.png|runtime\\.glb|runtime\\.kiln-metadata\\.json))$`));
+ identitySchema = z11.object({
inventoryId: assetIdSchema,
collectionId: assetIdSchema,
assetId: assetIdSchema,
revisionId: assetIdSchema,
canonicalGlbSha256: hashSchema
}).strict();
- projectBundleManifestSchema = z10.object({
- version: z10.literal("kiln.project-bundle.v1"),
- profile: z10.enum(["editable", "runtime"]),
- editable: z10.boolean(),
- resourceClosure: z10.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
- referenceMediaIncluded: z10.literal(false),
- originalAcquisitionFilesIncluded: z10.literal(false),
- assets: z10.array(identitySchema).max(1000),
- materials: z10.array(z10.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
- files: z10.record(pathSchema, z10.object({
+ projectBundleManifestSchema = z11.object({
+ version: z11.literal("kiln.project-bundle.v1"),
+ profile: z11.enum(["editable", "runtime"]),
+ editable: z11.boolean(),
+ resourceClosure: z11.enum(["normalized-maps-and-procedural-recipes", "embedded-runtime-only"]),
+ referenceMediaIncluded: z11.literal(false),
+ originalAcquisitionFilesIncluded: z11.literal(false),
+ assets: z11.array(identitySchema).max(1000),
+ materials: z11.array(z11.object({ materialId: assetIdSchema, revisionId: hashSchema }).strict()).max(1024),
+ files: z11.record(pathSchema, z11.object({
sha256: hashSchema,
- bytes: z10.number().int().nonnegative().max(64 * 1024 * 1024)
+ bytes: z11.number().int().nonnegative().max(64 * 1024 * 1024)
}).strict())
}).strict();
projectBundleManifestV2Schema = projectBundleManifestSchema.extend({
- version: z10.literal("kiln.project-bundle.v2")
+ version: z11.literal("kiln.project-bundle.v2")
});
- projectBundleManifestAnySchema = z10.union([
+ projectBundleManifestAnySchema = z11.union([
projectBundleManifestSchema,
projectBundleManifestV2Schema
]);
@@ -39805,10 +40282,10 @@ function createPartPlacementReader(root) {
};
};
}
-var round2 = (value) => {
+var round3 = (value) => {
const rounded = Math.round(value * 1e6) / 1e6;
return rounded === 0 ? 0 : rounded;
-}, rounded2 = (values) => values.map(round2);
+}, rounded2 = (values) => values.map(round3);
var init_part_placement = __esm(() => {
init_raster();
});
@@ -43708,8 +44185,8 @@ init_material_library_node();
// src/workspace.ts
init_projects();
-import { z as z9 } from "zod";
-var workspaceSelectionSchema = z9.object({
+import { z as z10 } from "zod";
+var workspaceSelectionSchema = z10.object({
projectId: projectIdSchema.nullable().optional().describe("Project; omit for the configured default, null for standalone."),
projectRevision: projectRevisionIdSchema.optional().describe("Exact project revision."),
materialDependencies: materialDependenciesSchema.optional().describe("Pins for this call; each replaces the project pin of its resourceId.")
@@ -44242,7 +44719,7 @@ var PRE_HANDSHAKE_METHODS = new Set(["initialize", "ping"]);
// src/tools/registry.ts
init_capture_cache();
init_assets();
-import { z as z24 } from "zod";
+import { z as z25 } from "zod";
// src/requirements-assets.ts
init_requirements_context();
@@ -44273,10 +44750,10 @@ function assertSavedRequirementsAuthorized(manifest, current) {
}
// src/tools/programs.ts
-import { z as z12 } from "zod";
+import { z as z13 } from "zod";
// src/tools/review-detail.ts
-import { z as z11 } from "zod";
+import { z as z12 } from "zod";
var COMPACT_PART_PREVIEW = 24;
var COMPACT_FINDINGS_PER_DIMENSION = 12;
var LEAD_BLOCKERS = 8;
@@ -44286,7 +44763,7 @@ var WARNING_CHARS = 1000;
var DEFAULT_RESULT_LIMIT = 20000;
var MAX_RESULT_LIMIT = 40000;
var COMPACT_DECIMALS = 6;
-var reviewDetailInput = z11.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
+var reviewDetailInput = z12.enum(["lean", "compact", "full"]).optional().describe("compact (default) groups findings by code; lean: verdict, blockers, metrics only; full: every finding, rule and part plus the retained report path");
function requestedDetail(input, fallback = "compact") {
const detail = input?.detail;
return detail === "full" || detail === "lean" || detail === "compact" ? detail : fallback;
@@ -44852,19 +45329,19 @@ function compactEditResult(result, detail = "compact", options = {}) {
}
// src/tools/programs.ts
-var refInput = z12.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
+var refInput = z13.string().regex(programRefPattern).describe("Returned p_ handle or full sha256 ref.");
function withProgramReferences(def, store, readSourceFile) {
- if (!(def.inputSchema instanceof z12.ZodObject))
+ if (!(def.inputSchema instanceof z13.ZodObject))
throw new Error(`${def.name} must have an object input schema.`);
const sources = readSourceFile ? "code, programRef OR file" : "code OR programRef";
const inputSchema = def.inputSchema.extend({
- code: z12.string().optional().describe("New source."),
+ code: z13.string().optional().describe("New source."),
programRef: refInput.optional(),
...readSourceFile ? {
- file: z12.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
+ file: z13.string().min(1).max(1024).optional().describe("A program file inside the workspace, relative to its root.")
} : {},
...def.name === "kiln_edit" ? {
- includeCode: z12.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
+ includeCode: z13.boolean().optional().describe("Also return the patched source, bounded with the result; kiln_source pages it. Default false.")
} : {}
}).refine((input) => [input.code, input.programRef, input.file].filter((value) => value !== undefined).length === 1, { message: `Supply exactly one of ${sources.replace(" OR ", " or ")}.` });
const summaries = {
@@ -44917,11 +45394,11 @@ function boundIncludedCode(result, limit) {
};
}
function createKilnSourceDef(store) {
- const inputSchema = z12.object({
+ const inputSchema = z13.object({
programRef: refInput,
- offset: z12.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
- limit: z12.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
- query: z12.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
+ offset: z13.number().int().min(0).default(0).describe("UTF-16 character offset; use nextOffset to continue."),
+ limit: z13.number().int().min(1).max(16000).default(8000).describe("Maximum characters returned."),
+ query: z13.string().min(1).max(1000).optional().describe("Find literal text at or after offset; return bounded surrounding source.")
});
return {
name: "kiln_source",
@@ -44954,34 +45431,34 @@ init_requirements_context();
init_helper_specs();
// src/discovery/catalog-schema.ts
-import { z as z13 } from "zod";
-var text6 = z13.string().trim().min(1);
-var texts = z13.array(text6);
-var id2 = z13.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
+import { z as z14 } from "zod";
+var text6 = z14.string().trim().min(1);
+var texts = z14.array(text6);
+var id3 = z14.string().regex(/^(operation|assembly|recipe|shape):[A-Za-z][A-Za-z0-9-]*$/);
var common = {
- version: z13.literal("kiln.catalog-entry.v1"),
- id: id2,
+ version: z14.literal("kiln.catalog-entry.v1"),
+ id: id3,
name: text6,
summary: text6.max(500),
family: text6.max(80),
tags: texts,
aliases: texts,
intents: texts,
- stability: z13.enum(["stable", "experimental", "deprecated"]),
- related: z13.array(z13.object({
- id: id2,
- relation: z13.enum(["alternative", "prerequisite", "companion"])
+ stability: z14.enum(["stable", "experimental", "deprecated"]),
+ related: z14.array(z14.object({
+ id: id3,
+ relation: z14.enum(["alternative", "prerequisite", "companion"])
}).strict()),
references: texts,
limitations: texts
};
-var operationContractSchema = z13.object({
+var operationContractSchema = z14.object({
signature: text6,
returns: text6,
units: text6,
axes: text6,
origin: text6,
- execution: z13.enum(["sync", "async"]),
+ execution: z14.enum(["sync", "async"]),
ownership: text6,
coordinates: text6,
parameters: texts,
@@ -44991,24 +45468,24 @@ var operationContractSchema = z13.object({
cost: text6,
example: text6
}).strict();
-var discoveryEntrySchema = z13.discriminatedUnion("kind", [
- z13.object({ ...common, kind: z13.literal("operation"), contract: operationContractSchema }).strict(),
- z13.object({ ...common, kind: z13.literal("assembly"), contract: operationContractSchema }).strict(),
- z13.object({
+var discoveryEntrySchema = z14.discriminatedUnion("kind", [
+ z14.object({ ...common, kind: z14.literal("operation"), contract: operationContractSchema }).strict(),
+ z14.object({ ...common, kind: z14.literal("assembly"), contract: operationContractSchema }).strict(),
+ z14.object({
...common,
- kind: z13.literal("recipe"),
- recipe: z13.object({
- prerequisites: z13.array(id2),
+ kind: z14.literal("recipe"),
+ recipe: z14.object({
+ prerequisites: z14.array(id3),
steps: texts.min(1),
example: text6,
adaptations: texts,
checks: texts
}).strict()
}).strict(),
- z13.object({
+ z14.object({
...common,
- kind: z13.literal("shape"),
- shape: z13.object({ tool: text6, field: text6, schema: z13.record(z13.string(), z13.unknown()) }).strict()
+ kind: z14.literal("shape"),
+ shape: z14.object({ tool: text6, field: text6, schema: z14.record(z14.string(), z14.unknown()) }).strict()
}).strict()
]).superRefine((entry, ctx) => {
if (!entry.id.startsWith(`${entry.kind}:`)) {
@@ -45027,7 +45504,7 @@ var discoveryEntrySchema = z13.discriminatedUnion("kind", [
}
});
function parseCatalog(value) {
- const entries = z13.array(discoveryEntrySchema).parse(value);
+ const entries = z14.array(discoveryEntrySchema).parse(value);
const ids = new Set;
const names = new Set;
for (const entry of entries) {
@@ -48622,24 +49099,24 @@ var discoveryRecipes = [
// src/discovery/shapes.ts
init_material_library();
init_projects();
-import { z as z15 } from "zod";
+import { z as z16 } from "zod";
// src/tools/capture-input.ts
init_background();
init_capture_limits();
-import { z as z14 } from "zod";
-var backdropInput = z14.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
-var legacyCaptureInput = z14.object({
- preset: z14.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
- cells: z14.array(z14.object({
- azimuthDeg: z14.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
- elevationDeg: z14.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
- zoom: z14.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
- name: z14.string().optional().describe("Label; defaults to angles.")
+import { z as z15 } from "zod";
+var backdropInput = z15.enum(BACKDROP_IDS).optional().describe("neutral (default); light for dark parts, dark for light parts.");
+var legacyCaptureInput = z15.object({
+ preset: z15.enum(["1x1", "1x2", "2x1", "3x1", "2x2", "3x2", "3x3"]).optional().describe("COLSxROWS; default 3x2. Fewer views for simple shapes, up to 3x3."),
+ cells: z15.array(z15.object({
+ azimuthDeg: z15.number().describe("0 = front, 90 = right, 180 = back, 270 = left. Wraps."),
+ elevationDeg: z15.number().describe("0 eye level; positive above, negative below. Clamped -89..89."),
+ zoom: z15.number().optional().describe("Bounds padding: below 1 crops, above 1 pulls back; omit for auto-framing."),
+ name: z15.string().optional().describe("Label; defaults to angles.")
})).optional().describe("Row-major cameras; omit for preset defaults. Count cannot exceed preset capacity (max 9)."),
backdrop: backdropInput
}).optional().describe("Sheet layout and cameras; omit for six views in a 3x2 grid.");
-var cameraVec3Input = z14.array(z14.number()).length(3);
+var cameraVec3Input = z15.array(z15.number()).length(3);
var orbitCameraError = (issue) => {
if (issue.code === "unrecognized_keys" && issue.keys?.some((key) => key === "target" || key === "distance")) {
return "Orbit cameras derive target and distance from the selected subject bounds; choose subject and padding, or use an explicit camera with position and target.";
@@ -48659,48 +49136,48 @@ var advancedCaptureError = (issue) => {
}
return;
};
-var cameraShotInput = z14.object({
- name: z14.string().optional(),
- subject: z14.object({ path: z14.string().optional(), name: z14.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
+var cameraShotInput = z15.object({
+ name: z15.string().optional(),
+ subject: z15.object({ path: z15.string().optional(), name: z15.string().optional() }).strict().refine((v) => v.path === undefined !== (v.name === undefined), {
message: "Choose subject path OR exact name."
}).optional(),
- visibility: z14.enum(["context", "isolate"]).optional(),
- hide: z14.array(z14.string().min(1).max(1024)).max(64).optional(),
- camera: z14.discriminatedUnion("type", [
- z14.strictObject({
- type: z14.literal("orbit"),
- azimuthDeg: z14.number().optional(),
- elevationDeg: z14.number().optional(),
- relativeTo: z14.enum(["world", "asset", "part"]).optional(),
- padding: z14.number().positive().max(100).optional()
+ visibility: z15.enum(["context", "isolate"]).optional(),
+ hide: z15.array(z15.string().min(1).max(1024)).max(64).optional(),
+ camera: z15.discriminatedUnion("type", [
+ z15.strictObject({
+ type: z15.literal("orbit"),
+ azimuthDeg: z15.number().optional(),
+ elevationDeg: z15.number().optional(),
+ relativeTo: z15.enum(["world", "asset", "part"]).optional(),
+ padding: z15.number().positive().max(100).optional()
}, { error: orbitCameraError }),
- z14.strictObject({
- type: z14.literal("explicit"),
- projection: z14.enum(["orthographic", "perspective"]),
+ z15.strictObject({
+ type: z15.literal("explicit"),
+ projection: z15.enum(["orthographic", "perspective"]),
position: cameraVec3Input,
target: cameraVec3Input.optional(),
- relativeTo: z14.enum(["world", "asset", "part", "local"]).optional(),
- frame: z14.object({
+ relativeTo: z15.enum(["world", "asset", "part", "local"]).optional(),
+ frame: z15.object({
origin: cameraVec3Input.optional(),
rotation: cameraVec3Input.optional()
}).strict().optional(),
- framing: z14.enum(["explicit", "bounds"]).optional(),
- padding: z14.number().positive().max(100).optional(),
+ framing: z15.enum(["explicit", "bounds"]).optional(),
+ padding: z15.number().positive().max(100).optional(),
targetOffset: cameraVec3Input.optional(),
up: cameraVec3Input.optional(),
- halfHeight: z14.number().positive().optional(),
- fovDeg: z14.number().positive().lt(180).optional(),
- near: z14.number().positive().optional(),
- far: z14.number().positive().optional()
+ halfHeight: z15.number().positive().optional(),
+ fovDeg: z15.number().positive().lt(180).optional(),
+ near: z15.number().positive().optional(),
+ far: z15.number().positive().optional()
}, { error: explicitCameraError })
]).optional()
}).strict();
-var advancedCaptureInput = z14.strictObject({
- version: z14.enum(["kiln.capture.v1", "kiln.capture.v2"]),
- shots: z14.array(cameraShotInput).min(1).max(9),
- cols: z14.number().int().min(1).max(3).optional(),
- size: z14.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
- output: z14.enum(["grid", "separate"]).optional(),
+var advancedCaptureInput = z15.strictObject({
+ version: z15.enum(["kiln.capture.v1", "kiln.capture.v2"]),
+ shots: z15.array(cameraShotInput).min(1).max(9),
+ cols: z15.number().int().min(1).max(3).optional(),
+ size: z15.number().int().min(128).max(MAX_CAPTURE_SHOT_SIZE).optional(),
+ output: z15.enum(["grid", "separate"]).optional(),
backdrop: backdropInput
}, { error: advancedCaptureError }).superRefine((input, context) => {
if (input.version === "kiln.capture.v1" && input.shots.some((shot) => shot.hide !== undefined))
@@ -48721,19 +49198,19 @@ function taggedCaptureError(issue) {
const details = issues.slice(0, 6).map((problem) => `${problem.path.join(".") || "capture"}: ${problem.message.slice(0, 240)}`);
return `Invalid ${input.version}: ${details.join("; ")}${issues.length > 6 ? "; additional issues omitted" : ""}`;
}
-var captureShapeInput = z14.union([
+var captureShapeInput = z15.union([
advancedCaptureInput,
- z14.strictObject(legacyCaptureInput.unwrap().shape, {
+ z15.strictObject(legacyCaptureInput.unwrap().shape, {
error: taggedCaptureError
})
], { error: taggedCaptureError });
var captureInput = captureShapeInput.optional().describe("Omit for six views; preset/cells for orbit sheets. Use kiln.capture.v1 or v2 with 1..9 shots for exact cameras. v2 adds hide: exact paths or unique names. Framing retains subject bounds.");
-var captureRecordInput = z14.record(z14.string(), z14.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
-var cameraShotRecordInput = z14.record(z14.string(), z14.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
+var captureRecordInput = z15.record(z15.string(), z15.unknown()).optional().describe('Cameras, as kiln_render capture takes them. Shape: kiln_discover ids ["shape:capture"].');
+var cameraShotRecordInput = z15.record(z15.string(), z15.unknown()).optional().describe('One exact camera shot. Shape: kiln_discover ids ["shape:camera-shot"].');
// src/discovery/shapes.ts
var jsonSchema = (schema) => {
- const { $schema: _dialect, ...rest } = z15.toJSONSchema(schema, { io: "input", reused: "ref" });
+ const { $schema: _dialect, ...rest } = z16.toJSONSchema(schema, { io: "input", reused: "ref" });
return rest;
};
var shape2 = (name, tool, field, summary, schema, extra = {}) => ({
@@ -48931,25 +49408,25 @@ function createLexicalDiscoveryIndex(entries) {
}
// src/discovery/query-schema.ts
-import { z as z16 } from "zod";
-var selector = z16.string().trim().min(1).max(120);
+import { z as z17 } from "zod";
+var selector = z17.string().trim().min(1).max(120);
function discoverySelectorMigration(keys) {
if (!keys.some((key) => ["category", "name", "names"].includes(key)))
return;
return "Legacy Discovery selectors category/name/names were removed. Use query for search, ids (CLI --id) for exact contracts, and family (CLI --family), kind or tags for filtering. See docs/migration.md.";
}
-var discoveryInputSchema = z16.object({
- query: z16.string().trim().min(1).max(500).optional(),
- ids: z16.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
+var discoveryInputSchema = z17.object({
+ query: z17.string().trim().min(1).max(500).optional(),
+ ids: z17.array(selector).min(1).max(6).refine((ids) => new Set(ids).size === ids.length, {
message: "Exact IDs must be unique."
}).optional(),
- overview: z16.literal(true).optional(),
- capabilities: z16.literal(true).optional(),
+ overview: z17.literal(true).optional(),
+ capabilities: z17.literal(true).optional(),
family: selector.optional(),
- kind: z16.enum(["operation", "assembly", "recipe", "shape"]).optional(),
- tags: z16.array(selector).min(1).max(8).optional(),
- offset: z16.number().int().min(0).max(1e4).optional(),
- limit: z16.number().int().min(1).max(12).optional()
+ kind: z17.enum(["operation", "assembly", "recipe", "shape"]).optional(),
+ tags: z17.array(selector).min(1).max(8).optional(),
+ offset: z17.number().int().min(0).max(1e4).optional(),
+ limit: z17.number().int().min(1).max(12).optional()
}, {
error: (issue) => issue.code === "unrecognized_keys" ? discoverySelectorMigration(issue.keys) : undefined
}).strict().superRefine((input, context) => {
@@ -49216,6 +49693,7 @@ init_capture_limits();
init_geometry_export();
init_community_exporter();
init_material_resources();
+init_requirements_context();
function createKilnDiscoveryDef(context, presentation = "grouped") {
const run = createDiscovery(() => currentCapabilities(context, presentation), async () => projectNotes(context), presentation === "operations" ? "kiln_capabilities({})" : "capabilities:true");
return {
@@ -49235,6 +49713,15 @@ Suggestions: ${structured.suggestions.join(", ")}` : text;
function configuredProject(context) {
return context.workspace?.configured?.() ?? null;
}
+function hostRequirements(context) {
+ const active = resolveRequirementsContext(context.requirements);
+ const validation = active.requirements.requirements.validation;
+ return {
+ bound: active.binding !== undefined,
+ policyHash: active.policyHash,
+ declared: validation?.state === "requested" ? { source: "host-binding", validationProfile: validation.value } : null
+ };
+}
function projectNotes(context) {
const projectId = configuredProject(context);
return projectId ? [
@@ -49276,6 +49763,7 @@ async function currentCapabilities(context, presentation) {
read: 'kiln_project { action: "get", projectId } returns the brief, design, inventory and material pins'
},
renderer,
+ requirements: hostRequirements(context),
execution: context.localExecution ?? (context.evaluatorPort ? { mode: "host-injected", limits: "unspecified by host" } : context.evaluatorProfile === "evaluator-required" ? { mode: "host-required", available: false } : { mode: "trusted-local", terminable: false }),
source: {
...context.programStore?.stats ? { storage: await context.programStore.stats() } : {},
@@ -49341,7 +49829,7 @@ async function currentCapabilities(context, presentation) {
// src/tools/projects.ts
init_projects();
-import { z as z17 } from "zod";
+import { z as z18 } from "zod";
// src/tools/actions.ts
var list = (fields) => fields.length <= 1 ? fields.join("") : `${fields.slice(0, -1).join(", ")} and ${fields.at(-1)}`;
@@ -49404,16 +49892,16 @@ var REQUIREMENTS = {
},
export: { required: ["projectId"] }
};
-var record10 = (description) => z17.record(z17.string(), z17.unknown()).optional().describe(description);
+var record10 = (description) => z18.record(z18.string(), z18.unknown()).optional().describe(description);
function projectToolInput(actions = PROJECT_ACTIONS) {
- return z17.strictObject({
- action: z17.enum(actions),
+ return z18.strictObject({
+ action: z18.enum(actions),
projectId: projectIdSchema.optional().describe("get, update, export."),
revisionId: projectRevisionIdSchema.optional().describe("get, export: an exact revision; omit for the current one."),
expectedRevision: projectRevisionIdSchema.optional().describe("update: the revision being replaced; a stale value is a conflict."),
draft: record10(nestedRecordDescription("create: name, brief, design, inventory, deliveryProfiles, materialDependencies, references, reviews; optional projectId.", "shape:project-draft")),
patch: record10(nestedRecordDescription("update: the same top-level fields as draft; each supplied field replaces its previous value whole.", "shape:project-patch")),
- profile: z17.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
+ profile: z18.enum(["editable", "runtime"]).optional().describe("export: editable (default) keeps source and resources; runtime is GLB plus metadata.")
});
}
function createKilnProjectDef(store, bundleReader) {
@@ -49497,7 +49985,7 @@ async function listAssetCatalog(library) {
// src/tools/materials.ts
init_material_library();
init_material_library_node();
-import { z as z19 } from "zod";
+import { z as z20 } from "zod";
// src/material-authoring-node.ts
init_material_library();
@@ -49546,7 +50034,7 @@ async function createProceduralMaterialRecord(value, library) {
// src/material-presets.ts
init_material_library();
-import { z as z18 } from "zod";
+import { z as z19 } from "zod";
var catalog2 = [
{
id: "warm-brick",
@@ -49627,10 +50115,10 @@ var catalog2 = [
}
];
var RECORD_V2_PRESETS = new Set(["palm-frond"]);
-var materialPresetOptionsSchema = z18.object({
- seed: z18.number().int().min(-2147483648).max(2147483647),
- size: z18.union([z18.literal(64), z18.literal(128), z18.literal(256), z18.literal(512)]).default(256),
- creator: z18.string().min(1).max(1000),
+var materialPresetOptionsSchema = z19.object({
+ seed: z19.number().int().min(-2147483648).max(2147483647),
+ size: z19.union([z19.literal(64), z19.literal(128), z19.literal(256), z19.literal(512)]).default(256),
+ creator: z19.string().min(1).max(1000),
license: materialSourceSchema.shape.license,
materialId: materialLibraryIdSchema.optional()
}).strict();
@@ -49933,15 +50421,15 @@ var MATERIAL_CONTRACT = {
description: "Import complete normalized material records and embedded PNGs. Does not fetch URLs or execute source."
}
};
-var record11 = (description) => z19.record(z19.string(), z19.unknown()).optional().describe(description);
-var tag = z19.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
-var materialToolInput = z19.strictObject({
- action: z19.enum(MATERIAL_ACTIONS),
+var record11 = (description) => z20.record(z20.string(), z20.unknown()).optional().describe(description);
+var tag = z20.string().min(1).max(80).optional().describe("presets, list: keep one tag.");
+var materialToolInput = z20.strictObject({
+ action: z20.enum(MATERIAL_ACTIONS),
tag,
- presetId: z19.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
- seed: z19.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
- size: z19.union([z19.literal(64), z19.literal(128), z19.literal(256), z19.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
- creator: z19.string().min(1).max(1000).optional().describe("create-preset."),
+ presetId: z20.string().min(1).max(80).optional().describe("create-preset: an id from presets."),
+ seed: z20.number().int().min(-2147483648).max(2147483647).optional().describe("create-preset."),
+ size: z20.union([z20.literal(64), z20.literal(128), z20.literal(256), z20.literal(512)]).optional().describe("create-preset: map edge in pixels; default 256."),
+ creator: z20.string().min(1).max(1000).optional().describe("create-preset."),
license: materialSourceSchema.shape.license.optional().describe("create-preset: spdx, url and attribution."),
materialId: materialLibraryIdSchema.optional().describe("get: the id a project palette lists as resourceId; create-preset: optional id."),
revisionId: materialLibraryHashSchema.optional().describe("get: the immutable revision; omitted, the material's only revision."),
@@ -50058,7 +50546,7 @@ function createKilnMaterialDef(library, presentation = "grouped") {
// src/tools/review.ts
init_assets();
init_requirements_context();
-import { z as z20 } from "zod";
+import { z as z21 } from "zod";
init_background();
// src/tools/preview-fidelity.ts
@@ -50078,8 +50566,8 @@ async function persistedPreviewFidelity(fidelity, glb) {
}
// src/tools/review.ts
-var operationId = z20.string().regex(/^op_[a-f0-9-]{36}$/);
-var assetId = z20.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
+var operationId = z21.string().regex(/^op_[a-f0-9-]{36}$/);
+var assetId = z21.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
var REVIEW_ACTIONS = ["list", "get", "pin", "save"];
var REQUIREMENTS2 = {
list: { required: [] },
@@ -50087,20 +50575,20 @@ var REQUIREMENTS2 = {
pin: { required: ["operationId", "pinned"] },
save: { required: ["operationId", "expectedRevision", "name"] }
};
-var reviewToolInput = z20.strictObject({
- action: z20.enum(REVIEW_ACTIONS),
+var reviewToolInput = z21.strictObject({
+ action: z21.enum(REVIEW_ACTIONS),
projectId: assetId.optional().describe("list: only operations bound to this project."),
- offset: z20.number().int().min(0).optional().describe("list: page start; default 0."),
- limit: z20.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
+ offset: z21.number().int().min(0).optional().describe("list: page start; default 0."),
+ limit: z21.number().int().min(1).max(100).optional().describe("list: page size; default 20."),
operationId: operationId.optional().describe("get, pin, save."),
- pinned: z20.boolean().optional().describe("pin: true keeps the operation past normal retention."),
- expectedRevision: z20.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
+ pinned: z21.boolean().optional().describe("pin: true keeps the operation past normal retention."),
+ expectedRevision: z21.number().int().nonnegative().optional().describe("save: the revision the listing displayed."),
collection: assetId.optional().describe("save: destination collection; default project."),
- name: z20.string().min(1).max(200).optional().describe("save."),
+ name: z21.string().min(1).max(200).optional().describe("save."),
assetId: assetId.optional().describe("save: revise this asset."),
parentRevision: assetId.optional().describe("save: the revision being revised."),
- description: z20.string().max(4000).optional().describe("save."),
- tags: z20.array(z20.string().max(80)).max(30).optional().describe("save.")
+ description: z21.string().max(4000).optional().describe("save."),
+ tags: z21.array(z21.string().max(80)).max(30).optional().describe("save.")
});
var DEFAULT_PAGE = 20;
function summarizeOperation(operation) {
@@ -50235,7 +50723,7 @@ function createKilnReviewDef(context) {
}))
];
const preview = operation.captures[0] ? await store.readFile(operation.operationId, operation.captures[0].name) : undefined;
- const capture = z20.object({ backdrop: z20.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
+ const capture = z21.object({ backdrop: z21.enum(BACKDROP_IDS).optional() }).safeParse(operation.result?.capture);
const asset = await context.assetLibrary.save(collection, {
name: input.name,
assetId: input.assetId,
@@ -50272,7 +50760,7 @@ function createKilnReviewDef(context) {
}
// src/tools/workspace.ts
-import { z as z21 } from "zod";
+import { z as z22 } from "zod";
async function observeLiveReview(observer, tool, input, run) {
let authoring;
const invokeOnce = () => authoring ??= Promise.resolve().then(run);
@@ -50320,7 +50808,7 @@ async function observeWorkspaceOperation(context, tool, input, run) {
function withWorkspaceContext(def, context) {
if (!observed.has(def.name))
return def;
- const schema = context.workspace && def.inputSchema instanceof z21.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
+ const schema = context.workspace && def.inputSchema instanceof z22.ZodObject ? def.inputSchema.safeExtend(workspaceSelectionSchema.shape) : def.inputSchema;
return {
...def,
inputSchema: schema,
@@ -50336,14 +50824,14 @@ function withWorkspaceContext(def, context) {
}
// src/tools/operations.ts
-import { z as z23 } from "zod";
+import { z as z24 } from "zod";
// src/tools/operation-contract.ts
-import { z as z22 } from "zod";
+import { z as z23 } from "zod";
function projectActionSchemas(name, input, actions) {
if (input.def.checks?.length)
throw new Error(`${name}: cross-field constraints require an explicit operation schema`);
- const json = z22.toJSONSchema(input, { io: "input" });
+ const json = z23.toJSONSchema(input, { io: "input" });
const selector = json.properties?.action;
const expected = Object.keys(actions).sort();
if (!Array.isArray(selector?.enum) || JSON.stringify([...selector.enum].sort()) !== JSON.stringify(expected))
@@ -50371,7 +50859,7 @@ function projectActionSchemas(name, input, actions) {
const source = input.shape[field];
shape[field] = contract.required.includes(field) ? source.nonoptional() : source;
}
- schemas.push([action, z22.strictObject(shape)]);
+ schemas.push([action, z23.strictObject(shape)]);
}
return Object.fromEntries(schemas);
}
@@ -50395,7 +50883,7 @@ function projectOperationDefs(defs, context) {
});
}
function actionTools(def) {
- if (!(def.inputSchema instanceof z23.ZodObject) || !def.actionContract)
+ if (!(def.inputSchema instanceof z24.ZodObject) || !def.actionContract)
throw new Error(`${def.name}: missing shared action contract`);
const schemas = projectActionSchemas(def.name, def.inputSchema, def.actionContract);
return Object.fromEntries(Object.entries(def.actionContract).map(([action, contract]) => [
@@ -50443,7 +50931,7 @@ function materialOperations(def) {
const tools = actionTools(def);
const presets = tools.presets;
const inputSchema = presets.inputSchema.extend({
- scope: z23.enum(["all", "presets", "saved"]).default("all")
+ scope: z24.enum(["all", "presets", "saved"]).default("all")
});
const search = {
...presets,
@@ -50463,10 +50951,10 @@ function materialOperations(def) {
};
const preset = tools["create-preset"];
const procedural = tools["create-procedural"];
- const createInput = z23.strictObject({
- definition: z23.discriminatedUnion("kind", [
- preset.inputSchema.extend({ kind: z23.literal("preset") }),
- procedural.inputSchema.extend({ kind: z23.literal("procedural") })
+ const createInput = z24.strictObject({
+ definition: z24.discriminatedUnion("kind", [
+ preset.inputSchema.extend({ kind: z24.literal("preset") }),
+ procedural.inputSchema.extend({ kind: z24.literal("procedural") })
])
});
const create = {
@@ -50484,7 +50972,7 @@ function materialOperations(def) {
function rendererOperations(def, context) {
if (!context.renderCapabilities || !context.reprobeRenderer)
return [];
- const inputSchema = z23.strictObject({});
+ const inputSchema = z24.strictObject({});
return [
{
...def,
@@ -50501,8 +50989,8 @@ function rendererOperations(def, context) {
function discoveryOperations(def) {
const original = def.inputSchema;
const { capabilities: _capabilities, ...fields } = original.shape;
- const inputSchema = z23.strictObject(fields);
- const empty = z23.strictObject({});
+ const inputSchema = z24.strictObject(fields);
+ const empty = z24.strictObject({});
return [
{
...def,
@@ -51005,11 +51493,11 @@ function derivativeReviewFidelity(receipts) {
...reasonCodes.length ? { reasonCodes } : {}
};
}
-var validateInput = z24.object({
- code: z24.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
+var validateInput = z25.object({
+ code: z25.string().describe("Kiln source code (defines `meta` + `build()`, optional `animate()`).")
});
-var renderInput = z24.object({
- code: z24.string().describe("Kiln source code to execute and render to an in-memory GLB.")
+var renderInput = z25.object({
+ code: z25.string().describe("Kiln source code to execute and render to an in-memory GLB.")
});
var renderViewsInput = renderInput.extend({ capture: captureInput, detail: reviewDetailInput });
var reviewDetailOptions = (context) => ({
@@ -51022,26 +51510,26 @@ var reviewDetailOptions = (context) => ({
}
});
var renderViewsBufferInput = renderViewsInput.omit({ code: true });
-var screenshotAnimationInput = z24.object({
+var screenshotAnimationInput = z25.object({
shot: cameraShotInput.optional(),
- measureParts: z24.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
- frames: z24.number().int().min(2).max(6).optional(),
- frameTimes: z24.array(z24.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
- framing: z24.enum(["locked", "follow"]).optional(),
- size: z24.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
+ measureParts: z25.array(cameraShotInput.shape.subject.unwrap()).min(1).max(16).optional().describe("Exact names or paths of subtrees measured together at each phase, independent of camera selection."),
+ frames: z25.number().int().min(2).max(6).optional(),
+ frameTimes: z25.array(z25.number().min(0).max(1)).min(1).max(9).optional().describe("Ordered phase fractions 0..1; mutually exclusive with frames."),
+ framing: z25.enum(["locked", "follow"]).optional(),
+ size: z25.number().int().min(128).max(1024).optional().describe("Frame size in px; default 256."),
detail: reviewDetailInput,
- code: z24.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
- clip: z24.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
- camera: z24.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
- perFrame: z24.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
+ code: z25.string().describe("Kiln source code to execute; must define animate() returning the named clip."),
+ clip: z25.string().describe('The animation clip to view, by name (e.g. "walk", "attack"). Must be one your animate() returns.'),
+ camera: z25.string().optional().describe("Camera angle: right (default — side profile, best for leg swing + knee bend direction), front " + "(reveals sideways/lateral motion), back, left, top, or three-quarter."),
+ perFrame: z25.boolean().optional().describe("Return the frames as separate high-res images instead of one composite grid. Default false.")
});
var screenshotAnimationAdvertisedInput = screenshotAnimationInput.extend({
shot: cameraShotRecordInput
});
-var viewInteriorInput = z24.object({
+var viewInteriorInput = z25.object({
capture: advancedCaptureInput.optional(),
- code: z24.string().describe("Kiln source code to execute and render with the roof hidden."),
- nodeName: z24.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
+ code: z25.string().describe("Kiln source code to execute and render with the roof hidden."),
+ nodeName: z25.string().optional().describe("Override: lift the roof by exact node name instead of by role. Matches that node and its " + "children. Normally OMIT it — Kiln finds the roof from its semantic role (anything built " + 'with createRoofPlanes/createGableRoof), falling back to historical "Roof" naming.')
});
var viewInteriorAdvertisedInput = viewInteriorInput.extend({ capture: captureRecordInput });
function runValidate(input, context) {
@@ -51056,11 +51544,11 @@ function runValidate(input, context) {
warnings: result.warnings.map((w) => w.fixHint ? `${w.message} (${w.fixHint})` : w.message)
};
}
-var partListInput = z24.object({
- query: z24.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
- offset: z24.number().int().min(0).optional(),
- limit: z24.number().int().min(1).max(100).optional(),
- placement: z24.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
+var partListInput = z25.object({
+ query: z25.string().max(4096).optional().describe("Case-insensitive substring of name or exact encoded path; not a regex."),
+ offset: z25.number().int().min(0).optional(),
+ limit: z25.number().int().min(1).max(100).optional(),
+ placement: z25.boolean().optional().describe("Add world position, rotation, scale, mirroring and bounds per part; pages of 50.")
}).strict();
var PLACEMENT_PAGE_LIMIT = 50;
async function listPartNames2(root, options = {}) {
@@ -51534,35 +52022,35 @@ function createKilnViewInteriorDef(context = {}) {
};
}
var kilnViewInteriorDef = createKilnViewInteriorDef();
-var attachmentEndpointInput = z24.object({
- subject: z24.object({ path: z24.string().optional(), name: z24.string().optional() }).strict(),
+var attachmentEndpointInput = z25.object({
+ subject: z25.object({ path: z25.string().optional(), name: z25.string().optional() }).strict(),
point: cameraVec3Input.optional()
}).strict();
-var surfacePairInput = z24.array(z24.string().max(4096)).length(2);
-var inspectInput = z24.object({
- image: z24.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
+var surfacePairInput = z25.array(z25.string().max(4096)).length(2);
+var inspectInput = z25.object({
+ image: z25.boolean().optional().describe("False: requires listParts/measure/surfacePairs/compare; no image or camera controls. Default true."),
detail: reviewDetailInput,
listParts: partListInput.optional().describe("List exported-scene paths, including nested parts. Default 80, max 100 per page. Follow partListing.nextOffset with the same programRef/query. image:false avoids rendering."),
- surfacePairs: z24.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
- compare: z24.object({
- programRef: z24.string().regex(programRefPattern),
- offset: z24.number().int().min(0).optional(),
- limit: z24.number().int().min(1).max(100).optional(),
- paths: z24.array(z24.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
+ surfacePairs: z25.array(surfacePairInput).min(1).max(12).optional().describe("[from,to] pairs of exact listParts paths or unambiguous node names; check surfaceMeasurements.status and each result."),
+ compare: z25.object({
+ programRef: z25.string().regex(programRefPattern),
+ offset: z25.number().int().min(0).optional(),
+ limit: z25.number().int().min(1).max(100).optional(),
+ paths: z25.array(z25.string().max(4096)).min(1).max(12).optional().describe("Exact baseline node paths, scene-prefixed without primitive children. Complete subtree summaries.")
}).strict().optional().describe("Static geometry/material/transform/bounds under current host settings. Follow nextOffset; paths adds complete subtrees."),
- measure: z24.object({
- mode: z24.enum(["anchors", "surface"]).optional(),
+ measure: z25.object({
+ mode: z25.enum(["anchors", "surface"]).optional(),
from: attachmentEndpointInput,
to: attachmentEndpointInput
}).strict().optional().describe("Default anchors: origin/local-point distance. Surface: disjoint mesh triangles, omit points. Rest pose, asset units. Check status/bounds; no solid clearance/attachment proof."),
shot: cameraShotInput.optional().describe("Exact shot; omit part/view/orbit controls."),
- code: z24.string().describe("Kiln source code to execute and inspect."),
- part: z24.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
- view: z24.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
- azimuthDeg: z24.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
- elevationDeg: z24.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
- zoom: z24.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
- isolate: z24.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
+ code: z25.string().describe("Kiln source code to execute and inspect."),
+ part: z25.string().optional().describe("Frame named part and descendants (case-insensitive, substring fallback). Omit for whole asset."),
+ view: z25.string().optional().describe("front/right/back/left/top/three-quarter (default). Orbit angles override."),
+ azimuthDeg: z25.number().optional().describe("Orbit degrees: 0 front, 90 right, 180 back, 270 left. Wraps."),
+ elevationDeg: z25.number().optional().describe("Elevation degrees: 0 eye level, positive above. Clamped -89..89."),
+ zoom: z25.number().optional().describe("Bounds padding 1..4; default 1.2. Larger = more context."),
+ isolate: z25.boolean().optional().describe("Hide surrounding geometry. Requires part; default false.")
});
var inspectBufferInput = inspectInput.omit({ code: true });
var inspectAdvertisedInput = inspectInput.extend({ shot: cameraShotRecordInput });
@@ -51722,15 +52210,15 @@ function createKilnInspectDef(context = {}) {
};
}
var kilnInspectDef = createKilnInspectDef();
-var editOperationInput = z24.object({
- oldString: z24.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
- newString: z24.string().describe("The replacement text. Use an empty string to delete."),
- replaceAll: z24.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
-});
-var editInput = z24.object({
- code: z24.string().describe("The Kiln program to patch. The full current source."),
- edits: z24.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
- render: z24.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
+var editOperationInput = z25.object({
+ oldString: z25.string().describe("The exact text to replace, copied verbatim from the program (including whitespace and indentation, and with no line-number prefixes). Must be unique unless replaceAll is true."),
+ newString: z25.string().describe("The replacement text. Use an empty string to delete."),
+ replaceAll: z25.boolean().optional().describe("Replace every occurrence instead of failing when oldString matches more than once.")
+});
+var editInput = z25.object({
+ code: z25.string().describe("The Kiln program to patch. The full current source."),
+ edits: z25.array(editOperationInput).min(1).max(20).describe("Edits applied in order against the program. If any one fails to match, none are applied and the reply says which. Batch related changes into a single call."),
+ render: z25.boolean().optional().describe("Render the patched program and return the views (default true). false = patch only."),
capture: captureInput,
detail: reviewDetailInput
});
@@ -51956,10 +52444,10 @@ function withCaptureCache(context) {
} : {}
};
}
-var rendererInput = z24.strictObject({
- action: z24.enum(["status", "reprobe"]).default("status")
+var rendererInput = z25.strictObject({
+ action: z25.enum(["status", "reprobe"]).default("status")
});
-var rendererStatusInput = z24.strictObject({});
+var rendererStatusInput = z25.strictObject({});
async function runRenderer(context, action) {
if (action === "reprobe" && !context.reprobeRenderer)
return {
@@ -52054,9 +52542,9 @@ function createKilnOperationToolRegistry(context = {}) {
return projectOperationDefs(createProgramDefs(context, "operations"), context);
}
var assetSelector = {
- collection: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
- assetId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
- revisionId: z24.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
+ collection: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/).describe("Collection ID (list with kiln_assets action=collections): the user destination, else project.").default("project"),
+ assetId: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/),
+ revisionId: z25.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)
};
var ASSET_CONTRACT = {
collections: {
@@ -52186,36 +52674,36 @@ function createKilnAssetDefs(context, presentation = "grouped") {
resources: (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).assetLinks(collection, asset),
downloadUrls: await context.assetDownloadUrls?.(collection, asset.assetId, asset.revisionId)
});
- const saveInput = z24.object({
+ const saveInput = z25.object({
collection: selector.collection,
- programRef: z24.string(),
- name: z24.string().min(1).max(200),
+ programRef: z25.string(),
+ name: z25.string().min(1).max(200),
assetId: selector.assetId.optional(),
parentRevision: selector.revisionId.optional(),
- tags: z24.array(z24.string().max(80)).max(30).optional(),
- brief: z24.string().max(8000).optional(),
- description: z24.string().max(4000).optional(),
- attribution: z24.object({
- model: z24.string().max(200).optional(),
- harness: z24.string().max(200).optional(),
- author: z24.string().max(200).optional()
+ tags: z25.array(z25.string().max(80)).max(30).optional(),
+ brief: z25.string().max(8000).optional(),
+ description: z25.string().max(4000).optional(),
+ attribution: z25.object({
+ model: z25.string().max(200).optional(),
+ harness: z25.string().max(200).optional(),
+ author: z25.string().max(200).optional()
}).optional(),
- backdrop: z24.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
+ backdrop: z25.enum(BACKDROP_IDS).optional().describe("Preview backdrop: the one the reviewed sheet used.")
});
- const assetsInput = z24.object({
- action: z24.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
+ const assetsInput = z25.object({
+ action: z25.enum(["collections", "catalog", "list", "get", "restore"]).default("list"),
collection: selector.collection,
assetId: selector.assetId.optional(),
revisionId: selector.revisionId.optional().describe("get, restore: the saved revision; omitted, the newest."),
- query: z24.string().max(200).optional(),
- offset: z24.number().int().min(0).default(0),
- limit: z24.number().int().min(1).max(50).default(20)
+ query: z25.string().max(200).optional(),
+ offset: z25.number().int().min(0).default(0),
+ limit: z25.number().int().min(1).max(50).default(20)
});
- const exportInput = z24.object(selector);
+ const exportInput = z25.object(selector);
const profileExportInput = exportInput.extend({
- profile: z24.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
+ profile: z25.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")
});
- const importInput = z24.object({
+ const importInput = z25.object({
...selector,
sourceCollection: selector.collection
});
@@ -52316,9 +52804,9 @@ function createKilnAssetDefs(context, presentation = "grouped") {
name: "kiln_present",
description: "Present one exact saved revision. Supporting MCP App clients show an interactive 3D card with GLB, editable ZIP, and source downloads. Every host receives exact artifact descriptors with resource URIs in the JSON result; verified hosts may also receive core MCP resource-link blocks. This tool does not launch a local browser in coding harnesses. Call after saving or when the user wants to see or download an asset.",
inputSchema: exportInput,
- outputSchema: z24.object({
- ok: z24.literal(true),
- collection: z24.string(),
+ outputSchema: z25.object({
+ ok: z25.literal(true),
+ collection: z25.string(),
asset: assetManifestSchema.pick({
assetId: true,
revisionId: true,
@@ -52329,25 +52817,25 @@ function createKilnAssetDefs(context, presentation = "grouped") {
editable: true,
files: true
}).extend({
- build: z24.object({
- engine: z24.string(),
- rebuild: z24.enum(["engine-required", "external-dependencies-required"]),
- warningCount: z24.number().int(),
- warnings: z24.array(z24.string())
+ build: z25.object({
+ engine: z25.string(),
+ rebuild: z25.enum(["engine-required", "external-dependencies-required"]),
+ warningCount: z25.number().int(),
+ warnings: z25.array(z25.string())
}).optional()
}),
- resources: z24.array(z24.object({
- type: z24.literal("resource_link"),
- name: z24.string(),
- uri: z24.string(),
- mimeType: z24.string(),
- size: z24.number().int().nonnegative(),
- annotations: z24.object({
- audience: z24.array(z24.enum(["user", "assistant"])),
- priority: z24.number()
+ resources: z25.array(z25.object({
+ type: z25.literal("resource_link"),
+ name: z25.string(),
+ uri: z25.string(),
+ mimeType: z25.string(),
+ size: z25.number().int().nonnegative(),
+ annotations: z25.object({
+ audience: z25.array(z25.enum(["user", "assistant"])),
+ priority: z25.number()
})
})),
- downloadUrls: z24.record(z24.string(), z24.string()).optional()
+ downloadUrls: z25.record(z25.string(), z25.string()).optional()
}),
ui: {
resourceUri: KILN_ASSET_WIDGET_URI,
diff --git a/docs/delivery-contract.md b/docs/delivery-contract.md
index 2f6ce48d..616b6ef0 100644
--- a/docs/delivery-contract.md
+++ b/docs/delivery-contract.md
@@ -165,6 +165,15 @@ impostor, baked attributes, a packed two-region atlas, a budget, a required soli
instanced bolts. `src/__tests__/delivery-fixture.test.ts` renders it through both
converters and loads its three.js runtime export through `GLTFLoader`.
+## Host validation profiles
+
+Nothing on this page requires a particular primitive count, attribute gradient or
+material flag. A host whose destination does can bind an opt-in
+[host validation profile](migration.md#host-validation-profile) in its requirements.
+That profile is the host's contract, evaluated on the final GLB by
+`HOST_VALIDATION_PROFILE`; its `enforce` findings block. Without such a binding,
+including in the neutral default, no profile runs and nothing on this page changes.
+
## Out of scope
Not built in this cycle: a crash-damage or tearing helper, a kit snap solver or
diff --git a/docs/install.md b/docs/install.md
index 79b4ca86..1320c163 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -481,7 +481,9 @@ For an explicitly bound asset brief, append `"--requirements"` and the absolute
path to a host-binding JSON file to `args`. This optional policy is fixed for the
server session; changing the file requires a new session. The default remains
neutral authoring. See [host requirements](migration.md#migrate-evaluator-integrations-together)
-for the binding format and task/asset lineage boundary.
+for the binding format and task/asset lineage boundary. A binding can also carry a
+[host validation profile](migration.md#host-validation-profile) that the final GLB
+must satisfy; `kiln_discover` with `capabilities: true` shows it to the author.
The legacy root plugin manifests launch the Node bundle from an engine installation.
The v1 local plugin below uses a smaller bundle and creates an explicit workspace.
diff --git a/docs/migration.md b/docs/migration.md
index 58208f3d..6ac61757 100644
--- a/docs/migration.md
+++ b/docs/migration.md
@@ -458,6 +458,87 @@ line and the connectivity observation becomes `GEO_PART_EXTERNAL_SUPPORT`, namin
declaration. A named part at another height stays a floating part with the mismatch
stated. Other parts and dispositions are unchanged. The declaration is part of the
policy hash; its `reason` is not.
+
+### Host validation profile
+
+A host whose destination expects particular glTF facts can state them as the
+optional `requirements.validation` statement of the binding. The value is a closed
+`kiln.validation-profile.v1` record; import its schema and type from
+`@instruktlabs/kiln/requirements` (`ValidationProfileV1Schema`). Only a `requested`
+statement is evaluated. A binding without the key, including the neutral default,
+runs nothing new.
+
+```json
+"validation": {
+ "state": "requested",
+ "value": {
+ "version": "kiln.validation-profile.v1",
+ "profileId": "holodeck.palm",
+ "mode": "enforce",
+ "checks": [
+ {
+ "id": "frond-sway",
+ "select": { "names": ["Mesh_frond_*"] },
+ "primitives": { "exactly": 1 },
+ "attributes": ["POSITION", "NORMAL", "TEXCOORD_0"],
+ "gradient": {
+ "attribute": "TEXCOORD_0", "component": 1, "axis": "+Y",
+ "from": 0, "to": 1, "tolerance": 0.1, "monotonic": true
+ },
+ "material": { "alphaMode": "OPAQUE", "doubleSided": true }
+ }
+ ]
+ }
+}
+```
+
+The exact rule `HOST_VALIDATION_PROFILE` evaluates the profile on the final GLB
+bytes, after export and any optimization, never on the source scene:
+
+- `select.names` holds 1 to 8 patterns. A pattern matches a whole node name, case
+ sensitively, as written in the final GLB. That is the name `kiln_inspect` shows;
+ `createPart('frond_0', ...)` exports its mesh node as `Mesh_frond_0`. `*` matches
+ any run of characters and `?` exactly one; every other character is literal.
+ Patterns have at most 128 characters and four `*`. Candidates are mesh nodes of
+ the default scene; lower `MSFT_lod` levels are not candidates. `minMatches`
+ defaults to 1, so renaming every matched node is a finding, never a silent pass.
+ `maxMatches` is optional, at most 512.
+- `primitives` is `{ exactly }` or `{ max }`, counted per glTF mesh before any
+ runtime batching. Each material group exports as its own primitive.
+- `attributes` lists semantics required on every primitive of each matched node.
+- `gradient` reads an attribute component along a straight local axis in mesh
+ space, without the node transform. The mean value of vertices in the first and
+ last 5% of the extent must be within `tolerance` of `from` and `to`. With
+ `monotonic`, 16 equal bins must not move against the direction by more than
+ `tolerance`. A primitive with no extent along the axis is unmeasured.
+- `range` is a plain minimum and maximum over every vertex, within `tolerance`.
+- `material` checks `alphaMode` and `doubleSided`. A primitive without a material
+ reads as the glTF default, `OPAQUE` and single-sided.
+
+A profile has 1 to 16 checks with unique ids, each with at least one assertion,
+and serializes to at most 8 KiB. One profile-level `mode` applies in v1: `enforce`
+findings block, so `kiln_render` and `kiln_save` fail like any other enforced
+requirement, and `warn` findings are reported without blocking. `KILN_QA_MODE`
+relaxes the rule as it relaxes every other rule. Findings appear under
+`requirementReadiness` with the codes `HOST_VALIDATION_SELECTOR_UNMATCHED`,
+`HOST_VALIDATION_PRIMITIVE_COUNT`, `HOST_VALIDATION_ATTRIBUTE_MISSING`,
+`HOST_VALIDATION_ATTRIBUTE_RANGE`, `HOST_VALIDATION_ATTRIBUTE_GRADIENT`,
+`HOST_VALIDATION_MATERIAL_ALPHA_MODE` and `HOST_VALIDATION_MATERIAL_DOUBLE_SIDED`,
+each with the profile and the check and assertion as `measurement.name`. A finding
+about a node also names its delivery node path. Evaluation reads at most 4 million attribute elements per profile and
+measures at most 512 nodes per check. Past either limit, or when the GLB cannot be
+read, `HOST_VALIDATION_UNMEASURED` is reported as `observe` and acceptance stays
+`incomplete`. Findings are capped at 32 per check and code, followed by one summary
+finding that counts the rest.
+
+The profile is part of the binding's `policyHash`. Changing it requires the host
+store's `replace`, which appends history and changes the hash. Retained artifacts
+from the earlier revision then fail `kiln_finish` and Live Review save, and
+`kiln_save` evaluates again under the new profile. Within one MCP session the
+binding is fixed; a new profile needs a new session. `kiln_discover` with
+`capabilities: true` reports `requirements.declared.validationProfile`, labelled
+as host-declared, so an author can read the destination's checks before building.
+
## Review explicit legacy data conversion
Library callers of `@instruktlabs/kiln/qa` now use `collectRequirementsSceneEvidence`
diff --git a/docs/sdk.md b/docs/sdk.md
index 9d8415a0..b97fc904 100644
--- a/docs/sdk.md
+++ b/docs/sdk.md
@@ -160,6 +160,14 @@ documented, qualified entrypoint rather than importing the entire Node host.
These entries require 1.1 or later; 1.0.0 does not expose them.
They contain no cloud-provider, account, tenant or hosted-service policy.
+The `requirements` entry exports the host requirements store, binding context and
+asset-requirements schema. Its optional `validation` statement
+(`ValidationProfileV1Schema`, `kiln.validation-profile.v1`) declares destination
+checks that the exact rule `HOST_VALIDATION_PROFILE` evaluates on the final GLB.
+The `qa` entry exports `evaluateValidationProfileGlb` to run the same evaluation
+on GLB bytes a host already holds. See the
+[host validation profile](migration.md#host-validation-profile).
+
`renderGLB` defaults to trusted in-process execution. A hosted service accepting
untrusted programs must inject or select the qualified isolated evaluator described
in the runtime contract. A subprocess provides a worker boundary; it does not alone
diff --git a/skills/kiln-qa-asset/references/integration-checks.md b/skills/kiln-qa-asset/references/integration-checks.md
index 328a2668..c05d54f3 100644
--- a/skills/kiln-qa-asset/references/integration-checks.md
+++ b/skills/kiln-qa-asset/references/integration-checks.md
@@ -6,6 +6,21 @@ These library APIs run in the destination project's TypeScript toolchain, not in
Kiln authors metres, +X forward, +Y up, +Z right. Confirm importer conversion in the destination. Ground correction must be applied in the frame it describes, especially under rotated/scaled parents. Bounds alone cannot prove that feet, wheels, or collision geometry make the intended contact.
+## Host-declared checks
+
+Before authoring, read `kiln_discover({ capabilities: true })`. When
+`requirements.declared.validationProfile` is present, the host has bound
+destination checks, such as primitive counts, required attributes, an attribute
+gradient along a local axis, or material alpha mode and sidedness, for the nodes
+its patterns name. Patterns match final GLB node names; `createPart('frond_0')`
+exports `Mesh_frond_0`. The rule `HOST_VALIDATION_PROFILE` checks the final GLB on
+every `kiln_render` and `kiln_save`. In `enforce` mode its findings block, and
+each names the check, assertion and node path. Meet the check in the asset;
+renaming nodes so nothing matches is reported as
+`HOST_VALIDATION_SELECTOR_UNMATCHED`. Tool arguments and source metadata cannot
+change the profile. Without a declared profile these checks do not exist; do not
+apply another destination's checks to a standalone asset.
+
## What to measure
| Question | Evidence |
diff --git a/src/__tests__/discovery.test.ts b/src/__tests__/discovery.test.ts
index 2b0af52e..5bbf5d01 100644
--- a/src/__tests__/discovery.test.ts
+++ b/src/__tests__/discovery.test.ts
@@ -3,6 +3,9 @@ import { createKilnProgramToolRegistry, createKilnNativeToolRegistry } from '../
import { createLocalToolContext } from '../local-runtime';
import type { DiscoveryResponse } from '../discovery/service';
import { MemoryProgramStore } from '../program-store';
+import { createAssetRequirementsStore } from '../requirements-store';
+import { createAssetRequirementsV1, requestedRequirement } from '../contracts/requirements';
+import { resolveRequirementsContext } from '../requirements-context';
const discovery = () =>
createKilnProgramToolRegistry().find((tool) => tool.name === 'kiln_discover')!;
@@ -130,6 +133,46 @@ describe('progressive capability discovery', () => {
expect(trusted.capabilities.execution.mode).toBe('trusted-local');
expect(trusted.capabilities.execution.deadlineMs).toBeUndefined();
});
+ it('reports the host-bound requirements and declared validation profile separately from engine advice', async () => {
+ const profile = {
+ version: 'kiln.validation-profile.v1' as const,
+ profileId: 'holodeck.palm',
+ mode: 'enforce' as const,
+ checks: [{ id: 'frond', select: { names: ['Mesh_frond_*'] }, primitives: { exactly: 1 } }],
+ };
+ const requirements = createAssetRequirementsStore().host.bind(
+ { taskId: 'palm', lineageId: 'palm-a' },
+ createAssetRequirementsV1({ requirements: { validation: requestedRequirement(profile) } }),
+ { actor: 'holodeck', reason: 'Destination', source: 'brief' },
+ );
+ type Capabilities = {
+ capabilities: {
+ requirements: {
+ bound: boolean;
+ policyHash: string;
+ declared: { source: string; validationProfile: unknown } | null;
+ };
+ };
+ };
+ const bound = (await createKilnProgramToolRegistry({ requirements })
+ .find((t) => t.name === 'kiln_discover')!
+ .run({ capabilities: true })) as Capabilities;
+ expect(bound.capabilities.requirements).toEqual({
+ bound: true,
+ policyHash: resolveRequirementsContext(requirements).policyHash,
+ declared: { source: 'host-binding', validationProfile: profile },
+ });
+ const native = (await createKilnNativeToolRegistry({ requirements }, {})
+ .find((t) => t.name === 'kiln_discover')!
+ .run({ capabilities: true })) as Capabilities;
+ expect(native.capabilities.requirements).toEqual(bound.capabilities.requirements);
+ const neutral = (await discovery().run({ capabilities: true })) as Capabilities;
+ expect(neutral.capabilities.requirements).toEqual({
+ bound: false,
+ policyHash: resolveRequirementsContext().policyHash,
+ declared: null,
+ });
+ });
it('returns a compact complete overview and an exact lookup with a usable example', async () => {
const tool = discovery();
const overview = (await tool.run({})) as Result;
diff --git a/src/contracts/requirements.ts b/src/contracts/requirements.ts
index 32a18cfb..a9b3fe9e 100644
--- a/src/contracts/requirements.ts
+++ b/src/contracts/requirements.ts
@@ -26,6 +26,7 @@ import {
VFX_SUBTYPES,
validateVfxIntentV1,
} from './breadth';
+import { ValidationProfileV1Schema } from './validation-profile';
const text = z
.string()
@@ -250,6 +251,8 @@ const requirements = z.strictObject({
access: statement(
z.strictObject({ enterable: z.boolean().optional(), driveable: z.boolean().optional() }),
).optional(),
+ /** Host-declared destination checks on the final GLB (#208); never model-authored. */
+ validation: statement(ValidationProfileV1Schema).optional(),
});
export const AssetRequirementsV1Schema = z
diff --git a/src/contracts/validation-profile.ts b/src/contracts/validation-profile.ts
new file mode 100644
index 00000000..ad97fdb9
--- /dev/null
+++ b/src/contracts/validation-profile.ts
@@ -0,0 +1,171 @@
+/**
+ * Host validation profile (#208): a closed, declarative statement a host binds inside
+ * `requirements.validation`. It names nodes and states glTF facts the destination needs.
+ * No host code runs and nothing here reads images.
+ */
+import { z } from 'zod';
+
+export const VALIDATION_PROFILE_VERSION = 'kiln.validation-profile.v1' as const;
+export const MAX_VALIDATION_PROFILE_BYTES = 8 * 1024;
+export const MAX_VALIDATION_CHECKS = 16;
+export const MAX_VALIDATION_PATTERN_CHARS = 128;
+export const MAX_VALIDATION_PATTERN_STARS = 4;
+/** Per-check ceiling on matched nodes; also the largest `maxMatches`. */
+export const MAX_VALIDATION_MATCHES = 512;
+
+export const VALIDATION_SEMANTICS = [
+ 'POSITION',
+ 'NORMAL',
+ 'TANGENT',
+ 'TEXCOORD_0',
+ 'TEXCOORD_1',
+ 'COLOR_0',
+ 'JOINTS_0',
+ 'WEIGHTS_0',
+] as const;
+export type ValidationSemantic = (typeof VALIDATION_SEMANTICS)[number];
+
+/** Largest component count glTF allows for each semantic. COLOR_0 may be VEC3 or VEC4. */
+export const VALIDATION_SEMANTIC_SIZE: Readonly<Record<ValidationSemantic, number>> = {
+ POSITION: 3,
+ NORMAL: 3,
+ TANGENT: 4,
+ TEXCOORD_0: 2,
+ TEXCOORD_1: 2,
+ COLOR_0: 4,
+ JOINTS_0: 4,
+ WEIGHTS_0: 4,
+};
+
+export const VALIDATION_AXES = ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const;
+
+const finite = z.number().finite();
+const id = (max: number) =>
+ z
+ .string()
+ .min(1)
+ .max(max)
+ .regex(/^[A-Za-z0-9._-]+$/, 'Use letters, digits, ".", "_" or "-".');
+
+const pattern = z
+ .string()
+ .min(1)
+ .refine((value) => Array.from(value).length <= MAX_VALIDATION_PATTERN_CHARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_CHARS} characters.`,
+ })
+ .refine((value) => value.split('*').length - 1 <= MAX_VALIDATION_PATTERN_STARS, {
+ message: `A pattern has at most ${MAX_VALIDATION_PATTERN_STARS} "*".`,
+ });
+
+const componentFits = (value: { attribute: ValidationSemantic; component: number }) =>
+ value.component < VALIDATION_SEMANTIC_SIZE[value.attribute];
+const componentMessage = {
+ message: 'component is outside the attribute.',
+ path: ['component'],
+};
+
+const gradient = z
+ .strictObject({
+ attribute: z.enum(['TEXCOORD_0', 'TEXCOORD_1', 'COLOR_0']),
+ component: z.number().int().min(0).max(3),
+ axis: z.enum(VALIDATION_AXES),
+ from: finite,
+ to: finite,
+ tolerance: finite.positive().max(0.5),
+ monotonic: z.boolean(),
+ })
+ .refine((value) => value.from !== value.to, {
+ message: 'from and to must differ.',
+ })
+ .refine(componentFits, componentMessage);
+
+const range = z
+ .strictObject({
+ attribute: z.enum(VALIDATION_SEMANTICS),
+ component: z.number().int().min(0).max(3),
+ min: finite,
+ max: finite,
+ tolerance: finite.nonnegative(),
+ })
+ .refine((value) => value.min <= value.max, {
+ message: 'min must not exceed max.',
+ })
+ .refine(componentFits, componentMessage);
+
+const check = z
+ .strictObject({
+ id: id(48),
+ select: z
+ .strictObject({
+ names: z.array(pattern).min(1).max(8),
+ /** Defaults to 1, so a renamed node is a finding rather than a silent pass. */
+ minMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ maxMatches: z.number().int().min(0).max(MAX_VALIDATION_MATCHES).optional(),
+ })
+ .refine(
+ (value) => value.maxMatches === undefined || (value.minMatches ?? 1) <= value.maxMatches,
+ { message: 'minMatches must not exceed maxMatches.' },
+ ),
+ primitives: z
+ .union([
+ z.strictObject({ exactly: z.number().int().min(1).max(64) }),
+ z.strictObject({ max: z.number().int().min(1).max(64) }),
+ ])
+ .optional(),
+ /** Every listed semantic is required on every primitive of each matched node. */
+ attributes: z
+ .array(z.enum(VALIDATION_SEMANTICS))
+ .min(1)
+ .max(8)
+ .refine((values) => new Set(values).size === values.length, {
+ message: 'Attributes must be unique.',
+ })
+ .optional(),
+ gradient: gradient.optional(),
+ range: range.optional(),
+ material: z
+ .strictObject({
+ alphaMode: z.enum(['OPAQUE', 'MASK', 'BLEND']).optional(),
+ doubleSided: z.boolean().optional(),
+ })
+ .refine((value) => value.alphaMode !== undefined || value.doubleSided !== undefined, {
+ message: 'A material check needs alphaMode or doubleSided.',
+ })
+ .optional(),
+ })
+ .refine(
+ (value) =>
+ value.primitives !== undefined ||
+ value.attributes !== undefined ||
+ value.gradient !== undefined ||
+ value.range !== undefined ||
+ value.material !== undefined,
+ { message: 'A check needs at least one assertion.' },
+ );
+
+export const ValidationProfileV1Schema = z
+ .strictObject({
+ version: z.literal(VALIDATION_PROFILE_VERSION),
+ profileId: id(64).regex(/^[a-z0-9._-]+$/, 'Use lowercase letters, digits, ".", "_" or "-".'),
+ /** One profile-level mode in v1: `enforce` findings block, `warn` findings warn. */
+ mode: z.enum(['warn', 'enforce']),
+ checks: z.array(check).min(1).max(MAX_VALIDATION_CHECKS),
+ })
+ .superRefine((value, context) => {
+ const ids = value.checks.map((item) => item.id);
+ if (new Set(ids).size !== ids.length)
+ context.addIssue({
+ code: 'custom',
+ path: ['checks'],
+ message: 'Check ids must be unique.',
+ });
+ const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
+ if (bytes > MAX_VALIDATION_PROFILE_BYTES)
+ context.addIssue({
+ code: 'custom',
+ message: `A validation profile serializes to at most ${MAX_VALIDATION_PROFILE_BYTES} bytes (got ${bytes}).`,
+ });
+ });
+
+export type ValidationProfileV1 = z.infer<typeof ValidationProfileV1Schema>;
+export type ValidationCheckV1 = ValidationProfileV1['checks'][number];
diff --git a/src/qa/index.ts b/src/qa/index.ts
index 7bf8267d..5e0e40b3 100644
--- a/src/qa/index.ts
+++ b/src/qa/index.ts
@@ -33,3 +33,4 @@ export { AssetQaBlockedError, gltfReportFindings, qaPolicyFromEnv, qaBlockingEna
export * from './requirements-run';
export * from './requirements-report';
export * from './requirements-applicability';
+export * from './validation-profile';
diff --git a/src/qa/registry.test.ts b/src/qa/registry.test.ts
index 16ef406a..3e248b67 100644
--- a/src/qa/registry.test.ts
+++ b/src/qa/registry.test.ts
@@ -791,9 +791,10 @@ describe('QaRegistry', () => {
test('publishes a stable auditable state and owner for every checked-in rule', () => {
const decisions = DETERMINISTIC_QA_REGISTRY.describePolicy();
- // 27 -> 28 with the approved bounded sweep/loft observation. The count means a rule can
- // never join the deterministic registry without someone noticing.
- expect(decisions).toHaveLength(28);
+ // 27 -> 28 with the approved bounded sweep/loft observation, 28 -> 29 with the host
+ // validation profile (#208). The count means a rule can never join the deterministic
+ // registry without someone noticing.
+ expect(decisions).toHaveLength(29);
expect(
decisions
.filter((item) => item.ruleClass === 'exact')
diff --git a/src/qa/requirements-applicability.test.ts b/src/qa/requirements-applicability.test.ts
index a07ef832..1d1d732f 100644
--- a/src/qa/requirements-applicability.test.ts
+++ b/src/qa/requirements-applicability.test.ts
@@ -5,11 +5,11 @@ import {
REQUIREMENTS_RULE_MAP,
resolveRequirementsApplicability,
} from './requirements-applicability';
-test('the migration map covers each of the 28 actual registered rules and preserves modes', () => {
+test('the migration map covers each of the 29 actual registered rules and preserves modes', () => {
const rules = DETERMINISTIC_QA_REGISTRY.list();
- expect(rules).toHaveLength(28);
- expect(REQUIREMENTS_RULE_MAP).toHaveLength(28);
- expect(new Set(REQUIREMENTS_RULE_MAP.map((rule) => rule.id)).size).toBe(28);
+ expect(rules).toHaveLength(29);
+ expect(REQUIREMENTS_RULE_MAP).toHaveLength(29);
+ expect(new Set(REQUIREMENTS_RULE_MAP.map((rule) => rule.id)).size).toBe(29);
expect(REQUIREMENTS_RULE_MAP.map((rule) => [rule.id, rule.mode]).sort()).toEqual(
rules.map((rule) => [rule.id, rule.defaultMode]).sort(),
);
diff --git a/src/qa/requirements-applicability.ts b/src/qa/requirements-applicability.ts
index 2de004af..e49437a8 100644
--- a/src/qa/requirements-applicability.ts
+++ b/src/qa/requirements-applicability.ts
@@ -19,7 +19,8 @@ interface RuleMapping {
| 'connectivity'
| 'partVolume'
| 'sweep'
- | 'rig';
+ | 'rig'
+ | 'validation';
observation?: true;
}
/** Exhaustive migration inventory. Labels and source categories are deliberately absent. */
@@ -96,6 +97,8 @@ export const REQUIREMENTS_RULE_MAP: readonly RuleMapping[] = [
},
{ id: 'REF_COMPARISON', mode: 'observe', keys: [], observation: true },
{ id: 'SWEEP_SELF_INTERSECTION', mode: 'observe', keys: [], observation: true, kernel: 'sweep' },
+ // Host-bound final-GLB profile (#208); evaluated by appendRequirementsFinalQa only.
+ { id: 'HOST_VALIDATION_PROFILE', mode: 'enforce', keys: ['validation'], kernel: 'validation' },
];
export interface UnevaluatedRequirement {
key: RequirementKey;
@@ -188,6 +191,7 @@ export function resolveRequirementsApplicability(
animation: ['clips'],
representation: ['precomputedTangents'],
externalSupport: ['supports'],
+ validation: ['version', 'profileId', 'mode', 'checks'],
};
for (const [key, statement] of Object.entries(requirements.requirements)) {
if (statement?.state !== 'requested') continue;
diff --git a/src/qa/requirements-run.ts b/src/qa/requirements-run.ts
index 4588a3a4..235efcf1 100644
--- a/src/qa/requirements-run.ts
+++ b/src/qa/requirements-run.ts
@@ -46,6 +46,7 @@ import {
ENVIRONMENT_QA_RULES,
} from './environment';
import { resolveRequirementsApplicability } from './requirements-applicability';
+import { evaluateValidationProfileGlb, HOST_VALIDATION_QA_RULE } from './validation-profile';
import {
createRequirementsQaReport,
type AssetRequirementsQaReportV2,
@@ -75,6 +76,7 @@ const registry = new QaRegistry([
VFX_EXACT_QA_RULE,
VFX_ADVISORY_QA_RULE,
ASSET_SCOPE_QA_RULE,
+ HOST_VALIDATION_QA_RULE,
]);
interface RequirementsSceneEvidence {
@@ -255,6 +257,8 @@ export function runRequirementsSceneQa(
continue;
}
if (decision.ruleId === ASSET_SCOPE_QA_RULE.id && !scopeObservation) continue;
+ // Only the final GLB shows the destination's primitives; appendRequirementsFinalQa runs it.
+ if (decision.ruleId === HOST_VALIDATION_QA_RULE.id) continue;
if (decision.ruleId === PART_CONNECTIVITY_QA_RULE.id && !(scene instanceof Object3D)) continue;
executedRules.push(decision.ruleId);
if (decision.ruleId === PROP_EXACT_QA_RULE.id) {
@@ -369,6 +373,8 @@ export function appendRequirementsQa(
report: AssetRequirementsQaReportV2,
findings: readonly (QaFinding | RequirementsQaFinding)[],
metrics: RequirementsQaReportOptions['metrics'] = {},
+ /** Rules measured only now, such as those that need final GLB bytes. */
+ executedRules: readonly string[] = [],
): AssetRequirementsQaReportV2 {
const priorMetrics = Object.fromEntries(
Object.entries(report.dimensions).flatMap(([dimension, value]) =>
@@ -380,7 +386,10 @@ export function appendRequirementsQa(
merged[dimension] = { ...priorMetrics[dimension], ...value };
return createRequirementsQaReport(context, {
findings: [...Object.values(report.dimensions).flatMap((x) => x.findings), ...findings],
- executedRules: report.rules.filter((x) => x.status === 'evaluated').map((x) => x.id),
+ executedRules: [
+ ...report.rules.filter((x) => x.status === 'evaluated').map((x) => x.id),
+ ...executedRules,
+ ],
modes: Object.fromEntries(report.rules.map((x) => [x.id, x.mode])),
evaluatedDimensions: [
...new Set([
@@ -471,5 +480,31 @@ export async function appendRequirementsFinalQa(
exportIntegrity: finalEffectsMetrics(evidence),
});
}
+ const validation = context.requirements.requirements.validation;
+ const hostRule = report.rules.find((r) => r.id === HOST_VALIDATION_QA_RULE.id);
+ if (
+ validation?.state === 'requested' &&
+ hostRule &&
+ hostRule.status !== 'notRequested' &&
+ hostRule.mode !== 'off'
+ ) {
+ const evaluation = await evaluateValidationProfileGlb(validation.value, bytes);
+ // The profile chooses block or warn; a relaxed rule mode (KILN_QA_MODE) only downgrades.
+ const findings =
+ hostRule.mode === 'enforce'
+ ? evaluation.findings
+ : evaluation.findings.map((f) => ({
+ ...f,
+ disposition:
+ f.disposition === 'observe' ? f.disposition : (hostRule.mode as 'observe' | 'warn'),
+ }));
+ result = appendRequirementsQa(
+ context,
+ result,
+ findings,
+ { requirementReadiness: evaluation.metrics },
+ evaluation.complete ? [HOST_VALIDATION_QA_RULE.id] : [],
+ );
+ }
return result;
}
diff --git a/src/qa/run.ts b/src/qa/run.ts
index c05c42f2..435d241d 100644
--- a/src/qa/run.ts
+++ b/src/qa/run.ts
@@ -27,6 +27,7 @@ import {
type QaFinding,
} from './types';
import { UNIVERSAL_QA_RULES } from './universal';
+import { HOST_VALIDATION_QA_RULE } from './validation-profile';
import type { KhronosGltfValidationReport } from './gltf';
import type { KhronosGltfIssue } from './gltf';
import type { MaterialBudgetWarningV1, MaterialMetricsV1 } from '../material-metrics';
@@ -46,6 +47,7 @@ export const DETERMINISTIC_QA_REGISTRY = new QaRegistry([
SWEEP_QA_RULE,
PART_CONNECTIVITY_QA_RULE,
REFERENCE_COMPARISON_QA_RULE,
+ HOST_VALIDATION_QA_RULE,
]);
export function runDeterministicSceneQa(
diff --git a/src/qa/validation-profile.test.ts b/src/qa/validation-profile.test.ts
new file mode 100644
index 00000000..a9eaa0c5
--- /dev/null
+++ b/src/qa/validation-profile.test.ts
@@ -0,0 +1,516 @@
+/**
+ * Conformance fixture for HOST_VALIDATION_PROFILE (#208). The rule's promotion
+ * evidence pins this file's exact bytes: change an assertion here and the
+ * registry test asks for a new owner-approved hash.
+ */
+import { describe, expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { Document, type Material } from '@gltf-transform/core';
+import { createGltfIO } from '../gltf-io';
+import {
+ createAssetRequirementsV1,
+ requestedRequirement,
+ validateAssetRequirementsV1,
+} from '../contracts/requirements';
+import type { ValidationProfileV1 } from '../contracts/validation-profile';
+import { createAssetRequirementsStore } from '../requirements-store';
+import { renderSceneToGLB } from '../render';
+import { AssetQaBlockedError } from './run';
+import {
+ evaluateValidationProfileDocument,
+ evaluateValidationProfileGlb,
+ matchValidationPattern,
+} from './validation-profile';
+
+type Check = ValidationProfileV1['checks'][number];
+
+const frondCheck: Check = {
+ id: 'frond-sway',
+ select: { names: ['frond_*'] },
+ primitives: { exactly: 1 },
+ attributes: ['POSITION', 'NORMAL', 'TEXCOORD_0'],
+ gradient: {
+ attribute: 'TEXCOORD_0',
+ component: 1,
+ axis: '+Y',
+ from: 0,
+ to: 1,
+ tolerance: 0.1,
+ monotonic: true,
+ },
+};
+
+function profile(
+ checks: Check[] = [frondCheck],
+ mode: 'warn' | 'enforce' = 'enforce',
+): ValidationProfileV1 {
+ return {
+ version: 'kiln.validation-profile.v1',
+ profileId: 'holodeck.palm',
+ mode,
+ checks,
+ };
+}
+
+function requirementsWith(value: unknown) {
+ return validateAssetRequirementsV1({
+ ...createAssetRequirementsV1(),
+ requirements: { validation: { state: 'requested', value } },
+ });
+}
+
+interface StripOptions {
+ name?: string;
+ primitives?: number;
+ reversed?: boolean;
+ uv?: boolean;
+ material?: (doc: Document) => Material | null;
+ flat?: boolean;
+}
+
+/** A vertical strip, 9 rows from y=0 to y=1, with UV.y following y. */
+function addStrip(
+ doc: Document,
+ parent: ReturnType<Document['createNode']>,
+ options: StripOptions,
+) {
+ const buffer = doc.getRoot().listBuffers()[0] ?? doc.createBuffer();
+ const mesh = doc.createMesh(options.name ?? 'frond');
+ for (let p = 0; p < (options.primitives ?? 1); p++) {
+ const positions: number[] = [];
+ const normals: number[] = [];
+ const uvs: number[] = [];
+ for (let row = 0; row <= 8; row++) {
+ const y = options.flat ? 0 : row / 8;
+ for (const x of [-0.1, 0.1]) {
+ positions.push(x, y, 0);
+ normals.push(0, 0, 1);
+ uvs.push(x > 0 ? 1 : 0, options.reversed ? 1 - row / 8 : row / 8);
+ }
+ }
+ const indices: number[] = [];
+ for (let row = 0; row < 8; row++) {
+ const a = row * 2;
+ indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
+ }
+ const accessor = (
+ type: 'VEC2' | 'VEC3' | 'SCALAR',
+ array: Float32Array<ArrayBuffer> | Uint16Array<ArrayBuffer>,
+ ) => doc.createAccessor().setType(type).setArray(array).setBuffer(buffer);
+ const primitive = doc
+ .createPrimitive()
+ .setAttribute('POSITION', accessor('VEC3', new Float32Array(positions)))
+ .setAttribute('NORMAL', accessor('VEC3', new Float32Array(normals)))
+ .setIndices(accessor('SCALAR', new Uint16Array(indices)));
+ if (options.uv !== false)
+ primitive.setAttribute('TEXCOORD_0', accessor('VEC2', new Float32Array(uvs)));
+ const material = options.material?.(doc);
+ if (material) primitive.setMaterial(material);
+ mesh.addPrimitive(primitive);
+ }
+ const node = doc.createNode(options.name ?? 'frond_0').setMesh(mesh);
+ parent.addChild(node);
+ return node;
+}
+
+function palm(...strips: StripOptions[]) {
+ const doc = new Document();
+ doc.createBuffer();
+ const root = doc.createNode('Palm');
+ doc.createScene('Scene').addChild(root);
+ doc.getRoot().setDefaultScene(doc.getRoot().listScenes()[0]!);
+ for (const strip of strips) addStrip(doc, root, strip);
+ return doc;
+}
+
+const codes = (result: { findings: readonly { code: string }[] }) =>
+ result.findings.map((finding) => finding.code);
+
+describe('kiln.validation-profile.v1 schema', () => {
+ test('a closed profile is accepted as a requested requirement', () => {
+ const result = requirementsWith(profile());
+ expect(result.valid).toBe(true);
+ expect(result.value!.requirements.validation).toEqual(requestedRequirement(profile()));
+ });
+
+ test('rejects unbounded or ambiguous profiles', () => {
+ const many = Array.from({ length: 17 }, (_, i) => ({
+ ...frondCheck,
+ id: `c${i}`,
+ }));
+ const rejected: unknown[] = [
+ profile(many),
+ profile([{ ...frondCheck, select: { names: ['a'.repeat(129)] } }]),
+ profile([{ ...frondCheck, select: { names: ['*a*b*c*d*'] } }]),
+ profile([frondCheck, frondCheck]),
+ profile([{ ...frondCheck, gradient: { ...frondCheck.gradient!, to: 0 } }]),
+ profile([{ ...frondCheck, gradient: { ...frondCheck.gradient!, component: 2 } }]),
+ profile([{ ...frondCheck, gradient: { ...frondCheck.gradient!, tolerance: 0 } }]),
+ profile([
+ {
+ id: 'range',
+ select: { names: ['x'] },
+ range: {
+ attribute: 'COLOR_0',
+ component: 0,
+ min: 1,
+ max: 0,
+ tolerance: 0,
+ },
+ },
+ ]),
+ profile([{ id: 'empty', select: { names: ['frond_*'] } }]),
+ profile([
+ {
+ ...frondCheck,
+ select: { names: ['x'], minMatches: 3, maxMatches: 2 },
+ },
+ ]),
+ profile([{ ...frondCheck, select: { names: ['x'], maxMatches: 513 } }]),
+ // v1 has one profile-level mode; a per-check mode is not part of the schema.
+ profile([{ ...frondCheck, mode: 'warn' } as Check]),
+ { ...profile(), extra: true },
+ ];
+ for (const value of rejected) expect(requirementsWith(value).valid).toBe(false);
+ // 128 characters and four stars are the limits, not violations.
+ expect(
+ requirementsWith(profile([{ ...frondCheck, select: { names: ['a'.repeat(128)] } }])).valid,
+ ).toBe(true);
+ expect(
+ requirementsWith(profile([{ ...frondCheck, select: { names: ['*a*b*c*'] } }])).valid,
+ ).toBe(true);
+ });
+
+ test('rejects a serialized profile over 8 KiB', () => {
+ const long = Array.from({ length: 8 }, (_, i) => `${'n'.repeat(120)}${i}`);
+ const checks = Array.from({ length: 16 }, (_, i) => ({
+ ...frondCheck,
+ id: `check-${i}`,
+ select: { names: long },
+ }));
+ expect(JSON.stringify(profile(checks)).length).toBeGreaterThan(8192);
+ expect(requirementsWith(profile(checks)).valid).toBe(false);
+ });
+});
+
+describe('node name patterns', () => {
+ test('match whole names case-sensitively with * and ? only', () => {
+ expect(matchValidationPattern('frond_*', 'frond_0')).toBe(true);
+ expect(matchValidationPattern('frond_*', 'frond_')).toBe(true);
+ expect(matchValidationPattern('frond_*', 'Frond_0')).toBe(false);
+ expect(matchValidationPattern('frond_*', 'big_frond_0')).toBe(false);
+ expect(matchValidationPattern('fr?nd', 'frond')).toBe(true);
+ expect(matchValidationPattern('fr?nd', 'frnd')).toBe(false);
+ expect(matchValidationPattern('?', '葉')).toBe(true);
+ expect(matchValidationPattern('a.b', 'aXb')).toBe(false);
+ expect(matchValidationPattern('[ab]', '[ab]')).toBe(true);
+ expect(matchValidationPattern('*', '')).toBe(true);
+ });
+
+ test('stay bounded on adversarial names', () => {
+ const name = 'a'.repeat(20_000);
+ const started = performance.now();
+ expect(matchValidationPattern('*a*a*a*b', name)).toBe(false);
+ expect(performance.now() - started).toBeLessThan(1000);
+ });
+});
+
+describe('HOST_VALIDATION_PROFILE evaluation', () => {
+ test('a conforming frond passes with every check measured', () => {
+ const result = evaluateValidationProfileDocument(profile(), palm({ name: 'frond_0' }));
+ expect(result.findings).toEqual([]);
+ expect(result.complete).toBe(true);
+ expect(result.metrics).toMatchObject({
+ hostValidationProfile: 'kiln.validation-profile.v1:holodeck.palm',
+ hostValidationMatchedNodes: 1,
+ });
+ });
+
+ test('a two-primitive frond and a reversed gradient fail at their exact node paths', () => {
+ const result = evaluateValidationProfileDocument(
+ profile(),
+ palm({ name: 'frond_0', primitives: 2 }, { name: 'frond_1', reversed: true }),
+ );
+ expect(codes(result)).toEqual([
+ 'HOST_VALIDATION_PRIMITIVE_COUNT',
+ 'HOST_VALIDATION_ATTRIBUTE_GRADIENT',
+ ]);
+ const [count, gradient] = result.findings;
+ expect(count).toMatchObject({
+ disposition: 'block',
+ dimension: 'categoryReadiness',
+ profile: 'kiln.validation-profile.v1:holodeck.palm',
+ affected: { node: 'frond_0', nodePath: '/Scene[0]/Palm[0]/frond_0[0]' },
+ measurement: {
+ name: 'checks.frond-sway.primitives',
+ actual: 2,
+ expected: 1,
+ },
+ });
+ expect(gradient).toMatchObject({
+ disposition: 'block',
+ affected: {
+ node: 'frond_1',
+ nodePath: '/Scene[0]/Palm[0]/frond_1[0]',
+ attribute: 'TEXCOORD_0',
+ },
+ measurement: {
+ name: 'checks.frond-sway.gradient',
+ breakdown: { fromMean: 1, toMean: 0 },
+ },
+ });
+ // A reversed gradient fails both the endpoint and the monotonic test.
+ expect(gradient!.message).toContain('endpoints');
+ expect(gradient!.message).toContain('monotonic');
+ });
+
+ test('warn mode reports the same findings without blocking', () => {
+ const result = evaluateValidationProfileDocument(
+ profile([frondCheck], 'warn'),
+ palm({ name: 'frond_0', reversed: true }),
+ );
+ expect(result.findings.map((finding) => finding.disposition)).toEqual(['warn']);
+ });
+
+ test('renaming every frond cannot pass silently', () => {
+ const result = evaluateValidationProfileDocument(profile(), palm({ name: 'leaf_0' }));
+ expect(codes(result)).toEqual(['HOST_VALIDATION_SELECTOR_UNMATCHED']);
+ expect(result.findings[0]).toMatchObject({
+ disposition: 'block',
+ measurement: {
+ name: 'checks.frond-sway.select',
+ actual: 0,
+ expected: '>= 1',
+ },
+ });
+ const bounded = evaluateValidationProfileDocument(
+ profile([{ ...frondCheck, select: { names: ['frond_*'], maxMatches: 1 } }]),
+ palm({ name: 'frond_0' }, { name: 'frond_1' }),
+ );
+ expect(codes(bounded)).toEqual(['HOST_VALIDATION_SELECTOR_UNMATCHED']);
+ const optional = evaluateValidationProfileDocument(
+ profile([{ ...frondCheck, select: { names: ['frond_*'], minMatches: 0 } }]),
+ palm({ name: 'leaf_0' }),
+ );
+ expect(optional.findings).toEqual([]);
+ });
+
+ test('missing attributes, ranges and material flags are reported per primitive', () => {
+ const blend = (doc: Document) =>
+ doc.createMaterial('leaf').setAlphaMode('BLEND').setDoubleSided(false);
+ const result = evaluateValidationProfileDocument(
+ profile([
+ {
+ id: 'leaf',
+ select: { names: ['frond_?'] },
+ attributes: ['TEXCOORD_0'],
+ range: {
+ attribute: 'POSITION',
+ component: 1,
+ min: 0,
+ max: 0.5,
+ tolerance: 0.01,
+ },
+ material: { alphaMode: 'MASK', doubleSided: true },
+ },
+ ]),
+ palm({ name: 'frond_0', uv: false, material: blend }),
+ );
+ expect(codes(result)).toEqual([
+ 'HOST_VALIDATION_ATTRIBUTE_MISSING',
+ 'HOST_VALIDATION_ATTRIBUTE_RANGE',
+ 'HOST_VALIDATION_MATERIAL_ALPHA_MODE',
+ 'HOST_VALIDATION_MATERIAL_DOUBLE_SIDED',
+ ]);
+ expect(result.findings[0]!.affected).toMatchObject({
+ attribute: 'TEXCOORD_0',
+ });
+ expect(result.findings[2]).toMatchObject({
+ affected: { material: 'leaf' },
+ measurement: { actual: 'BLEND', expected: 'MASK' },
+ });
+ // An absent material is the glTF default: opaque and single-sided.
+ const defaults = evaluateValidationProfileDocument(
+ profile([
+ {
+ id: 'defaults',
+ select: { names: ['frond_0'] },
+ material: { alphaMode: 'OPAQUE', doubleSided: false },
+ },
+ ]),
+ palm({ name: 'frond_0' }),
+ );
+ expect(defaults.findings).toEqual([]);
+ });
+
+ test('a gradient on a flat axis or past the read budget is unmeasured, never a pass', () => {
+ const flat = evaluateValidationProfileDocument(
+ profile(),
+ palm({ name: 'frond_0', flat: true }),
+ );
+ expect(codes(flat)).toEqual(['HOST_VALIDATION_UNMEASURED']);
+ expect(flat.findings[0]!.disposition).toBe('observe');
+ expect(flat.complete).toBe(false);
+
+ const budget = evaluateValidationProfileDocument(
+ profile(),
+ palm({ name: 'frond_0' }, { name: 'frond_1' }, { name: 'frond_2' }),
+ { maxAttributeReads: 40 },
+ );
+ expect(codes(budget)).toEqual(['HOST_VALIDATION_UNMEASURED']);
+ expect(budget.findings[0]).toMatchObject({
+ disposition: 'observe',
+ measurement: { breakdown: { nodesNotMeasured: 2 } },
+ });
+ expect(budget.complete).toBe(false);
+ });
+
+ test('findings are capped per check and code with a summary count', () => {
+ const strips = Array.from({ length: 40 }, (_, i) => ({
+ name: `frond_${i}`,
+ primitives: 2,
+ }));
+ const result = evaluateValidationProfileDocument(
+ profile([{ id: 'count', select: { names: ['frond_*'] }, primitives: { max: 1 } }]),
+ palm(...strips),
+ );
+ expect(result.findings).toHaveLength(33);
+ expect(result.findings.at(-1)).toMatchObject({
+ code: 'HOST_VALIDATION_PRIMITIVE_COUNT',
+ measurement: { breakdown: { omitted: 8 } },
+ });
+ });
+
+ test('only default-scene nodes are candidates', () => {
+ const doc = palm({ name: 'frond_0' });
+ const other = doc.createScene('Other');
+ const stray = doc.createNode('frond_9');
+ other.addChild(stray);
+ addStrip(doc, stray, { name: 'frond_10', reversed: true });
+ expect(evaluateValidationProfileDocument(profile(), doc).findings).toEqual([]);
+ });
+
+ test('reads the final GLB bytes', async () => {
+ const bytes = await createGltfIO().writeBinary(palm({ name: 'frond_0', reversed: true }));
+ const result = await evaluateValidationProfileGlb(profile(), bytes);
+ expect(codes(result)).toEqual(['HOST_VALIDATION_ATTRIBUTE_GRADIENT']);
+ const unreadable = await evaluateValidationProfileGlb(profile(), new Uint8Array([1, 2, 3]));
+ expect(codes(unreadable)).toEqual(['HOST_VALIDATION_UNMEASURED']);
+ expect(unreadable.complete).toBe(false);
+ });
+});
+
+function binding(value: ValidationProfileV1) {
+ return createAssetRequirementsStore().host.bind(
+ { taskId: 'palm', lineageId: 'palm-a' },
+ createAssetRequirementsV1({
+ requirements: { validation: requestedRequirement(value) },
+ }),
+ {
+ actor: 'holodeck',
+ reason: 'Destination shader contract',
+ source: 'brief',
+ },
+ );
+}
+
+function scenePalm(options: { split?: boolean; reversed?: boolean; name?: string } = {}) {
+ const root = new THREE.Group();
+ root.name = 'Palm';
+ const geometry = new THREE.PlaneGeometry(0.4, 2, 1, 4);
+ if (options.reversed) {
+ const uv = geometry.getAttribute('uv');
+ for (let i = 0; i < uv.count; i++) uv.setY(i, 1 - uv.getY(i));
+ }
+ let material: THREE.Material | THREE.Material[] = new THREE.MeshStandardMaterial();
+ if (options.split) {
+ geometry.clearGroups();
+ geometry.addGroup(0, 12, 0);
+ geometry.addGroup(12, 12, 1);
+ material = [
+ new THREE.MeshStandardMaterial({ color: '#336633' }),
+ new THREE.MeshStandardMaterial({ color: '#558855' }),
+ ];
+ }
+ const frond = new THREE.Mesh(geometry, material);
+ frond.name = options.name ?? 'frond_0';
+ root.add(frond);
+ return root;
+}
+
+describe('renderSceneToGLB with a host validation profile', () => {
+ test('a conforming frond is evaluated and accepted', async () => {
+ const result = await renderSceneToGLB(scenePalm(), {
+ requirements: binding(profile()),
+ });
+ expect(result.qaReport.rules.find((rule) => rule.id === 'HOST_VALIDATION_PROFILE')).toEqual({
+ id: 'HOST_VALIDATION_PROFILE',
+ mode: 'enforce',
+ status: 'evaluated',
+ });
+ expect(result.qaReport.acceptance).toBe('accepted');
+ expect(result.qaReport.unevaluatedRequirements).toEqual([]);
+ });
+
+ test('enforce blocks a split or reversed frond; warn completes with a warning', async () => {
+ for (const [options, code] of [
+ [{ split: true }, 'HOST_VALIDATION_PRIMITIVE_COUNT'],
+ [{ reversed: true }, 'HOST_VALIDATION_ATTRIBUTE_GRADIENT'],
+ ] as const) {
+ const blocked = await renderSceneToGLB(scenePalm(options), {
+ requirements: binding(profile()),
+ }).catch((error: unknown) => error);
+ expect(blocked).toBeInstanceOf(AssetQaBlockedError);
+ expect((blocked as AssetQaBlockedError).stage).toBe('final-glb');
+ expect((blocked as Error).message).toContain(code);
+ expect((blocked as Error).message).toContain('/Scene[0]/Palm[0]/frond_0[0]');
+
+ const warned = await renderSceneToGLB(scenePalm(options), {
+ requirements: binding(profile([frondCheck], 'warn')),
+ });
+ expect(warned.qaReport.disposition).toBe('warn');
+ expect(warned.qaReport.acceptance).toBe('accepted');
+ const finding = warned.qaReport.dimensions.requirementReadiness.findings.find(
+ (item) => item.code === code,
+ );
+ expect(finding).toMatchObject({
+ disposition: 'warn',
+ affected: { nodePath: '/Scene[0]/Palm[0]/frond_0[0]' },
+ });
+ }
+ });
+
+ test('a renamed frond blocks instead of passing silently', async () => {
+ await expect(
+ renderSceneToGLB(scenePalm({ name: 'leaf_0' }), {
+ requirements: binding(profile()),
+ }),
+ ).rejects.toThrow('HOST_VALIDATION_SELECTOR_UNMATCHED');
+ });
+
+ test('KILN_QA_MODE=observe relaxes the profile like any other enforced requirement', async () => {
+ const previous = process.env.KILN_QA_MODE;
+ process.env.KILN_QA_MODE = 'observe';
+ try {
+ const result = await renderSceneToGLB(scenePalm({ reversed: true }), {
+ requirements: binding(profile()),
+ });
+ const finding = result.qaReport.dimensions.requirementReadiness.findings.find(
+ (item) => item.code === 'HOST_VALIDATION_ATTRIBUTE_GRADIENT',
+ );
+ expect(finding?.disposition).toBe('observe');
+ expect(result.qaReport.acceptance).toBe('incomplete');
+ } finally {
+ if (previous === undefined) delete process.env.KILN_QA_MODE;
+ else process.env.KILN_QA_MODE = previous;
+ }
+ });
+
+ test('a neutral binding does not run the rule', async () => {
+ const result = await renderSceneToGLB(scenePalm({ reversed: true }));
+ expect(
+ result.qaReport.rules.find((rule) => rule.id === 'HOST_VALIDATION_PROFILE')?.status,
+ ).toBe('notRequested');
+ expect(result.qaReport.acceptance).toBe('accepted');
+ });
+});
diff --git a/src/qa/validation-profile.ts b/src/qa/validation-profile.ts
new file mode 100644
index 00000000..bb0c8d7e
--- /dev/null
+++ b/src/qa/validation-profile.ts
@@ -0,0 +1,544 @@
+/**
+ * HOST_VALIDATION_PROFILE (#208): evaluates a host-bound `kiln.validation-profile.v1`
+ * on the final GLB. Pure and image-free: it reads glTF data only, never runs host code,
+ * and never trusts the pre-export scene or authored metadata.
+ */
+import type { Accessor, Document, Primitive } from '@gltf-transform/core';
+import { createGltfIO } from '../gltf-io';
+import { deliveryNodePaths } from '../delivery-inspect';
+import {
+ MAX_VALIDATION_MATCHES,
+ VALIDATION_PROFILE_VERSION,
+ type ValidationCheckV1,
+ type ValidationProfileV1,
+} from '../contracts/validation-profile';
+import { conformancePromotionAuthorization, KILN_ENGINE_QA_OWNER, type QaRule } from './registry';
+import type { QaFinding } from './types';
+
+export const HOST_VALIDATION_RULE_ID = 'HOST_VALIDATION_PROFILE';
+/** Attribute element reads per profile; O(V) per primitive and assertion. */
+export const MAX_VALIDATION_ATTRIBUTE_READS = 4_000_000;
+/** Findings kept per check and code before one summary carries the rest as a count. */
+export const MAX_VALIDATION_FINDINGS_PER_CODE = 32;
+const ENDPOINT_BAND = 0.05;
+const GRADIENT_BINS = 16;
+const MIN_AXIS_EXTENT = 1e-6;
+
+/**
+ * Registry identity only. Final bytes are not part of `QaContext`, so the scene pass never
+ * executes this rule; `appendRequirementsFinalQa` evaluates the bound profile instead.
+ */
+export const HOST_VALIDATION_QA_RULE: QaRule = Object.freeze({
+ id: HOST_VALIDATION_RULE_ID,
+ profile: 'host.validation-profile',
+ scope: { kind: 'universal' as const },
+ ruleClass: 'exact' as const,
+ owner: KILN_ENGINE_QA_OWNER,
+ promotion: conformancePromotionAuthorization(
+ 'host-validation-profile-v1',
+ 'src/qa/validation-profile.test.ts',
+ 'b6b60fcbba0238688cb0d3ef497fa3ed837757422b43207f18fc8cbe0a412ffc',
+ KILN_ENGINE_QA_OWNER,
+ '2026-10-22T00:00:00.000Z',
+ 'enforce',
+ 'cpu-raster:1.3.1',
+ ),
+ defaultMode: 'enforce' as const,
+ evaluate: () => [],
+});
+
+/**
+ * Whole-name, case-sensitive glob: `*` is any run of characters, `?` exactly one, and every
+ * other character is literal. Greedy two-pointer matching with a single resume point never
+ * backtracks exponentially; the cost is bounded by name length times pattern length.
+ */
+export function matchValidationPattern(pattern: string, name: string): boolean {
+ const p = Array.from(pattern);
+ const s = Array.from(name);
+ let pi = 0;
+ let si = 0;
+ let star = -1;
+ let resume = 0;
+ while (si < s.length) {
+ if (pi < p.length && (p[pi] === '?' || (p[pi] !== '*' && p[pi] === s[si]))) {
+ pi++;
+ si++;
+ } else if (pi < p.length && p[pi] === '*') {
+ star = pi++;
+ resume = si;
+ } else if (star >= 0) {
+ pi = star + 1;
+ si = ++resume;
+ } else return false;
+ }
+ while (pi < p.length && p[pi] === '*') pi++;
+ return pi === p.length;
+}
+
+export interface ValidationProfileEvaluationV1 {
+ findings: QaFinding[];
+ /** False when any matched node or assertion stayed unmeasured; acceptance is then incomplete. */
+ complete: boolean;
+ metrics: Record<string, number | string | boolean>;
+}
+
+export interface ValidationProfileEvaluationOptions {
+ maxAttributeReads?: number;
+}
+
+type Assertion = 'select' | 'primitives' | 'attributes' | 'gradient' | 'range' | 'material';
+type Measured = Omit<NonNullable<QaFinding['measurement']>, 'name'>;
+
+const round = (value: number) => Math.round(value * 1_000_000) / 1_000_000;
+const AXIS_INDEX = { X: 0, Y: 1, Z: 2 } as const;
+
+function component(accessor: Accessor, index: number, slot: number, element: number[]): number {
+ accessor.getElement(index, element);
+ return element[slot]!;
+}
+
+export function evaluateValidationProfileDocument(
+ profile: ValidationProfileV1,
+ doc: Document,
+ options: ValidationProfileEvaluationOptions = {},
+): ValidationProfileEvaluationV1 {
+ const disposition = profile.mode === 'enforce' ? 'block' : 'warn';
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ const budget = options.maxAttributeReads ?? MAX_VALIDATION_ATTRIBUTE_READS;
+ const paths = deliveryNodePaths(doc);
+ // Default-scene nodes only: lower MSFT_lod levels are not scene children.
+ const candidates = [...paths.entries()].filter(([node]) => node.getMesh() !== null);
+ const findings: QaFinding[] = [];
+ let complete = true;
+ let reads = 0;
+ let matchedNodes = 0;
+ let notMeasured = 0;
+
+ for (const check of profile.checks) {
+ const kept = new Map<string, number>();
+ const omitted = new Map<
+ string,
+ {
+ count: number;
+ assertion: Assertion;
+ disposition: QaFinding['disposition'];
+ }
+ >();
+ const push = (
+ code: string,
+ assertion: Assertion,
+ message: string,
+ measurement: Measured,
+ affected: QaFinding['affected'],
+ findingDisposition: QaFinding['disposition'],
+ ) =>
+ findings.push({
+ code,
+ disposition: findingDisposition,
+ dimension: 'categoryReadiness',
+ profile: profileName,
+ message: `Host validation check ${check.id}: ${message}`,
+ ...(affected ? { affected } : {}),
+ measurement: {
+ name: `checks.${check.id}.${assertion}`,
+ ...measurement,
+ },
+ });
+ const report = (
+ code: string,
+ assertion: Assertion,
+ message: string,
+ { affected, measurement }: { affected?: QaFinding['affected']; measurement: Measured },
+ findingDisposition: QaFinding['disposition'] = disposition,
+ ) => {
+ const used = kept.get(code) ?? 0;
+ if (used < MAX_VALIDATION_FINDINGS_PER_CODE) {
+ kept.set(code, used + 1);
+ push(code, assertion, message, measurement, affected, findingDisposition);
+ return;
+ }
+ const entry = omitted.get(code) ?? {
+ count: 0,
+ assertion,
+ disposition: findingDisposition,
+ };
+ entry.count++;
+ omitted.set(code, entry);
+ };
+
+ const matched = candidates.filter(([node]) =>
+ check.select.names.some((pattern) => matchValidationPattern(pattern, node.getName())),
+ );
+ const minMatches = check.select.minMatches ?? 1;
+ if (
+ matched.length < minMatches ||
+ (check.select.maxMatches !== undefined && matched.length > check.select.maxMatches)
+ ) {
+ const expected =
+ check.select.maxMatches === undefined
+ ? `>= ${minMatches}`
+ : minMatches === check.select.maxMatches
+ ? `${minMatches}`
+ : `${minMatches}..${check.select.maxMatches}`;
+ report(
+ 'HOST_VALIDATION_SELECTOR_UNMATCHED',
+ 'select',
+ `${matched.length} default-scene mesh node(s) match ${JSON.stringify(check.select.names)}; the host expects ${expected}. Node names come from the final GLB.`,
+ { measurement: { actual: matched.length, expected } },
+ );
+ }
+ const measured = matched.slice(0, MAX_VALIDATION_MATCHES);
+ if (matched.length > measured.length) {
+ complete = false;
+ report(
+ 'HOST_VALIDATION_UNMEASURED',
+ 'select',
+ `${matched.length - measured.length} matched node(s) beyond the ${MAX_VALIDATION_MATCHES}-node limit were not measured.`,
+ {
+ measurement: {
+ actual: matched.length,
+ threshold: MAX_VALIDATION_MATCHES,
+ breakdown: { nodesNotMeasured: matched.length - measured.length },
+ },
+ },
+ 'observe',
+ );
+ }
+
+ for (const [node, nodePath] of measured) {
+ const primitives = node.getMesh()!.listPrimitives();
+ const cost = primitives.reduce(
+ (sum, primitive) =>
+ sum +
+ (primitive.getAttribute('POSITION')?.getCount() ?? 0) *
+ ((check.gradient ? 2 : 0) + (check.range ? 1 : 0)),
+ 0,
+ );
+ if (notMeasured > 0 || reads + cost > budget) {
+ notMeasured++;
+ continue;
+ }
+ reads += cost;
+ matchedNodes++;
+ const affected = { node: node.getName(), nodePath };
+ if (check.primitives) {
+ const limit =
+ 'exactly' in check.primitives ? check.primitives.exactly : check.primitives.max;
+ const fails =
+ 'exactly' in check.primitives ? primitives.length !== limit : primitives.length > limit;
+ if (fails)
+ report(
+ 'HOST_VALIDATION_PRIMITIVE_COUNT',
+ 'primitives',
+ `${node.getName()} has ${primitives.length} primitive(s) in the final GLB; the host expects ${'exactly' in check.primitives ? 'exactly' : 'at most'} ${limit}. Each material group exports as its own primitive.`,
+ {
+ affected,
+ measurement: {
+ actual: primitives.length,
+ expected: limit,
+ },
+ },
+ );
+ }
+ primitives.forEach((primitive, index) => {
+ const where = `${node.getName()} primitive ${index}`;
+ for (const semantic of check.attributes ?? []) {
+ if (primitive.getAttribute(semantic)) continue;
+ report(
+ 'HOST_VALIDATION_ATTRIBUTE_MISSING',
+ 'attributes',
+ `${where} has no ${semantic} attribute.`,
+ {
+ affected: { ...affected, attribute: semantic },
+ measurement: { actual: false, expected: true },
+ },
+ );
+ }
+ if (check.gradient) {
+ const outcome = measureGradient(primitive, check.gradient);
+ if (outcome.kind === 'missing')
+ report(
+ 'HOST_VALIDATION_ATTRIBUTE_MISSING',
+ 'gradient',
+ `${where} cannot be measured: ${outcome.reason}.`,
+ {
+ affected: { ...affected, attribute: outcome.attribute },
+ measurement: { actual: false, expected: true },
+ },
+ );
+ else if (outcome.kind === 'unmeasured') {
+ complete = false;
+ report(
+ 'HOST_VALIDATION_UNMEASURED',
+ 'gradient',
+ `${where} has no extent along ${check.gradient.axis}; the gradient is unmeasured.`,
+ {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: { actual: null },
+ },
+ 'observe',
+ );
+ } else if (outcome.failures.length > 0)
+ report(
+ 'HOST_VALIDATION_ATTRIBUTE_GRADIENT',
+ 'gradient',
+ `${where} ${check.gradient.attribute}[${check.gradient.component}] fails the ${outcome.failures.join(' and ')} test along local ${check.gradient.axis}: ${round(outcome.fromMean)} to ${round(outcome.toMean)}, expected ${check.gradient.from} to ${check.gradient.to} within ${check.gradient.tolerance}.`,
+ {
+ affected: { ...affected, attribute: check.gradient.attribute },
+ measurement: {
+ actual: `${round(outcome.fromMean)}..${round(outcome.toMean)}`,
+ expected: `${check.gradient.from}..${check.gradient.to}`,
+ threshold: check.gradient.tolerance,
+ breakdown: {
+ fromMean: round(outcome.fromMean),
+ toMean: round(outcome.toMean),
+ worstRegression: round(outcome.worstRegression),
+ },
+ },
+ },
+ );
+ }
+ if (check.range) {
+ const accessor = primitive.getAttribute(check.range.attribute);
+ if (!accessor || check.range.component >= accessor.getElementSize())
+ report(
+ 'HOST_VALIDATION_ATTRIBUTE_MISSING',
+ 'range',
+ `${where} has no ${check.range.attribute}[${check.range.component}].`,
+ {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: { actual: false, expected: true },
+ },
+ );
+ else {
+ const element: number[] = [];
+ let min = Infinity;
+ let max = -Infinity;
+ for (let i = 0; i < accessor.getCount(); i++) {
+ const value = component(accessor, i, check.range.component, element);
+ if (value < min) min = value;
+ if (value > max) max = value;
+ }
+ const { tolerance } = check.range;
+ if (
+ accessor.getCount() > 0 &&
+ (min < check.range.min - tolerance || max > check.range.max + tolerance)
+ )
+ report(
+ 'HOST_VALIDATION_ATTRIBUTE_RANGE',
+ 'range',
+ `${where} ${check.range.attribute}[${check.range.component}] spans ${round(min)}..${round(max)}; the host allows ${check.range.min}..${check.range.max} within ${tolerance}.`,
+ {
+ affected: { ...affected, attribute: check.range.attribute },
+ measurement: {
+ actual: `${round(min)}..${round(max)}`,
+ expected: `${check.range.min}..${check.range.max}`,
+ threshold: tolerance,
+ },
+ },
+ );
+ }
+ }
+ if (check.material) {
+ const material = primitive.getMaterial();
+ // An unnamed material is identified by its glTF materials index.
+ const label =
+ material?.getName() ||
+ (material
+ ? `materials[${doc.getRoot().listMaterials().indexOf(material)}]`
+ : '(glTF default)');
+ const alphaMode = material?.getAlphaMode() ?? 'OPAQUE';
+ const doubleSided = material?.getDoubleSided() ?? false;
+ if (check.material.alphaMode !== undefined && alphaMode !== check.material.alphaMode)
+ report(
+ 'HOST_VALIDATION_MATERIAL_ALPHA_MODE',
+ 'material',
+ `${where} uses alphaMode ${alphaMode}; the host expects ${check.material.alphaMode}.`,
+ {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: alphaMode,
+ expected: check.material.alphaMode,
+ },
+ },
+ );
+ if (
+ check.material.doubleSided !== undefined &&
+ doubleSided !== check.material.doubleSided
+ )
+ report(
+ 'HOST_VALIDATION_MATERIAL_DOUBLE_SIDED',
+ 'material',
+ `${where} is ${doubleSided ? 'double-sided' : 'single-sided'}; the host expects ${check.material.doubleSided ? 'double-sided' : 'single-sided'}.`,
+ {
+ affected: { ...affected, material: label },
+ measurement: {
+ actual: doubleSided,
+ expected: check.material.doubleSided,
+ },
+ },
+ );
+ }
+ });
+ }
+ for (const [code, entry] of omitted)
+ push(
+ code,
+ entry.assertion,
+ `${entry.count} more ${code} finding(s) omitted after the first ${MAX_VALIDATION_FINDINGS_PER_CODE}.`,
+ { actual: entry.count, breakdown: { omitted: entry.count } },
+ undefined,
+ entry.disposition,
+ );
+ }
+ if (notMeasured > 0) {
+ complete = false;
+ findings.push({
+ code: 'HOST_VALIDATION_UNMEASURED',
+ disposition: 'observe',
+ dimension: 'categoryReadiness',
+ profile: profileName,
+ message: `Host validation stopped at its ${budget} attribute-read budget; ${notMeasured} matched node(s) were not measured.`,
+ measurement: {
+ name: 'checks.*.budget',
+ actual: reads,
+ threshold: budget,
+ breakdown: { nodesNotMeasured: notMeasured },
+ },
+ });
+ }
+ return {
+ findings,
+ complete,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: matchedNodes,
+ hostValidationAttributeReads: reads,
+ hostValidationComplete: complete,
+ },
+ };
+}
+
+type GradientOutcome =
+ | { kind: 'missing'; attribute: string; reason: string }
+ | { kind: 'unmeasured' }
+ | {
+ kind: 'measured';
+ fromMean: number;
+ toMean: number;
+ worstRegression: number;
+ failures: string[];
+ };
+
+/** Straight local-axis gradient: endpoint bands and binned monotonicity (no node transform). */
+function measureGradient(
+ primitive: Primitive,
+ gradient: NonNullable<ValidationCheckV1['gradient']>,
+): GradientOutcome {
+ const position = primitive.getAttribute('POSITION');
+ if (!position)
+ return {
+ kind: 'missing',
+ attribute: 'POSITION',
+ reason: 'no POSITION attribute',
+ };
+ const values = primitive.getAttribute(gradient.attribute);
+ if (!values || gradient.component >= values.getElementSize())
+ return {
+ kind: 'missing',
+ attribute: gradient.attribute,
+ reason: `no ${gradient.attribute}[${gradient.component}]`,
+ };
+ const count = Math.min(position.getCount(), values.getCount());
+ const axis = AXIS_INDEX[gradient.axis[1] as 'X' | 'Y' | 'Z'];
+ const sign = gradient.axis[0] === '-' ? -1 : 1;
+ const t = new Float64Array(count);
+ const v = new Float64Array(count);
+ const element: number[] = [];
+ let tMin = Infinity;
+ let tMax = -Infinity;
+ for (let i = 0; i < count; i++) {
+ t[i] = sign * component(position, i, axis, element);
+ v[i] = component(values, i, gradient.component, element);
+ if (t[i]! < tMin) tMin = t[i]!;
+ if (t[i]! > tMax) tMax = t[i]!;
+ }
+ if (!(tMax - tMin >= MIN_AXIS_EXTENT)) return { kind: 'unmeasured' };
+ const sums = new Float64Array(GRADIENT_BINS);
+ const counts = new Uint32Array(GRADIENT_BINS);
+ let fromSum = 0;
+ let fromCount = 0;
+ let toSum = 0;
+ let toCount = 0;
+ for (let i = 0; i < count; i++) {
+ const s = (t[i]! - tMin) / (tMax - tMin);
+ if (s <= ENDPOINT_BAND) {
+ fromSum += v[i]!;
+ fromCount++;
+ }
+ if (s >= 1 - ENDPOINT_BAND) {
+ toSum += v[i]!;
+ toCount++;
+ }
+ const bin = Math.min(GRADIENT_BINS - 1, Math.floor(s * GRADIENT_BINS));
+ sums[bin] = sums[bin]! + v[i]!;
+ counts[bin] = counts[bin]! + 1;
+ }
+ const fromMean = fromSum / fromCount;
+ const toMean = toSum / toCount;
+ const direction = Math.sign(gradient.to - gradient.from);
+ let worstRegression = 0;
+ let previous: number | undefined;
+ for (let bin = 0; bin < GRADIENT_BINS; bin++) {
+ if (counts[bin] === 0) continue;
+ const mean = sums[bin]! / counts[bin]!;
+ if (previous !== undefined)
+ worstRegression = Math.max(worstRegression, (previous - mean) * direction);
+ previous = mean;
+ }
+ const failures: string[] = [];
+ if (
+ Math.abs(fromMean - gradient.from) > gradient.tolerance ||
+ Math.abs(toMean - gradient.to) > gradient.tolerance
+ )
+ failures.push('endpoints');
+ if (gradient.monotonic && worstRegression > gradient.tolerance) failures.push('monotonic');
+ return { kind: 'measured', fromMean, toMean, worstRegression, failures };
+}
+
+/** Re-open the exact serialized bytes, as the final VFX check does. */
+export async function evaluateValidationProfileGlb(
+ profile: ValidationProfileV1,
+ bytes: Uint8Array,
+ options: ValidationProfileEvaluationOptions = {},
+): Promise<ValidationProfileEvaluationV1> {
+ let doc: Document;
+ try {
+ doc = await createGltfIO().readBinary(bytes);
+ } catch (error) {
+ // Unreadable bytes (for example a codec without its decoder) are unmeasured, never a pass.
+ const profileName = `${VALIDATION_PROFILE_VERSION}:${profile.profileId}`;
+ return {
+ findings: [
+ {
+ code: 'HOST_VALIDATION_UNMEASURED',
+ disposition: 'observe',
+ dimension: 'categoryReadiness',
+ profile: profileName,
+ message: `Host validation could not read the final GLB: ${error instanceof Error ? error.message : String(error)}`,
+ measurement: { name: 'checks.*.read', actual: null },
+ },
+ ],
+ complete: false,
+ metrics: {
+ hostValidationProfile: profileName,
+ hostValidationChecks: profile.checks.length,
+ hostValidationMatchedNodes: 0,
+ hostValidationAttributeReads: 0,
+ hostValidationComplete: false,
+ },
+ };
+ }
+ return evaluateValidationProfileDocument(profile, doc, options);
+}
diff --git a/src/requirements-context.test.ts b/src/requirements-context.test.ts
index 9785d833..f3f4200c 100644
--- a/src/requirements-context.test.ts
+++ b/src/requirements-context.test.ts
@@ -108,3 +108,46 @@ test('checkpoint decoding rejects legacy policy and inconsistent hashes', () =>
checkpoint.binding.requirements.requirements.grounding = requestedRequirement({});
expect(() => readRequirementsCheckpoint(checkpoint)).toThrow(/binding|requirements/i);
});
+test('a validation profile is host policy: replacing it changes both policy hashes', () => {
+ const profile = (doubleSided: boolean) => ({
+ version: 'kiln.validation-profile.v1' as const,
+ profileId: 'holodeck.palm',
+ mode: 'enforce' as const,
+ checks: [{ id: 'frond', select: { names: ['frond_*'] }, material: { doubleSided } }],
+ });
+ const store = createAssetRequirementsStore();
+ const key = { taskId: 'palm', lineageId: 'palm-a' };
+ const first = store.host.bind(
+ key,
+ createAssetRequirementsV1({
+ requirements: { validation: requestedRequirement(profile(false)) },
+ }),
+ authority,
+ );
+ const second = store.host.replace(
+ key,
+ first.revision,
+ createAssetRequirementsV1({
+ requirements: { validation: requestedRequirement(profile(true)) },
+ }),
+ { ...authority, reason: 'stricter destination' },
+ );
+ expect(second.policyHash).not.toBe(first.policyHash);
+ expect(second.history.map((change) => change.policyHash)).toEqual([
+ first.policyHash,
+ second.policyHash,
+ ]);
+ const before = resolveRequirementsContext(first);
+ const after = resolveRequirementsContext(second);
+ expect(after.policyHash).not.toBe(before.policyHash);
+ expect(after.adviceHash).toBe(before.adviceHash);
+ // Only a requested profile is policy; an inferred one is advice and never evaluates.
+ const inferred = resolveRequirementsContext(
+ binding(
+ createAssetRequirementsV1({
+ requirements: { validation: { state: 'inferred', value: profile(true) } },
+ }),
+ ),
+ );
+ expect(inferred.policyHash).toBe(resolveRequirementsContext(binding()).policyHash);
+});
diff --git a/src/requirements.ts b/src/requirements.ts
index 0a252f2f..3bede42a 100644
--- a/src/requirements.ts
+++ b/src/requirements.ts
@@ -2,3 +2,4 @@
export * from './contracts/requirements';
export * from './requirements-store';
export * from './requirements-context';
+export * from './contracts/validation-profile';
diff --git a/src/review-tools.test.ts b/src/review-tools.test.ts
index 204d0695..bfb375b3 100644
--- a/src/review-tools.test.ts
+++ b/src/review-tools.test.ts
@@ -16,6 +16,8 @@ import {
} from './material-library-node';
import { materialLibraryPortableSpec } from './material-library';
import { decodeAssetBundle } from './assets';
+import { createAssetRequirementsStore } from './requirements-store';
+import { createAssetRequirementsV1, requestedRequirement } from './contracts/requirements';
test('review save preserves recorded GLB/source and refuses revision or policy mismatch', async () => {
const root = await mkdtemp(join(tmpdir(), 'kiln-exact-review-'));
@@ -285,3 +287,71 @@ test('reviewed save preserves mixed V1/V2 material identities and editable closu
await rm(root, { recursive: true, force: true });
}
});
+
+test('review save refuses an artifact reviewed under an earlier validation profile (#208)', async () => {
+ const root = await mkdtemp(join(tmpdir(), 'kiln-review-profile-'));
+ try {
+ const profile = (doubleSided?: boolean) => ({
+ version: 'kiln.validation-profile.v1' as const,
+ profileId: 'holodeck.palm',
+ mode: 'enforce' as const,
+ checks: [
+ {
+ id: 'frond',
+ select: { names: ['Mesh_frond_*'] },
+ primitives: { exactly: 1 },
+ ...(doubleSided === undefined ? {} : { material: { doubleSided } }),
+ },
+ ],
+ });
+ const store = createAssetRequirementsStore();
+ const key = { taskId: 'palm', lineageId: 'palm-a' };
+ const authority = { actor: 'holodeck', reason: 'Destination', source: 'brief' as const };
+ const v1 = store.host.bind(
+ key,
+ createAssetRequirementsV1({ requirements: { validation: requestedRequirement(profile()) } }),
+ authority,
+ );
+ const v2 = store.host.replace(
+ key,
+ v1.revision,
+ createAssetRequirementsV1({
+ requirements: { validation: requestedRequirement(profile(true)) },
+ }),
+ { ...authority, reason: 'Stricter destination' },
+ );
+ const code =
+ "function build(){const r=createRoot('Palm');createPart('frond_0',boxGeo(0.2,2,0.05),gameMaterial('#336633'),{parent:r});return r;}";
+ const rendered = await renderGLBInProcess(code, { requirements: v1 });
+ const review = new FileLiveReview(root);
+ await review.observe('fixture', {}, async () => {
+ review.artifact(code, rendered);
+ return { ok: true };
+ });
+ await review.flush();
+ const operation = (await review.snapshot()).operations[0]!;
+ const library = new FileAssetLibrary({ project: root });
+ const input = {
+ action: 'save',
+ operationId: operation.operationId,
+ expectedRevision: operation.revision,
+ name: 'Palm',
+ };
+ const stale = createKilnReviewDef({
+ reviewStore: review,
+ assetLibrary: library,
+ requirements: v2,
+ });
+ await expect(stale.run(input)).rejects.toThrow(/requirements/i);
+ expect(await library.list('project')).toHaveLength(0);
+ const current = createKilnReviewDef({
+ reviewStore: review,
+ assetLibrary: library,
+ requirements: v1,
+ });
+ await current.run(input);
+ expect(await library.list('project')).toHaveLength(1);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/src/tools/__tests__/registry-requirements.test.ts b/src/tools/__tests__/registry-requirements.test.ts
index dce43d31..6fb27ddd 100644
--- a/src/tools/__tests__/registry-requirements.test.ts
+++ b/src/tools/__tests__/registry-requirements.test.ts
@@ -1,7 +1,14 @@
import { expect, test } from 'bun:test';
import { createKilnProgramToolRegistry, createKilnNativeToolRegistry } from '../registry';
import { createAssetRequirementsStore } from '../../requirements-store';
-import { createAssetRequirementsV1 } from '../../contracts/requirements';
+import { createAssetRequirementsV1, requestedRequirement } from '../../contracts/requirements';
+import type { ValidationProfileV1 } from '../../contracts/validation-profile';
+import { MemoryProgramStore } from '../../program-store';
+import { ProgramArtifactStore } from '../program-artifacts';
+import { FileAssetLibrary } from '../../assets-node';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { inspect } from '../../inspect';
import { renderGLBInProcess } from '../../render';
import type { RequirementsContext } from '../../requirements-context';
@@ -77,3 +84,116 @@ test('legacy host category is rejected when constructing both tool surfaces', ()
'explicit migration',
);
});
+
+// Host validation profile (#208): the host binding is the only source of the profile.
+const frondSource = (
+ name: string,
+) => `const meta={name:'Palm',requirements:{validation:{state:'inapplicable'}}};
+function build(){const r=createRoot('Palm');const f=createPart('${name}',boxGeo(0.2,2,0.05),gameMaterial('#336633'),{parent:r});f.userData.requirements={validation:{state:'inapplicable'}};f.userData.kilnValidation={pass:true};return r;}`;
+function validationProfile(material?: { doubleSided: boolean }): ValidationProfileV1 {
+ return {
+ version: 'kiln.validation-profile.v1',
+ profileId: 'holodeck.palm',
+ mode: 'enforce',
+ checks: [
+ {
+ id: 'frond',
+ // createPart('frond_0') exports its mesh node as Mesh_frond_0; patterns match final names.
+ select: { names: ['Mesh_frond_*'] },
+ primitives: { exactly: 1 },
+ ...(material ? { material } : {}),
+ },
+ ],
+ };
+}
+const profileKey = { taskId: 'palm', lineageId: 'palm-a' };
+const hostAuthority = {
+ actor: 'holodeck',
+ reason: 'Destination shader contract',
+ source: 'brief' as const,
+};
+function profileBinding(profile = validationProfile()) {
+ return createAssetRequirementsStore().host.bind(
+ profileKey,
+ createAssetRequirementsV1({ requirements: { validation: requestedRequirement(profile) } }),
+ hostAuthority,
+ );
+}
+async function renderResult(
+ registry: ReturnType<typeof createKilnProgramToolRegistry>,
+ input: Record<string, unknown>,
+) {
+ return (await registry.find((tool) => tool.name === 'kiln_render')!.run(input)) as {
+ ok: boolean;
+ error?: string;
+ qaReport?: { acceptance: string };
+ };
+}
+
+test('tool input, source meta and userData cannot weaken a bound validation profile', async () => {
+ const tools = createKilnProgramToolRegistry({ requirements: profileBinding() });
+ const weakening = {
+ requirements: { validation: { state: 'inapplicable' } },
+ validation: { mode: 'warn', checks: [] },
+ };
+ const renamed = await renderResult(tools, { code: frondSource('leaf_0'), ...weakening });
+ expect(renamed.ok).toBe(false);
+ expect(renamed.error).toContain('HOST_VALIDATION_SELECTOR_UNMATCHED');
+ const conforming = await renderResult(tools, { code: frondSource('frond_0'), ...weakening });
+ expect(conforming.ok).toBe(true);
+ expect(conforming.qaReport?.acceptance).toBe('accepted');
+});
+
+test('a validation profile change invalidates earlier finish, render and save authorization', async () => {
+ const store = createAssetRequirementsStore();
+ const v1 = store.host.bind(
+ profileKey,
+ createAssetRequirementsV1({
+ requirements: { validation: requestedRequirement(validationProfile()) },
+ }),
+ hostAuthority,
+ );
+ const v2 = store.host.replace(
+ profileKey,
+ v1.revision,
+ createAssetRequirementsV1({
+ requirements: {
+ validation: requestedRequirement(validationProfile({ doubleSided: true })),
+ },
+ }),
+ { ...hostAuthority, reason: 'Fronds render both faces' },
+ );
+ expect(v2.policyHash).not.toBe(v1.policyHash);
+ expect(v2.history.at(-1)?.previousPolicyHash).toBe(v1.policyHash);
+
+ const programStore = new MemoryProgramStore();
+ const programArtifacts = new ProgramArtifactStore();
+ const shared = { programStore, programArtifacts, cacheEvaluations: false };
+ const programRef = await programStore.put(frondSource('frond_0'));
+ const before = createKilnNativeToolRegistry({ ...shared, requirements: v1 }, {});
+ const reviewed = (await before
+ .find((tool) => tool.name === 'kiln_render')!
+ .run({ programRef, capture: { preset: '1x1' } })) as { ok: boolean };
+ expect(reviewed.ok).toBe(true);
+ const after = createKilnNativeToolRegistry({ ...shared, requirements: v2 }, {});
+ await expect(
+ after.find((tool) => tool.name === 'kiln_finish')!.run({ programRef }),
+ ).rejects.toThrow('requirements');
+ const stricter = (await after
+ .find((tool) => tool.name === 'kiln_render')!
+ .run({ programRef, capture: { preset: '1x1' } })) as { ok: boolean; error?: string };
+ expect(stricter.ok).toBe(false);
+ expect(stricter.error).toContain('HOST_VALIDATION_MATERIAL_DOUBLE_SIDED');
+
+ const directory = await mkdtemp(join(tmpdir(), 'kiln-validation-profile-'));
+ try {
+ const assetLibrary = new FileAssetLibrary({ project: directory });
+ const saving = createKilnProgramToolRegistry({ assetLibrary, programStore, requirements: v2 });
+ await expect(
+ saving.find((tool) => tool.name === 'kiln_save')!.run({ programRef, name: 'Palm' }),
+ ).rejects.toThrow('HOST_VALIDATION_MATERIAL_DOUBLE_SIDED');
+ expect(await assetLibrary.list('project')).toHaveLength(0);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/src/tools/discovery.ts b/src/tools/discovery.ts
index f5ed082d..6d544c8e 100644
--- a/src/tools/discovery.ts
+++ b/src/tools/discovery.ts
@@ -9,6 +9,7 @@ import { MAX_CAPTURE_SHOT_SIZE, resolveCaptureLimits } from '../views/capture-li
import { geometryExportAttributes } from '../geometry-export';
import { resolveGltfExporter } from '../community-exporter';
import { approvedTextureCatalogV1 } from '../material-resources';
+import { resolveRequirementsContext } from '../requirements-context';
/** Shared native tool definition; all transports use the same Discovery service. */
export function createKilnDiscoveryDef(
@@ -43,6 +44,20 @@ function configuredProject(context: KilnToolContext): string | null {
return context.workspace?.configured?.() ?? null;
}
+/** Host-declared obligations, kept apart from engine advice (#176, #208). */
+function hostRequirements(context: KilnToolContext) {
+ const active = resolveRequirementsContext(context.requirements);
+ const validation = active.requirements.requirements.validation;
+ return {
+ bound: active.binding !== undefined,
+ policyHash: active.policyHash,
+ declared:
+ validation?.state === 'requested'
+ ? { source: 'host-binding', validationProfile: validation.value }
+ : null,
+ };
+}
+
function projectNotes(context: KilnToolContext): string[] {
const projectId = configuredProject(context);
return projectId
@@ -119,6 +134,7 @@ async function currentCapabilities(
read: 'kiln_project { action: "get", projectId } returns the brief, design, inventory and material pins',
},
renderer,
+ requirements: hostRequirements(context),
execution:
context.localExecution ??
(context.evaluatorPort
diff --git a/src/tools/review-detail.test.ts b/src/tools/review-detail.test.ts
index da83835b..1c59bed8 100644
--- a/src/tools/review-detail.test.ts
+++ b/src/tools/review-detail.test.ts
@@ -847,7 +847,12 @@ describe('review tool detail', () => {
expect((retained!.review.qaReport as { detail?: string }).detail).toBeUndefined();
expect(Array.isArray((retained!.review.qaReport as { rules?: unknown }).rules)).toBe(true);
- const full = (await render.run({ code: stack, detail: 'full' })) as ReviewView;
+ // Full detail of the 40-part stack sits near the 40,000-character bound, so each QA rule
+ // the engine adds can tip it into full-bounded. 32 parts keep the full report unbounded.
+ const full = (await render.run({
+ code: stack.replace('i < 40', 'i < 32'),
+ detail: 'full',
+ })) as ReviewView;
expect(full.qaReport.detail).toBeUndefined();
expect(Array.isArray(full.qaReport.rules)).toBe(true);
expect(full.parts.length).toBeGreaterThan(COMPACT_PART_PREVIEW);