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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
fix(render-service): keep a texture's UV set and transform, and shade each view for its own projection (#341)
Matthew Kissinger17608390b34c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e0c13b3d..b7ece4fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,20 @@ does not publish a package.render. That first capture is cached like any other: its repeat is a hit, where before it renderedagain (4.9 s instead of about 2 s for the default grid). The identity follows the port's ownconnection, so the start it makes is the one the first request would make.+- **The GPU render service samples the UV set a texture names, with its `KHR_texture_transform`.** The+ service replaces each decoded map with a `DataTexture` for upload and copied only colour space, flip,+ wrap and filters, so a map with `texCoord: 2` sampled UV0 and a transformed map drew untransformed:+ four assets whose base colour sampled UV0..UV3 rendered pixel-identical. The replacement now keeps+ `channel`, `offset`, `repeat`, `rotation`, `center` and the texture matrix.+- **A perspective view drawn after orthographic ones in one render-service request is shaded for its+ own camera.** three compiles a node material's view direction for the first camera that draws it,+ and its program cache ignores the camera, so the legacy `beauty` view, and any perspective camera+ after an orthographic one in camera mode, reused the orthographic program: on a glossy metal sphere+ 9% of the beauty's pixels differed by up to 97/255 from the same camera drawn alone. Materials are+ now keyed by projection, so the beauty matches a perspective-only render byte for byte; orthographic+ sheet views are unchanged. A request that switches projection builds one more program per material.+ Both changes alter render-service source, so its build identity changes and a running service of+ the previous build is reported as incompatible rather than joined.- `KILN_EVALUATOR_TIMEOUT_MS` now works above 60,000, as documented. Only the host read it: the workerkept its own 60-second timer, so a build that yielded to the event loop after that failed with`DEADLINE_EXCEEDED` at any limit, usually once the abandoned build had run to its end. The worker nowdiff --git a/render-service/package.json b/render-service/package.jsonindex 3b274fb8..1464ea9a 100644--- a/render-service/package.json+++ b/render-service/package.json@@ -6,7 +6,7 @@"description": "GLB in, PBR PNG views out. Dawn/WebGPU + three.js, headless. No Kiln engine coupling.","scripts": {"start": "node --import ./src/register-hooks.mjs src/server.mjs",- "test": "node --test test/bind-policy.test.mjs test/beauty-camera.test.mjs test/display-output.test.mjs test/readback.test.mjs test/cache-identity.test.mjs test/asset-camera.test.mjs test/contract.test.mjs test/framing.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs test/gallery-presentation.test.mjs test/display-transform.test.mjs test/instance.test.mjs test/hardening.test.mjs test/node-visibility.test.mjs",+ "test": "node --test test/bind-policy.test.mjs test/beauty-camera.test.mjs test/display-output.test.mjs test/readback.test.mjs test/cache-identity.test.mjs test/asset-camera.test.mjs test/contract.test.mjs test/framing.test.mjs test/material-fixture.test.mjs test/presentation-presets.test.mjs test/gallery-presentation.test.mjs test/display-transform.test.mjs test/instance.test.mjs test/hardening.test.mjs test/node-visibility.test.mjs test/data-textures.test.mjs test/projection-cache-key.test.mjs","smoke": "node --import ./src/register-hooks.mjs test/smoke.mjs","conformance:display": "node --import ./src/register-hooks.mjs test/display-output-conformance.mjs","conformance:material": "node --import ./src/register-hooks.mjs test/material-conformance.mjs"diff --git a/render-service/src/data-textures.mjs b/render-service/src/data-textures.mjsnew file mode 100644index 00000000..1417155a--- /dev/null+++ b/render-service/src/data-textures.mjs@@ -0,0 +1,55 @@+// Decoded glTF images -> DataTexture, for the service's WebGPU upload path.+//+// GLTFLoader's ImageBitmapLoader path yields the decoded bitmaps the renderer's+// createImageBitmap shim returns, which Dawn uploads as black; a DataTexture goes+// through writeTexture instead. The replacement must sample exactly as the loaded+// texture did, so it carries every sampling property the loader can set. No three+// import: the caller passes the namespace it renders with, so class identity holds.++/** Material slots GLTFLoader fills from a glTF core material. */+export const DATA_TEXTURE_SLOTS = Object.freeze([+ 'map',+ 'normalMap',+ 'roughnessMap',+ 'metalnessMap',+ 'aoMap',+ 'emissiveMap',+]);++/** Replace every decoded-image texture under `root` with an equivalent DataTexture. */+export function toDataTextures(root, THREE) {+ root.traverse((o) => {+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {+ for (const slot of DATA_TEXTURE_SLOTS) {+ const tex = mat[slot];+ if (tex?.image?.data && !tex.isDataTexture) {+ const dt = new THREE.DataTexture(+ tex.image.data,+ tex.image.width,+ tex.image.height,+ THREE.RGBAFormat,+ );+ dt.colorSpace = tex.colorSpace;+ dt.flipY = tex.flipY;+ dt.wrapS = tex.wrapS;+ dt.wrapT = tex.wrapT;+ dt.magFilter = tex.magFilter;+ // Which UV set, and KHR_texture_transform's offset/scale/rotation. GLTFLoader sets+ // `channel` from `texCoord` and from the transform's texCoord override.+ dt.channel = tex.channel;+ dt.offset.copy(tex.offset);+ dt.repeat.copy(tex.repeat);+ dt.rotation = tex.rotation;+ dt.center.copy(tex.center);+ dt.matrixAutoUpdate = tex.matrixAutoUpdate;+ dt.matrix.copy(tex.matrix);+ dt.minFilter = THREE.LinearMipmapLinearFilter;+ dt.generateMipmaps = true;+ dt.needsUpdate = true;+ mat[slot] = dt;+ mat.needsUpdate = true;+ }+ }+ }+ });+}diff --git a/render-service/src/projection-cache-key.mjs b/render-service/src/projection-cache-key.mjsnew file mode 100644index 00000000..b75e6c4f--- /dev/null+++ b/render-service/src/projection-cache-key.mjs@@ -0,0 +1,32 @@+// One program per camera projection.+//+// three 0.186's node material compiles `positionViewDirection` from the camera of the first+// draw (`nodes/accessors/Position.js`): the constant (0, 0, 1) for an orthographic camera,+// per-fragment for a perspective one. The render object and its program cache key ignore the+// camera, so a perspective view drawn after orthographic views in one request reuses the+// orthographic program and shades its reflections from the wrong direction. Naming the+// projection in the program cache key, and marking the material for update when it changes,+// makes three build the program for the camera that is drawing. No three import.++const PROJECTION = Symbol('kiln.renderService.projection');+const BASE_KEY = Symbol('kiln.renderService.baseProgramCacheKey');++function keyedProgramCacheKey() {+ return `${this[BASE_KEY]()}|projection:${this[PROJECTION]}`;+}++/** Key every material under `root` to `camera`'s projection before drawing with it. */+export function keyMaterialsByProjection(root, camera) {+ const projection = camera.isOrthographicCamera ? 'orthographic' : 'perspective';+ root.traverse((o) => {+ for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {+ if (mat[PROJECTION] === projection) continue;+ if (mat[BASE_KEY] === undefined) {+ mat[BASE_KEY] = mat.customProgramCacheKey.bind(mat);+ mat.customProgramCacheKey = keyedProgramCacheKey;+ }+ mat[PROJECTION] = projection;+ mat.needsUpdate = true;+ }+ });+}diff --git a/render-service/src/renderer.mjs b/render-service/src/renderer.mjsindex bddb5678..5c60f68a 100644--- a/render-service/src/renderer.mjs+++ b/render-service/src/renderer.mjs@@ -1,4 +1,5 @@import { renderDisplayTarget } from './display-output.mjs';+import { keyMaterialsByProjection } from './projection-cache-key.mjs';import { packRgbaReadback } from './readback.mjs';// GLB bytes -> PBR PNG views. Headless three.js WebGPURenderer, RenderTarget-only.//@@ -26,6 +27,7 @@ import { reviewNeutralToneMapping } from './review-tone-mapping.mjs';export { MAX_VIEW_DIRS, validateViewDirs } from './contract.mjs';import { beautyCameraSpec, orthoDepth, orthoHalfExtent } from './framing.mjs';import { applyNodeVisibility, expandByDrawnObject } from './node-visibility.mjs';+import { toDataTextures } from './data-textures.mjs';globalThis.self = globalThis;globalThis.requestAnimationFrame = (cb) => setTimeout(() => cb(performance.now()), 16);@@ -147,41 +149,6 @@ export async function initRenderer(opts = {}) {return ctx;}-function toDataTextures(root) {- root.traverse((o) => {- for (const mat of Array.isArray(o.material) ? o.material : o.material ? [o.material] : []) {- for (const slot of [- 'map',- 'normalMap',- 'roughnessMap',- 'metalnessMap',- 'aoMap',- 'emissiveMap',- ]) {- const tex = mat[slot];- if (tex?.image?.data && !tex.isDataTexture) {- const dt = new THREE.DataTexture(- tex.image.data,- tex.image.width,- tex.image.height,- THREE.RGBAFormat,- );- dt.colorSpace = tex.colorSpace;- dt.flipY = tex.flipY;- dt.wrapS = tex.wrapS;- dt.wrapT = tex.wrapT;- dt.magFilter = tex.magFilter;- dt.minFilter = THREE.LinearMipmapLinearFilter;- dt.generateMipmaps = true;- dt.needsUpdate = true;- mat[slot] = dt;- mat.needsUpdate = true;- }- }- }- });-}-/*** Release the GPU resources this request's parse allocated. `ctx.environment` is* seeded into the visited set because it is shared across every request and@@ -287,6 +254,12 @@ function orthoCam(center, min, max, dir) {return cam;}+/** Draw one view, with every material compiled for this camera's projection. */+function drawView(renderer, scene, camera, target) {+ keyMaterialsByProjection(scene, camera);+ renderDisplayTarget(renderer, scene, camera, target);+}+function exactPerspectiveCam(spec) {const cam =spec.projection === 'orthographic'@@ -359,7 +332,7 @@ export async function renderGlb(glbBytes, opts = {}) {const requestTargets = [];try {const hiddenNodes = applyNodeVisibility(gltf);- toDataTextures(gltf.scene);+ toDataTextures(gltf.scene, THREE);const tLoad = performance.now();scene = new THREE.Scene();@@ -383,7 +356,7 @@ export async function renderGlb(glbBytes, opts = {}) {samples: 4,});requestTargets.push(target);- renderDisplayTarget(renderer, scene, exactPerspectiveCam(camera), target);+ drawView(renderer, scene, exactPerspectiveCam(camera), target);}const views = [];for (const target of requestTargets) {@@ -420,7 +393,7 @@ export async function renderGlb(glbBytes, opts = {}) {// sync per view.const rts = rtPool(size, viewDirs.length);viewDirs.forEach((dir, i) => {- renderDisplayTarget(renderer, scene, orthoCam(center, boxMin, boxMax, dir), rts[i]);+ drawView(renderer, scene, orthoCam(center, boxMin, boxMax, dir), rts[i]);});const views = [];for (const vrt of rts) {@@ -432,7 +405,7 @@ export async function renderGlb(glbBytes, opts = {}) {if (beautySize) {const rtB = new THREE.RenderTarget(beautySize, beautySize, { depthBuffer: true, samples: 4 });requestTargets.push(rtB);- renderDisplayTarget(+ drawView(renderer,scene,exactPerspectiveCam(beautyCameraSpec(center.toArray(), sizes.length() * 0.62 + 1e-3)),diff --git a/render-service/test/data-textures.test.mjs b/render-service/test/data-textures.test.mjsnew file mode 100644index 00000000..22afba70--- /dev/null+++ b/render-service/test/data-textures.test.mjs@@ -0,0 +1,191 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import { PNG } from 'pngjs';+import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++import { DATA_TEXTURE_SLOTS, toDataTextures } from '../src/data-textures.mjs';++// The renderer's decode path, so GLTFLoader yields the same `{ width, height, data }` bitmaps+// it does in the service (renderer.mjs installs the same two globals).+globalThis.self ??= globalThis;+globalThis.createImageBitmap = async (blob) => {+ const png = PNG.sync.read(Buffer.from(await blob.arrayBuffer()));+ return { width: png.width, height: png.height, data: new Uint8Array(png.data), close() {} };+};++function pngBytes() {+ const png = new PNG({ width: 2, height: 2 });+ png.data.fill(200);+ return PNG.sync.write(png);+}++function pad4(bytes, fill = 0) {+ const out = new Uint8Array(Math.ceil(bytes.length / 4) * 4).fill(fill);+ out.set(bytes);+ return out;+}++/**+ * One triangle with TEXCOORD_0..3. The base colour samples TEXCOORD_2 through `texCoord`; the+ * normal map samples TEXCOORD_1 through KHR_texture_transform, with offset, rotation and scale.+ */+function glb() {+ const floats = [+ [0, 0, 0, 1, 0, 0, 0, 1, 0],+ [0, 0, 1, 0, 0, 1],+ [0.1, 0.1, 0.9, 0.1, 0.1, 0.9],+ [0.2, 0.2, 0.8, 0.2, 0.2, 0.8],+ [0.3, 0.3, 0.7, 0.3, 0.3, 0.7],+ ].map((a) => new Uint8Array(new Float32Array(a).buffer));+ const image = pad4(pngBytes());+ const chunks = [...floats, image];+ const bin = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));+ const bufferViews = [];+ let offset = 0;+ for (const chunk of chunks) {+ bin.set(chunk, offset);+ bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: chunk.length });+ offset += chunk.length;+ }+ bufferViews[5].byteLength = pngBytes().length;+ const json = {+ asset: { version: '2.0' },+ extensionsUsed: ['KHR_texture_transform'],+ scene: 0,+ scenes: [{ nodes: [0] }],+ nodes: [{ mesh: 0 }],+ meshes: [+ {+ primitives: [+ {+ attributes: { POSITION: 0, TEXCOORD_0: 1, TEXCOORD_1: 2, TEXCOORD_2: 3, TEXCOORD_3: 4 },+ material: 0,+ },+ ],+ },+ ],+ materials: [+ {+ pbrMetallicRoughness: { baseColorTexture: { index: 0, texCoord: 2 } },+ normalTexture: {+ index: 0,+ extensions: {+ KHR_texture_transform: {+ offset: [0.25, 0.5],+ rotation: 0.75,+ scale: [2, 3],+ texCoord: 1,+ },+ },+ },+ },+ ],+ textures: [{ source: 0, sampler: 0 }],+ samplers: [{ wrapS: 33071, wrapT: 33648 }],+ images: [{ bufferView: 5, mimeType: 'image/png' }],+ accessors: [+ {+ bufferView: 0,+ componentType: 5126,+ count: 3,+ type: 'VEC3',+ min: [0, 0, 0],+ max: [1, 1, 0],+ },+ ...[1, 2, 3, 4].map((bufferView) => ({+ bufferView,+ componentType: 5126,+ count: 3,+ type: 'VEC2',+ })),+ ],+ bufferViews,+ buffers: [{ byteLength: bin.length }],+ };+ const jsonBytes = pad4(new TextEncoder().encode(JSON.stringify(json)), 0x20);+ const out = new Uint8Array(12 + 8 + jsonBytes.length + 8 + bin.length);+ const view = new DataView(out.buffer);+ view.setUint32(0, 0x46546c67, true);+ view.setUint32(4, 2, true);+ view.setUint32(8, out.length, true);+ view.setUint32(12, jsonBytes.length, true);+ view.setUint32(16, 0x4e4f534a, true);+ out.set(jsonBytes, 20);+ view.setUint32(20 + jsonBytes.length, bin.length, true);+ view.setUint32(24 + jsonBytes.length, 0x004e4942, true);+ out.set(bin, 28 + jsonBytes.length);+ return out.buffer;+}++async function loadMaterial() {+ const gltf = await new GLTFLoader().parseAsync(glb(), '');+ let material = null;+ gltf.scene.traverse((o) => {+ if (o.isMesh) material = o.material;+ });+ return { scene: gltf.scene, material };+}++/** Everything that decides where a texel is sampled from. */+function sampling(texture) {+ texture.updateMatrix();+ return {+ channel: texture.channel,+ offset: texture.offset.toArray(),+ repeat: texture.repeat.toArray(),+ rotation: texture.rotation,+ center: texture.center.toArray(),+ matrixAutoUpdate: texture.matrixAutoUpdate,+ matrix: texture.matrix.toArray(),+ flipY: texture.flipY,+ wrapS: texture.wrapS,+ wrapT: texture.wrapT,+ colorSpace: texture.colorSpace,+ };+}++describe('toDataTextures', () => {+ it('keeps the UV set and KHR_texture_transform GLTFLoader gave each map', async () => {+ const { scene, material } = await loadMaterial();+ const before = { map: sampling(material.map), normalMap: sampling(material.normalMap) };+ // The fixture really exercises both: a non-zero UV set and a non-identity transform.+ assert.equal(before.map.channel, 2);+ assert.equal(before.normalMap.channel, 1);+ assert.deepEqual(before.normalMap.repeat, [2, 3]);++ toDataTextures(scene, THREE);++ assert.ok(material.map.isDataTexture);+ assert.ok(material.normalMap.isDataTexture);+ assert.deepEqual(sampling(material.map), before.map);+ assert.deepEqual(sampling(material.normalMap), before.normalMap);+ });++ it('keeps a hand-set centre and a manual matrix in every converted slot', () => {+ const material = new THREE.MeshStandardMaterial();+ const expected = {};+ DATA_TEXTURE_SLOTS.forEach((slot, i) => {+ const texture = new THREE.Texture({ data: new Uint8Array(4), width: 1, height: 1 });+ texture.channel = i % 4;+ texture.center.set(0.5, 0.25);+ texture.rotation = 0.1 * (i + 1);+ texture.offset.set(0.1, 0.2);+ texture.repeat.set(1.5, 0.5);+ if (i === 0) {+ texture.matrixAutoUpdate = false;+ texture.matrix.set(1, 0, 0.3, 0, 1, 0.4, 0, 0, 1);+ }+ material[slot] = texture;+ expected[slot] = sampling(texture);+ });+ const root = new THREE.Mesh(new THREE.BufferGeometry(), material);++ toDataTextures(root, THREE);++ for (const slot of DATA_TEXTURE_SLOTS) {+ assert.ok(material[slot].isDataTexture, slot);+ assert.deepEqual(sampling(material[slot]), expected[slot], slot);+ }+ });+});diff --git a/render-service/test/projection-cache-key.test.mjs b/render-service/test/projection-cache-key.test.mjsnew file mode 100644index 00000000..605f1a94--- /dev/null+++ b/render-service/test/projection-cache-key.test.mjs@@ -0,0 +1,63 @@+import assert from 'node:assert/strict';+import { describe, it } from 'node:test';+import * as THREE from 'three';++import { keyMaterialsByProjection } from '../src/projection-cache-key.mjs';++function scene() {+ const root = new THREE.Group();+ const shared = new THREE.MeshStandardMaterial();+ root.add(new THREE.Mesh(new THREE.BufferGeometry(), shared));+ root.add(new THREE.Mesh(new THREE.BufferGeometry(), [shared, new THREE.MeshBasicMaterial()]));+ return { root, materials: [shared, root.children[1].material[1]] };+}++const ortho = new THREE.OrthographicCamera();+const persp = new THREE.PerspectiveCamera();++describe('keyMaterialsByProjection', () => {+ // three's material cache key ignores the camera, and the node material compiles+ // positionViewDirection from the first camera that draws it: a constant for an orthographic+ // camera, per-fragment for a perspective one. A program cache key that names the projection+ // makes a perspective draw after an orthographic one compile its own program.+ it('gives each projection its own program cache key', () => {+ const { root, materials } = scene();+ const base = materials.map((m) => m.customProgramCacheKey());+ keyMaterialsByProjection(root, ortho);+ const orthoKeys = materials.map((m) => m.customProgramCacheKey());+ keyMaterialsByProjection(root, persp);+ const perspKeys = materials.map((m) => m.customProgramCacheKey());+ materials.forEach((_, i) => {+ assert.notEqual(orthoKeys[i], perspKeys[i]);+ assert.ok(orthoKeys[i].startsWith(base[i]));+ assert.ok(perspKeys[i].startsWith(base[i]));+ });+ });++ it('marks a material for update only when the projection changes', () => {+ const { root, materials } = scene();+ keyMaterialsByProjection(root, ortho);+ const afterFirst = materials.map((m) => m.version);+ keyMaterialsByProjection(root, new THREE.OrthographicCamera());+ assert.deepEqual(+ materials.map((m) => m.version),+ afterFirst,+ );+ keyMaterialsByProjection(root, persp);+ materials.forEach((m, i) => {+ assert.ok(m.version > afterFirst[i]);+ });+ });++ it('keys a perspective draw the same whether or not an orthographic one came first', () => {+ const a = scene();+ const b = scene();+ keyMaterialsByProjection(a.root, persp);+ keyMaterialsByProjection(b.root, ortho);+ keyMaterialsByProjection(b.root, persp);+ assert.deepEqual(+ a.materials.map((m) => m.customProgramCacheKey()),+ b.materials.map((m) => m.customProgramCacheKey()),+ );+ });+});