@monogrid/gainmap-js 3.4.1 → 3.6.0

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 (61) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +111 -133
  3. package/dist/{QuadRenderer-Bl8ThfRL.js → QuadRenderer-CXtNzoCY.js} +1 -1
  4. package/dist/{QuadRenderer-D1rYlVRa.js → QuadRenderer-DcBTBLz6.js} +1 -1
  5. package/dist/{_commonjsHelpers-CHnLGTFq.js → _commonjsHelpers-Cdw2adc2.js} +1 -1
  6. package/dist/{_commonjsHelpers-D4ntYHBT.js → _commonjsHelpers-CnYhShyx.js} +1 -1
  7. package/dist/{compress-B5svUHuf.js → compress-C42bpk6O.js} +1 -1
  8. package/dist/{compress-DBGuVQfM.js → compress-CzMz2bpX.js} +1 -2
  9. package/dist/core/iso-gainmap-metadata.d.ts +40 -0
  10. package/dist/decode/shared/extract.d.ts +5 -3
  11. package/dist/decode/shared/index.d.ts +2 -0
  12. package/dist/decode/shared/utils/create-textures.d.ts +26 -0
  13. package/dist/decode/shared/utils/extractISO.d.ts +15 -0
  14. package/dist/decode/shared/utils/warn-deprecated.d.ts +8 -0
  15. package/dist/decode/webgl/decode.d.ts +1 -0
  16. package/dist/decode/webgl/index.d.ts +4 -0
  17. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +3 -1
  18. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +3 -1
  19. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +1 -0
  20. package/dist/decode/webgpu/core/QuadRenderer.d.ts +1 -0
  21. package/dist/decode/webgpu/decode.d.ts +1 -0
  22. package/dist/decode/webgpu/index.d.ts +7 -0
  23. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +3 -1
  24. package/dist/decode/webgpu/loaders/GainMapNodeLoader.d.ts +42 -0
  25. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +3 -1
  26. package/dist/decode/webgpu/loaders/HDRJPGNodeLoader.d.ts +41 -0
  27. package/dist/decode/webgpu/loaders/LoaderBaseNode.d.ts +24 -0
  28. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +1 -0
  29. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +137 -0
  30. package/dist/decode.js +18 -4
  31. package/dist/decode.min.js +2 -2
  32. package/dist/decode.umd.cjs +207 -36
  33. package/dist/decode.umd.min.cjs +2 -2
  34. package/dist/decode.webgpu.js +453 -8
  35. package/dist/decode.webgpu.min.js +2 -2
  36. package/dist/decode.webgpu.umd.cjs +644 -38
  37. package/dist/decode.webgpu.umd.min.cjs +2 -2
  38. package/dist/encode.js +4 -4
  39. package/dist/encode.min.js +2 -2
  40. package/dist/encode.umd.cjs +1 -2
  41. package/dist/encode.umd.min.cjs +1 -1
  42. package/dist/iso-gainmap-metadata-ByNqnUPn.js +141 -0
  43. package/dist/iso-gainmap-metadata-CEaaU7RT.js +5 -0
  44. package/dist/libultrahdr/jpeg-assembler.d.ts +2 -0
  45. package/dist/libultrahdr.js +30 -7
  46. package/dist/libultrahdr.min.js +2 -2
  47. package/dist/libultrahdr.umd.cjs +104 -7
  48. package/dist/libultrahdr.umd.min.cjs +2 -2
  49. package/dist/third-party.txt +69 -69
  50. package/dist/{Loader-Bi9FKrn4.js → warn-deprecated-Bk17fVbj.js} +117 -38
  51. package/dist/warn-deprecated-D0kPpXtA.js +5 -0
  52. package/dist/worker-interface.js +2 -2
  53. package/dist/worker-interface.min.js +2 -2
  54. package/dist/worker-interface.umd.cjs +1 -1
  55. package/dist/worker-interface.umd.min.cjs +1 -1
  56. package/dist/worker.js +3 -3
  57. package/dist/worker.min.js +2 -2
  58. package/dist/worker.umd.cjs +1 -2
  59. package/dist/worker.umd.min.cjs +1 -1
  60. package/package.json +34 -37
  61. package/dist/Loader-uEDs4JZg.js +0 -5
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.4.1
2
+ * @monogrid/gainmap-js v3.6.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -50,6 +50,120 @@
50
50
  class XMPMetadataNotFoundError extends Error {
51
51
  }
52
52
 
53
+ /**
54
+ * ISO 21496-1 binary gain map metadata (de)serialization
55
+ * Based on libultrahdr gainmapmetadata.cpp implementation
56
+ *
57
+ * Layout (big endian):
58
+ * - u16 minimum_version, u16 writer_version
59
+ * - u8 flags (bit 7: multichannel, bit 6: use base colour space, bit 2: backward direction, bit 3: common denominator)
60
+ * - headroom: base_hdr_headroom, alternate_hdr_headroom (unsigned fractions)
61
+ * - per channel: gain_map_min (s), gain_map_max (s), gamma (u), base_offset (s), alternate_offset (s)
62
+ *
63
+ * Fractions are written as numerator + denominator, or numerator only when the common denominator flag is set.
64
+ */
65
+ /**
66
+ * Namespace identifying an ISO 21496-1 APP2 segment (null terminated)
67
+ */
68
+ const ISO_NAMESPACE = 'urn:iso:std:iso:ts:21496:-1\0';
69
+ const IS_MULTICHANNEL_MASK = 1 << 7;
70
+ const USE_COMMON_DENOMINATOR_MASK = 1 << 3;
71
+ const BACKWARD_DIRECTION_MASK = 1 << 2;
72
+ /**
73
+ * Parses an ISO 21496-1 binary payload (without namespace)
74
+ *
75
+ * @param data
76
+ * @returns the parsed metadata
77
+ * @throws {Error} if the payload is unsupported (version, backward direction) or malformed
78
+ */
79
+ const decodeISOGainMapMetadata = (data) => {
80
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
81
+ let pos = 0;
82
+ const readU16 = () => { const v = view.getUint16(pos); pos += 2; return v; };
83
+ const readU32 = () => { const v = view.getUint32(pos); pos += 4; return v; };
84
+ const readS32 = () => { const v = view.getInt32(pos); pos += 4; return v; };
85
+ const minimumVersion = readU16();
86
+ if (minimumVersion !== 0)
87
+ throw new Error(`Unsupported ISO 21496-1 minimum_version ${minimumVersion}`);
88
+ readU16(); // writer_version
89
+ const flags = view.getUint8(pos++);
90
+ if (flags & BACKWARD_DIRECTION_MASK)
91
+ throw new Error('ISO 21496-1 metadata with HDR base image is not supported');
92
+ const channelCount = flags & IS_MULTICHANNEL_MASK ? 3 : 1;
93
+ const commonDenominator = flags & USE_COMMON_DENOMINATOR_MASK ? readU32() : undefined;
94
+ const readFraction = (signed) => {
95
+ const n = signed ? readS32() : readU32();
96
+ const d = commonDenominator ?? readU32();
97
+ if (d === 0)
98
+ throw new Error('Invalid ISO 21496-1 fraction with zero denominator');
99
+ return n / d;
100
+ };
101
+ const hdrCapacityMin = readFraction(false);
102
+ const hdrCapacityMax = readFraction(false);
103
+ // base headroom greater than alternate headroom means the base image is the HDR rendition
104
+ if (hdrCapacityMin > hdrCapacityMax)
105
+ throw new Error('ISO 21496-1 metadata with HDR base image is not supported');
106
+ const gainMapMin = [];
107
+ const gainMapMax = [];
108
+ const gamma = [];
109
+ const offsetSdr = [];
110
+ const offsetHdr = [];
111
+ for (let i = 0; i < channelCount; i++) {
112
+ gainMapMin.push(readFraction(true));
113
+ gainMapMax.push(readFraction(true));
114
+ gamma.push(readFraction(false));
115
+ offsetSdr.push(readFraction(true));
116
+ offsetHdr.push(readFraction(true));
117
+ }
118
+ const toRGB = (v) => (channelCount === 3 ? v : [v[0], v[0], v[0]]);
119
+ return {
120
+ gainMapMin: toRGB(gainMapMin),
121
+ gainMapMax: toRGB(gainMapMax),
122
+ gamma: toRGB(gamma),
123
+ offsetSdr: toRGB(offsetSdr),
124
+ offsetHdr: toRGB(offsetHdr),
125
+ hdrCapacityMin,
126
+ hdrCapacityMax
127
+ };
128
+ };
129
+
130
+ const ISO_SIGNATURE = Array.from(ISO_NAMESPACE, c => c.charCodeAt(0));
131
+ /**
132
+ * Extracts ISO 21496-1 gain map metadata from a JPEG file
133
+ *
134
+ * Looks for APP2 segments carrying the ISO 21496-1 namespace, skipping
135
+ * the version-only segment stored in the primary image.
136
+ *
137
+ * `0xFF 0xE2` cannot appear inside entropy-coded data, so a byte scan is safe.
138
+ *
139
+ * @category Decoding Functions
140
+ * @group Decoding Functions
141
+ * @param input an `Uint8Array` containing an encoded JPEG file
142
+ * @returns the parsed metadata or `undefined` if no supported ISO 21496-1 metadata is found
143
+ */
144
+ const extractISO = (input) => {
145
+ const view = new DataView(input.buffer, input.byteOffset, input.byteLength);
146
+ const payloadStart = 4 + ISO_SIGNATURE.length;
147
+ for (let i = 0; i + payloadStart < input.length; i++) {
148
+ if (input[i] !== 0xff || input[i + 1] !== 0xe2)
149
+ continue;
150
+ if (!ISO_SIGNATURE.every((c, j) => input[i + 4 + j] === c))
151
+ continue;
152
+ // segment length includes the 2 length bytes
153
+ const end = Math.min(input.length, i + 2 + view.getUint16(i + 2));
154
+ // version-only block in the primary image
155
+ if (end - (i + payloadStart) <= 4)
156
+ continue;
157
+ try {
158
+ return decodeISOGainMapMetadata(input.subarray(i + payloadStart, end));
159
+ }
160
+ catch (e) {
161
+ // unsupported or malformed, let the caller fall back to XMP
162
+ return;
163
+ }
164
+ }
165
+ };
166
+
53
167
  const getXMLValue = (xml, tag, defaultValue) => {
54
168
  // Check for attribute format first: tag="value"
55
169
  const attributeMatch = new RegExp(`${tag}="([^"]*)"`, 'i').exec(xml);
@@ -275,14 +389,16 @@
275
389
  }
276
390
 
277
391
  /**
278
- * Extracts XMP Metadata and the gain map recovery image
392
+ * Extracts gain map metadata and the gain map recovery image
279
393
  * from a single JPEG file.
280
394
  *
395
+ * ISO 21496-1 metadata is preferred when present, XMP (Ultra HDR / Adobe hdrgm) is used as fallback.
396
+ *
281
397
  * @category Decoding Functions
282
398
  * @group Decoding Functions
283
399
  * @param jpegFile an `Uint8Array` containing and encoded JPEG file
284
- * @returns an sdr `Uint8Array` compressed in JPEG, a gainMap `Uint8Array` compressed in JPEG and the XMP parsed XMP metadata
285
- * @throws Error if XMP Metadata is not found
400
+ * @returns an sdr `Uint8Array` compressed in JPEG, a gainMap `Uint8Array` compressed in JPEG and the parsed metadata
401
+ * @throws Error if neither ISO 21496-1 nor XMP Metadata is found
286
402
  * @throws Error if Gain map image is not found
287
403
  * @example
288
404
  * import { FileLoader } from 'three'
@@ -295,7 +411,7 @@
295
411
  * const { sdr, gainMap, metadata } = extractGainmapFromJPEG(jpegFile)
296
412
  */
297
413
  const extractGainmapFromJPEG = async (jpegFile) => {
298
- const metadata = extractXMP(jpegFile);
414
+ const metadata = extractISO(jpegFile) ?? extractXMP(jpegFile);
299
415
  if (!metadata)
300
416
  throw new XMPMetadataNotFoundError('Gain map XMP metadata not found');
301
417
  const mpfExtractor = new MPFExtractor({ extractFII: true, extractNonFII: true });
@@ -325,6 +441,57 @@
325
441
  });
326
442
  };
327
443
 
444
+ /**
445
+ * Decodes the SDR and (optional) gain map JPEG buffers into images
446
+ *
447
+ * @param sdrBuffer
448
+ * @param gainMapBuffer
449
+ * @param imageOrientation
450
+ * @returns
451
+ */
452
+ const processImages = async (sdrBuffer, gainMapBuffer, imageOrientation) => {
453
+ const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
454
+ const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
455
+ let sdrImage;
456
+ let gainMapImage;
457
+ let needsFlip = false;
458
+ if (typeof createImageBitmap === 'undefined') {
459
+ const res = await Promise.all([
460
+ gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
461
+ getHTMLImageFromBlob(sdrBlob)
462
+ ]);
463
+ gainMapImage = res[0];
464
+ sdrImage = res[1];
465
+ needsFlip = imageOrientation === 'flipY';
466
+ }
467
+ else {
468
+ const res = await Promise.all([
469
+ gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
470
+ createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
471
+ ]);
472
+ gainMapImage = res[0];
473
+ sdrImage = res[1];
474
+ }
475
+ return { sdrImage, gainMapImage, needsFlip };
476
+ };
477
+ /**
478
+ * Creates the SDR (sRGB) and gain map (linear) textures from decoded images
479
+ *
480
+ * @param sdrImage
481
+ * @param gainMapImage
482
+ * @param needsFlip
483
+ * @returns
484
+ */
485
+ const createTextures = (sdrImage, gainMapImage, needsFlip) => {
486
+ const gainMap = new three.Texture(gainMapImage || new ImageData(2, 2), three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.LinearSRGBColorSpace);
487
+ gainMap.flipY = needsFlip;
488
+ gainMap.needsUpdate = true;
489
+ const sdr = new three.Texture(sdrImage, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
490
+ sdr.flipY = needsFlip;
491
+ sdr.needsUpdate = true;
492
+ return { gainMap, sdr };
493
+ };
494
+
328
495
  /**
329
496
  * Shared base class for loaders that extracts common logic
330
497
  */
@@ -374,39 +541,11 @@
374
541
  renderTargetOptions: this._renderTargetOptions
375
542
  });
376
543
  }
377
- async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
378
- const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
379
- const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
380
- let sdrImage;
381
- let gainMapImage;
382
- let needsFlip = false;
383
- if (typeof createImageBitmap === 'undefined') {
384
- const res = await Promise.all([
385
- gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
386
- getHTMLImageFromBlob(sdrBlob)
387
- ]);
388
- gainMapImage = res[0];
389
- sdrImage = res[1];
390
- needsFlip = imageOrientation === 'flipY';
391
- }
392
- else {
393
- const res = await Promise.all([
394
- gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
395
- createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
396
- ]);
397
- gainMapImage = res[0];
398
- sdrImage = res[1];
399
- }
400
- return { sdrImage, gainMapImage, needsFlip };
544
+ processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
545
+ return processImages(sdrBuffer, gainMapBuffer, imageOrientation);
401
546
  }
402
547
  createTextures(sdrImage, gainMapImage, needsFlip) {
403
- const gainMap = new three.Texture(gainMapImage || new ImageData(2, 2), three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.LinearSRGBColorSpace);
404
- gainMap.flipY = needsFlip;
405
- gainMap.needsUpdate = true;
406
- const sdr = new three.Texture(sdrImage, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
407
- sdr.flipY = needsFlip;
408
- sdr.needsUpdate = true;
409
- return { gainMap, sdr };
548
+ return createTextures(sdrImage, gainMapImage, needsFlip);
410
549
  }
411
550
  updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
412
551
  quadRenderer.width = sdrImage.width;
@@ -428,6 +567,7 @@
428
567
  /**
429
568
  * Utility class used for rendering a texture with a material (WebGPU version)
430
569
  *
570
+ * @deprecated Will be removed in v4.0.0. The WebGPU decode now happens in {@link GainMapNode}, use {@link HDRJPGNodeLoader}, {@link GainMapNodeLoader} or {@link gainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
431
571
  * @category Core
432
572
  * @group Core
433
573
  */
@@ -650,13 +790,30 @@
650
790
  get colorSpace() { return this._colorSpace; }
651
791
  }
652
792
 
793
+ const warned = new Set();
794
+ /**
795
+ * Warns once per API that a render target based decode API is going away in v4.0.0
796
+ *
797
+ * @param name deprecated API
798
+ * @param entry entry point exposing the deprecated API
799
+ * @param replacement node based API replacing it, from `@monogrid/gainmap-js/webgpu`
800
+ */
801
+ const warnDeprecated = (name, entry, replacement) => {
802
+ const key = `${entry}:${name}`;
803
+ if (warned.has(key))
804
+ return;
805
+ warned.add(key);
806
+ console.warn(`gainmap-js: ${name} from '${entry}' is deprecated and will be removed in v4.0.0. Use ${replacement} from '@monogrid/gainmap-js/webgpu' with WebGPURenderer (which also has a WebGL2 backend) instead. It is not a drop-in replacement (it returns a GainMapNode, not a render target), see https://github.com/MONOGRID/gainmap-js#migrating-to-v400`);
807
+ };
808
+
653
809
  // min half float value
654
810
  const HALF_FLOAT_MIN = tsl.vec3(-65504, -65504, -65504);
655
811
  // max half float value
656
- const HALF_FLOAT_MAX = tsl.vec3(65504, 65504, 65504);
812
+ const HALF_FLOAT_MAX$1 = tsl.vec3(65504, 65504, 65504);
657
813
  /**
658
814
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
659
815
  *
816
+ * @deprecated Will be removed in v4.0.0. The decode now happens in {@link GainMapNode}, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
660
817
  * @category Materials
661
818
  * @group Materials
662
819
  */
@@ -707,7 +864,7 @@
707
864
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
708
865
  const gain = tsl.vec3(2).pow(logBoost.mul(this._weightFactorUniform));
709
866
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
710
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
867
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
711
868
  this.colorNode = clampedHdrColor;
712
869
  }
713
870
  get sdr() { return this._sdrTexture.value; }
@@ -810,6 +967,7 @@
810
967
  /**
811
968
  * Decodes a gain map using WebGPU RenderTarget
812
969
  *
970
+ * @deprecated Will be removed in v4.0.0. Use {@link gainMapNode} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
813
971
  * @category Decoding Functions
814
972
  * @group Decoding Functions
815
973
  * @example
@@ -863,6 +1021,7 @@
863
1021
  * @throws {Error} if the WebGPURenderer fails to render the gain map
864
1022
  */
865
1023
  const decode = async (params) => {
1024
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
866
1025
  // Ensure renderer is defined for the base function
867
1026
  if (!params.renderer) {
868
1027
  throw new Error('Renderer is required for decode function');
@@ -913,6 +1072,7 @@
913
1072
  /**
914
1073
  * A Three.js Loader for the gain map format (WebGPU version).
915
1074
  *
1075
+ * @deprecated Will be removed in v4.0.0. Use {@link GainMapNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
916
1076
  * @category Loaders
917
1077
  * @group Loaders
918
1078
  *
@@ -959,6 +1119,10 @@
959
1119
  *
960
1120
  */
961
1121
  class GainMapLoader extends LoaderBaseWebGPU {
1122
+ constructor(renderer, manager) {
1123
+ super(renderer, manager);
1124
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
1125
+ }
962
1126
  /**
963
1127
  * Loads a gainmap using separate data
964
1128
  * * sdr image
@@ -1096,9 +1260,344 @@
1096
1260
  }
1097
1261
  }
1098
1262
 
1263
+ // max half float value
1264
+ const HALF_FLOAT_MAX = 65504;
1265
+ /**
1266
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
1267
+ *
1268
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
1269
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
1270
+ * texture read, like any other texture.
1271
+ *
1272
+ * The node updates itself before rendering whenever it is part of a rendered node graph
1273
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
1274
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
1275
+ *
1276
+ * Re-decoding also flags the texture for PMREM regeneration,
1277
+ * so environment maps are recomputed only when the image actually changes.
1278
+ *
1279
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
1280
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
1281
+ *
1282
+ * @category Nodes
1283
+ * @group Nodes
1284
+ *
1285
+ * @example
1286
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
1287
+ * import { equirectUV } from 'three/tsl'
1288
+ *
1289
+ * const hdr = new GainMapNode()
1290
+ * .setTextures(sdrTexture, gainMapTexture)
1291
+ * .setMetadata(metadata)
1292
+ *
1293
+ * material.colorNode = hdr
1294
+ * scene.backgroundNode = hdr.sample(equirectUV())
1295
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
1296
+ */
1297
+ class GainMapNode extends webgpu.TextureNode {
1298
+ static get type() { return 'GainMapNode'; }
1299
+ /**
1300
+ * Shared textures and uniforms
1301
+ */
1302
+ uniforms;
1303
+ /**
1304
+ * The render target holding the decoded HDR image
1305
+ */
1306
+ renderTarget;
1307
+ _quadMesh;
1308
+ _material;
1309
+ // filled by RendererUtils.resetRendererState
1310
+ _rendererState = {};
1311
+ _state = [];
1312
+ constructor() {
1313
+ const renderTarget = new webgpu.RenderTarget(1, 1, {
1314
+ type: webgpu.HalfFloatType,
1315
+ colorSpace: webgpu.LinearSRGBColorSpace,
1316
+ depthBuffer: false,
1317
+ generateMipmaps: true,
1318
+ minFilter: webgpu.LinearMipmapLinearFilter,
1319
+ magFilter: webgpu.LinearFilter
1320
+ });
1321
+ super(renderTarget.texture);
1322
+ this.renderTarget = renderTarget;
1323
+ this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1324
+ const u = this.uniforms = {
1325
+ sdr: tsl.texture(new webgpu.Texture()),
1326
+ gainMap: tsl.texture(new webgpu.Texture()),
1327
+ gamma: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1328
+ offsetSdr: tsl.uniform(new webgpu.Vector3()),
1329
+ offsetHdr: tsl.uniform(new webgpu.Vector3()),
1330
+ gainMapMin: tsl.uniform(new webgpu.Vector3()),
1331
+ gainMapMax: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1332
+ hdrCapacityMin: tsl.uniform(0),
1333
+ hdrCapacityMax: tsl.uniform(1),
1334
+ maxDisplayBoost: tsl.uniform(1)
1335
+ };
1336
+ const logRecovery = u.gainMap.rgb.pow(tsl.vec3(1).div(u.gamma));
1337
+ const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
1338
+ const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
1339
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
1340
+ this._material = new webgpu.MeshBasicNodeMaterial();
1341
+ this._material.name = 'GainMapDecoder';
1342
+ this._material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
1343
+ this._quadMesh = new webgpu.QuadMesh(this._material);
1344
+ }
1345
+ /** The SDR rendition texture (sRGB) */
1346
+ get sdr() { return this.uniforms.sdr.value; }
1347
+ /** The gain map recovery texture (linear) */
1348
+ get gainMap() { return this.uniforms.gainMap.value; }
1349
+ /** @see {@link GainMapMetadata.gamma} */
1350
+ get gamma() { return this.uniforms.gamma; }
1351
+ /** @see {@link GainMapMetadata.offsetSdr} */
1352
+ get offsetSdr() { return this.uniforms.offsetSdr; }
1353
+ /** @see {@link GainMapMetadata.offsetHdr} */
1354
+ get offsetHdr() { return this.uniforms.offsetHdr; }
1355
+ /** @see {@link GainMapMetadata.gainMapMin} */
1356
+ get gainMapMin() { return this.uniforms.gainMapMin; }
1357
+ /** @see {@link GainMapMetadata.gainMapMax} */
1358
+ get gainMapMax() { return this.uniforms.gainMapMax; }
1359
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
1360
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
1361
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
1362
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
1363
+ /**
1364
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
1365
+ * @remarks Non Logarithmic space
1366
+ */
1367
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
1368
+ /** Width of the SDR image, 0 until loaded */
1369
+ get width() { return this.sdr.image?.width ?? 0; }
1370
+ /** Height of the SDR image, 0 until loaded */
1371
+ get height() { return this.sdr.image?.height ?? 0; }
1372
+ /**
1373
+ * Sets the SDR and gain map textures.
1374
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
1375
+ *
1376
+ * @param sdr
1377
+ * @param gainMap
1378
+ */
1379
+ setTextures(sdr, gainMap) {
1380
+ this.uniforms.sdr.value = sdr;
1381
+ this.uniforms.gainMap.value = gainMap;
1382
+ // size the render target right away, so `value` has its final size before the first decode
1383
+ if (this.width > 0 && this.height > 0)
1384
+ this.renderTarget.setSize(this.width, this.height);
1385
+ return this;
1386
+ }
1387
+ /**
1388
+ * Copies the gain map metadata into the uniforms.
1389
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
1390
+ *
1391
+ * @param metadata
1392
+ */
1393
+ setMetadata(metadata) {
1394
+ const u = this.uniforms;
1395
+ u.gamma.value.fromArray(metadata.gamma);
1396
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
1397
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
1398
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
1399
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
1400
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
1401
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
1402
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
1403
+ return this;
1404
+ }
1405
+ _currentState() {
1406
+ const u = this.uniforms;
1407
+ return [
1408
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
1409
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
1410
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
1411
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
1412
+ ];
1413
+ }
1414
+ /**
1415
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
1416
+ *
1417
+ * Called automatically when the node is part of a rendered node graph.
1418
+ *
1419
+ * @param renderer
1420
+ * @returns `true` if the image was decoded
1421
+ */
1422
+ decode(renderer) {
1423
+ // not loaded yet
1424
+ if (this.width === 0 || this.height === 0)
1425
+ return false;
1426
+ const state = this._currentState();
1427
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
1428
+ return false;
1429
+ this._state = state;
1430
+ webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
1431
+ renderer.setRenderTarget(this.renderTarget);
1432
+ this._quadMesh.render(renderer);
1433
+ webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
1434
+ this.value.needsPMREMUpdate = true;
1435
+ return true;
1436
+ }
1437
+ updateBefore(frame) {
1438
+ if (frame.renderer)
1439
+ this.decode(frame.renderer);
1440
+ return undefined;
1441
+ }
1442
+ set value(value) {
1443
+ if (this.renderTarget && value !== this.renderTarget.texture) {
1444
+ throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
1445
+ }
1446
+ }
1447
+ get value() {
1448
+ return this.renderTarget?.texture;
1449
+ }
1450
+ /**
1451
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
1452
+ * they keep it updated before rendering as well
1453
+ */
1454
+ clone() {
1455
+ const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
1456
+ node.sampler = this.sampler;
1457
+ node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1458
+ node.updateBefore = (frame) => this.updateBefore(frame);
1459
+ return node;
1460
+ }
1461
+ /**
1462
+ * Disposes the render target, the SDR and gain map textures
1463
+ */
1464
+ dispose() {
1465
+ this.renderTarget.dispose();
1466
+ this._material.dispose();
1467
+ this.sdr.dispose();
1468
+ this.gainMap.dispose();
1469
+ super.dispose();
1470
+ }
1471
+ }
1472
+ /**
1473
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
1474
+ *
1475
+ * @param sdr
1476
+ * @param gainMap
1477
+ * @param metadata
1478
+ */
1479
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
1480
+
1481
+ /**
1482
+ * Base class for loaders returning a {@link GainMapNode}
1483
+ * @template TUrl - The type of URL used to load resources
1484
+ */
1485
+ class LoaderBaseNode extends webgpu.Loader {
1486
+ /**
1487
+ * @private
1488
+ * @param responseType
1489
+ */
1490
+ createFileLoader(responseType) {
1491
+ const loader = new webgpu.FileLoader(this.manager);
1492
+ if (responseType)
1493
+ loader.setResponseType(responseType);
1494
+ loader.setRequestHeader(this.requestHeader);
1495
+ loader.setPath(this.path);
1496
+ loader.setWithCredentials(this.withCredentials);
1497
+ return loader;
1498
+ }
1499
+ /**
1500
+ * Decodes the images and feeds them to the node, together with the metadata
1501
+ *
1502
+ * @private
1503
+ * @param node
1504
+ * @param metadata
1505
+ * @param sdrBuffer
1506
+ * @param gainMapBuffer
1507
+ */
1508
+ async fillNode(node, metadata, sdrBuffer, gainMapBuffer) {
1509
+ // flipY like any other three.js texture, so the node can be sampled with regular uvs
1510
+ const { sdrImage, gainMapImage } = await processImages(sdrBuffer, gainMapBuffer, 'from-image');
1511
+ const { sdr, gainMap } = createTextures(sdrImage, gainMapImage, true);
1512
+ node.setTextures(sdr, gainMap).setMetadata(metadata);
1513
+ }
1514
+ }
1515
+
1516
+ /**
1517
+ * A Three.js Loader for the gain map format stored as separate files (sdr image, gain map image, metadata json),
1518
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1519
+ *
1520
+ * No renderer is needed: `load` returns the node synchronously, it can be assigned to materials right away
1521
+ * and it is decoded on the GPU once loaded.
1522
+ *
1523
+ * @category Loaders
1524
+ * @group Loaders
1525
+ *
1526
+ * @example
1527
+ * import { GainMapNodeLoader } from '@monogrid/gainmap-js/webgpu'
1528
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1529
+ *
1530
+ * const hdr = new GainMapNodeLoader().load([
1531
+ * 'sdr.webp',
1532
+ * 'gainmap.webp',
1533
+ * 'metadata.json'
1534
+ * ])
1535
+ *
1536
+ * const material = new MeshBasicNodeMaterial()
1537
+ * material.colorNode = hdr
1538
+ */
1539
+ class GainMapNodeLoader extends LoaderBaseNode {
1540
+ /**
1541
+ * Loads a gainmap using separate data
1542
+ * * sdr image
1543
+ * * gain map image
1544
+ * * metadata json
1545
+ *
1546
+ * useful for webp gain maps
1547
+ *
1548
+ * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
1549
+ * @param onLoad Load complete callback, will receive the node
1550
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1551
+ * @param onError Error callback
1552
+ * @returns a node which can be used immediately, it will hold the image once loaded
1553
+ */
1554
+ load(urls, onLoad, onProgress, onError) {
1555
+ const node = new GainMapNode();
1556
+ const progress = urls.map(() => ({ lengthComputable: true, loaded: 0, total: 0 }));
1557
+ const loadFile = (url, index, responseType) => new Promise((resolve, reject) => {
1558
+ this.manager.itemStart(url);
1559
+ this.createFileLoader(responseType).load(url, resolve, (e) => {
1560
+ progress[index] = { lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total };
1561
+ if (typeof onProgress === 'function') {
1562
+ onProgress(new ProgressEvent('progress', {
1563
+ lengthComputable: progress.every(p => p.lengthComputable),
1564
+ loaded: progress.reduce((sum, p) => sum + p.loaded, 0),
1565
+ total: progress.reduce((sum, p) => sum + p.total, 0)
1566
+ }));
1567
+ }
1568
+ }, reject);
1569
+ });
1570
+ const [sdrUrl, gainMapUrl, metadataUrl] = urls;
1571
+ Promise.all([
1572
+ loadFile(sdrUrl, 0, 'arraybuffer'),
1573
+ loadFile(gainMapUrl, 1, 'arraybuffer'),
1574
+ loadFile(metadataUrl, 2)
1575
+ ]).then(async ([sdr, gainMap, json]) => {
1576
+ /* istanbul ignore if
1577
+ this condition exists only because of three.js types + strict mode
1578
+ */
1579
+ if (typeof sdr === 'string' || typeof gainMap === 'string' || typeof json !== 'string')
1580
+ throw new Error('Invalid response types');
1581
+ // TODO: implement check on JSON file
1582
+ const metadata = JSON.parse(json);
1583
+ await this.fillNode(node, metadata, sdr, gainMap);
1584
+ }).then(() => {
1585
+ if (typeof onLoad === 'function')
1586
+ onLoad(node);
1587
+ urls.forEach(url => this.manager.itemEnd(url));
1588
+ }, (error) => {
1589
+ urls.forEach(url => this.manager.itemError(url));
1590
+ if (typeof onError === 'function')
1591
+ onError(error);
1592
+ });
1593
+ return node;
1594
+ }
1595
+ }
1596
+
1099
1597
  /**
1100
1598
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
1101
1599
  *
1600
+ * @deprecated Will be removed in v4.0.0. Use {@link HDRJPGNodeLoader} instead: it is **not a drop-in replacement**, it returns a {@link GainMapNode} instead of a render target, see the [migration guide](https://github.com/MONOGRID/gainmap-js#migrating-to-v400).
1102
1601
  * @category Loaders
1103
1602
  * @group Loaders
1104
1603
  *
@@ -1145,6 +1644,10 @@
1145
1644
  *
1146
1645
  */
1147
1646
  class HDRJPGLoader extends LoaderBaseWebGPU {
1647
+ constructor(renderer, manager) {
1648
+ super(renderer, manager);
1649
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1650
+ }
1148
1651
  /**
1149
1652
  * Loads a JPEG containing gain map metadata
1150
1653
  * Renders a normal SDR image if gainmap data is not found
@@ -1223,18 +1726,121 @@
1223
1726
  }
1224
1727
  }
1225
1728
 
1729
+ /**
1730
+ * A Three.js Loader for a JPEG with embedded gain map metadata,
1731
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1732
+ *
1733
+ * No renderer is needed: `load` returns the node synchronously
1734
+ * (like `TextureLoader` returns a `Texture`), it can be assigned to materials right away
1735
+ * and it is decoded on the GPU once loaded.
1736
+ *
1737
+ * @category Loaders
1738
+ * @group Loaders
1739
+ *
1740
+ * @example
1741
+ * import { HDRJPGNodeLoader } from '@monogrid/gainmap-js/webgpu'
1742
+ * import { equirectUV } from 'three/tsl'
1743
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1744
+ *
1745
+ * const hdr = new HDRJPGNodeLoader().load('gainmap.jpeg')
1746
+ *
1747
+ * const material = new MeshBasicNodeMaterial()
1748
+ * material.colorNode = hdr
1749
+ *
1750
+ * scene.backgroundNode = hdr.sample(equirectUV())
1751
+ *
1752
+ * // all parameters are uniforms, changing them re-decodes the image once
1753
+ * hdr.maxDisplayBoost.value = 2
1754
+ */
1755
+ class HDRJPGNodeLoader extends LoaderBaseNode {
1756
+ /**
1757
+ * Loads a JPEG containing gain map metadata
1758
+ * Renders a normal SDR image if gainmap data is not found
1759
+ *
1760
+ * @param url Path to a JPEG file containing embedded gain map metadata
1761
+ * @param onLoad Load complete callback, will receive the node
1762
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1763
+ * @param onError Error callback
1764
+ * @returns a node which can be used immediately, it will hold the image once loaded
1765
+ */
1766
+ load(url, onLoad, onProgress, onError) {
1767
+ const node = new GainMapNode();
1768
+ this.manager.itemStart(url);
1769
+ this.createFileLoader('arraybuffer').load(url, async (jpeg) => {
1770
+ try {
1771
+ /* istanbul ignore if
1772
+ this condition exists only because of three.js types + strict mode
1773
+ */
1774
+ if (typeof jpeg === 'string')
1775
+ throw new Error('Invalid buffer, received [string], was expecting [ArrayBuffer]');
1776
+ const jpegBuffer = new Uint8Array(jpeg);
1777
+ let sdrJPEG;
1778
+ let gainMapJPEG;
1779
+ let metadata;
1780
+ try {
1781
+ const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
1782
+ sdrJPEG = extractionResult.sdr;
1783
+ gainMapJPEG = extractionResult.gainMap;
1784
+ metadata = extractionResult.metadata;
1785
+ }
1786
+ catch (e) {
1787
+ // render the SDR version if this is not a gainmap
1788
+ if (e instanceof XMPMetadataNotFoundError || e instanceof GainMapNotFoundError) {
1789
+ console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`);
1790
+ metadata = {
1791
+ gainMapMin: [0, 0, 0],
1792
+ gainMapMax: [1, 1, 1],
1793
+ gamma: [1, 1, 1],
1794
+ hdrCapacityMin: 0,
1795
+ hdrCapacityMax: 1,
1796
+ offsetHdr: [0, 0, 0],
1797
+ offsetSdr: [0, 0, 0]
1798
+ };
1799
+ sdrJPEG = jpegBuffer;
1800
+ }
1801
+ else {
1802
+ throw e;
1803
+ }
1804
+ }
1805
+ await this.fillNode(node, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer);
1806
+ }
1807
+ catch (error) {
1808
+ this.manager.itemError(url);
1809
+ if (typeof onError === 'function')
1810
+ onError(error);
1811
+ return;
1812
+ }
1813
+ if (typeof onLoad === 'function')
1814
+ onLoad(node);
1815
+ this.manager.itemEnd(url);
1816
+ }, onProgress, (error) => {
1817
+ this.manager.itemError(url);
1818
+ if (typeof onError === 'function')
1819
+ onError(error);
1820
+ });
1821
+ return node;
1822
+ }
1823
+ }
1824
+
1226
1825
  exports.GainMapDecoderMaterial = GainMapDecoderMaterial;
1227
1826
  exports.GainMapLoader = GainMapLoader;
1827
+ exports.GainMapNode = GainMapNode;
1828
+ exports.GainMapNodeLoader = GainMapNodeLoader;
1228
1829
  exports.GainMapNotFoundError = GainMapNotFoundError;
1229
1830
  exports.HDRJPGLoader = HDRJPGLoader;
1831
+ exports.HDRJPGNodeLoader = HDRJPGNodeLoader;
1230
1832
  exports.JPEGRLoader = HDRJPGLoader;
1231
1833
  exports.LoaderBaseShared = LoaderBaseShared;
1232
1834
  exports.MPFExtractor = MPFExtractor;
1233
1835
  exports.QuadRenderer = QuadRenderer;
1234
1836
  exports.XMPMetadataNotFoundError = XMPMetadataNotFoundError;
1235
1837
  exports.createDecodeFunction = createDecodeFunction;
1838
+ exports.createTextures = createTextures;
1236
1839
  exports.decode = decode;
1237
1840
  exports.extractGainmapFromJPEG = extractGainmapFromJPEG;
1841
+ exports.extractISO = extractISO;
1238
1842
  exports.extractXMP = extractXMP;
1843
+ exports.gainMapNode = gainMapNode;
1844
+ exports.processImages = processImages;
1239
1845
 
1240
1846
  }));