@forgeax/engine-image 0.1.2
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.
- package/LICENSE +202 -0
- package/README.md +168 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/__tests__/compression-mode.unit.test.d.ts +2 -0
- package/dist/__tests__/compression-mode.unit.test.d.ts.map +1 -0
- package/dist/__tests__/encode-source-too-large.unit.test.d.ts +2 -0
- package/dist/__tests__/encode-source-too-large.unit.test.d.ts.map +1 -0
- package/dist/__tests__/errors.test-d.d.ts +2 -0
- package/dist/__tests__/errors.test-d.d.ts.map +1 -0
- package/dist/__tests__/image-importer-conversion-failure.unit.test.d.ts +2 -0
- package/dist/__tests__/image-importer-conversion-failure.unit.test.d.ts.map +1 -0
- package/dist/__tests__/image-importer-hdr-equirect.test.d.ts +2 -0
- package/dist/__tests__/image-importer-hdr-equirect.test.d.ts.map +1 -0
- package/dist/__tests__/image-importer-topology.unit.test.d.ts +2 -0
- package/dist/__tests__/image-importer-topology.unit.test.d.ts.map +1 -0
- package/dist/__tests__/image-importer.test.d.ts +2 -0
- package/dist/__tests__/image-importer.test.d.ts.map +1 -0
- package/dist/__tests__/image-local-artifacts.test.d.ts +2 -0
- package/dist/__tests__/image-local-artifacts.test.d.ts.map +1 -0
- package/dist/__tests__/image.unit.test.d.ts +2 -0
- package/dist/__tests__/image.unit.test.d.ts.map +1 -0
- package/dist/__tests__/ktx2-basis-importer.unit.test.d.ts +2 -0
- package/dist/__tests__/ktx2-basis-importer.unit.test.d.ts.map +1 -0
- package/dist/__tests__/ktx2-encode-mode-owner.test-d.d.ts +2 -0
- package/dist/__tests__/ktx2-encode-mode-owner.test-d.d.ts.map +1 -0
- package/dist/__tests__/make-fixture.d.ts +12 -0
- package/dist/__tests__/make-fixture.d.ts.map +1 -0
- package/dist/__tests__/parse-image-downscale.test.d.ts +2 -0
- package/dist/__tests__/parse-image-downscale.test.d.ts.map +1 -0
- package/dist/__tests__/runtime-decode.unit.test.d.ts +2 -0
- package/dist/__tests__/runtime-decode.unit.test.d.ts.map +1 -0
- package/dist/__tests__/source-key.unit.test.d.ts +2 -0
- package/dist/__tests__/source-key.unit.test.d.ts.map +1 -0
- package/dist/__tests__/tga.unit.test.d.ts +2 -0
- package/dist/__tests__/tga.unit.test.d.ts.map +1 -0
- package/dist/decode-image-from-file.d.ts +40 -0
- package/dist/decode-image-from-file.d.ts.map +1 -0
- package/dist/decode-image-from-file.mjs +590 -0
- package/dist/decode-image-from-file.mjs.map +1 -0
- package/dist/errors.d.ts +14 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/hdr-decoder.d.ts +28 -0
- package/dist/hdr-decoder.d.ts.map +1 -0
- package/dist/hdr-decoder.mjs +212 -0
- package/dist/hdr-decoder.mjs.map +1 -0
- package/dist/image-decoder-browser.d.ts +22 -0
- package/dist/image-decoder-browser.d.ts.map +1 -0
- package/dist/image-decoder-node.d.ts +50 -0
- package/dist/image-decoder-node.d.ts.map +1 -0
- package/dist/image-importer.d.ts +15 -0
- package/dist/image-importer.d.ts.map +1 -0
- package/dist/image-importer.mjs +1107 -0
- package/dist/image-importer.mjs.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +503 -0
- package/dist/index.mjs.map +1 -0
- package/dist/ktx2-encode.d.ts +84 -0
- package/dist/ktx2-encode.d.ts.map +1 -0
- package/dist/ktx2-encode.mjs +100 -0
- package/dist/ktx2-encode.mjs.map +1 -0
- package/dist/parse-image.d.ts +48 -0
- package/dist/parse-image.d.ts.map +1 -0
- package/dist/parse-image.mjs +231 -0
- package/dist/parse-image.mjs.map +1 -0
- package/dist/reimport-reuse-meta.d.ts +81 -0
- package/dist/reimport-reuse-meta.d.ts.map +1 -0
- package/dist/resize-image.d.ts +7 -0
- package/dist/resize-image.d.ts.map +1 -0
- package/dist/result.d.ts +2 -0
- package/dist/result.d.ts.map +1 -0
- package/dist/runtime/__tests__/asset-decoders.unit.test.d.ts +2 -0
- package/dist/runtime/__tests__/asset-decoders.unit.test.d.ts.map +1 -0
- package/dist/runtime/asset-decoders.d.ts +4 -0
- package/dist/runtime/asset-decoders.d.ts.map +1 -0
- package/dist/runtime/decode-image-bytes.d.ts +7 -0
- package/dist/runtime/decode-image-bytes.d.ts.map +1 -0
- package/dist/runtime/image-error.d.ts +3 -0
- package/dist/runtime/image-error.d.ts.map +1 -0
- package/dist/source-key.d.ts +21 -0
- package/dist/source-key.d.ts.map +1 -0
- package/dist/sub-asset-key.d.ts +50 -0
- package/dist/sub-asset-key.d.ts.map +1 -0
- package/dist/to-asset-pack.d.ts +61 -0
- package/dist/to-asset-pack.d.ts.map +1 -0
- package/package.json +105 -0
- package/src/__tests__/compression-mode.unit.test.ts +104 -0
- package/src/__tests__/encode-source-too-large.unit.test.ts +81 -0
- package/src/__tests__/errors.test-d.ts +148 -0
- package/src/__tests__/image-importer-conversion-failure.unit.test.ts +297 -0
- package/src/__tests__/image-importer-hdr-equirect.test.ts +218 -0
- package/src/__tests__/image-importer-topology.unit.test.ts +209 -0
- package/src/__tests__/image-importer.test.ts +12 -0
- package/src/__tests__/image-local-artifacts.test.ts +38 -0
- package/src/__tests__/image.unit.test.ts +1387 -0
- package/src/__tests__/ktx2-basis-importer.unit.test.ts +126 -0
- package/src/__tests__/ktx2-encode-mode-owner.test-d.ts +70 -0
- package/src/__tests__/make-fixture.ts +100 -0
- package/src/__tests__/parse-image-downscale.test.ts +26 -0
- package/src/__tests__/runtime-decode.unit.test.ts +22 -0
- package/src/__tests__/source-key.unit.test.ts +65 -0
- package/src/__tests__/tga.unit.test.ts +59 -0
- package/src/decode-image-from-file.ts +298 -0
- package/src/errors.ts +60 -0
- package/src/hdr-decoder.ts +255 -0
- package/src/image-decoder-browser.ts +88 -0
- package/src/image-decoder-node.ts +67 -0
- package/src/image-decoders.d.ts +23 -0
- package/src/image-importer.ts +780 -0
- package/src/index.ts +46 -0
- package/src/ktx2-encode.ts +221 -0
- package/src/parse-image.ts +276 -0
- package/src/reimport-reuse-meta.ts +160 -0
- package/src/resize-image.ts +39 -0
- package/src/result.ts +13 -0
- package/src/runtime/__tests__/asset-decoders.unit.test.ts +66 -0
- package/src/runtime/asset-decoders.ts +152 -0
- package/src/runtime/decode-image-bytes.ts +41 -0
- package/src/runtime/image-error.ts +8 -0
- package/src/source-key.ts +41 -0
- package/src/sub-asset-key.ts +67 -0
- package/src/to-asset-pack.ts +95 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// @forgeax/engine-image -- main entry public surface.
|
|
2
|
+
//
|
|
3
|
+
// Browser-safe pure functions translate disk-side image bytes + sidecar
|
|
4
|
+
// settings into POD that the runtime Render DeviceScope path consumes
|
|
5
|
+
// (plan-strategy section 3.2 sequence A; charter P5 producer /
|
|
6
|
+
// consumer split). Node-only decoders (parseImage / decodeImageFromFile)
|
|
7
|
+
// are split into Node-only sub-exports per feat-20260524-browser-safe-subexports
|
|
8
|
+
// and are NOT re-exported from this main entry -- import them via:
|
|
9
|
+
// - `@forgeax/engine-image/parse-image` (Node-only sub-export)
|
|
10
|
+
// - `@forgeax/engine-image/decode-image-from-file` (Node-only sub-export)
|
|
11
|
+
//
|
|
12
|
+
// Main entry surface (browser-safe):
|
|
13
|
+
// - decodeImageInBrowser -- browser-mode createImageBitmap path
|
|
14
|
+
// - toAssetPack(decoded, meta) -- POD -> external-asset-package envelope
|
|
15
|
+
// - subAssetKey / subAssetKeyEqual -- gltf-aligned sub-asset matching
|
|
16
|
+
// - reimportReuseMeta -- two-phase GUID preservation
|
|
17
|
+
// - imageError / ImageErrorImpl -- structured 4-field error class
|
|
18
|
+
// - decodeHdr -- HDR sub-export passthrough (legacy)
|
|
19
|
+
// - loadJpeg / loadUpng -- lazy Node decoder loaders (legacy; OOS-2)
|
|
20
|
+
|
|
21
|
+
export { IMAGE_ERROR_EXPECTED, ImageErrorImpl, imageError } from './errors.js';
|
|
22
|
+
export { decodeHdr } from './hdr-decoder.js';
|
|
23
|
+
export { decodeImageInBrowser } from './image-decoder-browser.js';
|
|
24
|
+
export type { JpegModule, UpngModule } from './image-decoder-node.js';
|
|
25
|
+
export { loadJpeg, loadUpng } from './image-decoder-node.js';
|
|
26
|
+
export type {
|
|
27
|
+
EmittedSubAsset,
|
|
28
|
+
ExistingExternalAssetPackage,
|
|
29
|
+
ExistingSubAsset,
|
|
30
|
+
} from './reimport-reuse-meta.js';
|
|
31
|
+
export { reimportReuseMeta } from './reimport-reuse-meta.js';
|
|
32
|
+
export type { Result, ResultErr, ResultOk } from './result.js';
|
|
33
|
+
export { err, ok } from './result.js';
|
|
34
|
+
export { equirectContribution, textureContribution } from './runtime/asset-decoders.js';
|
|
35
|
+
export { decodeImageBytes } from './runtime/decode-image-bytes.js';
|
|
36
|
+
export { runtimeImageError } from './runtime/image-error.js';
|
|
37
|
+
export type { ImageSourceKeyLocator } from './source-key.js';
|
|
38
|
+
export { deriveImageSourceKey } from './source-key.js';
|
|
39
|
+
export type { SubAssetKey, SubAssetKeyInput } from './sub-asset-key.js';
|
|
40
|
+
export { subAssetKey, subAssetKeyEqual } from './sub-asset-key.js';
|
|
41
|
+
export type {
|
|
42
|
+
ExternalAssetPackage,
|
|
43
|
+
ExternalSubAsset,
|
|
44
|
+
ImageImportSettings,
|
|
45
|
+
} from './to-asset-pack.js';
|
|
46
|
+
export { toAssetPack } from './to-asset-pack.js';
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// ktx2-encode.ts -- the image-side offline texture encode arm (M3 w18, D-5).
|
|
2
|
+
//
|
|
3
|
+
// This module is the image-semantic layer of the Basis encode path: it maps the
|
|
4
|
+
// sidecar `compressionMode` control-plane value + the source's colorSpace / HDR
|
|
5
|
+
// signal into a delivery encoding (D-12 'auto' derivation), maps that to the
|
|
6
|
+
// encoder parameters, and drives the low-level `basisEncode` binding that lives
|
|
7
|
+
// in `@forgeax/engine-codec/encode` (the WASM + enum plumbing stays in codec;
|
|
8
|
+
// the image semantics stay here -- D-5 "arm in image, binary in codec/encode").
|
|
9
|
+
//
|
|
10
|
+
// It is a NODE-ONLY build-time module (consumed by imageImporter, itself a
|
|
11
|
+
// node-only sub-export). It never touches GPU (isolation path b) and is never
|
|
12
|
+
// bundled into the runtime (isolation path a/d: runtime does not import
|
|
13
|
+
// @forgeax/engine-image nor @forgeax/engine-codec/encode).
|
|
14
|
+
//
|
|
15
|
+
// M3 sequencing constraint (plan R-9): the 'auto' derivation is implemented and
|
|
16
|
+
// tested here, but the sidecar DEFAULT stays 'none'. The default flip to 'auto'
|
|
17
|
+
// is M5 (w38); doing it here would make every existing texture encode to Basis
|
|
18
|
+
// ahead of loader support and redden the whole fixture fleet.
|
|
19
|
+
|
|
20
|
+
import type { BasisEncodeMode } from '@forgeax/engine-codec/encode';
|
|
21
|
+
import { basisEncode } from '@forgeax/engine-codec/encode';
|
|
22
|
+
|
|
23
|
+
const COMPRESSION_MODES = ['auto', 'etc1s', 'uastc', 'none'] as const;
|
|
24
|
+
|
|
25
|
+
/** The sidecar control-plane value (ImageMetadata.compressionMode). */
|
|
26
|
+
export type CompressionMode = (typeof COMPRESSION_MODES)[number];
|
|
27
|
+
|
|
28
|
+
const RESOLVED_ENCODE_MODES = ['etc1s', 'uastc', 'uastc-hdr', 'none'] as const;
|
|
29
|
+
|
|
30
|
+
/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */
|
|
31
|
+
export type ResolvedEncodeMode = (typeof RESOLVED_ENCODE_MODES)[number];
|
|
32
|
+
|
|
33
|
+
/** Source signals that drive 'auto' derivation (D-12) and encoder params. */
|
|
34
|
+
export interface EncodeSourceInfo {
|
|
35
|
+
/** Color transfer of the source (from the sidecar importSettings). */
|
|
36
|
+
readonly colorSpace: 'srgb' | 'linear';
|
|
37
|
+
/** Whether the source is an HDR image (.hdr -> rgba16float). */
|
|
38
|
+
readonly isHdr: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the sidecar `compressionMode` into a concrete delivery encoding.
|
|
43
|
+
*
|
|
44
|
+
* D-12 'auto' derivation (zero new required inputs, derived from existing
|
|
45
|
+
* sidecar signals):
|
|
46
|
+
* - HDR source -> 'uastc-hdr' (BC6H target downstream)
|
|
47
|
+
* - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)
|
|
48
|
+
* - colorSpace 'linear' -> 'uastc' (normals / ORM / data)
|
|
49
|
+
*
|
|
50
|
+
* Explicit modes pass through, except an explicit 'uastc' on an HDR source
|
|
51
|
+
* resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'
|
|
52
|
+
* and 'etc1s' pass through verbatim.
|
|
53
|
+
*/
|
|
54
|
+
export function resolveEncodeMode(
|
|
55
|
+
mode: CompressionMode,
|
|
56
|
+
source: EncodeSourceInfo,
|
|
57
|
+
): ResolvedEncodeMode {
|
|
58
|
+
switch (mode) {
|
|
59
|
+
case COMPRESSION_MODES[3]:
|
|
60
|
+
return RESOLVED_ENCODE_MODES[3];
|
|
61
|
+
case COMPRESSION_MODES[1]:
|
|
62
|
+
return RESOLVED_ENCODE_MODES[0];
|
|
63
|
+
case COMPRESSION_MODES[2]:
|
|
64
|
+
return source.isHdr ? RESOLVED_ENCODE_MODES[2] : RESOLVED_ENCODE_MODES[1];
|
|
65
|
+
case COMPRESSION_MODES[0]:
|
|
66
|
+
if (source.isHdr) return RESOLVED_ENCODE_MODES[2];
|
|
67
|
+
return source.colorSpace === 'srgb' ? RESOLVED_ENCODE_MODES[0] : RESOLVED_ENCODE_MODES[1];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Encoder parameters for a resolved delivery encoding. */
|
|
72
|
+
export interface BasisEncodeParams {
|
|
73
|
+
/** The codec-side delivery encoding. */
|
|
74
|
+
readonly mode: BasisEncodeMode;
|
|
75
|
+
/** Write the sRGB transfer function (LDR color only). */
|
|
76
|
+
readonly srgb: boolean;
|
|
77
|
+
/** ETC1S perceptual (sRGB) metric. */
|
|
78
|
+
readonly perceptual: boolean;
|
|
79
|
+
/** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */
|
|
80
|
+
readonly uastcSupercompression: boolean;
|
|
81
|
+
/** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */
|
|
82
|
+
readonly mipGen: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Map the sidecar mode + source into encoder parameters. Returns `null` for the
|
|
87
|
+
* 'none' path -- the caller keeps the uncompressed `.bin` path and never calls
|
|
88
|
+
* the encoder.
|
|
89
|
+
*/
|
|
90
|
+
export function basisEncodeParamsFor(
|
|
91
|
+
mode: CompressionMode,
|
|
92
|
+
source: EncodeSourceInfo,
|
|
93
|
+
): BasisEncodeParams | null {
|
|
94
|
+
const resolved = resolveEncodeMode(mode, source);
|
|
95
|
+
const srgbColor = source.colorSpace === 'srgb';
|
|
96
|
+
switch (resolved) {
|
|
97
|
+
case RESOLVED_ENCODE_MODES[3]:
|
|
98
|
+
return null;
|
|
99
|
+
case RESOLVED_ENCODE_MODES[0]:
|
|
100
|
+
return {
|
|
101
|
+
mode: RESOLVED_ENCODE_MODES[0],
|
|
102
|
+
srgb: srgbColor,
|
|
103
|
+
perceptual: srgbColor,
|
|
104
|
+
uastcSupercompression: false,
|
|
105
|
+
mipGen: false,
|
|
106
|
+
};
|
|
107
|
+
case RESOLVED_ENCODE_MODES[1]:
|
|
108
|
+
return {
|
|
109
|
+
mode: 'uastc-ldr',
|
|
110
|
+
srgb: srgbColor,
|
|
111
|
+
perceptual: srgbColor,
|
|
112
|
+
uastcSupercompression: true,
|
|
113
|
+
mipGen: false,
|
|
114
|
+
};
|
|
115
|
+
case RESOLVED_ENCODE_MODES[2]:
|
|
116
|
+
return {
|
|
117
|
+
mode: RESOLVED_ENCODE_MODES[2],
|
|
118
|
+
srgb: false,
|
|
119
|
+
perceptual: false,
|
|
120
|
+
uastcSupercompression: false,
|
|
121
|
+
mipGen: false,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */
|
|
127
|
+
export interface EncodedTexture {
|
|
128
|
+
readonly ktx2: Uint8Array;
|
|
129
|
+
readonly mode: ResolvedEncodeMode;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx
|
|
134
|
+
* = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`
|
|
135
|
+
* ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).
|
|
136
|
+
* Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`
|
|
137
|
+
* error rather than reaching the encoder and getting a silent 0-byte failure.
|
|
138
|
+
*/
|
|
139
|
+
export const MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;
|
|
140
|
+
|
|
141
|
+
/** Failure result carrying a short reason (encoder-side or invalid request). */
|
|
142
|
+
export interface EncodeFailure {
|
|
143
|
+
readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';
|
|
144
|
+
readonly mode: ResolvedEncodeMode;
|
|
145
|
+
readonly reason: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export type EncodeTextureResult =
|
|
149
|
+
| { readonly ok: true; readonly value: EncodedTexture }
|
|
150
|
+
| { readonly ok: false; readonly error: EncodeFailure };
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Encode source pixels into a Basis KTX2 texture per the sidecar mode.
|
|
154
|
+
*
|
|
155
|
+
* `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes
|
|
156
|
+
* for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar
|
|
157
|
+
* mode resolves to 'none' -- the importer treats that as "no encode, keep the
|
|
158
|
+
* .bin path" rather than an error (see importer callsite w18).
|
|
159
|
+
*/
|
|
160
|
+
export async function encodeTextureToKtx2(
|
|
161
|
+
pixels: Uint8Array,
|
|
162
|
+
width: number,
|
|
163
|
+
height: number,
|
|
164
|
+
mode: CompressionMode,
|
|
165
|
+
source: EncodeSourceInfo,
|
|
166
|
+
): Promise<EncodeTextureResult> {
|
|
167
|
+
const params = basisEncodeParamsFor(mode, source);
|
|
168
|
+
if (params === null) {
|
|
169
|
+
return {
|
|
170
|
+
ok: false,
|
|
171
|
+
error: {
|
|
172
|
+
code: 'ktx2-encode-failed',
|
|
173
|
+
mode: 'none',
|
|
174
|
+
reason: 'compressionMode resolved to none',
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
const resolved = resolveEncodeMode(mode, source);
|
|
179
|
+
// Fail fast above the wasm32 encoder's source-pixel ceiling (4096^2). Above
|
|
180
|
+
// this the encoder returns 0 bytes silently; surface a structured, actionable
|
|
181
|
+
// error instead so the importer reports "reduce resolution or set
|
|
182
|
+
// compressionMode:'none'" rather than an opaque encode failure.
|
|
183
|
+
if (width * height > MAX_ENCODE_SOURCE_PIXELS) {
|
|
184
|
+
return {
|
|
185
|
+
ok: false,
|
|
186
|
+
error: {
|
|
187
|
+
code: 'ktx2-encode-source-too-large',
|
|
188
|
+
mode: resolved,
|
|
189
|
+
reason:
|
|
190
|
+
`source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px ` +
|
|
191
|
+
'(4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 ' +
|
|
192
|
+
"or set compressionMode:'none' in the sidecar to keep it uncompressed",
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const result = await basisEncode(pixels, {
|
|
197
|
+
mode: params.mode,
|
|
198
|
+
width,
|
|
199
|
+
height,
|
|
200
|
+
srgb: params.srgb,
|
|
201
|
+
perceptual: params.perceptual,
|
|
202
|
+
uastcSupercompression: params.uastcSupercompression,
|
|
203
|
+
mipGen: params.mipGen,
|
|
204
|
+
});
|
|
205
|
+
if (!result.ok) {
|
|
206
|
+
const reason =
|
|
207
|
+
result.error.detail !== undefined && 'reason' in result.error.detail
|
|
208
|
+
? String((result.error.detail as { reason: unknown }).reason)
|
|
209
|
+
: result.error.code;
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
error: {
|
|
213
|
+
code:
|
|
214
|
+
result.error.code === 'codec-init-failed' ? 'codec-init-failed' : 'ktx2-encode-failed',
|
|
215
|
+
mode: resolved,
|
|
216
|
+
reason,
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
return { ok: true, value: { ktx2: result.value, mode: resolved } };
|
|
221
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';
|
|
2
|
+
import * as jpeg from 'jpeg-js';
|
|
3
|
+
// Static imports of upng-js + jpeg-js. tsup external keeps both as runtime
|
|
4
|
+
// require() calls so the browser bundle still tree-shakes them out when
|
|
5
|
+
// only image-decoder-browser.ts (createImageBitmap) is reached at runtime.
|
|
6
|
+
// Synchronous decode is required by the parseImage signature contract (see
|
|
7
|
+
// plan-strategy section 3.3).
|
|
8
|
+
import * as UPNG from 'upng-js';
|
|
9
|
+
import { imageError } from './errors.js';
|
|
10
|
+
import { downscaleRgba } from './resize-image.js';
|
|
11
|
+
import type { Result } from './result.js';
|
|
12
|
+
import { err, ok } from './result.js';
|
|
13
|
+
|
|
14
|
+
export interface ParseImageOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Maximum allowed dimension (width or height). Defaults to 16384 -- the
|
|
17
|
+
* conservative WebGPU `maxTextureDimension2D` floor across desktop +
|
|
18
|
+
* high-end mobile (research F-3 / spec). Test fixtures pass smaller
|
|
19
|
+
* values to exercise the bounds-check code path with tiny fixtures.
|
|
20
|
+
*/
|
|
21
|
+
readonly maxDimension?: number;
|
|
22
|
+
|
|
23
|
+
/** Optional asset-owned cooked-payload target; source bytes remain unchanged. */
|
|
24
|
+
readonly downscaleMaxDimension?: number;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Sidecar `colorSpace` carried over to the DecodedImage POD. Defaults to
|
|
28
|
+
* 'srgb' (typical baseColor / albedo path; plan-strategy section 2.5).
|
|
29
|
+
*/
|
|
30
|
+
readonly colorSpace?: ImageColorSpace;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Sidecar `mipmap` flag carried over to DecodedImage. Defaults to true
|
|
34
|
+
* (auto-generate via runtime mipmap-generator; plan-strategy section 2.6).
|
|
35
|
+
*/
|
|
36
|
+
readonly mipmap?: boolean;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Optional source path to embed in error.detail.path (decode-failed /
|
|
40
|
+
* format-unsupported variants). decodeImageFromFile fills this in;
|
|
41
|
+
* in-memory parseImage callers leave it empty.
|
|
42
|
+
*/
|
|
43
|
+
readonly path?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const DEFAULT_MAX_DIMENSION = 16384;
|
|
47
|
+
|
|
48
|
+
const SUPPORTED_MIMES: readonly string[] = ['image/png', 'image/jpeg', 'image/x-tga'];
|
|
49
|
+
|
|
50
|
+
interface UpngDecoded {
|
|
51
|
+
readonly width: number;
|
|
52
|
+
readonly height: number;
|
|
53
|
+
readonly data: Uint8Array;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface JpegDecoded {
|
|
57
|
+
readonly width: number;
|
|
58
|
+
readonly height: number;
|
|
59
|
+
readonly data: Uint8Array;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Pure synchronous image decoder. Translates raw byte stream + mime hint
|
|
64
|
+
* into a tight-packed RGBA `DecodedImage` POD. Surfaces all four
|
|
65
|
+
* ImageErrorCode members through the structured `Result<DecodedImage,
|
|
66
|
+
* ImageError>` return (charter P3 explicit failure; AGENTS.md "Return
|
|
67
|
+
* Result, never throw").
|
|
68
|
+
*
|
|
69
|
+
* Decoder selection follows the mime hint:
|
|
70
|
+
* - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`
|
|
71
|
+
* - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`
|
|
72
|
+
* - `image/x-tga` -> the built-in TGA true-color/grayscale decoder
|
|
73
|
+
* - other -> `image-format-unsupported`
|
|
74
|
+
*
|
|
75
|
+
* Decoded bytes are always tight-packed RGBA (`bytes.length === width *
|
|
76
|
+
* height * 4`). `colorSpace` and `mipmap` are carried from the supplied
|
|
77
|
+
* `ParseImageOptions` (decodeImageFromFile passes the sidecar settings).
|
|
78
|
+
*/
|
|
79
|
+
export function parseImage(
|
|
80
|
+
bytes: Uint8Array,
|
|
81
|
+
mime: string,
|
|
82
|
+
opts: ParseImageOptions = {},
|
|
83
|
+
): Result<DecodedImage, ImageError> {
|
|
84
|
+
if (!SUPPORTED_MIMES.includes(mime)) {
|
|
85
|
+
return err(
|
|
86
|
+
imageError({
|
|
87
|
+
code: 'image-format-unsupported',
|
|
88
|
+
actualMime: mime,
|
|
89
|
+
...(opts.path !== undefined ? { path: opts.path } : {}),
|
|
90
|
+
}),
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
let width = 0;
|
|
95
|
+
let height = 0;
|
|
96
|
+
let rgba: Uint8Array;
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
if (mime === 'image/png') {
|
|
100
|
+
const upngMod: {
|
|
101
|
+
decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;
|
|
102
|
+
toRGBA8: (i: UpngDecoded) => ArrayBuffer[];
|
|
103
|
+
} = ((UPNG as unknown as { default?: typeof UPNG }).default ?? UPNG) as unknown as {
|
|
104
|
+
decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;
|
|
105
|
+
toRGBA8: (i: UpngDecoded) => ArrayBuffer[];
|
|
106
|
+
};
|
|
107
|
+
const decoded = upngMod.decode(bytes);
|
|
108
|
+
width = decoded.width;
|
|
109
|
+
height = decoded.height;
|
|
110
|
+
const frames = upngMod.toRGBA8(decoded);
|
|
111
|
+
const first = frames[0];
|
|
112
|
+
if (first === undefined) {
|
|
113
|
+
return err(
|
|
114
|
+
imageError({
|
|
115
|
+
code: 'image-decode-failed',
|
|
116
|
+
reason: 'UPNG.toRGBA8 returned no frames',
|
|
117
|
+
...(opts.path !== undefined ? { path: opts.path } : {}),
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
rgba = new Uint8Array(first);
|
|
122
|
+
} else if (mime === 'image/jpeg') {
|
|
123
|
+
// image/jpeg
|
|
124
|
+
const jpegMod: {
|
|
125
|
+
decode: (
|
|
126
|
+
b: Uint8Array | ArrayBuffer,
|
|
127
|
+
o?: { useTArray?: boolean; formatAsRGBA?: boolean },
|
|
128
|
+
) => JpegDecoded;
|
|
129
|
+
} = ((jpeg as unknown as { default?: typeof jpeg }).default ?? jpeg) as unknown as {
|
|
130
|
+
decode: (
|
|
131
|
+
b: Uint8Array | ArrayBuffer,
|
|
132
|
+
o?: { useTArray?: boolean; formatAsRGBA?: boolean },
|
|
133
|
+
) => JpegDecoded;
|
|
134
|
+
};
|
|
135
|
+
const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });
|
|
136
|
+
width = decoded.width;
|
|
137
|
+
height = decoded.height;
|
|
138
|
+
rgba = decoded.data;
|
|
139
|
+
} else {
|
|
140
|
+
const decoded = decodeTga(bytes);
|
|
141
|
+
width = decoded.width;
|
|
142
|
+
height = decoded.height;
|
|
143
|
+
rgba = decoded.bytes;
|
|
144
|
+
}
|
|
145
|
+
} catch (e) {
|
|
146
|
+
return err(
|
|
147
|
+
imageError({
|
|
148
|
+
code: 'image-decode-failed',
|
|
149
|
+
reason: e instanceof Error ? e.message : String(e),
|
|
150
|
+
...(opts.path !== undefined ? { path: opts.path } : {}),
|
|
151
|
+
}),
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const downscaleLimit = opts.downscaleMaxDimension;
|
|
156
|
+
if (downscaleLimit !== undefined && Number.isInteger(downscaleLimit) && downscaleLimit > 0) {
|
|
157
|
+
const downscaled = downscaleRgba(rgba, width, height, downscaleLimit);
|
|
158
|
+
rgba = downscaled.bytes;
|
|
159
|
+
width = downscaled.width;
|
|
160
|
+
height = downscaled.height;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const limit = opts.maxDimension ?? DEFAULT_MAX_DIMENSION;
|
|
164
|
+
if (width > limit || height > limit) {
|
|
165
|
+
return err(
|
|
166
|
+
imageError({
|
|
167
|
+
code: 'image-dimension-out-of-bounds',
|
|
168
|
+
requested: { width, height },
|
|
169
|
+
limit,
|
|
170
|
+
}),
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return ok({
|
|
175
|
+
bytes: rgba,
|
|
176
|
+
width,
|
|
177
|
+
height,
|
|
178
|
+
mime: mime as 'image/png' | 'image/jpeg' | 'image/x-tga',
|
|
179
|
+
colorSpace: opts.colorSpace ?? 'srgb',
|
|
180
|
+
mipmap: opts.mipmap ?? true,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
interface TgaDecoded {
|
|
185
|
+
readonly width: number;
|
|
186
|
+
readonly height: number;
|
|
187
|
+
readonly bytes: Uint8Array;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Decode the portable TGA subset used by common FBX exports.
|
|
192
|
+
*
|
|
193
|
+
* The decoder owns the format boundary instead of trusting the extension: it
|
|
194
|
+
* validates the header, supports uncompressed and RLE true-colour (24/32-bit)
|
|
195
|
+
* plus grayscale (8-bit), and applies the origin bits from the image
|
|
196
|
+
* descriptor while producing a top-left RGBA POD.
|
|
197
|
+
*/
|
|
198
|
+
function decodeTga(bytes: Uint8Array): TgaDecoded {
|
|
199
|
+
if (bytes.length < 18) throw new Error('TGA header is truncated');
|
|
200
|
+
|
|
201
|
+
const colorMapType = bytes[1];
|
|
202
|
+
const imageType = bytes[2];
|
|
203
|
+
const idLength = bytes[0] ?? 0;
|
|
204
|
+
const width = (bytes[12] ?? 0) | ((bytes[13] ?? 0) << 8);
|
|
205
|
+
const height = (bytes[14] ?? 0) | ((bytes[15] ?? 0) << 8);
|
|
206
|
+
const pixelDepth = bytes[16] ?? 0;
|
|
207
|
+
const descriptor = bytes[17] ?? 0;
|
|
208
|
+
if (colorMapType !== 0) throw new Error('color-mapped TGA is unsupported');
|
|
209
|
+
if (width < 1 || height < 1) throw new Error('TGA dimensions must be positive');
|
|
210
|
+
|
|
211
|
+
const isTrueColor = imageType === 2 || imageType === 10;
|
|
212
|
+
const isGray = imageType === 3 || imageType === 11;
|
|
213
|
+
if (!isTrueColor && !isGray) throw new Error(`TGA image type ${imageType} is unsupported`);
|
|
214
|
+
if (isTrueColor && pixelDepth !== 24 && pixelDepth !== 32) {
|
|
215
|
+
throw new Error(`TGA true-color depth ${pixelDepth} is unsupported`);
|
|
216
|
+
}
|
|
217
|
+
if (isGray && pixelDepth !== 8)
|
|
218
|
+
throw new Error(`TGA grayscale depth ${pixelDepth} is unsupported`);
|
|
219
|
+
|
|
220
|
+
const bytesPerPixel = pixelDepth / 8;
|
|
221
|
+
let offset = 18 + idLength;
|
|
222
|
+
const pixelCount = width * height;
|
|
223
|
+
const out = new Uint8Array(pixelCount * 4);
|
|
224
|
+
const topOrigin = (descriptor & 0x20) !== 0;
|
|
225
|
+
const rightOrigin = (descriptor & 0x10) !== 0;
|
|
226
|
+
let filePixel = 0;
|
|
227
|
+
|
|
228
|
+
const writePixel = (pixel: Uint8Array): void => {
|
|
229
|
+
if (filePixel >= pixelCount) throw new Error('TGA pixel data has too many pixels');
|
|
230
|
+
const fileX = filePixel % width;
|
|
231
|
+
const fileY = Math.floor(filePixel / width);
|
|
232
|
+
const x = rightOrigin ? width - 1 - fileX : fileX;
|
|
233
|
+
const y = topOrigin ? fileY : height - 1 - fileY;
|
|
234
|
+
const destination = (y * width + x) * 4;
|
|
235
|
+
if (isGray) {
|
|
236
|
+
const value = pixel[0] ?? 0;
|
|
237
|
+
out[destination] = value;
|
|
238
|
+
out[destination + 1] = value;
|
|
239
|
+
out[destination + 2] = value;
|
|
240
|
+
out[destination + 3] = 255;
|
|
241
|
+
} else {
|
|
242
|
+
out[destination] = pixel[2] ?? 0;
|
|
243
|
+
out[destination + 1] = pixel[1] ?? 0;
|
|
244
|
+
out[destination + 2] = pixel[0] ?? 0;
|
|
245
|
+
out[destination + 3] = bytesPerPixel === 4 ? (pixel[3] ?? 255) : 255;
|
|
246
|
+
}
|
|
247
|
+
filePixel += 1;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const readPixel = (): Uint8Array => {
|
|
251
|
+
if (offset + bytesPerPixel > bytes.length) throw new Error('TGA pixel data is truncated');
|
|
252
|
+
const pixel = bytes.slice(offset, offset + bytesPerPixel);
|
|
253
|
+
offset += bytesPerPixel;
|
|
254
|
+
return pixel;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
if (imageType === 2 || imageType === 3) {
|
|
258
|
+
while (filePixel < pixelCount) writePixel(readPixel());
|
|
259
|
+
} else {
|
|
260
|
+
while (filePixel < pixelCount) {
|
|
261
|
+
if (offset >= bytes.length) throw new Error('TGA RLE packet header is truncated');
|
|
262
|
+
const packet = bytes[offset++] ?? 0;
|
|
263
|
+
const count = (packet & 0x7f) + 1;
|
|
264
|
+
if (filePixel + count > pixelCount) throw new Error('TGA RLE packet exceeds image bounds');
|
|
265
|
+
if ((packet & 0x80) !== 0) {
|
|
266
|
+
const pixel = readPixel();
|
|
267
|
+
for (let i = 0; i < count; i++) writePixel(pixel);
|
|
268
|
+
} else {
|
|
269
|
+
for (let i = 0; i < count; i++) writePixel(readPixel());
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (filePixel !== pixelCount) throw new Error('TGA pixel count mismatch');
|
|
275
|
+
return { width, height, bytes: out };
|
|
276
|
+
}
|