@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
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { BasisEncodeMode } from '@forgeax/engine-codec/encode';
|
|
2
|
+
declare const COMPRESSION_MODES: readonly ["auto", "etc1s", "uastc", "none"];
|
|
3
|
+
/** 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"];
|
|
6
|
+
/** The resolved delivery encoding after 'auto' derivation. `'none'` = no encode. */
|
|
7
|
+
export type ResolvedEncodeMode = (typeof RESOLVED_ENCODE_MODES)[number];
|
|
8
|
+
/** Source signals that drive 'auto' derivation (D-12) and encoder params. */
|
|
9
|
+
export interface EncodeSourceInfo {
|
|
10
|
+
/** Color transfer of the source (from the sidecar importSettings). */
|
|
11
|
+
readonly colorSpace: 'srgb' | 'linear';
|
|
12
|
+
/** Whether the source is an HDR image (.hdr -> rgba16float). */
|
|
13
|
+
readonly isHdr: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Resolve the sidecar `compressionMode` into a concrete delivery encoding.
|
|
17
|
+
*
|
|
18
|
+
* D-12 'auto' derivation (zero new required inputs, derived from existing
|
|
19
|
+
* sidecar signals):
|
|
20
|
+
* - HDR source -> 'uastc-hdr' (BC6H target downstream)
|
|
21
|
+
* - colorSpace 'srgb' -> 'etc1s' (albedo / UI color)
|
|
22
|
+
* - colorSpace 'linear' -> 'uastc' (normals / ORM / data)
|
|
23
|
+
*
|
|
24
|
+
* Explicit modes pass through, except an explicit 'uastc' on an HDR source
|
|
25
|
+
* resolves to 'uastc-hdr' (there is no LDR UASTC path for HDR pixels). 'none'
|
|
26
|
+
* and 'etc1s' pass through verbatim.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveEncodeMode(mode: CompressionMode, source: EncodeSourceInfo): ResolvedEncodeMode;
|
|
29
|
+
/** Encoder parameters for a resolved delivery encoding. */
|
|
30
|
+
export interface BasisEncodeParams {
|
|
31
|
+
/** The codec-side delivery encoding. */
|
|
32
|
+
readonly mode: BasisEncodeMode;
|
|
33
|
+
/** Write the sRGB transfer function (LDR color only). */
|
|
34
|
+
readonly srgb: boolean;
|
|
35
|
+
/** ETC1S perceptual (sRGB) metric. */
|
|
36
|
+
readonly perceptual: boolean;
|
|
37
|
+
/** Wrap the UASTC-LDR payload in KTX2 zstd supercompression. */
|
|
38
|
+
readonly uastcSupercompression: boolean;
|
|
39
|
+
/** Encoder-side mip generation. M3 keeps this false (offline mips land in M5). */
|
|
40
|
+
readonly mipGen: boolean;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Map the sidecar mode + source into encoder parameters. Returns `null` for the
|
|
44
|
+
* 'none' path -- the caller keeps the uncompressed `.bin` path and never calls
|
|
45
|
+
* the encoder.
|
|
46
|
+
*/
|
|
47
|
+
export declare function basisEncodeParamsFor(mode: CompressionMode, source: EncodeSourceInfo): BasisEncodeParams | null;
|
|
48
|
+
/** A successful encode result: KTX2 bytes + the resolved delivery encoding. */
|
|
49
|
+
export interface EncodedTexture {
|
|
50
|
+
readonly ktx2: Uint8Array;
|
|
51
|
+
readonly mode: ResolvedEncodeMode;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Maximum source pixels the wasm32 Basis encoder accepts (4096x4096 = 16.78 Mpx
|
|
55
|
+
* = 1024*1024*16). This mirrors the raised `BASISU_ENCODER_MAX_SOURCE_IMAGE_PIXELS`
|
|
56
|
+
* ceiling patched into the encoder WASM (packages/codec/scripts/build-wasm.mjs).
|
|
57
|
+
* Sources above this are rejected fast with a structured `ktx2-encode-source-too-large`
|
|
58
|
+
* error rather than reaching the encoder and getting a silent 0-byte failure.
|
|
59
|
+
*/
|
|
60
|
+
export declare const MAX_ENCODE_SOURCE_PIXELS: number;
|
|
61
|
+
/** Failure result carrying a short reason (encoder-side or invalid request). */
|
|
62
|
+
export interface EncodeFailure {
|
|
63
|
+
readonly code: 'ktx2-encode-failed' | 'codec-init-failed' | 'ktx2-encode-source-too-large';
|
|
64
|
+
readonly mode: ResolvedEncodeMode;
|
|
65
|
+
readonly reason: string;
|
|
66
|
+
}
|
|
67
|
+
export type EncodeTextureResult = {
|
|
68
|
+
readonly ok: true;
|
|
69
|
+
readonly value: EncodedTexture;
|
|
70
|
+
} | {
|
|
71
|
+
readonly ok: false;
|
|
72
|
+
readonly error: EncodeFailure;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Encode source pixels into a Basis KTX2 texture per the sidecar mode.
|
|
76
|
+
*
|
|
77
|
+
* `pixels` is tight-packed RGBA: 8-bit RGBA for LDR sources, rgba16float bytes
|
|
78
|
+
* for HDR sources. Returns `{ ok: false }` with `mode: 'none'` if the sidecar
|
|
79
|
+
* mode resolves to 'none' -- the importer treats that as "no encode, keep the
|
|
80
|
+
* .bin path" rather than an error (see importer callsite w18).
|
|
81
|
+
*/
|
|
82
|
+
export declare function encodeTextureToKtx2(pixels: Uint8Array, width: number, height: number, mode: CompressionMode, source: EncodeSourceInfo): Promise<EncodeTextureResult>;
|
|
83
|
+
export {};
|
|
84
|
+
//# sourceMappingURL=ktx2-encode.d.ts.map
|
|
@@ -0,0 +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,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AW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,mBAAmB,GAAG,8BAA8B,CAAC;IAC3F,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,mBAAmB,GAC3B;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAA;CAAE,GACrD;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAA;CAAE,CAAC;AAE1D;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,UAAU,EAClB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,eAAe,EACrB,MAAM,EAAE,gBAAgB,GACvB,OAAO,CAAC,mBAAmB,CAAC,CAuD9B"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { basisEncode } from '@forgeax/engine-codec/encode';
|
|
2
|
+
|
|
3
|
+
// src/ktx2-encode.ts
|
|
4
|
+
var COMPRESSION_MODES = ["auto", "etc1s", "uastc", "none"];
|
|
5
|
+
var RESOLVED_ENCODE_MODES = ["etc1s", "uastc", "uastc-hdr", "none"];
|
|
6
|
+
function resolveEncodeMode(mode, source) {
|
|
7
|
+
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];
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function basisEncodeParamsFor(mode, source) {
|
|
20
|
+
const resolved = resolveEncodeMode(mode, source);
|
|
21
|
+
const srgbColor = source.colorSpace === "srgb";
|
|
22
|
+
switch (resolved) {
|
|
23
|
+
case RESOLVED_ENCODE_MODES[3]:
|
|
24
|
+
return null;
|
|
25
|
+
case RESOLVED_ENCODE_MODES[0]:
|
|
26
|
+
return {
|
|
27
|
+
mode: RESOLVED_ENCODE_MODES[0],
|
|
28
|
+
srgb: srgbColor,
|
|
29
|
+
perceptual: srgbColor,
|
|
30
|
+
uastcSupercompression: false,
|
|
31
|
+
mipGen: false
|
|
32
|
+
};
|
|
33
|
+
case RESOLVED_ENCODE_MODES[1]:
|
|
34
|
+
return {
|
|
35
|
+
mode: "uastc-ldr",
|
|
36
|
+
srgb: srgbColor,
|
|
37
|
+
perceptual: srgbColor,
|
|
38
|
+
uastcSupercompression: true,
|
|
39
|
+
mipGen: false
|
|
40
|
+
};
|
|
41
|
+
case RESOLVED_ENCODE_MODES[2]:
|
|
42
|
+
return {
|
|
43
|
+
mode: RESOLVED_ENCODE_MODES[2],
|
|
44
|
+
srgb: false,
|
|
45
|
+
perceptual: false,
|
|
46
|
+
uastcSupercompression: false,
|
|
47
|
+
mipGen: false
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
var MAX_ENCODE_SOURCE_PIXELS = 4096 * 4096;
|
|
52
|
+
async function encodeTextureToKtx2(pixels, width, height, mode, source) {
|
|
53
|
+
const params = basisEncodeParamsFor(mode, source);
|
|
54
|
+
if (params === null) {
|
|
55
|
+
return {
|
|
56
|
+
ok: false,
|
|
57
|
+
error: {
|
|
58
|
+
code: "ktx2-encode-failed",
|
|
59
|
+
mode: "none",
|
|
60
|
+
reason: "compressionMode resolved to none"
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const resolved = resolveEncodeMode(mode, source);
|
|
65
|
+
if (width * height > MAX_ENCODE_SOURCE_PIXELS) {
|
|
66
|
+
return {
|
|
67
|
+
ok: false,
|
|
68
|
+
error: {
|
|
69
|
+
code: "ktx2-encode-source-too-large",
|
|
70
|
+
mode: resolved,
|
|
71
|
+
reason: `source ${width}x${height} (${width * height} px) exceeds the ${MAX_ENCODE_SOURCE_PIXELS} px (4096x4096) Basis encode ceiling; reduce the texture resolution to <=4096x4096 or set compressionMode:'none' in the sidecar to keep it uncompressed`
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const result = await basisEncode(pixels, {
|
|
76
|
+
mode: params.mode,
|
|
77
|
+
width,
|
|
78
|
+
height,
|
|
79
|
+
srgb: params.srgb,
|
|
80
|
+
perceptual: params.perceptual,
|
|
81
|
+
uastcSupercompression: params.uastcSupercompression,
|
|
82
|
+
mipGen: params.mipGen
|
|
83
|
+
});
|
|
84
|
+
if (!result.ok) {
|
|
85
|
+
const reason = result.error.detail !== void 0 && "reason" in result.error.detail ? String(result.error.detail.reason) : result.error.code;
|
|
86
|
+
return {
|
|
87
|
+
ok: false,
|
|
88
|
+
error: {
|
|
89
|
+
code: result.error.code === "codec-init-failed" ? "codec-init-failed" : "ktx2-encode-failed",
|
|
90
|
+
mode: resolved,
|
|
91
|
+
reason
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return { ok: true, value: { ktx2: result.value, mode: resolved } };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export { MAX_ENCODE_SOURCE_PIXELS, basisEncodeParamsFor, encodeTextureToKtx2, resolveEncodeMode };
|
|
99
|
+
//# sourceMappingURL=ktx2-encode.mjs.map
|
|
100
|
+
//# sourceMappingURL=ktx2-encode.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ktx2-encode.ts"],"names":[],"mappings":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G5F,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"]}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';
|
|
2
|
+
import type { Result } from './result.js';
|
|
3
|
+
export interface ParseImageOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Maximum allowed dimension (width or height). Defaults to 16384 -- the
|
|
6
|
+
* conservative WebGPU `maxTextureDimension2D` floor across desktop +
|
|
7
|
+
* high-end mobile (research F-3 / spec). Test fixtures pass smaller
|
|
8
|
+
* values to exercise the bounds-check code path with tiny fixtures.
|
|
9
|
+
*/
|
|
10
|
+
readonly maxDimension?: number;
|
|
11
|
+
/** Optional asset-owned cooked-payload target; source bytes remain unchanged. */
|
|
12
|
+
readonly downscaleMaxDimension?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Sidecar `colorSpace` carried over to the DecodedImage POD. Defaults to
|
|
15
|
+
* 'srgb' (typical baseColor / albedo path; plan-strategy section 2.5).
|
|
16
|
+
*/
|
|
17
|
+
readonly colorSpace?: ImageColorSpace;
|
|
18
|
+
/**
|
|
19
|
+
* Sidecar `mipmap` flag carried over to DecodedImage. Defaults to true
|
|
20
|
+
* (auto-generate via runtime mipmap-generator; plan-strategy section 2.6).
|
|
21
|
+
*/
|
|
22
|
+
readonly mipmap?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Optional source path to embed in error.detail.path (decode-failed /
|
|
25
|
+
* format-unsupported variants). decodeImageFromFile fills this in;
|
|
26
|
+
* in-memory parseImage callers leave it empty.
|
|
27
|
+
*/
|
|
28
|
+
readonly path?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Pure synchronous image decoder. Translates raw byte stream + mime hint
|
|
32
|
+
* into a tight-packed RGBA `DecodedImage` POD. Surfaces all four
|
|
33
|
+
* ImageErrorCode members through the structured `Result<DecodedImage,
|
|
34
|
+
* ImageError>` return (charter P3 explicit failure; AGENTS.md "Return
|
|
35
|
+
* Result, never throw").
|
|
36
|
+
*
|
|
37
|
+
* Decoder selection follows the mime hint:
|
|
38
|
+
* - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`
|
|
39
|
+
* - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`
|
|
40
|
+
* - `image/x-tga` -> the built-in TGA true-color/grayscale decoder
|
|
41
|
+
* - other -> `image-format-unsupported`
|
|
42
|
+
*
|
|
43
|
+
* Decoded bytes are always tight-packed RGBA (`bytes.length === width *
|
|
44
|
+
* height * 4`). `colorSpace` and `mipmap` are carried from the supplied
|
|
45
|
+
* `ParseImageOptions` (decodeImageFromFile passes the sidecar settings).
|
|
46
|
+
*/
|
|
47
|
+
export declare function parseImage(bytes: Uint8Array, mime: string, opts?: ParseImageOptions): Result<DecodedImage, ImageError>;
|
|
48
|
+
//# sourceMappingURL=parse-image.d.ts.map
|
|
@@ -0,0 +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;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAE/B,iFAAiF;IACjF,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAExC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,eAAe,CAAC;IAEtC;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAE1B;;;;OAIG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AAkBD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,UAAU,EACjB,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,iBAAsB,GAC3B,MAAM,CAAC,YAAY,EAAE,UAAU,CAAC,CAmGlC"}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import * as jpeg from 'jpeg-js';
|
|
2
|
+
import * as UPNG from 'upng-js';
|
|
3
|
+
import { err, ok, IMAGE_ERROR_HINTS } from '@forgeax/engine-types';
|
|
4
|
+
|
|
5
|
+
// src/parse-image.ts
|
|
6
|
+
var IMAGE_ERROR_EXPECTED = {
|
|
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",
|
|
9
|
+
"image-dimension-out-of-bounds": "width and height fall under device caps maxTextureDimension2D (or 16384 hard cap)",
|
|
10
|
+
"image-meta-missing": "<source>.meta.json sidecar (importer: 'image') exists in the same directory",
|
|
11
|
+
"image-hdr-decode-failed": "Radiance RGBE header is valid and pixel data decodes successfully",
|
|
12
|
+
// feat-20260521-sprite-atlas-animation M1 T-03 — vite-plugin-image atlas
|
|
13
|
+
// hook .expected literals (plan-strategy section 2 D-2 + AC-10 a/b/c).
|
|
14
|
+
// ImageErrorImpl construction path is unchanged: the new atlas-* errors
|
|
15
|
+
// flow through `new ImageErrorImpl({ code: 'atlas-...', ...detail })` and
|
|
16
|
+
// pick the .expected string up from this Record at construction time
|
|
17
|
+
// (charter P3 explicit failure SSOT — AI users surface .expected next to
|
|
18
|
+
// .hint after switch (err.code) without parsing the message).
|
|
19
|
+
"atlas-empty-input": "images.length >= 1",
|
|
20
|
+
"atlas-size-exceeded": "image width x height <= maxAtlasSize^2 and each image fits in the atlas footprint",
|
|
21
|
+
"atlas-region-mismatch": "sum(regions[i].w x regions[i].h) <= atlasWidth x atlasHeight"
|
|
22
|
+
};
|
|
23
|
+
var ImageErrorImpl = class extends Error {
|
|
24
|
+
code;
|
|
25
|
+
expected;
|
|
26
|
+
hint;
|
|
27
|
+
detail;
|
|
28
|
+
constructor(detail) {
|
|
29
|
+
const code = detail.code;
|
|
30
|
+
const expected = IMAGE_ERROR_EXPECTED[code];
|
|
31
|
+
const hint = IMAGE_ERROR_HINTS[code];
|
|
32
|
+
super(`[ImageError ${code}] expected: ${expected}; hint: ${hint}`);
|
|
33
|
+
this.name = "ImageError";
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.expected = expected;
|
|
36
|
+
this.hint = hint;
|
|
37
|
+
this.detail = detail;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
function imageError(detail) {
|
|
41
|
+
return new ImageErrorImpl(detail);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/resize-image.ts
|
|
45
|
+
function downscaleRgba(bytes, width, height, maxDimension) {
|
|
46
|
+
if (width <= maxDimension && height <= maxDimension) {
|
|
47
|
+
return { bytes, width, height };
|
|
48
|
+
}
|
|
49
|
+
const scale = maxDimension / Math.max(width, height);
|
|
50
|
+
const targetWidth = Math.max(1, Math.round(width * scale));
|
|
51
|
+
const targetHeight = Math.max(1, Math.round(height * scale));
|
|
52
|
+
const output = new Uint8Array(targetWidth * targetHeight * 4);
|
|
53
|
+
const source = (x, y, channel) => bytes[(y * width + x) * 4 + channel] ?? 0;
|
|
54
|
+
for (let y = 0; y < targetHeight; y += 1) {
|
|
55
|
+
const sourceY = (y + 0.5) * height / targetHeight - 0.5;
|
|
56
|
+
const y0 = Math.max(0, Math.floor(sourceY));
|
|
57
|
+
const y1 = Math.min(height - 1, y0 + 1);
|
|
58
|
+
const yWeight = Math.max(0, Math.min(1, sourceY - y0));
|
|
59
|
+
for (let x = 0; x < targetWidth; x += 1) {
|
|
60
|
+
const sourceX = (x + 0.5) * width / targetWidth - 0.5;
|
|
61
|
+
const x0 = Math.max(0, Math.floor(sourceX));
|
|
62
|
+
const x1 = Math.min(width - 1, x0 + 1);
|
|
63
|
+
const xWeight = Math.max(0, Math.min(1, sourceX - x0));
|
|
64
|
+
const outputOffset = (y * targetWidth + x) * 4;
|
|
65
|
+
for (let channel = 0; channel < 4; channel += 1) {
|
|
66
|
+
const top = source(x0, y0, channel) * (1 - xWeight) + source(x1, y0, channel) * xWeight;
|
|
67
|
+
const bottom = source(x0, y1, channel) * (1 - xWeight) + source(x1, y1, channel) * xWeight;
|
|
68
|
+
output[outputOffset + channel] = Math.round(top * (1 - yWeight) + bottom * yWeight);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { bytes: output, width: targetWidth, height: targetHeight };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// src/parse-image.ts
|
|
76
|
+
var DEFAULT_MAX_DIMENSION = 16384;
|
|
77
|
+
var SUPPORTED_MIMES = ["image/png", "image/jpeg", "image/x-tga"];
|
|
78
|
+
function parseImage(bytes, mime, opts = {}) {
|
|
79
|
+
if (!SUPPORTED_MIMES.includes(mime)) {
|
|
80
|
+
return err(
|
|
81
|
+
imageError({
|
|
82
|
+
code: "image-format-unsupported",
|
|
83
|
+
actualMime: mime,
|
|
84
|
+
...opts.path !== void 0 ? { path: opts.path } : {}
|
|
85
|
+
})
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
let width = 0;
|
|
89
|
+
let height = 0;
|
|
90
|
+
let rgba;
|
|
91
|
+
try {
|
|
92
|
+
if (mime === "image/png") {
|
|
93
|
+
const upngMod = UPNG.default ?? UPNG;
|
|
94
|
+
const decoded = upngMod.decode(bytes);
|
|
95
|
+
width = decoded.width;
|
|
96
|
+
height = decoded.height;
|
|
97
|
+
const frames = upngMod.toRGBA8(decoded);
|
|
98
|
+
const first = frames[0];
|
|
99
|
+
if (first === void 0) {
|
|
100
|
+
return err(
|
|
101
|
+
imageError({
|
|
102
|
+
code: "image-decode-failed",
|
|
103
|
+
reason: "UPNG.toRGBA8 returned no frames",
|
|
104
|
+
...opts.path !== void 0 ? { path: opts.path } : {}
|
|
105
|
+
})
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
rgba = new Uint8Array(first);
|
|
109
|
+
} else if (mime === "image/jpeg") {
|
|
110
|
+
const jpegMod = jpeg.default ?? jpeg;
|
|
111
|
+
const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });
|
|
112
|
+
width = decoded.width;
|
|
113
|
+
height = decoded.height;
|
|
114
|
+
rgba = decoded.data;
|
|
115
|
+
} else {
|
|
116
|
+
const decoded = decodeTga(bytes);
|
|
117
|
+
width = decoded.width;
|
|
118
|
+
height = decoded.height;
|
|
119
|
+
rgba = decoded.bytes;
|
|
120
|
+
}
|
|
121
|
+
} catch (e) {
|
|
122
|
+
return err(
|
|
123
|
+
imageError({
|
|
124
|
+
code: "image-decode-failed",
|
|
125
|
+
reason: e instanceof Error ? e.message : String(e),
|
|
126
|
+
...opts.path !== void 0 ? { path: opts.path } : {}
|
|
127
|
+
})
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
const downscaleLimit = opts.downscaleMaxDimension;
|
|
131
|
+
if (downscaleLimit !== void 0 && Number.isInteger(downscaleLimit) && downscaleLimit > 0) {
|
|
132
|
+
const downscaled = downscaleRgba(rgba, width, height, downscaleLimit);
|
|
133
|
+
rgba = downscaled.bytes;
|
|
134
|
+
width = downscaled.width;
|
|
135
|
+
height = downscaled.height;
|
|
136
|
+
}
|
|
137
|
+
const limit = opts.maxDimension ?? DEFAULT_MAX_DIMENSION;
|
|
138
|
+
if (width > limit || height > limit) {
|
|
139
|
+
return err(
|
|
140
|
+
imageError({
|
|
141
|
+
code: "image-dimension-out-of-bounds",
|
|
142
|
+
requested: { width, height },
|
|
143
|
+
limit
|
|
144
|
+
})
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
return ok({
|
|
148
|
+
bytes: rgba,
|
|
149
|
+
width,
|
|
150
|
+
height,
|
|
151
|
+
mime,
|
|
152
|
+
colorSpace: opts.colorSpace ?? "srgb",
|
|
153
|
+
mipmap: opts.mipmap ?? true
|
|
154
|
+
});
|
|
155
|
+
}
|
|
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
|
+
|
|
229
|
+
export { parseImage };
|
|
230
|
+
//# sourceMappingURL=parse-image.mjs.map
|
|
231
|
+
//# sourceMappingURL=parse-image.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/resize-image.ts","../src/parse-image.ts"],"names":[],"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,CAAA;AAGO,IAAM,cAAA,GAAN,cACG,KAAA,CAEV;AAAA,EACW,IAAA;AAAA,EACA,QAAA;AAAA,EACA,IAAA;AAAA,EACA,MAA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,MAAM,KAAA,GAAA,CAAS,SAAS,GAAA,IAAQ,CAAA;AAChC,MAAA,IAAI,YAAY,KAAA,GAAQ,UAAA,EAAY,MAAM,IAAI,MAAM,qCAAqC,CAAA;AACzF,MAAA,IAAA,CAAK,MAAA,GAAS,SAAU,CAAA,EAAG;AACzB,QAAA,MAAM,QAAQ,SAAA,EAAU;AACxB,QAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,KAAA,EAAO,CAAA,EAAA,aAAgB,KAAK,CAAA;AAAA,MAClD,CAAA,MAAO;AACL,QAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,OAAO,CAAA,EAAA,EAAK,UAAA,CAAW,WAAW,CAAA;AAAA,MACxD;AAAA,IACF;AAAA,EACF;AAEA,EAAA,IAAI,SAAA,KAAc,UAAA,EAAY,MAAM,IAAI,MAAM,0BAA0B,CAAA;AACxE,EAAA,OAAO,EAAE,KAAA,EAAO,MAAA,EAAQ,KAAA,EAAO,GAAA,EAAI;AACrC","file":"parse-image.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","/** Deterministically downscale tight-packed RGBA pixels with bilinear sampling. */\nexport function downscaleRgba(\n bytes: Uint8Array,\n width: number,\n height: number,\n maxDimension: number,\n): { readonly bytes: Uint8Array; readonly width: number; readonly height: number } {\n if (width <= maxDimension && height <= maxDimension) {\n return { bytes, width, height };\n }\n\n const scale = maxDimension / Math.max(width, height);\n const targetWidth = Math.max(1, Math.round(width * scale));\n const targetHeight = Math.max(1, Math.round(height * scale));\n const output = new Uint8Array(targetWidth * targetHeight * 4);\n const source = (x: number, y: number, channel: number): number =>\n bytes[(y * width + x) * 4 + channel] ?? 0;\n\n for (let y = 0; y < targetHeight; y += 1) {\n const sourceY = ((y + 0.5) * height) / targetHeight - 0.5;\n const y0 = Math.max(0, Math.floor(sourceY));\n const y1 = Math.min(height - 1, y0 + 1);\n const yWeight = Math.max(0, Math.min(1, sourceY - y0));\n for (let x = 0; x < targetWidth; x += 1) {\n const sourceX = ((x + 0.5) * width) / targetWidth - 0.5;\n const x0 = Math.max(0, Math.floor(sourceX));\n const x1 = Math.min(width - 1, x0 + 1);\n const xWeight = Math.max(0, Math.min(1, sourceX - x0));\n const outputOffset = (y * targetWidth + x) * 4;\n for (let channel = 0; channel < 4; channel += 1) {\n const top = source(x0, y0, channel) * (1 - xWeight) + source(x1, y0, channel) * xWeight;\n const bottom = source(x0, y1, channel) * (1 - xWeight) + source(x1, y1, channel) * xWeight;\n output[outputOffset + channel] = Math.round(top * (1 - yWeight) + bottom * yWeight);\n }\n }\n }\n\n return { bytes: output, width: targetWidth, height: targetHeight };\n}\n","import type { DecodedImage, ImageColorSpace, ImageError } from '@forgeax/engine-types';\nimport * as jpeg from 'jpeg-js';\n// Static imports of upng-js + jpeg-js. tsup external keeps both as runtime\n// require() calls so the browser bundle still tree-shakes them out when\n// only image-decoder-browser.ts (createImageBitmap) is reached at runtime.\n// Synchronous decode is required by the parseImage signature contract (see\n// plan-strategy section 3.3).\nimport * as UPNG from 'upng-js';\nimport { imageError } from './errors.js';\nimport { downscaleRgba } from './resize-image.js';\nimport type { Result } from './result.js';\nimport { err, ok } from './result.js';\n\nexport interface ParseImageOptions {\n /**\n * Maximum allowed dimension (width or height). Defaults to 16384 -- the\n * conservative WebGPU `maxTextureDimension2D` floor across desktop +\n * high-end mobile (research F-3 / spec). Test fixtures pass smaller\n * values to exercise the bounds-check code path with tiny fixtures.\n */\n readonly maxDimension?: number;\n\n /** Optional asset-owned cooked-payload target; source bytes remain unchanged. */\n readonly downscaleMaxDimension?: number;\n\n /**\n * Sidecar `colorSpace` carried over to the DecodedImage POD. Defaults to\n * 'srgb' (typical baseColor / albedo path; plan-strategy section 2.5).\n */\n readonly colorSpace?: ImageColorSpace;\n\n /**\n * Sidecar `mipmap` flag carried over to DecodedImage. Defaults to true\n * (auto-generate via runtime mipmap-generator; plan-strategy section 2.6).\n */\n readonly mipmap?: boolean;\n\n /**\n * Optional source path to embed in error.detail.path (decode-failed /\n * format-unsupported variants). decodeImageFromFile fills this in;\n * in-memory parseImage callers leave it empty.\n */\n readonly path?: string;\n}\n\nconst DEFAULT_MAX_DIMENSION = 16384;\n\nconst SUPPORTED_MIMES: readonly string[] = ['image/png', 'image/jpeg', 'image/x-tga'];\n\ninterface UpngDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\ninterface JpegDecoded {\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\n/**\n * Pure synchronous image decoder. Translates raw byte stream + mime hint\n * into a tight-packed RGBA `DecodedImage` POD. Surfaces all four\n * ImageErrorCode members through the structured `Result<DecodedImage,\n * ImageError>` return (charter P3 explicit failure; AGENTS.md \"Return\n * Result, never throw\").\n *\n * Decoder selection follows the mime hint:\n * - `image/png` -> upng-js `UPNG.decode` + `UPNG.toRGBA8`\n * - `image/jpeg` -> jpeg-js `decode` with `formatAsRGBA: true`\n * - `image/x-tga` -> the built-in TGA true-color/grayscale decoder\n * - other -> `image-format-unsupported`\n *\n * Decoded bytes are always tight-packed RGBA (`bytes.length === width *\n * height * 4`). `colorSpace` and `mipmap` are carried from the supplied\n * `ParseImageOptions` (decodeImageFromFile passes the sidecar settings).\n */\nexport function parseImage(\n bytes: Uint8Array,\n mime: string,\n opts: ParseImageOptions = {},\n): Result<DecodedImage, ImageError> {\n if (!SUPPORTED_MIMES.includes(mime)) {\n return err(\n imageError({\n code: 'image-format-unsupported',\n actualMime: mime,\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n let width = 0;\n let height = 0;\n let rgba: Uint8Array;\n\n try {\n if (mime === 'image/png') {\n const upngMod: {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n } = ((UPNG as unknown as { default?: typeof UPNG }).default ?? UPNG) as unknown as {\n decode: (b: Uint8Array | ArrayBuffer) => UpngDecoded;\n toRGBA8: (i: UpngDecoded) => ArrayBuffer[];\n };\n const decoded = upngMod.decode(bytes);\n width = decoded.width;\n height = decoded.height;\n const frames = upngMod.toRGBA8(decoded);\n const first = frames[0];\n if (first === undefined) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: 'UPNG.toRGBA8 returned no frames',\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n rgba = new Uint8Array(first);\n } else if (mime === 'image/jpeg') {\n // image/jpeg\n const jpegMod: {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n } = ((jpeg as unknown as { default?: typeof jpeg }).default ?? jpeg) as unknown as {\n decode: (\n b: Uint8Array | ArrayBuffer,\n o?: { useTArray?: boolean; formatAsRGBA?: boolean },\n ) => JpegDecoded;\n };\n const decoded = jpegMod.decode(bytes, { useTArray: true, formatAsRGBA: true });\n width = decoded.width;\n height = decoded.height;\n rgba = decoded.data;\n } else {\n const decoded = decodeTga(bytes);\n width = decoded.width;\n height = decoded.height;\n rgba = decoded.bytes;\n }\n } catch (e) {\n return err(\n imageError({\n code: 'image-decode-failed',\n reason: e instanceof Error ? e.message : String(e),\n ...(opts.path !== undefined ? { path: opts.path } : {}),\n }),\n );\n }\n\n const downscaleLimit = opts.downscaleMaxDimension;\n if (downscaleLimit !== undefined && Number.isInteger(downscaleLimit) && downscaleLimit > 0) {\n const downscaled = downscaleRgba(rgba, width, height, downscaleLimit);\n rgba = downscaled.bytes;\n width = downscaled.width;\n height = downscaled.height;\n }\n\n const limit = opts.maxDimension ?? DEFAULT_MAX_DIMENSION;\n if (width > limit || height > limit) {\n return err(\n imageError({\n code: 'image-dimension-out-of-bounds',\n requested: { width, height },\n limit,\n }),\n );\n }\n\n return ok({\n bytes: rgba,\n width,\n height,\n mime: mime as 'image/png' | 'image/jpeg' | 'image/x-tga',\n colorSpace: opts.colorSpace ?? 'srgb',\n mipmap: opts.mipmap ?? true,\n });\n}\n\ninterface TgaDecoded {\n readonly width: number;\n readonly height: number;\n readonly bytes: Uint8Array;\n}\n\n/**\n * Decode the portable TGA subset used by common FBX exports.\n *\n * The decoder owns the format boundary instead of trusting the extension: it\n * validates the header, supports uncompressed and RLE true-colour (24/32-bit)\n * plus grayscale (8-bit), and applies the origin bits from the image\n * descriptor while producing a top-left RGBA POD.\n */\nfunction decodeTga(bytes: Uint8Array): TgaDecoded {\n if (bytes.length < 18) throw new Error('TGA header is truncated');\n\n const colorMapType = bytes[1];\n const imageType = bytes[2];\n const idLength = bytes[0] ?? 0;\n const width = (bytes[12] ?? 0) | ((bytes[13] ?? 0) << 8);\n const height = (bytes[14] ?? 0) | ((bytes[15] ?? 0) << 8);\n const pixelDepth = bytes[16] ?? 0;\n const descriptor = bytes[17] ?? 0;\n if (colorMapType !== 0) throw new Error('color-mapped TGA is unsupported');\n if (width < 1 || height < 1) throw new Error('TGA dimensions must be positive');\n\n const isTrueColor = imageType === 2 || imageType === 10;\n const isGray = imageType === 3 || imageType === 11;\n if (!isTrueColor && !isGray) throw new Error(`TGA image type ${imageType} is unsupported`);\n if (isTrueColor && pixelDepth !== 24 && pixelDepth !== 32) {\n throw new Error(`TGA true-color depth ${pixelDepth} is unsupported`);\n }\n if (isGray && pixelDepth !== 8)\n throw new Error(`TGA grayscale depth ${pixelDepth} is unsupported`);\n\n const bytesPerPixel = pixelDepth / 8;\n let offset = 18 + idLength;\n const pixelCount = width * height;\n const out = new Uint8Array(pixelCount * 4);\n const topOrigin = (descriptor & 0x20) !== 0;\n const rightOrigin = (descriptor & 0x10) !== 0;\n let filePixel = 0;\n\n const writePixel = (pixel: Uint8Array): void => {\n if (filePixel >= pixelCount) throw new Error('TGA pixel data has too many pixels');\n const fileX = filePixel % width;\n const fileY = Math.floor(filePixel / width);\n const x = rightOrigin ? width - 1 - fileX : fileX;\n const y = topOrigin ? fileY : height - 1 - fileY;\n const destination = (y * width + x) * 4;\n if (isGray) {\n const value = pixel[0] ?? 0;\n out[destination] = value;\n out[destination + 1] = value;\n out[destination + 2] = value;\n out[destination + 3] = 255;\n } else {\n out[destination] = pixel[2] ?? 0;\n out[destination + 1] = pixel[1] ?? 0;\n out[destination + 2] = pixel[0] ?? 0;\n out[destination + 3] = bytesPerPixel === 4 ? (pixel[3] ?? 255) : 255;\n }\n filePixel += 1;\n };\n\n const readPixel = (): Uint8Array => {\n if (offset + bytesPerPixel > bytes.length) throw new Error('TGA pixel data is truncated');\n const pixel = bytes.slice(offset, offset + bytesPerPixel);\n offset += bytesPerPixel;\n return pixel;\n };\n\n if (imageType === 2 || imageType === 3) {\n while (filePixel < pixelCount) writePixel(readPixel());\n } else {\n while (filePixel < pixelCount) {\n if (offset >= bytes.length) throw new Error('TGA RLE packet header is truncated');\n const packet = bytes[offset++] ?? 0;\n const count = (packet & 0x7f) + 1;\n if (filePixel + count > pixelCount) throw new Error('TGA RLE packet exceeds image bounds');\n if ((packet & 0x80) !== 0) {\n const pixel = readPixel();\n for (let i = 0; i < count; i++) writePixel(pixel);\n } else {\n for (let i = 0; i < count; i++) writePixel(readPixel());\n }\n }\n }\n\n if (filePixel !== pixelCount) throw new Error('TGA pixel count mismatch');\n return { width, height, bytes: out };\n}\n"]}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { DecodedImage, ImageColorSpace } from '@forgeax/engine-types';
|
|
2
|
+
/**
|
|
3
|
+
* Existing `*.meta.json` (importer: 'image') sub-asset record (free-form sub-shape; the
|
|
4
|
+
* meta.schema.json $defs/subAsset locks `guid` + `sourceIndex` + `kind` only).
|
|
5
|
+
* Image importer treats the open shape as a key-bearing tuple; the gltf-loader
|
|
6
|
+
* feat works on the same shape.
|
|
7
|
+
*/
|
|
8
|
+
export interface ExistingSubAsset {
|
|
9
|
+
readonly guid: string;
|
|
10
|
+
readonly sourceIndex: number;
|
|
11
|
+
readonly kind: string;
|
|
12
|
+
readonly name?: string;
|
|
13
|
+
readonly sourceKey?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Existing `*.meta.json` (importer: 'image') package record. Mirrors the
|
|
17
|
+
* meta.schema.json $defs/ExternalAssetPackage shape (research F-9). Only
|
|
18
|
+
* the fields consumed by the reimport reuse algorithm are typed here;
|
|
19
|
+
* importSettings stays a free-form open shape.
|
|
20
|
+
*/
|
|
21
|
+
export interface ExistingExternalAssetPackage {
|
|
22
|
+
readonly schemaVersion: string;
|
|
23
|
+
readonly kind: 'external-asset-package';
|
|
24
|
+
readonly importer: 'image';
|
|
25
|
+
readonly source: string;
|
|
26
|
+
readonly importSettings: Readonly<Record<string, unknown>>;
|
|
27
|
+
readonly subAssets: readonly ExistingSubAsset[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Sub-asset record emitted into the regenerated `*.meta.json` (importer: 'image')
|
|
31
|
+
* `subAssets[]` slot. Shape matches `ExistingSubAsset` so two consecutive
|
|
32
|
+
* reimports of byte-identical bytes produce byte-identical JSON
|
|
33
|
+
* (AC-16 byte-stable reimport guarantee).
|
|
34
|
+
*/
|
|
35
|
+
export interface EmittedSubAsset {
|
|
36
|
+
readonly guid: string;
|
|
37
|
+
readonly sourceIndex: number;
|
|
38
|
+
readonly kind: string;
|
|
39
|
+
readonly name?: string;
|
|
40
|
+
readonly sourceKey?: string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Two-phase reimport reuse algorithm (plan-strategy section 2.2 D-4
|
|
44
|
+
* mirroring the in-flight gltf-loader algorithm).
|
|
45
|
+
*
|
|
46
|
+
* For each fresh sub-asset key the importer would emit, this function:
|
|
47
|
+
* 1. Searches the `existing.subAssets[]` for a `subAssetKeyEqual` hit.
|
|
48
|
+
* 2. On hit -- reuses the existing GUID byte-for-byte.
|
|
49
|
+
* 3. On miss -- mints a fresh UUIDv7 via `AssetGuid.random()`.
|
|
50
|
+
*
|
|
51
|
+
* Image disk schema currently emits a single `kind='texture'` sub-asset per
|
|
52
|
+
* source (cubemap face / array layer reserved for future feat); the
|
|
53
|
+
* algorithm scales to multi-sub-asset sources without modification (charter
|
|
54
|
+
* P5 consistent abstraction).
|
|
55
|
+
*
|
|
56
|
+
* Returns the regenerated `subAssets[]` array. The caller (toAssetPack /
|
|
57
|
+
* runAssetImport) splices it into the `*.meta.json` (importer: 'image') envelope.
|
|
58
|
+
*/
|
|
59
|
+
export declare function reimportReuseMeta(decoded: DecodedImage, existing: ExistingExternalAssetPackage | undefined): readonly EmittedSubAsset[];
|
|
60
|
+
/**
|
|
61
|
+
* HDR colorSpace validator for *.image.meta.json sidecar importSettings
|
|
62
|
+
* (plan-strategy D-8 -- HDR files must use colorSpace=linear).
|
|
63
|
+
*
|
|
64
|
+
* Extension is matched case-insensitively against the HDR set
|
|
65
|
+
* (`.hdr`, `.exr`). When the extension belongs to the HDR set:
|
|
66
|
+
* - `colorSpace='linear'` -> ok, returns `'linear'`
|
|
67
|
+
* - any other colorSpace -> structured rejection with expected/actual
|
|
68
|
+
*
|
|
69
|
+
* Non-HDR extensions pass through the colorSpace unchanged. Downstream
|
|
70
|
+
* callers (decodeImageFromFile, parseImage) invoke this at the
|
|
71
|
+
* sidecar-read entry to fail-fast when an .hdr meta carries srgb.
|
|
72
|
+
*/
|
|
73
|
+
export declare function validateColorSpaceForHdr(ext: string, colorSpace: ImageColorSpace): {
|
|
74
|
+
ok: true;
|
|
75
|
+
value: ImageColorSpace;
|
|
76
|
+
} | {
|
|
77
|
+
ok: false;
|
|
78
|
+
expected: string;
|
|
79
|
+
actual: string;
|
|
80
|
+
};
|
|
81
|
+
//# sourceMappingURL=reimport-reuse-meta.d.ts.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AG,SAAS,GACjD,SAAS,eAAe,EAAE,CA0D5B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,eAAe,GAC1B;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,eAAe,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAaxF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Deterministically downscale tight-packed RGBA pixels with bilinear sampling. */
|
|
2
|
+
export declare function downscaleRgba(bytes: Uint8Array, width: number, height: number, maxDimension: number): {
|
|
3
|
+
readonly bytes: Uint8Array;
|
|
4
|
+
readonly width: number;
|
|
5
|
+
readonly height: number;
|
|
6
|
+
};
|
|
7
|
+
//# sourceMappingURL=resize-image.d.ts.map
|