@forgeax/engine-image 0.1.3 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +5 -7
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/decode-image-from-file.d.ts.map +1 -1
  4. package/dist/decode-image-from-file.mjs +5 -135
  5. package/dist/decode-image-from-file.mjs.map +1 -1
  6. package/dist/hdr-decoder.mjs +1 -1
  7. package/dist/hdr-decoder.mjs.map +1 -1
  8. package/dist/image-importer.d.ts +5 -2
  9. package/dist/image-importer.d.ts.map +1 -1
  10. package/dist/image-importer.mjs +80 -102
  11. package/dist/image-importer.mjs.map +1 -1
  12. package/dist/index.d.ts +1 -3
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.mjs +2 -36
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/ktx2-encode.d.ts +2 -5
  17. package/dist/ktx2-encode.d.ts.map +1 -1
  18. package/dist/ktx2-encode.mjs +15 -17
  19. package/dist/ktx2-encode.mjs.map +1 -1
  20. package/dist/parse-image.d.ts +0 -1
  21. package/dist/parse-image.d.ts.map +1 -1
  22. package/dist/parse-image.mjs +3 -80
  23. package/dist/parse-image.mjs.map +1 -1
  24. package/package.json +6 -6
  25. package/src/__tests__/image.unit.test.ts +28 -162
  26. package/src/decode-image-from-file.ts +3 -68
  27. package/src/errors.ts +1 -1
  28. package/src/image-decoder-browser.ts +1 -1
  29. package/src/image-importer.ts +83 -5
  30. package/src/index.ts +3 -5
  31. package/src/ktx2-encode.ts +17 -21
  32. package/src/parse-image.ts +3 -103
  33. package/dist/__tests__/ktx2-encode-mode-owner.test-d.d.ts +0 -2
  34. package/dist/__tests__/ktx2-encode-mode-owner.test-d.d.ts.map +0 -1
  35. package/dist/__tests__/runtime-decode.unit.test.d.ts +0 -2
  36. package/dist/__tests__/runtime-decode.unit.test.d.ts.map +0 -1
  37. package/dist/__tests__/tga.unit.test.d.ts +0 -2
  38. package/dist/__tests__/tga.unit.test.d.ts.map +0 -1
  39. package/dist/runtime/__tests__/asset-decoders.unit.test.d.ts +0 -2
  40. package/dist/runtime/__tests__/asset-decoders.unit.test.d.ts.map +0 -1
  41. package/dist/runtime/decode-image-bytes.d.ts +0 -7
  42. package/dist/runtime/decode-image-bytes.d.ts.map +0 -1
  43. package/dist/runtime/image-error.d.ts +0 -3
  44. package/dist/runtime/image-error.d.ts.map +0 -1
  45. package/src/__tests__/ktx2-encode-mode-owner.test-d.ts +0 -70
  46. package/src/__tests__/runtime-decode.unit.test.ts +0 -22
  47. package/src/__tests__/tga.unit.test.ts +0 -59
  48. package/src/runtime/__tests__/asset-decoders.unit.test.ts +0 -66
  49. package/src/runtime/decode-image-bytes.ts +0 -41
  50. package/src/runtime/image-error.ts +0 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/hdr-decoder.ts","../src/image-decoder-browser.ts","../src/image-decoder-node.ts","../src/source-key.ts","../src/sub-asset-key.ts","../src/reimport-reuse-meta.ts","../src/runtime/asset-decoders.ts","../src/runtime/image-error.ts","../src/runtime/decode-image-bytes.ts","../src/to-asset-pack.ts"],"names":["err","ok"],"mappings":";;;;;;AAOA,IAAM,oBAAA,GAAiE;AAAA,EACrE,qBAAA,EAAuB,4CAAA;AAAA,EACvB,0BAAA,EACE,8GAAA;AAAA,EACF,+BAAA,EACE,mFAAA;AAAA,EACF,oBAAA,EACE,6EAAA;AAAA,EACF,yBAAA,EAA2B,mEAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ3B,mBAAA,EAAqB,oBAAA;AAAA,EACrB,qBAAA,EACE,mFAAA;AAAA,EACF,uBAAA,EAAyB;AAC3B;AAGO,IAAM,cAAA,GAAN,cACG,KAAA,CAEV;AAAA,EACW,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,MAAA,EAAgC;AAC1C,IAAA,MAA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.mjs","sourcesContent":["import type { ImageErrorCode, ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Per-code .expected string literals SSOT.\n// Mirrors ASSET_ERROR_HINTS / IMAGE_ERROR_HINTS shape (charter P5 consistent\n// abstraction). AI users surface .expected when a structured error needs to\n// describe the precondition that was violated.\nconst IMAGE_ERROR_EXPECTED: Readonly<Record<ImageErrorCode, string>> = {\n 'image-decode-failed': 'PNG / JPG byte stream decodes successfully',\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg', 'image/x-tga']; uploadTexture format <-> colorSpace family agrees\",\n 'image-dimension-out-of-bounds':\n 'width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)',\n 'image-meta-missing':\n \"<source>.meta.json sidecar (importer: 'image') exists in the same directory\",\n 'image-hdr-decode-failed': 'Radiance RGBE header is valid and pixel data decodes successfully',\n // feat-20260521-sprite-atlas-animation M1 T-03 — vite-plugin-image atlas\n // hook .expected literals (plan-strategy section 2 D-2 + AC-10 a/b/c).\n // ImageErrorImpl construction path is unchanged: the new atlas-* errors\n // flow through `new ImageErrorImpl({ code: 'atlas-...', ...detail })` and\n // pick the .expected string up from this Record at construction time\n // (charter P3 explicit failure SSOT — AI users surface .expected next to\n // .hint after switch (err.code) without parsing the message).\n 'atlas-empty-input': 'images.length >= 1',\n 'atlas-size-exceeded':\n 'image width x height <= maxAtlasSize^2 and each image fits in the atlas footprint',\n 'atlas-region-mismatch': 'sum(regions[i].w x regions[i].h) <= atlasWidth x atlasHeight',\n};\n\n/** Runtime implementation of the correlated `ImageErrorFor<C>` envelope. */\nexport class ImageErrorImpl<C extends ImageErrorCode = ImageErrorCode>\n extends Error\n implements ImageErrorFor<C>\n{\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ImageErrorDetailFor<C>;\n\n constructor(detail: ImageErrorDetailFor<C>) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/** Construct a structured image error while preserving its code/detail pair. */\nexport function imageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return new ImageErrorImpl<C>(detail);\n}\n\nexport { IMAGE_ERROR_EXPECTED };\n","import type { ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Decoded HDR image POD.\n *\n * `data` is an interleaved RGBA Float32Array (4 floats per pixel, row-major).\n * Color space is always linear (RGBE is radiance).\n */\nexport interface HdrDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Float32Array;\n}\n\n// ASCII code points\nconst LF = 0x0a;\n\n/**\n * Decode a Radiance RGBE (.hdr) byte stream into linear RGBA float pixels.\n *\n * Steps per research F-6:\n * 1. Parse ASCII header: magic (#?RADIANCE), FORMAT=32-bit_rle_rgbe,\n * resolution line (-Y height +X width).\n * 2. Decode per-scanline new-RLE pixel data: 4 independent channel runs.\n * 3. Convert RGBE to float: if E==0 -> 0; else f=2^(E-136), R=(Rm+0.5)*f.\n * 4. Output as interleaved RGBA Float32Array (alpha=1.0).\n *\n * Old-RLE scanlines (prefix not matching 0x02,0x02,hi,lo with correct width)\n * return image-hdr-decode-failed.\n */\nexport function decodeHdr(bytes: Uint8Array): Result<HdrDecoded, ImageError> {\n let pos = 0;\n\n // Step 1a: magic -- must start with \"#?RADIANCE\" or \"#?RGBE\"\n if (bytes.length < 11) {\n return err(hdrDecodeError('file too short for Radiance HDR header'));\n }\n const magic = String.fromCharCode(...bytes.subarray(0, 11));\n if (magic !== '#?RADIANCE\\n' && magic !== '#?RGBE\\n') {\n return err(\n hdrDecodeError('missing or invalid Radiance HDR magic; expected #?RADIANCE or #?RGBE'),\n );\n }\n pos = 11;\n\n // Step 1b: key=value lines until empty line\n let formatFound = false;\n while (pos < bytes.length) {\n const lineEnd = findByte(bytes, LF, pos);\n if (lineEnd === -1) return err(hdrDecodeError('header truncated before empty line'));\n const line = asciiSubstring(bytes, pos, lineEnd);\n pos = lineEnd + 1;\n if (line === '') break;\n if (line.startsWith('FORMAT=')) {\n const val = line.slice(7);\n if (val === '32-bit_rle_rgbe') {\n formatFound = true;\n }\n }\n }\n if (!formatFound) {\n return err(hdrDecodeError('missing or unsupported FORMAT; expected FORMAT=32-bit_rle_rgbe'));\n }\n\n // Step 1c: resolution line (-Y height +X width)\n if (pos >= bytes.length) return err(hdrDecodeError('missing resolution line'));\n const resLineEnd = findByte(bytes, LF, pos);\n if (resLineEnd === -1) return err(hdrDecodeError('resolution line truncated'));\n const resLine = asciiSubstring(bytes, pos, resLineEnd);\n pos = resLineEnd + 1;\n const resMatch = /^-Y\\s+(\\d+)\\s+\\+X\\s+(\\d+)\\s*$/.exec(resLine);\n if (resMatch === null) {\n return err(\n hdrDecodeError(`unexpected resolution line format: \"${resLine}\"; expected \"-Y H +X W\"`),\n );\n }\n const height = Number(resMatch[1]);\n const width = Number(resMatch[2]);\n if (height === undefined || width === undefined || height <= 0 || width <= 0) {\n return err(hdrDecodeError(`invalid dimensions: ${width}x${height}`));\n }\n\n // Step 2: decode per-scanline new-RLE pixel data\n const pixelCount = width * height;\n const rgbe = new Uint8Array(pixelCount * 4);\n const scanlineBytes = width * 4;\n\n for (let y = 0; y < height; y++) {\n if (pos + 4 > bytes.length) {\n return err(hdrDecodeError(`truncated at scanline ${y}: expected 4-byte prefix`));\n }\n const p0 = bytes[pos];\n const p1 = bytes[pos + 1];\n const pHi = bytes[pos + 2];\n const pLo = bytes[pos + 3];\n if (p0 === undefined || p1 === undefined || pHi === undefined || pLo === undefined) {\n return err(hdrDecodeError(`truncated at scanline ${y}`));\n }\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const prefixWidth = (pHi! << 8) | pLo!;\n\n if (p0 === 0x02 && p1 === 0x02 && prefixWidth === width && width >= 8 && width <= 32767) {\n // New-RLE: 4 channels independently RLE-encoded, then interleaved\n const decoded = decodeNewRleScanline(bytes, pos + 4, width);\n if (decoded === null) {\n return err(hdrDecodeError(`RLE decode failed at scanline ${y}`));\n }\n // Copy into rgbe interleaved buffer\n const base = y * scanlineBytes;\n const channels = [decoded[0], decoded[1], decoded[2], decoded[3]];\n for (let x = 0; x < width; x++) {\n for (let ch = 0; ch < 4; ch++) {\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n rgbe[base + x * 4 + ch] = channels[ch]![x]!;\n }\n }\n // Advance pos past the 4-byte prefix + the total RLE bytes consumed\n pos += 4 + decoded.totalBytes;\n } else {\n // Old-RLE: not supported\n return err(\n hdrDecodeError(\n 'old-RLE format is not supported; only new-RLE (32-bit_rle_rgbe) is accepted',\n ),\n );\n }\n }\n\n // Step 3: RGBE to float\n const out = new Float32Array(pixelCount * 4);\n for (let i = 0; i < pixelCount; i++) {\n const base = i * 4;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const r = rgbe[base]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const g = rgbe[base + 1]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const b = rgbe[base + 2]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const e = rgbe[base + 3]!;\n out[base + 3] = 1.0;\n\n if (e === 0) {\n out[base] = 0;\n out[base + 1] = 0;\n out[base + 2] = 0;\n } else {\n // f = 2^(E - 136) = ldexp(1.0, E - 128 - 8)\n // Equivalent: ldexp(1.0 / 256.0, E - 128)\n // But simpler: const f = (1.0 / 256.0) * Math.pow(2, e - 128);\n // Using ldexp: Math.pow(2, e - 136)\n const f = 2 ** (e - 136);\n out[base] = (r + 0.5) * f;\n out[base + 1] = (g + 0.5) * f;\n out[base + 2] = (b + 0.5) * f;\n }\n }\n\n return ok({ width, height, data: out });\n}\n\ninterface DecodedScanline {\n /** 4 channels, each width bytes */\n readonly 0: Uint8Array;\n readonly 1: Uint8Array;\n readonly 2: Uint8Array;\n readonly 3: Uint8Array;\n readonly totalBytes: number;\n}\n\n/**\n * Decode one scanline of new-RLE data into 4 channel arrays.\n * Returns null on failure (data underrun).\n */\nfunction decodeNewRleScanline(\n bytes: Uint8Array,\n start: number,\n width: number,\n): DecodedScanline | null {\n const channels: Uint8Array[] = [];\n let cursor = start;\n\n for (let ch = 0; ch < 4; ch++) {\n const data = new Uint8Array(width);\n let x = 0;\n while (x < width) {\n if (cursor >= bytes.length) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const code = bytes[cursor]!;\n cursor++;\n if (code > 128) {\n // RLE run: next byte repeated (code - 128) times\n const count = code - 128;\n if (cursor >= bytes.length || x + count > width) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const val = bytes[cursor]!;\n cursor++;\n data.fill(val, x, x + count);\n x += count;\n } else {\n // Literal run: next `code` bytes copied verbatim\n if (code === 0) continue;\n if (cursor + code > bytes.length || x + code > width) return null;\n for (let k = 0; k < code; k++) {\n // biome-ignore lint/style/noNonNullAssertion: checked above\n data[x + k] = bytes[cursor + k]!;\n }\n cursor += code;\n x += code;\n }\n }\n channels.push(data);\n }\n\n const ch0 = channels[0];\n const ch1 = channels[1];\n const ch2 = channels[2];\n const ch3 = channels[3];\n if (ch0 === undefined || ch1 === undefined || ch2 === undefined || ch3 === undefined) {\n return null; // channels should always have 4 entries\n }\n return {\n 0: ch0,\n 1: ch1,\n 2: ch2,\n 3: ch3,\n totalBytes: cursor - start,\n };\n}\n\nfunction findByte(bytes: Uint8Array, target: number, start: number): number {\n for (let i = start; i < bytes.length; i++) {\n if (bytes[i] === target) return i;\n }\n return -1;\n}\n\nfunction asciiSubstring(bytes: Uint8Array, start: number, end: number): string {\n let s = '';\n for (let i = start; i < end; i++) {\n // biome-ignore lint/style/noNonNullAssertion: in bounds\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\n}\n\nfunction hdrDecodeError(reason: string): ImageError {\n return imageError({\n code: 'image-hdr-decode-failed',\n reason,\n });\n}\n","import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Browser image decoder (plan-strategy section 3.3 + section 2.4 D Open Q-3).\n *\n * Uses `createImageBitmap(blob, { colorSpaceConversion: 'none' })` to keep\n * the bytes in their authored color space (sRGB / linear); the runtime\n * uploadTexture entry asserts `format <-> colorSpace` consistency at GPU\n * upload time (plan-strategy section 2.5 D Open Q-4 (c)).\n *\n * Pixel readback uses an offscreen 2D canvas + `getImageData`; AI users\n * never call this directly -- it is the browser-mode counterpart of\n * `parseImage` (Node-mode upng / jpeg-js path) consumed by future M2b\n * vite-plugin overlay paths and direct browser-mode loaders. The Node\n * decoder remains the SSOT for parseImage; this file is the browser\n * fallback when running inside vitest browser mode or the Vite dev server.\n */\nexport async function decodeImageInBrowser(\n bytes: Uint8Array,\n mime: 'image/png' | 'image/jpeg',\n opts: { colorSpace?: ImageColorSpace; mipmap?: boolean } = {},\n): Promise<Result<DecodedImage, ImageError>> {\n if (typeof createImageBitmap !== 'function') {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'createImageBitmap is not available in this environment',\n }),\n );\n }\n\n let bitmap: ImageBitmap;\n try {\n const blob = new Blob([bytes as BlobPart], { type: mime });\n bitmap = await createImageBitmap(blob, {\n colorSpaceConversion: 'none',\n premultiplyAlpha: 'none',\n });\n } catch (e) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: e instanceof Error ? e.message : String(e),\n }),\n );\n }\n\n // Read pixels back via OffscreenCanvas (browser context) -- 2D context is\n // ubiquitous and avoids the WebGPU readback round-trip during disk-side\n // decode (charter P5 producer / consumer split: GPU upload happens inside\n // the Render DeviceScope, not in this byte decoder).\n const canvas =\n typeof OffscreenCanvas !== 'undefined'\n ? new OffscreenCanvas(bitmap.width, bitmap.height)\n : (() => {\n const c = document.createElement('canvas');\n c.width = bitmap.width;\n c.height = bitmap.height;\n return c;\n })();\n const ctx = canvas.getContext('2d') as\n | OffscreenCanvasRenderingContext2D\n | CanvasRenderingContext2D\n | null;\n if (ctx === null) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'failed to acquire 2d canvas context for pixel readback',\n }),\n );\n }\n ctx.drawImage(bitmap, 0, 0);\n const data = ctx.getImageData(0, 0, bitmap.width, bitmap.height);\n bitmap.close();\n\n return ok({\n bytes: new Uint8Array(data.data.buffer.slice(0)),\n width: data.width,\n height: data.height,\n mime,\n colorSpace: opts.colorSpace ?? 'srgb',\n mipmap: opts.mipmap ?? true,\n });\n}\n","// Node-only image decoder shell for @forgeax/engine-image.\n//\n// Lazy-loads `upng-js` (PNG) and `jpeg-js` (JPEG) via dynamic imports so the\n// browser bundle tree-shakes both decoders out of the ESM output (the\n// browser path uses createImageBitmap instead). Migrated from the original\n// packages/runtime/src/ home in feat-20260515-learn-render-getting-started\n// M2 T-M2-02 (Open Q-3 option a; plan-strategy section 2.4) -- runtime now\n// only consumes DecodedImage POD and never imports the decoders.\n//\n// The implementation surface is filled out by T-M2-05; this file is staged\n// here in T-M2-02 so the migration touches a single owner directory and the\n// runtime package never ships a half-migrated state.\n\n/**\n * Local widening of the upng-js dynamic-import surface (the package ships\n * without a usable @types entry; the d.ts in image-decoders.d.ts only adds\n * the module declaration). Lists the two functions consumed by the Node\n * decoder path; widening here keeps the import site free of `as any` casts\n * (charter P3 explicit failure -- structural typing > escape hatches).\n */\nexport interface UpngModule {\n decode: (bytes: Uint8Array | ArrayBuffer) => {\n width: number;\n height: number;\n depth: number;\n ctype: number;\n data: Uint8Array;\n frames?: unknown[];\n };\n toRGBA8: (img: { width: number; height: number; data: Uint8Array }) => ArrayBuffer[];\n}\n\n/**\n * Local widening of the jpeg-js dynamic-import surface. Mirrors the subset\n * used by the Node decoder; jpeg-js has @types/jpeg-js but we keep a local\n * shape so the d.ts ambient declaration stays the SSOT for runtime resolution\n * (charter P5 producer / consumer split).\n */\nexport interface JpegModule {\n decode: (\n bytes: Uint8Array | ArrayBuffer,\n opts?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => {\n width: number;\n height: number;\n data: Uint8Array;\n };\n}\n\n/**\n * Lazy-load the upng-js Node decoder module. Browser bundlers tree-shake\n * this dynamic import out when only the createImageBitmap path is reached\n * at runtime; tsup external keeps the package name from being inlined.\n */\nexport async function loadUpng(): Promise<UpngModule> {\n const mod = (await import('upng-js')) as { default?: UpngModule } & UpngModule;\n return (mod.default ?? mod) as UpngModule;\n}\n\n/**\n * Lazy-load the jpeg-js Node decoder module. Same tree-shake guarantee as\n * loadUpng -- browser bundles never reach this path.\n */\nexport async function loadJpeg(): Promise<JpegModule> {\n const mod = (await import('jpeg-js')) as { default?: JpegModule } & JpegModule;\n return (mod.default ?? mod) as JpegModule;\n}\n","/**\n * Derive the semantic identity for an image producer output.\n *\n * The role is the producer-owned identity. Source path and sourceIndex are\n * locators only and must not be folded into this key.\n */\nexport interface ImageSourceKeyLocator {\n readonly sourcePath?: string;\n readonly sourceIndex?: number;\n}\n\nexport type ImageSourceKeyResult =\n | { readonly ok: true; readonly keys: readonly string[] }\n | {\n readonly ok: false;\n readonly code: 'missing-source-key' | 'duplicate-source-key';\n readonly roles: readonly string[];\n };\n\nexport function deriveImageSourceKey(\n role: string,\n _locator?: ImageSourceKeyLocator,\n): string | undefined {\n const normalizedRole = role.trim();\n if (normalizedRole.length === 0) return undefined;\n return `image:${normalizedRole}`;\n}\n\nexport function deriveImageSourceKeys(roles: readonly string[]): ImageSourceKeyResult {\n const keys = roles.map((role) => deriveImageSourceKey(role));\n const missing = roles.filter((_role, index) => keys[index] === undefined);\n if (missing.length > 0) return { ok: false, code: 'missing-source-key', roles: missing };\n\n const seen = new Set<string>();\n for (const key of keys) {\n if (key === undefined) continue;\n if (seen.has(key)) return { ok: false, code: 'duplicate-source-key', roles };\n seen.add(key);\n }\n return { ok: true, keys: keys as string[] };\n}\n","/**\n * Sub-asset-key shape mirroring the in-flight gltf-loader feat (plan-strategy\n * section 2.2 D-4 same-shape). Each sub-asset emitted into a `*.meta.json`\n * sidecar (uniformly `<source>.meta.json` across image / gltf arms,\n * dispatched on top-level `importer` field per feat-20260521) carries a\n * `{kind, name?, indexFallback}` triple so the importer can deterministically\n * match an existing sub-asset across reimports (charter P5 producer/consumer\n * split + AC-14 cross-feat alignment).\n *\n * The image disk schema is currently single-sub-asset; this file collapses\n * to `kind='texture'` + `indexFallback='textures/0'` so the same matching\n * algorithm is reusable when the future cubemap / array-layer feat lands\n * (plan-strategy R5 free-form schema).\n */\n\nexport interface SubAssetKey {\n /** Discriminator literal -- 'texture' for engine-image; 'mesh' / 'material' / 'scene' / 'image' for gltf-loader. */\n readonly kind: string;\n /** Optional human-readable name field; absent when the source has no symbolic identifier. */\n readonly name?: string;\n /** Path-style fallback identifier (e.g. 'images/0' / 'meshes/0'); always non-empty. */\n readonly indexFallback: string;\n}\n\nexport interface SubAssetKeyInput {\n readonly kind: string;\n readonly sourceIndex: number;\n readonly name?: string;\n}\n\n/**\n * Construct a sub-asset key from importer input. The `indexFallback` is\n * synthesised from the kind literal + sourceIndex so two importers\n * (image / gltf-loader) emit identical fallback strings for the same\n * `(kind, sourceIndex)` pair (AC-14).\n */\nexport function subAssetKey(input: SubAssetKeyInput): SubAssetKey {\n const indexFallback = `${input.kind}s/${input.sourceIndex}`;\n if (input.name !== undefined) {\n return { kind: input.kind, name: input.name, indexFallback };\n }\n return { kind: input.kind, indexFallback };\n}\n\n/**\n * Two-phase equality predicate used by reimportReuseMeta for GUID\n * preservation across reimports:\n *\n * Phase 1 -- (kind + name + idx) full match: identical in all three fields\n * Phase 2 -- (kind + idx) match: same kind + indexFallback, name absent or\n * equal (collapses when both sides omit name)\n * Phase 3 -- otherwise: false (importer mints fresh UUIDv7)\n *\n * The two phases are folded into a single boolean predicate here; the\n * reimportReuseMeta caller iterates the existing subAssets list and picks\n * the first hit (deterministic order; matches AC-16 byte-identical\n * reimport).\n */\nexport function subAssetKeyEqual(a: SubAssetKey, b: SubAssetKey): boolean {\n if (a.kind !== b.kind) return false;\n if (a.indexFallback !== b.indexFallback) return false;\n // name comparison: undefined === undefined is fine; if one side has a name\n // and the other does not, the keys are NOT equal (charter P4 explicit\n // failure -- name carries a meaningful identifier when present)\n if (a.name !== b.name) return false;\n return true;\n}\n","import { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type { DecodedImage, ImageColorSpace } from '@forgeax/engine-types';\n\nimport { deriveImageSourceKey } from './source-key.js';\nimport type { SubAssetKey } from './sub-asset-key.js';\nimport { subAssetKey, subAssetKeyEqual } from './sub-asset-key.js';\n\n/**\n * Existing `*.meta.json` (importer: 'image') sub-asset record (free-form sub-shape; the\n * meta.schema.json $defs/subAsset locks `guid` + `sourceIndex` + `kind` only).\n * Image importer treats the open shape as a key-bearing tuple; the gltf-loader\n * feat works on the same shape.\n */\nexport interface ExistingSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n readonly sourceKey?: string;\n}\n\n/**\n * Existing `*.meta.json` (importer: 'image') package record. Mirrors the\n * meta.schema.json $defs/ExternalAssetPackage shape (research F-9). Only\n * the fields consumed by the reimport reuse algorithm are typed here;\n * importSettings stays a free-form open shape.\n */\nexport interface ExistingExternalAssetPackage {\n readonly schemaVersion: string;\n readonly kind: 'external-asset-package';\n readonly importer: 'image';\n readonly source: string;\n readonly importSettings: Readonly<Record<string, unknown>>;\n readonly subAssets: readonly ExistingSubAsset[];\n}\n\n/**\n * Sub-asset record emitted into the regenerated `*.meta.json` (importer: 'image')\n * `subAssets[]` slot. Shape matches `ExistingSubAsset` so two consecutive\n * reimports of byte-identical bytes produce byte-identical JSON\n * (AC-16 byte-stable reimport guarantee).\n */\nexport interface EmittedSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n readonly sourceKey?: string;\n}\n\n/**\n * Two-phase reimport reuse algorithm (plan-strategy section 2.2 D-4\n * mirroring the in-flight gltf-loader algorithm).\n *\n * For each fresh sub-asset key the importer would emit, this function:\n * 1. Searches the `existing.subAssets[]` for a `subAssetKeyEqual` hit.\n * 2. On hit -- reuses the existing GUID byte-for-byte.\n * 3. On miss -- mints a fresh UUIDv7 via `AssetGuid.random()`.\n *\n * Image disk schema currently emits a single `kind='texture'` sub-asset per\n * source (cubemap face / array layer reserved for future feat); the\n * algorithm scales to multi-sub-asset sources without modification (charter\n * P5 consistent abstraction).\n *\n * Returns the regenerated `subAssets[]` array. The caller (toAssetPack /\n * runAssetImport) splices it into the `*.meta.json` (importer: 'image') envelope.\n */\nexport function reimportReuseMeta(\n decoded: DecodedImage,\n existing: ExistingExternalAssetPackage | undefined,\n): readonly EmittedSubAsset[] {\n // Image disk schema is single-sub-asset; the future multi-asset path\n // iterates a producer-side list of sub-asset keys instead of a single one.\n const freshKeys: readonly SubAssetKey[] = [subAssetKey({ kind: 'texture', sourceIndex: 0 })];\n\n const out: EmittedSubAsset[] = [];\n const sourceKey = deriveImageSourceKey('texture');\n\n for (let i = 0; i < freshKeys.length; i++) {\n const fresh = freshKeys[i];\n if (fresh === undefined) continue;\n\n let reuseGuid: string | undefined;\n if (existing !== undefined) {\n for (const candidate of existing.subAssets) {\n if (sourceKey !== undefined && candidate.sourceKey === sourceKey) {\n reuseGuid = candidate.guid;\n break;\n }\n const candidateKey = subAssetKey({\n kind: candidate.kind,\n sourceIndex: candidate.sourceIndex,\n ...(candidate.name !== undefined ? { name: candidate.name } : {}),\n });\n if (subAssetKeyEqual(fresh, candidateKey)) {\n reuseGuid = candidate.guid;\n break;\n }\n }\n }\n\n const guid = reuseGuid ?? AssetGuid.format(AssetGuid.random());\n const emit: EmittedSubAsset =\n fresh.name !== undefined\n ? {\n guid,\n sourceIndex: i,\n kind: fresh.kind,\n name: fresh.name,\n ...(sourceKey === undefined ? {} : { sourceKey }),\n }\n : {\n guid,\n sourceIndex: i,\n kind: fresh.kind,\n ...(sourceKey === undefined ? {} : { sourceKey }),\n };\n out.push(emit);\n }\n\n // Ensure decoded ref is consumed (decoded.bytes is the producer signal that\n // a sub-asset exists; without bytes there is nothing to emit). The\n // signature keeps `decoded` in the public surface so the future cubemap /\n // array-layer feat can derive its multi-sub-asset list from `decoded`\n // metadata without a breaking change (charter P5 consistent abstraction).\n void decoded;\n\n return out;\n}\n\n/**\n * HDR colorSpace validator for *.image.meta.json sidecar importSettings\n * (plan-strategy D-8 -- HDR files must use colorSpace=linear).\n *\n * Extension is matched case-insensitively against the HDR set\n * (`.hdr`, `.exr`). When the extension belongs to the HDR set:\n * - `colorSpace='linear'` -> ok, returns `'linear'`\n * - any other colorSpace -> structured rejection with expected/actual\n *\n * Non-HDR extensions pass through the colorSpace unchanged. Downstream\n * callers (decodeImageFromFile, parseImage) invoke this at the\n * sidecar-read entry to fail-fast when an .hdr meta carries srgb.\n */\nexport function validateColorSpaceForHdr(\n ext: string,\n colorSpace: ImageColorSpace,\n): { ok: true; value: ImageColorSpace } | { ok: false; expected: string; actual: string } {\n const lower = ext.toLowerCase();\n if (lower === '.hdr' || lower === '.exr') {\n if (colorSpace !== 'linear') {\n return {\n ok: false,\n expected: 'colorSpace=linear for HDR source files',\n actual: `colorSpace=${colorSpace}`,\n };\n }\n return { ok: true, value: 'linear' };\n }\n return { ok: true, value: colorSpace };\n}\n","import { parseKtx2, transcodeBasis, transcodeKtx2 } from '@forgeax/engine-codec';\nimport {\n type AssetDecoderContribution,\n type AssetDecoderInput,\n type AssetDecoderResult,\n type AssetKind,\n type AssetLoadError,\n type EquirectAsset,\n err,\n ok,\n type TextureAsset,\n} from '@forgeax/engine-types';\n\nfunction invalid(guid: string, expected: string, reason: string) {\n return err<AssetLoadError>({\n code: 'asset-package-invalid',\n expected,\n hint: 'recook the image asset and publish its complete device-neutral payload',\n detail: { guid, reason },\n });\n}\n\nfunction validDimensions(width: number, height: number): boolean {\n return Number.isSafeInteger(width) && width > 0 && Number.isSafeInteger(height) && height > 0;\n}\n\nfunction imageBytes(value: unknown): Uint8Array | Uint8ClampedArray | undefined {\n if (value instanceof Uint8Array || value instanceof Uint8ClampedArray) return value;\n if (!Array.isArray(value)) return undefined;\n if (!value.every((item) => Number.isInteger(item) && item >= 0 && item <= 255)) {\n return undefined;\n }\n return Uint8Array.from(value);\n}\n\nfunction compressedImageTarget(colorSpace: TextureAsset['colorSpace']): TextureAsset['format'] {\n return colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n}\n\nfunction validImageSurface(\n value: unknown,\n): value is Pick<TextureAsset, 'width' | 'height' | 'format' | 'data' | 'colorSpace'> {\n if (value === null || typeof value !== 'object') return false;\n const candidate = value as Partial<TextureAsset>;\n return (\n validDimensions(candidate.width ?? 0, candidate.height ?? 0) &&\n typeof candidate.format === 'string' &&\n imageBytes(candidate.data) !== undefined &&\n (candidate.colorSpace === 'srgb' || candidate.colorSpace === 'linear')\n );\n}\n\nasync function readImageSurface<P extends TextureAsset | EquirectAsset>(\n input: AssetDecoderInput<P>,\n kind: P['kind'],\n expected: string,\n): Promise<AssetDecoderResult<P>> {\n const { envelope, artifacts } = input;\n const payload = envelope.payload as unknown;\n if (\n payload === null ||\n typeof payload !== 'object' ||\n (payload as { kind?: unknown }).kind !== kind\n ) {\n return invalid(envelope.guid, expected, `${kind} owner validation failed`);\n }\n\n const body = envelope.artifacts.body ?? envelope.artifacts.atlas;\n let data = imageBytes((payload as { data?: unknown }).data);\n if (body !== undefined) {\n const read = await artifacts.read(body);\n if (!read.ok) return err(read.error);\n const bytes = read.value;\n data = bytes;\n\n // Pack v2 keeps the authored TextureAsset format device-neutral while the\n // artifact may carry a Basis KTX2/raw-Basis delivery codec. The new\n // AssetDecoder seam has no device-capability input, so its safe baseline is\n // an uncompressed RGBA target; the renderer can upload that POD on every\n // backend without interpreting container bytes as pixels.\n if (body.assetCodec?.name === 'basis' && body.assetCodec.container !== undefined) {\n const candidate = payload as Partial<TextureAsset>;\n if (candidate.colorSpace !== 'srgb' && candidate.colorSpace !== 'linear') {\n return invalid(envelope.guid, expected, `${kind} color space is invalid`);\n }\n const target = compressedImageTarget(candidate.colorSpace);\n const transcoded =\n body.assetCodec.container === 'ktx2'\n ? await parseKtx2(bytes).then((parsed) =>\n parsed.ok ? transcodeKtx2(parsed.value, target) : parsed,\n )\n : await transcodeBasis(bytes, target);\n if (!transcoded.ok) {\n return invalid(envelope.guid, expected, `codec:${transcoded.error.code}`);\n }\n const mip = transcoded.value.mips[0];\n if (mip === undefined) return invalid(envelope.guid, expected, 'codec:base-mip-missing');\n data = mip.data;\n return readDecodedSurface(envelope.guid, expected, {\n ...payload,\n width: mip.width,\n height: mip.height,\n format: target,\n data,\n });\n }\n }\n\n return readDecodedSurface(envelope.guid, expected, {\n ...payload,\n ...(data === undefined ? {} : { data }),\n });\n}\n\nfunction readDecodedSurface<P extends TextureAsset | EquirectAsset>(\n guid: string,\n expected: string,\n candidate: unknown,\n): ReturnType<typeof ok<P>> | ReturnType<typeof err<AssetLoadError>> {\n if (!validImageSurface(candidate)) {\n return invalid(guid, expected, 'image owner validation failed');\n }\n return ok(candidate as P);\n}\n\nexport const textureContribution: AssetDecoderContribution<TextureAsset, 'texture'> = {\n kind: { kind: 'texture' } as AssetKind<TextureAsset, 'texture'>,\n consumer: 'Image/Render DeviceScope',\n decoder: {\n async decode(input) {\n return readImageSurface(\n input,\n 'texture',\n 'a texture payload with dimensions, format, color space, and bytes',\n );\n },\n },\n};\n\nexport const equirectContribution: AssetDecoderContribution<EquirectAsset, 'equirect'> = {\n kind: { kind: 'equirect' } as AssetKind<EquirectAsset, 'equirect'>,\n consumer: 'Image/Render DeviceScope',\n decoder: {\n async decode(input) {\n return readImageSurface(\n input,\n 'equirect',\n 'an equirect payload with dimensions, format, color space, and bytes',\n );\n },\n },\n};\n","import type { ImageErrorCode, ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { imageError } from '../errors';\n\nexport function runtimeImageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return imageError(detail);\n}\n","import type { ImageError, Result, TextureAsset } from '@forgeax/engine-types';\nimport { err, ok } from '@forgeax/engine-types';\nimport { decodeImageInBrowser } from '../image-decoder-browser';\nimport { runtimeImageError } from './image-error';\n\nconst SUPPORTED_MIMES = ['image/png', 'image/jpeg'] as const;\ntype SupportedMime = (typeof SUPPORTED_MIMES)[number];\n\nfunction isSupportedMime(mime: string): mime is SupportedMime {\n return SUPPORTED_MIMES.some((supportedMime) => supportedMime === mime);\n}\n\nfunction mipLevels(width: number, height: number): number {\n return Math.floor(Math.log2(Math.max(width, height))) + 1;\n}\n\n/** Image-owned runtime boundary from encoded bytes to a TextureAsset POD. */\nexport async function decodeImageBytes(\n bytes: Uint8Array | ArrayBuffer,\n mime: string,\n opts: { readonly colorSpace?: 'srgb' | 'linear'; readonly mipmap?: boolean } = {},\n): Promise<Result<TextureAsset, ImageError>> {\n if (!isSupportedMime(mime)) {\n return err(runtimeImageError({ code: 'image-format-unsupported', actualMime: mime }));\n }\n const colorSpace = opts.colorSpace ?? 'srgb';\n const mipmap = opts.mipmap ?? true;\n const input = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n const decoded = await decodeImageInBrowser(input, mime as SupportedMime, { colorSpace, mipmap });\n if (!decoded.ok) return err(decoded.error);\n return ok({\n kind: 'texture',\n width: decoded.value.width,\n height: decoded.value.height,\n format: colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm',\n data: decoded.value.bytes,\n colorSpace,\n mipmap,\n mipLevelCount: mipmap ? mipLevels(decoded.value.width, decoded.value.height) : 1,\n });\n}\n","import type { AssetCompression, DecodedImage, ImageMeta } from '@forgeax/engine-types';\n\n/**\n * External-asset-package envelope shape mirroring the\n * `packages/pack/schema/meta.schema.json` $defs/ExternalAssetPackage.\n * Consumed by `forgeax-engine-remote-asset import` (CLI entry, M3b) +\n * the image importer in M2 build-time path. The internal-text-package\n * variant ($defs/InternalTextPackage) is owned by the gltf-loader feat.\n */\nexport interface ExternalAssetPackage {\n readonly schemaVersion: string;\n readonly kind: 'external-asset-package';\n readonly importer: 'image';\n readonly source: string;\n readonly importSettings: ImageImportSettings;\n readonly subAssets: readonly ExternalSubAsset[];\n}\n\n/**\n * Free-form image importer settings persisted into `*.meta.json` (importer: 'image')\n * `importSettings`. Matches `ImageMeta` POD field-for-field (charter P5\n * single SSOT) but the open Record shape allows future minor adds (cubemap\n * face / array layer / custom colorSpace) without breaking existing meta\n * files (plan-strategy R5).\n */\nexport interface ImageImportSettings extends Readonly<Record<string, unknown>> {\n readonly colorSpace: ImageMeta['colorSpace'];\n readonly mipmap: ImageMeta['mipmap'];\n readonly addressMode: ImageMeta['addressMode'];\n readonly filterMode: ImageMeta['filterMode'];\n readonly downscaleMaxDimension?: number;\n /**\n * Explicit per-asset compression override (AC-01: importSettings carries\n * compression intent). When omitted, the build-time compression strategy\n * table decides by artifact kind (mesh -> zstd, texture -> none). When set,\n * this value wins over the default table for this asset.\n */\n readonly compression?: AssetCompression;\n}\n\nexport interface ExternalSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n}\n\n/**\n * Pure function that translates a DecodedImage POD + ImageMeta POD into\n * an external-asset-package envelope ready to be JSON-stringified into a\n * `*.meta.json` sidecar with importer: 'image' (plan-strategy section 3.2 sequence A; AC-13\n * disk schema reuse).\n *\n * The single sub-asset emitted carries:\n * - `guid` -- copied verbatim from `meta.guid` (the producer guarantees\n * the GUID is freshly minted or reused via `reimportReuseMeta`)\n * - `sourceIndex: 0` (single-sub-asset shape; cubemap / array reserved\n * for future feat)\n * - `kind: 'texture'` (closed literal for image-importer emit)\n *\n * Two consecutive calls with identical inputs produce JSON.stringify\n * byte-equal output (AC-16 idempotent reimport).\n */\nexport function toAssetPack(decoded: DecodedImage, meta: ImageMeta): ExternalAssetPackage {\n // decoded.bytes are not embedded in the meta envelope -- the source bytes\n // live next to the sidecar on disk (the runtime reads them via\n // decodeImageFromFile at app load time). We keep the parameter so future\n // cubemap / array-layer feats can derive multi-sub-asset emit from decoded\n // dimensions without breaking the call surface (charter P5 consistent\n // abstraction).\n void decoded;\n\n return {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n importer: 'image',\n source: '',\n importSettings: {\n colorSpace: meta.colorSpace,\n mipmap: meta.mipmap,\n addressMode: meta.addressMode,\n filterMode: meta.filterMode,\n ...(meta.downscaleMaxDimension !== undefined\n ? { downscaleMaxDimension: meta.downscaleMaxDimension }\n : {}),\n },\n subAssets: [\n {\n guid: meta.guid,\n sourceIndex: 0,\n kind: 'texture',\n },\n ],\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/hdr-decoder.ts","../src/image-decoder-browser.ts","../src/image-decoder-node.ts","../src/source-key.ts","../src/sub-asset-key.ts","../src/reimport-reuse-meta.ts","../src/runtime/asset-decoders.ts","../src/to-asset-pack.ts"],"names":["err","ok"],"mappings":";;;;;;AAOA,IAAM,oBAAA,GAAiE;AAAA,EACrE,qBAAA,EAAuB,4CAAA;AAAA,EACvB,0BAAA,EACE,+FAAA;AAAA,EACF,+BAAA,EACE,mFAAA;AAAA,EACF,oBAAA,EACE,6EAAA;AAAA,EACF,yBAAA,EAA2B,mEAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ3B,mBAAA,EAAqB,oBAAA;AAAA,EACrB,qBAAA,EACE,mFAAA;AAAA,EACF,uBAAA,EAAyB;AAC3B;AAGO,IAAM,cAAA,GAAN,cACG,KAAA,CAEV;AAAA,EACW,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,MAAA,EAAgC;AAC1C,IAAA,MAAM,OAAO,MAAA,CAAO,IAAA;AACpB,IAAA,MAAM,QAAA,GAAW,qBAAqB,IAAI,CAAA;AAC1C,IAAA,MAAM,IAAA,GAAO,kBAAkB,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,EAAW;AAAA,EACzB,QAAA,EAAU,0BAAA;AAAA,EACV,OAAA,EAAS;AAAA,IACP,MAAM,OAAO,KAAA,EAAO;AAClB,MAAA,OAAO,gBAAA;AAAA,QACL,KAAA;AAAA,QACA,UAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AAAA;AAEJ;;;ACxFO,SAAS,WAAA,CAAY,SAAuB,IAAA,EAAuC;AASxF,EAAA,OAAO;AAAA,IACL,aAAA,EAAe,OAAA;AAAA,IACf,IAAA,EAAM,wBAAA;AAAA,IACN,QAAA,EAAU,OAAA;AAAA,IACV,MAAA,EAAQ,EAAA;AAAA,IACR,cAAA,EAAgB;AAAA,MACd,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,aAAa,IAAA,CAAK,WAAA;AAAA,MAClB,YAAY,IAAA,CAAK,UAAA;AAAA,MACjB,GAAI,KAAK,qBAAA,KAA0B,MAAA,GAC/B,EAAE,qBAAA,EAAuB,IAAA,CAAK,qBAAA,EAAsB,GACpD;AAAC,KACP;AAAA,IACA,SAAA,EAAW;AAAA,MACT;AAAA,QACE,MAAM,IAAA,CAAK,IAAA;AAAA,QACX,WAAA,EAAa,CAAA;AAAA,QACb,IAAA,EAAM;AAAA;AACR;AACF,GACF;AACF","file":"index.mjs","sourcesContent":["import type { ImageErrorCode, ImageErrorDetailFor, ImageErrorFor } from '@forgeax/engine-types';\nimport { IMAGE_ERROR_HINTS } from '@forgeax/engine-types';\n\n// Per-code .expected string literals SSOT.\n// Mirrors ASSET_ERROR_HINTS / IMAGE_ERROR_HINTS shape (charter P5 consistent\n// abstraction). AI users surface .expected when a structured error needs to\n// describe the precondition that was violated.\nconst IMAGE_ERROR_EXPECTED: Readonly<Record<ImageErrorCode, string>> = {\n 'image-decode-failed': 'PNG / JPG byte stream decodes successfully',\n 'image-format-unsupported':\n \"mime is one of ['image/png', 'image/jpeg']; uploadTexture format <-> colorSpace family agrees\",\n 'image-dimension-out-of-bounds':\n 'width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)',\n 'image-meta-missing':\n \"<source>.meta.json sidecar (importer: 'image') exists in the same directory\",\n 'image-hdr-decode-failed': 'Radiance RGBE header is valid and pixel data decodes successfully',\n // feat-20260521-sprite-atlas-animation M1 T-03 — vite-plugin-image atlas\n // hook .expected literals (plan-strategy section 2 D-2 + AC-10 a/b/c).\n // ImageErrorImpl construction path is unchanged: the new atlas-* errors\n // flow through `new ImageErrorImpl({ code: 'atlas-...', ...detail })` and\n // pick the .expected string up from this Record at construction time\n // (charter P3 explicit failure SSOT — AI users surface .expected next to\n // .hint after switch (err.code) without parsing the message).\n 'atlas-empty-input': 'images.length >= 1',\n 'atlas-size-exceeded':\n 'image width x height <= maxAtlasSize^2 and each image fits in the atlas footprint',\n 'atlas-region-mismatch': 'sum(regions[i].w x regions[i].h) <= atlasWidth x atlasHeight',\n};\n\n/** Runtime implementation of the correlated `ImageErrorFor<C>` envelope. */\nexport class ImageErrorImpl<C extends ImageErrorCode = ImageErrorCode>\n extends Error\n implements ImageErrorFor<C>\n{\n readonly code: C;\n readonly expected: string;\n readonly hint: string;\n readonly detail: ImageErrorDetailFor<C>;\n\n constructor(detail: ImageErrorDetailFor<C>) {\n const code = detail.code;\n const expected = IMAGE_ERROR_EXPECTED[code];\n const hint = IMAGE_ERROR_HINTS[code];\n super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);\n this.name = 'ImageError';\n this.code = code;\n this.expected = expected;\n this.hint = hint;\n this.detail = detail;\n }\n}\n\n/** Construct a structured image error while preserving its code/detail pair. */\nexport function imageError<C extends ImageErrorCode>(\n detail: ImageErrorDetailFor<C>,\n): ImageErrorFor<C> {\n return new ImageErrorImpl<C>(detail);\n}\n\nexport { IMAGE_ERROR_EXPECTED };\n","import type { ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Decoded HDR image POD.\n *\n * `data` is an interleaved RGBA Float32Array (4 floats per pixel, row-major).\n * Color space is always linear (RGBE is radiance).\n */\nexport interface HdrDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Float32Array;\n}\n\n// ASCII code points\nconst LF = 0x0a;\n\n/**\n * Decode a Radiance RGBE (.hdr) byte stream into linear RGBA float pixels.\n *\n * Steps per research F-6:\n * 1. Parse ASCII header: magic (#?RADIANCE), FORMAT=32-bit_rle_rgbe,\n * resolution line (-Y height +X width).\n * 2. Decode per-scanline new-RLE pixel data: 4 independent channel runs.\n * 3. Convert RGBE to float: if E==0 -> 0; else f=2^(E-136), R=(Rm+0.5)*f.\n * 4. Output as interleaved RGBA Float32Array (alpha=1.0).\n *\n * Old-RLE scanlines (prefix not matching 0x02,0x02,hi,lo with correct width)\n * return image-hdr-decode-failed.\n */\nexport function decodeHdr(bytes: Uint8Array): Result<HdrDecoded, ImageError> {\n let pos = 0;\n\n // Step 1a: magic -- must start with \"#?RADIANCE\" or \"#?RGBE\"\n if (bytes.length < 11) {\n return err(hdrDecodeError('file too short for Radiance HDR header'));\n }\n const magic = String.fromCharCode(...bytes.subarray(0, 11));\n if (magic !== '#?RADIANCE\\n' && magic !== '#?RGBE\\n') {\n return err(\n hdrDecodeError('missing or invalid Radiance HDR magic; expected #?RADIANCE or #?RGBE'),\n );\n }\n pos = 11;\n\n // Step 1b: key=value lines until empty line\n let formatFound = false;\n while (pos < bytes.length) {\n const lineEnd = findByte(bytes, LF, pos);\n if (lineEnd === -1) return err(hdrDecodeError('header truncated before empty line'));\n const line = asciiSubstring(bytes, pos, lineEnd);\n pos = lineEnd + 1;\n if (line === '') break;\n if (line.startsWith('FORMAT=')) {\n const val = line.slice(7);\n if (val === '32-bit_rle_rgbe') {\n formatFound = true;\n }\n }\n }\n if (!formatFound) {\n return err(hdrDecodeError('missing or unsupported FORMAT; expected FORMAT=32-bit_rle_rgbe'));\n }\n\n // Step 1c: resolution line (-Y height +X width)\n if (pos >= bytes.length) return err(hdrDecodeError('missing resolution line'));\n const resLineEnd = findByte(bytes, LF, pos);\n if (resLineEnd === -1) return err(hdrDecodeError('resolution line truncated'));\n const resLine = asciiSubstring(bytes, pos, resLineEnd);\n pos = resLineEnd + 1;\n const resMatch = /^-Y\\s+(\\d+)\\s+\\+X\\s+(\\d+)\\s*$/.exec(resLine);\n if (resMatch === null) {\n return err(\n hdrDecodeError(`unexpected resolution line format: \"${resLine}\"; expected \"-Y H +X W\"`),\n );\n }\n const height = Number(resMatch[1]);\n const width = Number(resMatch[2]);\n if (height === undefined || width === undefined || height <= 0 || width <= 0) {\n return err(hdrDecodeError(`invalid dimensions: ${width}x${height}`));\n }\n\n // Step 2: decode per-scanline new-RLE pixel data\n const pixelCount = width * height;\n const rgbe = new Uint8Array(pixelCount * 4);\n const scanlineBytes = width * 4;\n\n for (let y = 0; y < height; y++) {\n if (pos + 4 > bytes.length) {\n return err(hdrDecodeError(`truncated at scanline ${y}: expected 4-byte prefix`));\n }\n const p0 = bytes[pos];\n const p1 = bytes[pos + 1];\n const pHi = bytes[pos + 2];\n const pLo = bytes[pos + 3];\n if (p0 === undefined || p1 === undefined || pHi === undefined || pLo === undefined) {\n return err(hdrDecodeError(`truncated at scanline ${y}`));\n }\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const prefixWidth = (pHi! << 8) | pLo!;\n\n if (p0 === 0x02 && p1 === 0x02 && prefixWidth === width && width >= 8 && width <= 32767) {\n // New-RLE: 4 channels independently RLE-encoded, then interleaved\n const decoded = decodeNewRleScanline(bytes, pos + 4, width);\n if (decoded === null) {\n return err(hdrDecodeError(`RLE decode failed at scanline ${y}`));\n }\n // Copy into rgbe interleaved buffer\n const base = y * scanlineBytes;\n const channels = [decoded[0], decoded[1], decoded[2], decoded[3]];\n for (let x = 0; x < width; x++) {\n for (let ch = 0; ch < 4; ch++) {\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n rgbe[base + x * 4 + ch] = channels[ch]![x]!;\n }\n }\n // Advance pos past the 4-byte prefix + the total RLE bytes consumed\n pos += 4 + decoded.totalBytes;\n } else {\n // Old-RLE: not supported\n return err(\n hdrDecodeError(\n 'old-RLE format is not supported; only new-RLE (32-bit_rle_rgbe) is accepted',\n ),\n );\n }\n }\n\n // Step 3: RGBE to float\n const out = new Float32Array(pixelCount * 4);\n for (let i = 0; i < pixelCount; i++) {\n const base = i * 4;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const r = rgbe[base]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const g = rgbe[base + 1]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const b = rgbe[base + 2]!;\n // biome-ignore lint/style/noNonNullAssertion: checked at allocation\n const e = rgbe[base + 3]!;\n out[base + 3] = 1.0;\n\n if (e === 0) {\n out[base] = 0;\n out[base + 1] = 0;\n out[base + 2] = 0;\n } else {\n // f = 2^(E - 136) = ldexp(1.0, E - 128 - 8)\n // Equivalent: ldexp(1.0 / 256.0, E - 128)\n // But simpler: const f = (1.0 / 256.0) * Math.pow(2, e - 128);\n // Using ldexp: Math.pow(2, e - 136)\n const f = 2 ** (e - 136);\n out[base] = (r + 0.5) * f;\n out[base + 1] = (g + 0.5) * f;\n out[base + 2] = (b + 0.5) * f;\n }\n }\n\n return ok({ width, height, data: out });\n}\n\ninterface DecodedScanline {\n /** 4 channels, each width bytes */\n readonly 0: Uint8Array;\n readonly 1: Uint8Array;\n readonly 2: Uint8Array;\n readonly 3: Uint8Array;\n readonly totalBytes: number;\n}\n\n/**\n * Decode one scanline of new-RLE data into 4 channel arrays.\n * Returns null on failure (data underrun).\n */\nfunction decodeNewRleScanline(\n bytes: Uint8Array,\n start: number,\n width: number,\n): DecodedScanline | null {\n const channels: Uint8Array[] = [];\n let cursor = start;\n\n for (let ch = 0; ch < 4; ch++) {\n const data = new Uint8Array(width);\n let x = 0;\n while (x < width) {\n if (cursor >= bytes.length) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const code = bytes[cursor]!;\n cursor++;\n if (code > 128) {\n // RLE run: next byte repeated (code - 128) times\n const count = code - 128;\n if (cursor >= bytes.length || x + count > width) return null;\n // biome-ignore lint/style/noNonNullAssertion: checked above\n const val = bytes[cursor]!;\n cursor++;\n data.fill(val, x, x + count);\n x += count;\n } else {\n // Literal run: next `code` bytes copied verbatim\n if (code === 0) continue;\n if (cursor + code > bytes.length || x + code > width) return null;\n for (let k = 0; k < code; k++) {\n // biome-ignore lint/style/noNonNullAssertion: checked above\n data[x + k] = bytes[cursor + k]!;\n }\n cursor += code;\n x += code;\n }\n }\n channels.push(data);\n }\n\n const ch0 = channels[0];\n const ch1 = channels[1];\n const ch2 = channels[2];\n const ch3 = channels[3];\n if (ch0 === undefined || ch1 === undefined || ch2 === undefined || ch3 === undefined) {\n return null; // channels should always have 4 entries\n }\n return {\n 0: ch0,\n 1: ch1,\n 2: ch2,\n 3: ch3,\n totalBytes: cursor - start,\n };\n}\n\nfunction findByte(bytes: Uint8Array, target: number, start: number): number {\n for (let i = start; i < bytes.length; i++) {\n if (bytes[i] === target) return i;\n }\n return -1;\n}\n\nfunction asciiSubstring(bytes: Uint8Array, start: number, end: number): string {\n let s = '';\n for (let i = start; i < end; i++) {\n // biome-ignore lint/style/noNonNullAssertion: in bounds\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\n}\n\nfunction hdrDecodeError(reason: string): ImageError {\n return imageError({\n code: 'image-hdr-decode-failed',\n reason,\n });\n}\n","import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';\nimport { imageError } from './errors.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\n/**\n * Browser image decoder (plan-strategy section 3.3 + section 2.4 D Open Q-3).\n *\n * Uses `createImageBitmap(blob, { colorSpaceConversion: 'none' })` to keep\n * the bytes in their authored color space (sRGB / linear); the runtime\n * uploadTexture entry asserts `format <-> colorSpace` consistency at GPU\n * upload time (plan-strategy section 2.5 D Open Q-4 (c)).\n *\n * Pixel readback uses an offscreen 2D canvas + `getImageData`; AI users\n * never call this directly -- it is the browser-mode counterpart of\n * `parseImage` (Node-mode upng / jpeg-js path) consumed by future M2b\n * vite-plugin overlay paths and direct browser-mode loaders. The Node\n * decoder remains the SSOT for parseImage; this file is the browser\n * fallback when running inside vitest browser mode or the Vite dev server.\n */\nexport async function decodeImageInBrowser(\n bytes: Uint8Array,\n mime: 'image/png' | 'image/jpeg',\n opts: { colorSpace?: ImageColorSpace; mipmap?: boolean } = {},\n): Promise<Result<DecodedImage, ImageError>> {\n if (typeof createImageBitmap !== 'function') {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'createImageBitmap is not available in this environment',\n }),\n );\n }\n\n let bitmap: ImageBitmap;\n try {\n const blob = new Blob([bytes as BlobPart], { type: mime });\n bitmap = await createImageBitmap(blob, {\n colorSpaceConversion: 'none',\n premultiplyAlpha: 'none',\n });\n } catch (e) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: e instanceof Error ? e.message : String(e),\n }),\n );\n }\n\n // Read pixels back via OffscreenCanvas (browser context) -- 2D context is\n // ubiquitous and avoids the WebGPU readback round-trip during disk-side\n // decode (charter P5 producer / consumer split: GPU upload happens inside\n // @forgeax/engine-runtime AssetRegistry.uploadTexture, not here).\n const canvas =\n typeof OffscreenCanvas !== 'undefined'\n ? new OffscreenCanvas(bitmap.width, bitmap.height)\n : (() => {\n const c = document.createElement('canvas');\n c.width = bitmap.width;\n c.height = bitmap.height;\n return c;\n })();\n const ctx = canvas.getContext('2d') as\n | OffscreenCanvasRenderingContext2D\n | CanvasRenderingContext2D\n | null;\n if (ctx === null) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'failed to acquire 2d canvas context for pixel readback',\n }),\n );\n }\n ctx.drawImage(bitmap, 0, 0);\n const data = ctx.getImageData(0, 0, bitmap.width, bitmap.height);\n bitmap.close();\n\n return ok({\n bytes: new Uint8Array(data.data.buffer.slice(0)),\n width: data.width,\n height: data.height,\n mime,\n colorSpace: opts.colorSpace ?? 'srgb',\n mipmap: opts.mipmap ?? true,\n });\n}\n","// Node-only image decoder shell for @forgeax/engine-image.\n//\n// Lazy-loads `upng-js` (PNG) and `jpeg-js` (JPEG) via dynamic imports so the\n// browser bundle tree-shakes both decoders out of the ESM output (the\n// browser path uses createImageBitmap instead). Migrated from the original\n// packages/runtime/src/ home in feat-20260515-learn-render-getting-started\n// M2 T-M2-02 (Open Q-3 option a; plan-strategy section 2.4) -- runtime now\n// only consumes DecodedImage POD and never imports the decoders.\n//\n// The implementation surface is filled out by T-M2-05; this file is staged\n// here in T-M2-02 so the migration touches a single owner directory and the\n// runtime package never ships a half-migrated state.\n\n/**\n * Local widening of the upng-js dynamic-import surface (the package ships\n * without a usable @types entry; the d.ts in image-decoders.d.ts only adds\n * the module declaration). Lists the two functions consumed by the Node\n * decoder path; widening here keeps the import site free of `as any` casts\n * (charter P3 explicit failure -- structural typing > escape hatches).\n */\nexport interface UpngModule {\n decode: (bytes: Uint8Array | ArrayBuffer) => {\n width: number;\n height: number;\n depth: number;\n ctype: number;\n data: Uint8Array;\n frames?: unknown[];\n };\n toRGBA8: (img: { width: number; height: number; data: Uint8Array }) => ArrayBuffer[];\n}\n\n/**\n * Local widening of the jpeg-js dynamic-import surface. Mirrors the subset\n * used by the Node decoder; jpeg-js has @types/jpeg-js but we keep a local\n * shape so the d.ts ambient declaration stays the SSOT for runtime resolution\n * (charter P5 producer / consumer split).\n */\nexport interface JpegModule {\n decode: (\n bytes: Uint8Array | ArrayBuffer,\n opts?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => {\n width: number;\n height: number;\n data: Uint8Array;\n };\n}\n\n/**\n * Lazy-load the upng-js Node decoder module. Browser bundlers tree-shake\n * this dynamic import out when only the createImageBitmap path is reached\n * at runtime; tsup external keeps the package name from being inlined.\n */\nexport async function loadUpng(): Promise<UpngModule> {\n const mod = (await import('upng-js')) as { default?: UpngModule } & UpngModule;\n return (mod.default ?? mod) as UpngModule;\n}\n\n/**\n * Lazy-load the jpeg-js Node decoder module. Same tree-shake guarantee as\n * loadUpng -- browser bundles never reach this path.\n */\nexport async function loadJpeg(): Promise<JpegModule> {\n const mod = (await import('jpeg-js')) as { default?: JpegModule } & JpegModule;\n return (mod.default ?? mod) as JpegModule;\n}\n","/**\n * Derive the semantic identity for an image producer output.\n *\n * The role is the producer-owned identity. Source path and sourceIndex are\n * locators only and must not be folded into this key.\n */\nexport interface ImageSourceKeyLocator {\n readonly sourcePath?: string;\n readonly sourceIndex?: number;\n}\n\nexport type ImageSourceKeyResult =\n | { readonly ok: true; readonly keys: readonly string[] }\n | {\n readonly ok: false;\n readonly code: 'missing-source-key' | 'duplicate-source-key';\n readonly roles: readonly string[];\n };\n\nexport function deriveImageSourceKey(\n role: string,\n _locator?: ImageSourceKeyLocator,\n): string | undefined {\n const normalizedRole = role.trim();\n if (normalizedRole.length === 0) return undefined;\n return `image:${normalizedRole}`;\n}\n\nexport function deriveImageSourceKeys(roles: readonly string[]): ImageSourceKeyResult {\n const keys = roles.map((role) => deriveImageSourceKey(role));\n const missing = roles.filter((_role, index) => keys[index] === undefined);\n if (missing.length > 0) return { ok: false, code: 'missing-source-key', roles: missing };\n\n const seen = new Set<string>();\n for (const key of keys) {\n if (key === undefined) continue;\n if (seen.has(key)) return { ok: false, code: 'duplicate-source-key', roles };\n seen.add(key);\n }\n return { ok: true, keys: keys as string[] };\n}\n","/**\n * Sub-asset-key shape mirroring the in-flight gltf-loader feat (plan-strategy\n * section 2.2 D-4 same-shape). Each sub-asset emitted into a `*.meta.json`\n * sidecar (uniformly `<source>.meta.json` across image / gltf arms,\n * dispatched on top-level `importer` field per feat-20260521) carries a\n * `{kind, name?, indexFallback}` triple so the importer can deterministically\n * match an existing sub-asset across reimports (charter P5 producer/consumer\n * split + AC-14 cross-feat alignment).\n *\n * The image disk schema is currently single-sub-asset; this file collapses\n * to `kind='texture'` + `indexFallback='textures/0'` so the same matching\n * algorithm is reusable when the future cubemap / array-layer feat lands\n * (plan-strategy R5 free-form schema).\n */\n\nexport interface SubAssetKey {\n /** Discriminator literal -- 'texture' for engine-image; 'mesh' / 'material' / 'scene' / 'image' for gltf-loader. */\n readonly kind: string;\n /** Optional human-readable name field; absent when the source has no symbolic identifier. */\n readonly name?: string;\n /** Path-style fallback identifier (e.g. 'images/0' / 'meshes/0'); always non-empty. */\n readonly indexFallback: string;\n}\n\nexport interface SubAssetKeyInput {\n readonly kind: string;\n readonly sourceIndex: number;\n readonly name?: string;\n}\n\n/**\n * Construct a sub-asset key from importer input. The `indexFallback` is\n * synthesised from the kind literal + sourceIndex so two importers\n * (image / gltf-loader) emit identical fallback strings for the same\n * `(kind, sourceIndex)` pair (AC-14).\n */\nexport function subAssetKey(input: SubAssetKeyInput): SubAssetKey {\n const indexFallback = `${input.kind}s/${input.sourceIndex}`;\n if (input.name !== undefined) {\n return { kind: input.kind, name: input.name, indexFallback };\n }\n return { kind: input.kind, indexFallback };\n}\n\n/**\n * Two-phase equality predicate used by reimportReuseMeta for GUID\n * preservation across reimports:\n *\n * Phase 1 -- (kind + name + idx) full match: identical in all three fields\n * Phase 2 -- (kind + idx) match: same kind + indexFallback, name absent or\n * equal (collapses when both sides omit name)\n * Phase 3 -- otherwise: false (importer mints fresh UUIDv7)\n *\n * The two phases are folded into a single boolean predicate here; the\n * reimportReuseMeta caller iterates the existing subAssets list and picks\n * the first hit (deterministic order; matches AC-16 byte-identical\n * reimport).\n */\nexport function subAssetKeyEqual(a: SubAssetKey, b: SubAssetKey): boolean {\n if (a.kind !== b.kind) return false;\n if (a.indexFallback !== b.indexFallback) return false;\n // name comparison: undefined === undefined is fine; if one side has a name\n // and the other does not, the keys are NOT equal (charter P4 explicit\n // failure -- name carries a meaningful identifier when present)\n if (a.name !== b.name) return false;\n return true;\n}\n","import { AssetGuid } from '@forgeax/engine-pack/guid';\nimport type { DecodedImage, ImageColorSpace } from '@forgeax/engine-types';\n\nimport { deriveImageSourceKey } from './source-key.js';\nimport type { SubAssetKey } from './sub-asset-key.js';\nimport { subAssetKey, subAssetKeyEqual } from './sub-asset-key.js';\n\n/**\n * Existing `*.meta.json` (importer: 'image') sub-asset record (free-form sub-shape; the\n * meta.schema.json $defs/subAsset locks `guid` + `sourceIndex` + `kind` only).\n * Image importer treats the open shape as a key-bearing tuple; the gltf-loader\n * feat works on the same shape.\n */\nexport interface ExistingSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n readonly sourceKey?: string;\n}\n\n/**\n * Existing `*.meta.json` (importer: 'image') package record. Mirrors the\n * meta.schema.json $defs/ExternalAssetPackage shape (research F-9). Only\n * the fields consumed by the reimport reuse algorithm are typed here;\n * importSettings stays a free-form open shape.\n */\nexport interface ExistingExternalAssetPackage {\n readonly schemaVersion: string;\n readonly kind: 'external-asset-package';\n readonly importer: 'image';\n readonly source: string;\n readonly importSettings: Readonly<Record<string, unknown>>;\n readonly subAssets: readonly ExistingSubAsset[];\n}\n\n/**\n * Sub-asset record emitted into the regenerated `*.meta.json` (importer: 'image')\n * `subAssets[]` slot. Shape matches `ExistingSubAsset` so two consecutive\n * reimports of byte-identical bytes produce byte-identical JSON\n * (AC-16 byte-stable reimport guarantee).\n */\nexport interface EmittedSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n readonly sourceKey?: string;\n}\n\n/**\n * Two-phase reimport reuse algorithm (plan-strategy section 2.2 D-4\n * mirroring the in-flight gltf-loader algorithm).\n *\n * For each fresh sub-asset key the importer would emit, this function:\n * 1. Searches the `existing.subAssets[]` for a `subAssetKeyEqual` hit.\n * 2. On hit -- reuses the existing GUID byte-for-byte.\n * 3. On miss -- mints a fresh UUIDv7 via `AssetGuid.random()`.\n *\n * Image disk schema currently emits a single `kind='texture'` sub-asset per\n * source (cubemap face / array layer reserved for future feat); the\n * algorithm scales to multi-sub-asset sources without modification (charter\n * P5 consistent abstraction).\n *\n * Returns the regenerated `subAssets[]` array. The caller (toAssetPack /\n * runAssetImport) splices it into the `*.meta.json` (importer: 'image') envelope.\n */\nexport function reimportReuseMeta(\n decoded: DecodedImage,\n existing: ExistingExternalAssetPackage | undefined,\n): readonly EmittedSubAsset[] {\n // Image disk schema is single-sub-asset; the future multi-asset path\n // iterates a producer-side list of sub-asset keys instead of a single one.\n const freshKeys: readonly SubAssetKey[] = [subAssetKey({ kind: 'texture', sourceIndex: 0 })];\n\n const out: EmittedSubAsset[] = [];\n const sourceKey = deriveImageSourceKey('texture');\n\n for (let i = 0; i < freshKeys.length; i++) {\n const fresh = freshKeys[i];\n if (fresh === undefined) continue;\n\n let reuseGuid: string | undefined;\n if (existing !== undefined) {\n for (const candidate of existing.subAssets) {\n if (sourceKey !== undefined && candidate.sourceKey === sourceKey) {\n reuseGuid = candidate.guid;\n break;\n }\n const candidateKey = subAssetKey({\n kind: candidate.kind,\n sourceIndex: candidate.sourceIndex,\n ...(candidate.name !== undefined ? { name: candidate.name } : {}),\n });\n if (subAssetKeyEqual(fresh, candidateKey)) {\n reuseGuid = candidate.guid;\n break;\n }\n }\n }\n\n const guid = reuseGuid ?? AssetGuid.format(AssetGuid.random());\n const emit: EmittedSubAsset =\n fresh.name !== undefined\n ? {\n guid,\n sourceIndex: i,\n kind: fresh.kind,\n name: fresh.name,\n ...(sourceKey === undefined ? {} : { sourceKey }),\n }\n : {\n guid,\n sourceIndex: i,\n kind: fresh.kind,\n ...(sourceKey === undefined ? {} : { sourceKey }),\n };\n out.push(emit);\n }\n\n // Ensure decoded ref is consumed (decoded.bytes is the producer signal that\n // a sub-asset exists; without bytes there is nothing to emit). The\n // signature keeps `decoded` in the public surface so the future cubemap /\n // array-layer feat can derive its multi-sub-asset list from `decoded`\n // metadata without a breaking change (charter P5 consistent abstraction).\n void decoded;\n\n return out;\n}\n\n/**\n * HDR colorSpace validator for *.image.meta.json sidecar importSettings\n * (plan-strategy D-8 -- HDR files must use colorSpace=linear).\n *\n * Extension is matched case-insensitively against the HDR set\n * (`.hdr`, `.exr`). When the extension belongs to the HDR set:\n * - `colorSpace='linear'` -> ok, returns `'linear'`\n * - any other colorSpace -> structured rejection with expected/actual\n *\n * Non-HDR extensions pass through the colorSpace unchanged. Downstream\n * callers (decodeImageFromFile, parseImage) invoke this at the\n * sidecar-read entry to fail-fast when an .hdr meta carries srgb.\n */\nexport function validateColorSpaceForHdr(\n ext: string,\n colorSpace: ImageColorSpace,\n): { ok: true; value: ImageColorSpace } | { ok: false; expected: string; actual: string } {\n const lower = ext.toLowerCase();\n if (lower === '.hdr' || lower === '.exr') {\n if (colorSpace !== 'linear') {\n return {\n ok: false,\n expected: 'colorSpace=linear for HDR source files',\n actual: `colorSpace=${colorSpace}`,\n };\n }\n return { ok: true, value: 'linear' };\n }\n return { ok: true, value: colorSpace };\n}\n","import { parseKtx2, transcodeBasis, transcodeKtx2 } from '@forgeax/engine-codec';\nimport {\n type AssetDecoderContribution,\n type AssetDecoderInput,\n type AssetDecoderResult,\n type AssetKind,\n type AssetLoadError,\n type EquirectAsset,\n err,\n ok,\n type TextureAsset,\n} from '@forgeax/engine-types';\n\nfunction invalid(guid: string, expected: string, reason: string) {\n return err<AssetLoadError>({\n code: 'asset-package-invalid',\n expected,\n hint: 'recook the image asset and publish its complete device-neutral payload',\n detail: { guid, reason },\n });\n}\n\nfunction validDimensions(width: number, height: number): boolean {\n return Number.isSafeInteger(width) && width > 0 && Number.isSafeInteger(height) && height > 0;\n}\n\nfunction imageBytes(value: unknown): Uint8Array | Uint8ClampedArray | undefined {\n if (value instanceof Uint8Array || value instanceof Uint8ClampedArray) return value;\n if (!Array.isArray(value)) return undefined;\n if (!value.every((item) => Number.isInteger(item) && item >= 0 && item <= 255)) {\n return undefined;\n }\n return Uint8Array.from(value);\n}\n\nfunction compressedImageTarget(colorSpace: TextureAsset['colorSpace']): TextureAsset['format'] {\n return colorSpace === 'srgb' ? 'rgba8unorm-srgb' : 'rgba8unorm';\n}\n\nfunction validImageSurface(\n value: unknown,\n): value is Pick<TextureAsset, 'width' | 'height' | 'format' | 'data' | 'colorSpace'> {\n if (value === null || typeof value !== 'object') return false;\n const candidate = value as Partial<TextureAsset>;\n return (\n validDimensions(candidate.width ?? 0, candidate.height ?? 0) &&\n typeof candidate.format === 'string' &&\n imageBytes(candidate.data) !== undefined &&\n (candidate.colorSpace === 'srgb' || candidate.colorSpace === 'linear')\n );\n}\n\nasync function readImageSurface<P extends TextureAsset | EquirectAsset>(\n input: AssetDecoderInput<P>,\n kind: P['kind'],\n expected: string,\n): Promise<AssetDecoderResult<P>> {\n const { envelope, artifacts } = input;\n const payload = envelope.payload as unknown;\n if (\n payload === null ||\n typeof payload !== 'object' ||\n (payload as { kind?: unknown }).kind !== kind\n ) {\n return invalid(envelope.guid, expected, `${kind} owner validation failed`);\n }\n\n const body = envelope.artifacts.body ?? envelope.artifacts.atlas;\n let data = imageBytes((payload as { data?: unknown }).data);\n if (body !== undefined) {\n const read = await artifacts.read(body);\n if (!read.ok) return err(read.error);\n const bytes = read.value;\n data = bytes;\n\n // Pack v2 keeps the authored TextureAsset format device-neutral while the\n // artifact may carry a Basis KTX2/raw-Basis delivery codec. The new\n // AssetDecoder seam has no device-capability input, so its safe baseline is\n // an uncompressed RGBA target; the renderer can upload that POD on every\n // backend without interpreting container bytes as pixels.\n if (body.assetCodec?.name === 'basis' && body.assetCodec.container !== undefined) {\n const candidate = payload as Partial<TextureAsset>;\n if (candidate.colorSpace !== 'srgb' && candidate.colorSpace !== 'linear') {\n return invalid(envelope.guid, expected, `${kind} color space is invalid`);\n }\n const target = compressedImageTarget(candidate.colorSpace);\n const transcoded =\n body.assetCodec.container === 'ktx2'\n ? await parseKtx2(bytes).then((parsed) =>\n parsed.ok ? transcodeKtx2(parsed.value, target) : parsed,\n )\n : await transcodeBasis(bytes, target);\n if (!transcoded.ok) {\n return invalid(envelope.guid, expected, `codec:${transcoded.error.code}`);\n }\n const mip = transcoded.value.mips[0];\n if (mip === undefined) return invalid(envelope.guid, expected, 'codec:base-mip-missing');\n data = mip.data;\n return readDecodedSurface(envelope.guid, expected, {\n ...payload,\n width: mip.width,\n height: mip.height,\n format: target,\n data,\n });\n }\n }\n\n return readDecodedSurface(envelope.guid, expected, {\n ...payload,\n ...(data === undefined ? {} : { data }),\n });\n}\n\nfunction readDecodedSurface<P extends TextureAsset | EquirectAsset>(\n guid: string,\n expected: string,\n candidate: unknown,\n): ReturnType<typeof ok<P>> | ReturnType<typeof err<AssetLoadError>> {\n if (!validImageSurface(candidate)) {\n return invalid(guid, expected, 'image owner validation failed');\n }\n return ok(candidate as P);\n}\n\nexport const textureContribution: AssetDecoderContribution<TextureAsset, 'texture'> = {\n kind: { kind: 'texture' } as AssetKind<TextureAsset, 'texture'>,\n consumer: 'Image/Render DeviceScope',\n decoder: {\n async decode(input) {\n return readImageSurface(\n input,\n 'texture',\n 'a texture payload with dimensions, format, color space, and bytes',\n );\n },\n },\n};\n\nexport const equirectContribution: AssetDecoderContribution<EquirectAsset, 'equirect'> = {\n kind: { kind: 'equirect' } as AssetKind<EquirectAsset, 'equirect'>,\n consumer: 'Image/Render DeviceScope',\n decoder: {\n async decode(input) {\n return readImageSurface(\n input,\n 'equirect',\n 'an equirect payload with dimensions, format, color space, and bytes',\n );\n },\n },\n};\n","import type { AssetCompression, DecodedImage, ImageMeta } from '@forgeax/engine-types';\n\n/**\n * External-asset-package envelope shape mirroring the\n * `packages/pack/schema/meta.schema.json` $defs/ExternalAssetPackage.\n * Consumed by `forgeax-engine-remote-asset import` (CLI entry, M3b) +\n * the image importer in M2 build-time path. The internal-text-package\n * variant ($defs/InternalTextPackage) is owned by the gltf-loader feat.\n */\nexport interface ExternalAssetPackage {\n readonly schemaVersion: string;\n readonly kind: 'external-asset-package';\n readonly importer: 'image';\n readonly source: string;\n readonly importSettings: ImageImportSettings;\n readonly subAssets: readonly ExternalSubAsset[];\n}\n\n/**\n * Free-form image importer settings persisted into `*.meta.json` (importer: 'image')\n * `importSettings`. Matches `ImageMeta` POD field-for-field (charter P5\n * single SSOT) but the open Record shape allows future minor adds (cubemap\n * face / array layer / custom colorSpace) without breaking existing meta\n * files (plan-strategy R5).\n */\nexport interface ImageImportSettings extends Readonly<Record<string, unknown>> {\n readonly colorSpace: ImageMeta['colorSpace'];\n readonly mipmap: ImageMeta['mipmap'];\n readonly addressMode: ImageMeta['addressMode'];\n readonly filterMode: ImageMeta['filterMode'];\n readonly downscaleMaxDimension?: number;\n /**\n * Explicit per-asset compression override (AC-01: importSettings carries\n * compression intent). When omitted, the build-time compression strategy\n * table decides by artifact kind (mesh -> zstd, texture -> none). When set,\n * this value wins over the default table for this asset.\n */\n readonly compression?: AssetCompression;\n}\n\nexport interface ExternalSubAsset {\n readonly guid: string;\n readonly sourceIndex: number;\n readonly kind: string;\n readonly name?: string;\n}\n\n/**\n * Pure function that translates a DecodedImage POD + ImageMeta POD into\n * an external-asset-package envelope ready to be JSON-stringified into a\n * `*.meta.json` sidecar with importer: 'image' (plan-strategy section 3.2 sequence A; AC-13\n * disk schema reuse).\n *\n * The single sub-asset emitted carries:\n * - `guid` -- copied verbatim from `meta.guid` (the producer guarantees\n * the GUID is freshly minted or reused via `reimportReuseMeta`)\n * - `sourceIndex: 0` (single-sub-asset shape; cubemap / array reserved\n * for future feat)\n * - `kind: 'texture'` (closed literal for image-importer emit)\n *\n * Two consecutive calls with identical inputs produce JSON.stringify\n * byte-equal output (AC-16 idempotent reimport).\n */\nexport function toAssetPack(decoded: DecodedImage, meta: ImageMeta): ExternalAssetPackage {\n // decoded.bytes are not embedded in the meta envelope -- the source bytes\n // live next to the sidecar on disk (the runtime reads them via\n // decodeImageFromFile at app load time). We keep the parameter so future\n // cubemap / array-layer feats can derive multi-sub-asset emit from decoded\n // dimensions without breaking the call surface (charter P5 consistent\n // abstraction).\n void decoded;\n\n return {\n schemaVersion: '1.0.0',\n kind: 'external-asset-package',\n importer: 'image',\n source: '',\n importSettings: {\n colorSpace: meta.colorSpace,\n mipmap: meta.mipmap,\n addressMode: meta.addressMode,\n filterMode: meta.filterMode,\n ...(meta.downscaleMaxDimension !== undefined\n ? { downscaleMaxDimension: meta.downscaleMaxDimension }\n : {}),\n },\n subAssets: [\n {\n guid: meta.guid,\n sourceIndex: 0,\n kind: 'texture',\n },\n ],\n };\n}\n"]}
@@ -1,10 +1,8 @@
1
1
  import type { BasisEncodeMode } from '@forgeax/engine-codec/encode';
2
- declare const COMPRESSION_MODES: readonly ["auto", "etc1s", "uastc", "none"];
3
2
  /** The sidecar control-plane value (ImageMetadata.compressionMode). */
4
- export type CompressionMode = (typeof COMPRESSION_MODES)[number];
5
- declare const RESOLVED_ENCODE_MODES: readonly ["etc1s", "uastc", "uastc-hdr", "none"];
3
+ export type CompressionMode = 'auto' | 'etc1s' | 'uastc' | 'none';
6
4
  /** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */
7
- export type ResolvedEncodeMode = (typeof RESOLVED_ENCODE_MODES)[number];
5
+ export type ResolvedEncodeMode = 'etc1s' | 'uastc' | 'uastc-hdr' | 'none';
8
6
  /** Source signals that drive 'auto' derivation (D-12) and encoder params. */
9
7
  export interface EncodeSourceInfo {
10
8
  /** Color transfer of the source (from the sidecar importSettings). */
@@ -80,5 +78,4 @@ export type EncodeTextureResult = {
80
78
  * .bin path" rather than an error (see importer callsite w18).
81
79
  */
82
80
  export declare function encodeTextureToKtx2(pixels: Uint8Array, width: number, height: number, mode: CompressionMode, source: EncodeSourceInfo): Promise<EncodeTextureResult>;
83
- export {};
84
81
  //# sourceMappingURL=ktx2-encode.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ktx2-encode.d.ts","sourceRoot":"","sources":["../src/ktx2-encode.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAGpE,QAAA,MAAM,iBAAiB,6CAA8C,CAAC;AAEtE,uEAAuE;AACvE,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEjE,QAAA,MAAM,qBAAqB,kDAAmD,CAAC;AA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2-encode.ts
4
- var COMPRESSION_MODES = ["auto", "etc1s", "uastc", "none"];
5
- var RESOLVED_ENCODE_MODES = ["etc1s", "uastc", "uastc-hdr", "none"];
6
4
  function resolveEncodeMode(mode, source) {
7
5
  switch (mode) {
8
- case COMPRESSION_MODES[3]:
9
- return RESOLVED_ENCODE_MODES[3];
10
- case COMPRESSION_MODES[1]:
11
- return RESOLVED_ENCODE_MODES[0];
12
- case COMPRESSION_MODES[2]:
13
- return source.isHdr ? RESOLVED_ENCODE_MODES[2] : RESOLVED_ENCODE_MODES[1];
14
- case COMPRESSION_MODES[0]:
15
- if (source.isHdr) return RESOLVED_ENCODE_MODES[2];
16
- return source.colorSpace === "srgb" ? RESOLVED_ENCODE_MODES[0] : RESOLVED_ENCODE_MODES[1];
6
+ case "none":
7
+ return "none";
8
+ case "etc1s":
9
+ return "etc1s";
10
+ case "uastc":
11
+ return source.isHdr ? "uastc-hdr" : "uastc";
12
+ case "auto":
13
+ if (source.isHdr) return "uastc-hdr";
14
+ return source.colorSpace === "srgb" ? "etc1s" : "uastc";
17
15
  }
18
16
  }
19
17
  function basisEncodeParamsFor(mode, source) {
20
18
  const resolved = resolveEncodeMode(mode, source);
21
19
  const srgbColor = source.colorSpace === "srgb";
22
20
  switch (resolved) {
23
- case RESOLVED_ENCODE_MODES[3]:
21
+ case "none":
24
22
  return null;
25
- case RESOLVED_ENCODE_MODES[0]:
23
+ case "etc1s":
26
24
  return {
27
- mode: RESOLVED_ENCODE_MODES[0],
25
+ mode: "etc1s",
28
26
  srgb: srgbColor,
29
27
  perceptual: srgbColor,
30
28
  uastcSupercompression: false,
31
29
  mipGen: false
32
30
  };
33
- case RESOLVED_ENCODE_MODES[1]:
31
+ case "uastc":
34
32
  return {
35
33
  mode: "uastc-ldr",
36
34
  srgb: srgbColor,
@@ -38,9 +36,9 @@ function basisEncodeParamsFor(mode, source) {
38
36
  uastcSupercompression: true,
39
37
  mipGen: false
40
38
  };
41
- case RESOLVED_ENCODE_MODES[2]:
39
+ case "uastc-hdr":
42
40
  return {
43
- mode: RESOLVED_ENCODE_MODES[2],
41
+ mode: "uastc-hdr",
44
42
  srgb: false,
45
43
  perceptual: false,
46
44
  uastcSupercompression: false,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ktx2-encode.ts"],"names":[],"mappings":";;;AAsBA,IAAM,iBAAA,GAAoB,CAAC,MAAA,EAAQ,OAAA,EAAS,SAAS,MAAM,CAAA;AAK3D,IAAM,qBAAA,GAAwB,CAAC,OAAA,EAAS,OAAA,EAAS,aAAa,MAAM,CAAA;AA0B7D,SAAS,iBAAA,CACd,MACA,MAAA,EACoB;AACpB,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,kBAAkB,CAAC,CAAA;AACtB,MAAA,OAAO,sBAAsB,CAAC,CAAA;AAAA,IAChC,KAAK,kBAAkB,CAAC,CAAA;AACtB,MAAA,OAAO,sBAAsB,CAAC,CAAA;AAAA,IAChC,KAAK,kBAAkB,CAAC,CAAA;AACtB,MAAA,OAAO,OAAO,KAAA,GAAQ,qBAAA,CAAsB,CAAC,CAAA,GAAI,sBAAsB,CAAC,CAAA;AAAA,IAC1E,KAAK,kBAAkB,CAAC,CAAA;AACtB,MAAA,IAAI,MAAA,CAAO,KAAA,EAAO,OAAO,qBAAA,CAAsB,CAAC,CAAA;AAChD,MAAA,OAAO,OAAO,UAAA,KAAe,MAAA,GAAS,sBAAsB,CAAC,CAAA,GAAI,sBAAsB,CAAC,CAAA;AAAA;AAE9F;AAqBO,SAAS,oBAAA,CACd,MACA,MAAA,EAC0B;AAC1B,EAAA,MAAM,QAAA,GAAW,iBAAA,CAAkB,IAAA,EAAM,MAAM,CAAA;AAC/C,EAAA,MAAM,SAAA,GAAY,OAAO,UAAA,KAAe,MAAA;AACxC,EAAA,QAAQ,QAAA;AAAU,IAChB,KAAK,sBAAsB,CAAC,CAAA;AAC1B,MAAA,OAAO,IAAA;AAAA,IACT,KAAK,sBAAsB,CAAC,CAAA;AAC1B,MAAA,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IAAA,EAAM,8BAAA;AAAA,QACN,IAAA,EAAM,QAAA;AAAA,QACN,MAAA,EACE,UAAU,KAAK,CAAA,CAAA,EAAI,MAAM,CAAA,EAAA,EAAK,KAAA,GAAQ,MAAM,CAAA,iBAAA,EAAoB,wBAAwB,CAAA,uJAAA;AAAA;AAG5F,KACF;AAAA,EACF;AACA,EAAA,MAAM,MAAA,GAAS,MAAM,WAAA,CAAY,MAAA,EAAQ;AAAA,IACvC,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,KAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,YAAY,MAAA,CAAO,UAAA;AAAA,IACnB,uBAAuB,MAAA,CAAO,qBAAA;AAAA,IAC9B,QAAQ,MAAA,CAAO;AAAA,GAChB,CAAA;AACD,EAAA,IAAI,CAAC,OAAO,EAAA,EAAI;AACd,IAAA,MAAM,SACJ,MAAA,CAAO,KAAA,CAAM,MAAA,KAAW,MAAA,IAAa,YAAY,MAAA,CAAO,KAAA,CAAM,MAAA,GAC1D,MAAA,CAAQ,OAAO,KAAA,CAAM,MAAA,CAA+B,MAAM,CAAA,GAC1D,OAAO,KAAA,CAAM,IAAA;AACnB,IAAA,OAAO;AAAA,MACL,EAAA,EAAI,KAAA;AAAA,MACJ,KAAA,EAAO;AAAA,QACL,IAAA,EACE,MAAA,CAAO,KAAA,CAAM,IAAA,KAAS,sBAAsB,mBAAA,GAAsB,oBAAA;AAAA,QACpE,IAAA,EAAM,QAAA;AAAA,QACN;AAAA;AACF,KACF;AAAA,EACF;AACA,EAAA,OAAO,EAAE,EAAA,EAAI,IAAA,EAAM,KAAA,EAAO,EAAE,MAAM,MAAA,CAAO,KAAA,EAAO,IAAA,EAAM,QAAA,EAAS,EAAE;AACnE","file":"ktx2-encode.mjs","sourcesContent":["// ktx2-encode.ts -- the image-side offline texture encode arm (M3 w18, D-5).\n//\n// This module is the image-semantic layer of the Basis encode path: it maps the\n// sidecar `compressionMode` control-plane value + the source's colorSpace / HDR\n// signal into a delivery encoding (D-12 'auto' derivation), maps that to the\n// encoder parameters, and drives the low-level `basisEncode` binding that lives\n// in `@forgeax/engine-codec/encode` (the WASM + enum plumbing stays in codec;\n// the image semantics stay here -- D-5 \"arm in image, binary in codec/encode\").\n//\n// It is a NODE-ONLY build-time module (consumed by imageImporter, itself a\n// node-only sub-export). It never touches GPU (isolation path b) and is never\n// bundled into the runtime (isolation path a/d: runtime does not import\n// @forgeax/engine-image nor @forgeax/engine-codec/encode).\n//\n// M3 sequencing constraint (plan R-9): the 'auto' derivation is implemented and\n// tested here, but the sidecar DEFAULT stays 'none'. The default flip to 'auto'\n// is M5 (w38); doing it here would make every existing texture encode to Basis\n// ahead of loader support and redden the whole fixture fleet.\n\nimport type { BasisEncodeMode } from '@forgeax/engine-codec/encode';\nimport { basisEncode } from '@forgeax/engine-codec/encode';\n\nconst COMPRESSION_MODES = ['auto', 'etc1s', 'uastc', 'none'] as const;\n\n/** The sidecar control-plane value (ImageMetadata.compressionMode). */\nexport type CompressionMode = (typeof COMPRESSION_MODES)[number];\n\nconst RESOLVED_ENCODE_MODES = ['etc1s', 'uastc', 'uastc-hdr', 'none'] as const;\n\n/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */\nexport type ResolvedEncodeMode = (typeof RESOLVED_ENCODE_MODES)[number];\n\n/** Source signals that drive 'auto' derivation (D-12) and encoder params. */\nexport interface EncodeSourceInfo {\n /** Color transfer of the source (from the sidecar importSettings). */\n readonly colorSpace: 'srgb' | 'linear';\n /** Whether the source is an HDR image (.hdr -> rgba16float). */\n readonly isHdr: boolean;\n}\n\n/**\n * Resolve the sidecar `compressionMode` into a concrete delivery encoding.\n *\n * D-12 'auto' derivation (zero new required inputs, derived from existing\n * sidecar signals):\n * - HDR source -> 'uastc-hdr' (BC6H target downstream)\n * - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)\n * - colorSpace 'linear' -> 'uastc' (normals / ORM / data)\n *\n * Explicit modes pass through, except an explicit 'uastc' on an HDR source\n * resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'\n * and 'etc1s' pass through verbatim.\n */\nexport function resolveEncodeMode(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): ResolvedEncodeMode {\n switch (mode) {\n case COMPRESSION_MODES[3]:\n return RESOLVED_ENCODE_MODES[3];\n case COMPRESSION_MODES[1]:\n return RESOLVED_ENCODE_MODES[0];\n case COMPRESSION_MODES[2]:\n return source.isHdr ? RESOLVED_ENCODE_MODES[2] : RESOLVED_ENCODE_MODES[1];\n case COMPRESSION_MODES[0]:\n if (source.isHdr) return RESOLVED_ENCODE_MODES[2];\n return source.colorSpace === 'srgb' ? RESOLVED_ENCODE_MODES[0] : RESOLVED_ENCODE_MODES[1];\n }\n}\n\n/** Encoder parameters for a resolved delivery encoding. */\nexport interface BasisEncodeParams {\n /** The codec-side delivery encoding. */\n readonly mode: BasisEncodeMode;\n /** Write the sRGB transfer function (LDR color only). */\n readonly srgb: boolean;\n /** ETC1S perceptual (sRGB) metric. */\n readonly perceptual: boolean;\n /** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */\n readonly uastcSupercompression: boolean;\n /** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */\n readonly mipGen: boolean;\n}\n\n/**\n * Map the sidecar mode + source into encoder parameters. Returns `null` for the\n * 'none' path -- the caller keeps the uncompressed `.bin` path and never calls\n * the encoder.\n */\nexport function basisEncodeParamsFor(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): BasisEncodeParams | null {\n const resolved = resolveEncodeMode(mode, source);\n const srgbColor = source.colorSpace === 'srgb';\n switch (resolved) {\n case RESOLVED_ENCODE_MODES[3]:\n return null;\n case RESOLVED_ENCODE_MODES[0]:\n return {\n mode: RESOLVED_ENCODE_MODES[0],\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: false,\n mipGen: false,\n };\n case RESOLVED_ENCODE_MODES[1]:\n return {\n mode: 'uastc-ldr',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: true,\n mipGen: false,\n };\n case RESOLVED_ENCODE_MODES[2]:\n return {\n mode: RESOLVED_ENCODE_MODES[2],\n srgb: false,\n perceptual: false,\n uastcSupercompression: false,\n mipGen: false,\n };\n }\n}\n\n/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */\nexport interface EncodedTexture {\n readonly ktx2: Uint8Array;\n readonly mode: ResolvedEncodeMode;\n}\n\n/**\n * Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx\n * = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`\n * ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).\n * Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`\n * error rather than reaching the encoder and getting a silent 0-byte failure.\n */\nexport const MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;\n\n/** Failure result carrying a short reason (encoder-side or invalid request). */\nexport interface EncodeFailure {\n readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';\n readonly mode: ResolvedEncodeMode;\n readonly reason: string;\n}\n\nexport type EncodeTextureResult =\n | { readonly ok: true; readonly value: EncodedTexture }\n | { readonly ok: false; readonly error: EncodeFailure };\n\n/**\n * Encode source pixels into a Basis KTX2 texture per the sidecar mode.\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes\n * for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar\n * mode resolves to 'none' -- the importer treats that as \"no encode, keep the\n * .bin path\" rather than an error (see importer callsite w18).\n */\nexport async function encodeTextureToKtx2(\n pixels: Uint8Array,\n width: number,\n height: number,\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): Promise<EncodeTextureResult> {\n const params = basisEncodeParamsFor(mode, source);\n if (params === null) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-failed',\n mode: 'none',\n reason: 'compressionMode resolved to none',\n },\n };\n }\n const resolved = resolveEncodeMode(mode, source);\n // Fail fast above the wasm32 encoder's source-pixel ceiling (4096^2). Above\n // this the encoder returns 0 bytes silently; surface a structured, actionable\n // error instead so the importer reports \"reduce resolution or set\n // compressionMode:'none'\" rather than an opaque encode failure.\n if (width * height > MAX_ENCODE_SOURCE_PIXELS) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-source-too-large',\n mode: resolved,\n reason:\n `source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px ` +\n '(4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 ' +\n \"or set compressionMode:'none' in the sidecar to keep it uncompressed\",\n },\n };\n }\n const result = await basisEncode(pixels, {\n mode: params.mode,\n width,\n height,\n srgb: params.srgb,\n perceptual: params.perceptual,\n uastcSupercompression: params.uastcSupercompression,\n mipGen: params.mipGen,\n });\n if (!result.ok) {\n const reason =\n result.error.detail !== undefined && 'reason' in result.error.detail\n ? String((result.error.detail as { reason: unknown }).reason)\n : result.error.code;\n return {\n ok: false,\n error: {\n code:\n result.error.code === 'codec-init-failed' ? 'codec-init-failed' : 'ktx2-encode-failed',\n mode: resolved,\n reason,\n },\n };\n }\n return { ok: true, value: { ktx2: result.value, mode: resolved } };\n}\n"]}
1
+ {"version":3,"sources":["../src/ktx2-encode.ts"],"names":[],"mappings":";;;AAiDO,SAAS,iBAAA,CACd,MACA,MAAA,EACoB;AACpB,EAAA,QAAQ,IAAA;AAAM,IACZ,KAAK,MAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,OAAA;AACH,MAAA,OAAO,OAAA;AAAA,IACT,KAAK,OAAA;AACH,MAAA,OAAO,MAAA,CAAO,QAAQ,WAAA,GAAc,OAAA;AAAA,IACtC,KAAK,MAAA;AACH,MAAA,IAAI,MAAA,CAAO,OAAO,OAAO,WAAA;AACzB,MAAA,OAAO,MAAA,CAAO,UAAA,KAAe,MAAA,GAAS,OAAA,GAAU,OAA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AAA,EAAM,KAAA,EAAO,EAAE,MAAM,MAAA,CAAO,KAAA,EAAO,IAAA,EAAM,QAAA,EAAS,EAAE;AACnE","file":"ktx2-encode.mjs","sourcesContent":["// ktx2-encode.ts -- the image-side offline texture encode arm (M3 w18, D-5).\n//\n// This module is the image-semantic layer of the Basis encode path: it maps the\n// sidecar `compressionMode` control-plane value + the source's colorSpace / HDR\n// signal into a delivery encoding (D-12 'auto' derivation), maps that to the\n// encoder parameters, and drives the low-level `basisEncode` binding that lives\n// in `@forgeax/engine-codec/encode` (the WASM + enum plumbing stays in codec;\n// the image semantics stay here -- D-5 \"arm in image, binary in codec/encode\").\n//\n// It is a NODE-ONLY build-time module (consumed by imageImporter, itself a\n// node-only sub-export). It never touches GPU (isolation path b) and is never\n// bundled into the runtime (isolation path a/d: runtime does not import\n// @forgeax/engine-image nor @forgeax/engine-codec/encode).\n//\n// M3 sequencing constraint (plan R-9): the 'auto' derivation is implemented and\n// tested here, but the sidecar DEFAULT stays 'none'. The default flip to 'auto'\n// is M5 (w38); doing it here would make every existing texture encode to Basis\n// ahead of loader support and redden the whole fixture fleet.\n\nimport type { BasisEncodeMode } from '@forgeax/engine-codec/encode';\nimport { basisEncode } from '@forgeax/engine-codec/encode';\n\n/** The sidecar control-plane value (ImageMetadata.compressionMode). */\nexport type CompressionMode = 'auto' | 'etc1s' | 'uastc' | 'none';\n\n/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */\nexport type ResolvedEncodeMode = 'etc1s' | 'uastc' | 'uastc-hdr' | 'none';\n\n/** Source signals that drive 'auto' derivation (D-12) and encoder params. */\nexport interface EncodeSourceInfo {\n /** Color transfer of the source (from the sidecar importSettings). */\n readonly colorSpace: 'srgb' | 'linear';\n /** Whether the source is an HDR image (.hdr -> rgba16float). */\n readonly isHdr: boolean;\n}\n\n/**\n * Resolve the sidecar `compressionMode` into a concrete delivery encoding.\n *\n * D-12 'auto' derivation (zero new required inputs, derived from existing\n * sidecar signals):\n * - HDR source -> 'uastc-hdr' (BC6H target downstream)\n * - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)\n * - colorSpace 'linear' -> 'uastc' (normals / ORM / data)\n *\n * Explicit modes pass through, except an explicit 'uastc' on an HDR source\n * resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'\n * and 'etc1s' pass through verbatim.\n */\nexport function resolveEncodeMode(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): ResolvedEncodeMode {\n switch (mode) {\n case 'none':\n return 'none';\n case 'etc1s':\n return 'etc1s';\n case 'uastc':\n return source.isHdr ? 'uastc-hdr' : 'uastc';\n case 'auto':\n if (source.isHdr) return 'uastc-hdr';\n return source.colorSpace === 'srgb' ? 'etc1s' : 'uastc';\n }\n}\n\n/** Encoder parameters for a resolved delivery encoding. */\nexport interface BasisEncodeParams {\n /** The codec-side delivery encoding. */\n readonly mode: BasisEncodeMode;\n /** Write the sRGB transfer function (LDR color only). */\n readonly srgb: boolean;\n /** ETC1S perceptual (sRGB) metric. */\n readonly perceptual: boolean;\n /** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */\n readonly uastcSupercompression: boolean;\n /** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */\n readonly mipGen: boolean;\n}\n\n/**\n * Map the sidecar mode + source into encoder parameters. Returns `null` for the\n * 'none' path -- the caller keeps the uncompressed `.bin` path and never calls\n * the encoder.\n */\nexport function basisEncodeParamsFor(\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): BasisEncodeParams | null {\n const resolved = resolveEncodeMode(mode, source);\n const srgbColor = source.colorSpace === 'srgb';\n switch (resolved) {\n case 'none':\n return null;\n case 'etc1s':\n return {\n mode: 'etc1s',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: false,\n mipGen: false,\n };\n case 'uastc':\n return {\n mode: 'uastc-ldr',\n srgb: srgbColor,\n perceptual: srgbColor,\n uastcSupercompression: true,\n mipGen: false,\n };\n case 'uastc-hdr':\n return {\n mode: 'uastc-hdr',\n srgb: false,\n perceptual: false,\n uastcSupercompression: false,\n mipGen: false,\n };\n }\n}\n\n/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */\nexport interface EncodedTexture {\n readonly ktx2: Uint8Array;\n readonly mode: ResolvedEncodeMode;\n}\n\n/**\n * Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx\n * = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`\n * ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).\n * Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`\n * error rather than reaching the encoder and getting a silent 0-byte failure.\n */\nexport const MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;\n\n/** Failure result carrying a short reason (encoder-side or invalid request). */\nexport interface EncodeFailure {\n readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';\n readonly mode: ResolvedEncodeMode;\n readonly reason: string;\n}\n\nexport type EncodeTextureResult =\n | { readonly ok: true; readonly value: EncodedTexture }\n | { readonly ok: false; readonly error: EncodeFailure };\n\n/**\n * Encode source pixels into a Basis KTX2 texture per the sidecar mode.\n *\n * `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes\n * for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar\n * mode resolves to 'none' -- the importer treats that as \"no encode, keep the\n * .bin path\" rather than an error (see importer callsite w18).\n */\nexport async function encodeTextureToKtx2(\n pixels: Uint8Array,\n width: number,\n height: number,\n mode: CompressionMode,\n source: EncodeSourceInfo,\n): Promise<EncodeTextureResult> {\n const params = basisEncodeParamsFor(mode, source);\n if (params === null) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-failed',\n mode: 'none',\n reason: 'compressionMode resolved to none',\n },\n };\n }\n const resolved = resolveEncodeMode(mode, source);\n // Fail fast above the wasm32 encoder's source-pixel ceiling (4096^2). Above\n // this the encoder returns 0 bytes silently; surface a structured, actionable\n // error instead so the importer reports \"reduce resolution or set\n // compressionMode:'none'\" rather than an opaque encode failure.\n if (width * height > MAX_ENCODE_SOURCE_PIXELS) {\n return {\n ok: false,\n error: {\n code: 'ktx2-encode-source-too-large',\n mode: resolved,\n reason:\n `source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px ` +\n '(4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 ' +\n \"or set compressionMode:'none' in the sidecar to keep it uncompressed\",\n },\n };\n }\n const result = await basisEncode(pixels, {\n mode: params.mode,\n width,\n height,\n srgb: params.srgb,\n perceptual: params.perceptual,\n uastcSupercompression: params.uastcSupercompression,\n mipGen: params.mipGen,\n });\n if (!result.ok) {\n const reason =\n result.error.detail !== undefined && 'reason' in result.error.detail\n ? String((result.error.detail as { reason: unknown }).reason)\n : result.error.code;\n return {\n ok: false,\n error: {\n code:\n result.error.code === 'codec-init-failed' ? 'codec-init-failed' : 'ktx2-encode-failed',\n mode: resolved,\n reason,\n },\n };\n }\n return { ok: true, value: { ktx2: result.value, mode: resolved } };\n}\n"]}
@@ -37,7 +37,6 @@ export interface ParseImageOptions {
37
37
  * Decoder selection follows the mime hint:
38
38
  * - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`
39
39
  * - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`
40
- * - `image/x-tga` -> the built-in TGA true-color/grayscale decoder
41
40
  * - other -> `image-format-unsupported`
42
41
  *
43
42
  * Decoded bytes are always tight-packed RGBA (`bytes.length === width *
@@ -1 +1 @@
1
- {"version":3,"file":"parse-image.d.ts","sourceRoot":"","sources":["../src/parse-image.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAUvF,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAG1C,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IAC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}
@@ -5,7 +5,7 @@ import { err, ok, IMAGE_ERROR_HINTS } from '@forgeax/engine-types';
5
5
  // src/parse-image.ts
6
6
  var IMAGE_ERROR_EXPECTED = {
7
7
  "image-decode-failed": "PNG / JPG byte stream decodes successfully",
8
- "image-format-unsupported": "mime is one of ['image/png', 'image/jpeg', 'image/x-tga']; uploadTexture format <-> colorSpace family agrees",
8
+ "image-format-unsupported": "mime is one of ['image/png', 'image/jpeg']; uploadTexture format <-> colorSpace family agrees",
9
9
  "image-dimension-out-of-bounds": "width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)",
10
10
  "image-meta-missing": "<source>.meta.json sidecar (importer: 'image') exists in the same directory",
11
11
  "image-hdr-decode-failed": "Radiance RGBE header is valid and pixel data decodes successfully",
@@ -74,7 +74,7 @@ function downscaleRgba(bytes, width, height, maxDimension) {
74
74
 
75
75
  // src/parse-image.ts
76
76
  var DEFAULT_MAX_DIMENSION = 16384;
77
- var SUPPORTED_MIMES = ["image/png", "image/jpeg", "image/x-tga"];
77
+ var SUPPORTED_MIMES = ["image/png", "image/jpeg"];
78
78
  function parseImage(bytes, mime, opts = {}) {
79
79
  if (!SUPPORTED_MIMES.includes(mime)) {
80
80
  return err(
@@ -106,17 +106,12 @@ function parseImage(bytes, mime, opts = {}) {
106
106
  );
107
107
  }
108
108
  rgba = new Uint8Array(first);
109
- } else if (mime === "image/jpeg") {
109
+ } else {
110
110
  const jpegMod = jpeg.default ?? jpeg;
111
111
  const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });
112
112
  width = decoded.width;
113
113
  height = decoded.height;
114
114
  rgba = decoded.data;
115
- } else {
116
- const decoded = decodeTga(bytes);
117
- width = decoded.width;
118
- height = decoded.height;
119
- rgba = decoded.bytes;
120
115
  }
121
116
  } catch (e) {
122
117
  return err(
@@ -153,78 +148,6 @@ function parseImage(bytes, mime, opts = {}) {
153
148
  mipmap: opts.mipmap ?? true
154
149
  });
155
150
  }
156
- function decodeTga(bytes) {
157
- if (bytes.length < 18) throw new Error("TGA header is truncated");
158
- const colorMapType = bytes[1];
159
- const imageType = bytes[2];
160
- const idLength = bytes[0] ?? 0;
161
- const width = (bytes[12] ?? 0) | (bytes[13] ?? 0) << 8;
162
- const height = (bytes[14] ?? 0) | (bytes[15] ?? 0) << 8;
163
- const pixelDepth = bytes[16] ?? 0;
164
- const descriptor = bytes[17] ?? 0;
165
- if (colorMapType !== 0) throw new Error("color-mapped TGA is unsupported");
166
- if (width < 1 || height < 1) throw new Error("TGA dimensions must be positive");
167
- const isTrueColor = imageType === 2 || imageType === 10;
168
- const isGray = imageType === 3 || imageType === 11;
169
- if (!isTrueColor && !isGray) throw new Error(`TGA image type ${imageType} is unsupported`);
170
- if (isTrueColor && pixelDepth !== 24 && pixelDepth !== 32) {
171
- throw new Error(`TGA true-color depth ${pixelDepth} is unsupported`);
172
- }
173
- if (isGray && pixelDepth !== 8)
174
- throw new Error(`TGA grayscale depth ${pixelDepth} is unsupported`);
175
- const bytesPerPixel = pixelDepth / 8;
176
- let offset = 18 + idLength;
177
- const pixelCount = width * height;
178
- const out = new Uint8Array(pixelCount * 4);
179
- const topOrigin = (descriptor & 32) !== 0;
180
- const rightOrigin = (descriptor & 16) !== 0;
181
- let filePixel = 0;
182
- const writePixel = (pixel) => {
183
- if (filePixel >= pixelCount) throw new Error("TGA pixel data has too many pixels");
184
- const fileX = filePixel % width;
185
- const fileY = Math.floor(filePixel / width);
186
- const x = rightOrigin ? width - 1 - fileX : fileX;
187
- const y = topOrigin ? fileY : height - 1 - fileY;
188
- const destination = (y * width + x) * 4;
189
- if (isGray) {
190
- const value = pixel[0] ?? 0;
191
- out[destination] = value;
192
- out[destination + 1] = value;
193
- out[destination + 2] = value;
194
- out[destination + 3] = 255;
195
- } else {
196
- out[destination] = pixel[2] ?? 0;
197
- out[destination + 1] = pixel[1] ?? 0;
198
- out[destination + 2] = pixel[0] ?? 0;
199
- out[destination + 3] = bytesPerPixel === 4 ? pixel[3] ?? 255 : 255;
200
- }
201
- filePixel += 1;
202
- };
203
- const readPixel = () => {
204
- if (offset + bytesPerPixel > bytes.length) throw new Error("TGA pixel data is truncated");
205
- const pixel = bytes.slice(offset, offset + bytesPerPixel);
206
- offset += bytesPerPixel;
207
- return pixel;
208
- };
209
- if (imageType === 2 || imageType === 3) {
210
- while (filePixel < pixelCount) writePixel(readPixel());
211
- } else {
212
- while (filePixel < pixelCount) {
213
- if (offset >= bytes.length) throw new Error("TGA RLE packet header is truncated");
214
- const packet = bytes[offset++] ?? 0;
215
- const count = (packet & 127) + 1;
216
- if (filePixel + count > pixelCount) throw new Error("TGA RLE packet exceeds image bounds");
217
- if ((packet & 128) !== 0) {
218
- const pixel = readPixel();
219
- for (let i = 0; i < count; i++) writePixel(pixel);
220
- } else {
221
- for (let i = 0; i < count; i++) writePixel(readPixel());
222
- }
223
- }
224
- }
225
- if (filePixel !== pixelCount) throw new Error("TGA pixel count mismatch");
226
- return { width, height, bytes: out };
227
- }
228
151
 
229
152
  export { parseImage };
230
153
  //# sourceMappingURL=parse-image.mjs.map