@monogrid/gainmap-js 3.5.0 → 3.6.1

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 (55) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +111 -133
  3. package/dist/{QuadRenderer-DIHDdKl6.js → QuadRenderer-Bhn3yOPC.js} +1 -1
  4. package/dist/{QuadRenderer-DPiEee1I.js → QuadRenderer-DMno-Vj6.js} +1 -1
  5. package/dist/{_commonjsHelpers-S7tZmPW-.js → _commonjsHelpers-C8qmDUO8.js} +1 -1
  6. package/dist/{_commonjsHelpers-DVRbpukU.js → _commonjsHelpers-DFuDJEaJ.js} +1 -1
  7. package/dist/{compress-5gFn7Y4a.js → compress-TBp7MS8D.js} +1 -1
  8. package/dist/{compress-CTBeaiI1.js → compress-oIjJuPa8.js} +1 -2
  9. package/dist/decode/shared/index.d.ts +1 -0
  10. package/dist/decode/shared/utils/create-textures.d.ts +26 -0
  11. package/dist/decode/shared/utils/warn-deprecated.d.ts +8 -0
  12. package/dist/decode/webgl/decode.d.ts +1 -0
  13. package/dist/decode/webgl/index.d.ts +4 -0
  14. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +3 -1
  15. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +3 -1
  16. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +1 -0
  17. package/dist/decode/webgpu/core/QuadRenderer.d.ts +1 -0
  18. package/dist/decode/webgpu/decode.d.ts +1 -0
  19. package/dist/decode/webgpu/index.d.ts +7 -0
  20. package/dist/decode/webgpu/loaders/GainMapLoader.d.ts +3 -1
  21. package/dist/decode/webgpu/loaders/GainMapNodeLoader.d.ts +42 -0
  22. package/dist/decode/webgpu/loaders/HDRJPGLoader.d.ts +3 -1
  23. package/dist/decode/webgpu/loaders/HDRJPGNodeLoader.d.ts +41 -0
  24. package/dist/decode/webgpu/loaders/LoaderBaseNode.d.ts +24 -0
  25. package/dist/decode/webgpu/materials/GainMapDecoderMaterial.d.ts +1 -0
  26. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +142 -0
  27. package/dist/decode.js +18 -5
  28. package/dist/decode.min.js +2 -2
  29. package/dist/decode.umd.cjs +86 -32
  30. package/dist/decode.umd.min.cjs +2 -2
  31. package/dist/decode.webgpu.js +472 -10
  32. package/dist/decode.webgpu.min.js +2 -2
  33. package/dist/decode.webgpu.umd.cjs +542 -35
  34. package/dist/decode.webgpu.umd.min.cjs +2 -2
  35. package/dist/encode.js +3 -3
  36. package/dist/encode.min.js +2 -2
  37. package/dist/encode.umd.cjs +1 -2
  38. package/dist/encode.umd.min.cjs +1 -1
  39. package/dist/{iso-gainmap-metadata-Dk2F4Eoz.js → iso-gainmap-metadata-C1io5isX.js} +1 -1
  40. package/dist/{iso-gainmap-metadata-DNTSE4Qp.js → iso-gainmap-metadata-Oi7gAKNC.js} +1 -1
  41. package/dist/libultrahdr.js +2 -2
  42. package/dist/libultrahdr.min.js +2 -2
  43. package/dist/libultrahdr.umd.cjs +1 -1
  44. package/dist/libultrahdr.umd.min.cjs +1 -1
  45. package/dist/{Loader-CL7itwBq.js → warn-deprecated-DtCQWGKi.js} +74 -35
  46. package/dist/{Loader-BdKdEGSJ.js → warn-deprecated-gLZfP_DV.js} +2 -2
  47. package/dist/worker-interface.js +2 -2
  48. package/dist/worker-interface.min.js +2 -2
  49. package/dist/worker-interface.umd.cjs +1 -1
  50. package/dist/worker-interface.umd.min.cjs +1 -1
  51. package/dist/worker.js +3 -3
  52. package/dist/worker.min.js +2 -2
  53. package/dist/worker.umd.cjs +1 -2
  54. package/dist/worker.umd.min.cjs +1 -1
  55. package/package.json +35 -42
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.5.0
2
+ * @monogrid/gainmap-js v3.6.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -441,6 +441,57 @@
441
441
  });
442
442
  };
443
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
+
444
495
  /**
445
496
  * Shared base class for loaders that extracts common logic
446
497
  */
@@ -490,39 +541,11 @@
490
541
  renderTargetOptions: this._renderTargetOptions
491
542
  });
492
543
  }
493
- async processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
494
- const gainMapBlob = gainMapBuffer ? new Blob([gainMapBuffer], { type: 'image/jpeg' }) : undefined;
495
- const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
496
- let sdrImage;
497
- let gainMapImage;
498
- let needsFlip = false;
499
- if (typeof createImageBitmap === 'undefined') {
500
- const res = await Promise.all([
501
- gainMapBlob ? getHTMLImageFromBlob(gainMapBlob) : Promise.resolve(undefined),
502
- getHTMLImageFromBlob(sdrBlob)
503
- ]);
504
- gainMapImage = res[0];
505
- sdrImage = res[1];
506
- needsFlip = imageOrientation === 'flipY';
507
- }
508
- else {
509
- const res = await Promise.all([
510
- gainMapBlob ? createImageBitmap(gainMapBlob, { imageOrientation: imageOrientation || 'flipY' }) : Promise.resolve(undefined),
511
- createImageBitmap(sdrBlob, { imageOrientation: imageOrientation || 'flipY' })
512
- ]);
513
- gainMapImage = res[0];
514
- sdrImage = res[1];
515
- }
516
- return { sdrImage, gainMapImage, needsFlip };
544
+ processImages(sdrBuffer, gainMapBuffer, imageOrientation) {
545
+ return processImages(sdrBuffer, gainMapBuffer, imageOrientation);
517
546
  }
518
547
  createTextures(sdrImage, gainMapImage, needsFlip) {
519
- 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);
520
- gainMap.flipY = needsFlip;
521
- gainMap.needsUpdate = true;
522
- const sdr = new three.Texture(sdrImage, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
523
- sdr.flipY = needsFlip;
524
- sdr.needsUpdate = true;
525
- return { gainMap, sdr };
548
+ return createTextures(sdrImage, gainMapImage, needsFlip);
526
549
  }
527
550
  updateQuadRenderer(quadRenderer, sdrImage, gainMap, sdr, metadata) {
528
551
  quadRenderer.width = sdrImage.width;
@@ -544,6 +567,7 @@
544
567
  /**
545
568
  * Utility class used for rendering a texture with a material (WebGPU version)
546
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).
547
571
  * @category Core
548
572
  * @group Core
549
573
  */
@@ -645,7 +669,20 @@
645
669
  if (!this._supportsReadPixels)
646
670
  throw new Error('Can\'t read pixels in this browser');
647
671
  const out = await this._renderer.readRenderTargetPixelsAsync(this._renderTarget, 0, 0, this._width, this._height);
648
- return out;
672
+ if (!this._renderer.backend.isWebGPUBackend) {
673
+ return out;
674
+ }
675
+ // the WebGPU backend returns rows top-down, each padded to 256 bytes,
676
+ // the WebGL backend returns tightly packed rows bottom-up:
677
+ // repack to the WebGL layout so both backends return the same data
678
+ const rowLength = this._width * 4;
679
+ const paddedRowLength = Math.ceil(rowLength * out.BYTES_PER_ELEMENT / 256) * 256 / out.BYTES_PER_ELEMENT;
680
+ const packed = new out.constructor(rowLength * this._height);
681
+ for (let y = 0; y < this._height; y++) {
682
+ const start = (this._height - 1 - y) * paddedRowLength;
683
+ packed.set(out.subarray(start, start + rowLength), y * rowLength);
684
+ }
685
+ return packed;
649
686
  }
650
687
  /**
651
688
  * Performs a readPixel operation in the renderTarget
@@ -766,13 +803,30 @@
766
803
  get colorSpace() { return this._colorSpace; }
767
804
  }
768
805
 
806
+ const warned = new Set();
807
+ /**
808
+ * Warns once per API that a render target based decode API is going away in v4.0.0
809
+ *
810
+ * @param name deprecated API
811
+ * @param entry entry point exposing the deprecated API
812
+ * @param replacement node based API replacing it, from `@monogrid/gainmap-js/webgpu`
813
+ */
814
+ const warnDeprecated = (name, entry, replacement) => {
815
+ const key = `${entry}:${name}`;
816
+ if (warned.has(key))
817
+ return;
818
+ warned.add(key);
819
+ 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`);
820
+ };
821
+
769
822
  // min half float value
770
823
  const HALF_FLOAT_MIN = tsl.vec3(-65504, -65504, -65504);
771
824
  // max half float value
772
- const HALF_FLOAT_MAX = tsl.vec3(65504, 65504, 65504);
825
+ const HALF_FLOAT_MAX$1 = tsl.vec3(65504, 65504, 65504);
773
826
  /**
774
827
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
775
828
  *
829
+ * @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).
776
830
  * @category Materials
777
831
  * @group Materials
778
832
  */
@@ -823,7 +877,7 @@
823
877
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
824
878
  const gain = tsl.vec3(2).pow(logBoost.mul(this._weightFactorUniform));
825
879
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
826
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
880
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
827
881
  this.colorNode = clampedHdrColor;
828
882
  }
829
883
  get sdr() { return this._sdrTexture.value; }
@@ -926,6 +980,7 @@
926
980
  /**
927
981
  * Decodes a gain map using WebGPU RenderTarget
928
982
  *
983
+ * @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).
929
984
  * @category Decoding Functions
930
985
  * @group Decoding Functions
931
986
  * @example
@@ -979,6 +1034,7 @@
979
1034
  * @throws {Error} if the WebGPURenderer fails to render the gain map
980
1035
  */
981
1036
  const decode = async (params) => {
1037
+ warnDeprecated('decode()', '@monogrid/gainmap-js/webgpu', 'gainMapNode()');
982
1038
  // Ensure renderer is defined for the base function
983
1039
  if (!params.renderer) {
984
1040
  throw new Error('Renderer is required for decode function');
@@ -1029,6 +1085,7 @@
1029
1085
  /**
1030
1086
  * A Three.js Loader for the gain map format (WebGPU version).
1031
1087
  *
1088
+ * @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).
1032
1089
  * @category Loaders
1033
1090
  * @group Loaders
1034
1091
  *
@@ -1075,6 +1132,10 @@
1075
1132
  *
1076
1133
  */
1077
1134
  class GainMapLoader extends LoaderBaseWebGPU {
1135
+ constructor(renderer, manager) {
1136
+ super(renderer, manager);
1137
+ warnDeprecated('GainMapLoader', '@monogrid/gainmap-js/webgpu', 'GainMapNodeLoader');
1138
+ }
1078
1139
  /**
1079
1140
  * Loads a gainmap using separate data
1080
1141
  * * sdr image
@@ -1212,9 +1273,349 @@
1212
1273
  }
1213
1274
  }
1214
1275
 
1276
+ // max half float value
1277
+ const HALF_FLOAT_MAX = 65504;
1278
+ /**
1279
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
1280
+ *
1281
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
1282
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
1283
+ * texture read, like any other texture.
1284
+ *
1285
+ * The node updates itself before rendering whenever it is part of a rendered node graph
1286
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
1287
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
1288
+ *
1289
+ * Re-decoding also flags the texture for PMREM regeneration,
1290
+ * so environment maps are recomputed only when the image actually changes.
1291
+ *
1292
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
1293
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
1294
+ *
1295
+ * @category Nodes
1296
+ * @group Nodes
1297
+ *
1298
+ * @example
1299
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
1300
+ * import { equirectUV } from 'three/tsl'
1301
+ *
1302
+ * const hdr = new GainMapNode()
1303
+ * .setTextures(sdrTexture, gainMapTexture)
1304
+ * .setMetadata(metadata)
1305
+ *
1306
+ * material.colorNode = hdr
1307
+ * scene.backgroundNode = hdr.sample(equirectUV())
1308
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
1309
+ */
1310
+ class GainMapNode extends webgpu.TextureNode {
1311
+ static get type() { return 'GainMapNode'; }
1312
+ /**
1313
+ * Shared textures and uniforms
1314
+ */
1315
+ uniforms;
1316
+ /**
1317
+ * The render target holding the decoded HDR image
1318
+ */
1319
+ renderTarget;
1320
+ _quadMesh;
1321
+ _material;
1322
+ // filled by RendererUtils.resetRendererState
1323
+ _rendererState = {};
1324
+ _state = [];
1325
+ constructor() {
1326
+ const renderTarget = new webgpu.RenderTarget(1, 1, {
1327
+ type: webgpu.HalfFloatType,
1328
+ colorSpace: webgpu.LinearSRGBColorSpace,
1329
+ depthBuffer: false,
1330
+ generateMipmaps: true,
1331
+ minFilter: webgpu.LinearMipmapLinearFilter,
1332
+ magFilter: webgpu.LinearFilter
1333
+ });
1334
+ super(renderTarget.texture);
1335
+ this.renderTarget = renderTarget;
1336
+ this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1337
+ const u = this.uniforms = {
1338
+ sdr: tsl.texture(new webgpu.Texture()),
1339
+ gainMap: tsl.texture(new webgpu.Texture()),
1340
+ gamma: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1341
+ offsetSdr: tsl.uniform(new webgpu.Vector3()),
1342
+ offsetHdr: tsl.uniform(new webgpu.Vector3()),
1343
+ gainMapMin: tsl.uniform(new webgpu.Vector3()),
1344
+ gainMapMax: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
1345
+ hdrCapacityMin: tsl.uniform(0),
1346
+ hdrCapacityMax: tsl.uniform(1),
1347
+ maxDisplayBoost: tsl.uniform(1)
1348
+ };
1349
+ const logRecovery = u.gainMap.rgb.pow(tsl.vec3(1).div(u.gamma));
1350
+ const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
1351
+ const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
1352
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
1353
+ this._material = new webgpu.MeshBasicNodeMaterial();
1354
+ this._material.name = 'GainMapDecoder';
1355
+ this._material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
1356
+ this._quadMesh = new webgpu.QuadMesh(this._material);
1357
+ }
1358
+ /** The SDR rendition texture (sRGB) */
1359
+ get sdr() { return this.uniforms.sdr.value; }
1360
+ /** The gain map recovery texture (linear) */
1361
+ get gainMap() { return this.uniforms.gainMap.value; }
1362
+ /** @see {@link GainMapMetadata.gamma} */
1363
+ get gamma() { return this.uniforms.gamma; }
1364
+ /** @see {@link GainMapMetadata.offsetSdr} */
1365
+ get offsetSdr() { return this.uniforms.offsetSdr; }
1366
+ /** @see {@link GainMapMetadata.offsetHdr} */
1367
+ get offsetHdr() { return this.uniforms.offsetHdr; }
1368
+ /** @see {@link GainMapMetadata.gainMapMin} */
1369
+ get gainMapMin() { return this.uniforms.gainMapMin; }
1370
+ /** @see {@link GainMapMetadata.gainMapMax} */
1371
+ get gainMapMax() { return this.uniforms.gainMapMax; }
1372
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
1373
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
1374
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
1375
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
1376
+ /**
1377
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
1378
+ * @remarks Non Logarithmic space
1379
+ */
1380
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
1381
+ /** Width of the SDR image, 0 until loaded */
1382
+ get width() { return this.sdr.image?.width ?? 0; }
1383
+ /** Height of the SDR image, 0 until loaded */
1384
+ get height() { return this.sdr.image?.height ?? 0; }
1385
+ /**
1386
+ * Sets the SDR and gain map textures.
1387
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
1388
+ *
1389
+ * @param sdr
1390
+ * @param gainMap
1391
+ */
1392
+ setTextures(sdr, gainMap) {
1393
+ this.uniforms.sdr.value = sdr;
1394
+ this.uniforms.gainMap.value = gainMap;
1395
+ // size the render target right away, so `value` has its final size before the first decode
1396
+ if (this.width > 0 && this.height > 0)
1397
+ this.renderTarget.setSize(this.width, this.height);
1398
+ return this;
1399
+ }
1400
+ /**
1401
+ * Copies the gain map metadata into the uniforms.
1402
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
1403
+ *
1404
+ * @param metadata
1405
+ */
1406
+ setMetadata(metadata) {
1407
+ const u = this.uniforms;
1408
+ u.gamma.value.fromArray(metadata.gamma);
1409
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
1410
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
1411
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
1412
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
1413
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
1414
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
1415
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
1416
+ return this;
1417
+ }
1418
+ _currentState() {
1419
+ const u = this.uniforms;
1420
+ return [
1421
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
1422
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
1423
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
1424
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
1425
+ ];
1426
+ }
1427
+ /**
1428
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
1429
+ *
1430
+ * Called automatically when the node is part of a rendered node graph.
1431
+ *
1432
+ * @param renderer
1433
+ * @returns `true` if the image was decoded
1434
+ */
1435
+ decode(renderer) {
1436
+ // not loaded yet
1437
+ if (this.width === 0 || this.height === 0)
1438
+ return false;
1439
+ const state = this._currentState();
1440
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
1441
+ return false;
1442
+ this._state = state;
1443
+ webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
1444
+ renderer.setRenderTarget(this.renderTarget);
1445
+ this._quadMesh.render(renderer);
1446
+ webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
1447
+ this.value.needsPMREMUpdate = true;
1448
+ return true;
1449
+ }
1450
+ /**
1451
+ * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
1452
+ *
1453
+ * @param frame
1454
+ */
1455
+ updateBefore(frame) {
1456
+ if (frame.renderer)
1457
+ this.decode(frame.renderer);
1458
+ return undefined;
1459
+ }
1460
+ set value(value) {
1461
+ if (this.renderTarget && value !== this.renderTarget.texture) {
1462
+ throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
1463
+ }
1464
+ }
1465
+ get value() {
1466
+ return this.renderTarget?.texture;
1467
+ }
1468
+ /**
1469
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
1470
+ * they keep it updated before rendering as well
1471
+ */
1472
+ clone() {
1473
+ const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
1474
+ node.sampler = this.sampler;
1475
+ node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
1476
+ node.updateBefore = (frame) => this.updateBefore(frame);
1477
+ return node;
1478
+ }
1479
+ /**
1480
+ * Disposes the render target, the SDR and gain map textures
1481
+ */
1482
+ dispose() {
1483
+ this.renderTarget.dispose();
1484
+ this._material.dispose();
1485
+ this.sdr.dispose();
1486
+ this.gainMap.dispose();
1487
+ super.dispose();
1488
+ }
1489
+ }
1490
+ /**
1491
+ * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
1492
+ *
1493
+ * @param sdr
1494
+ * @param gainMap
1495
+ * @param metadata
1496
+ */
1497
+ const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
1498
+
1499
+ /**
1500
+ * Base class for loaders returning a {@link GainMapNode}
1501
+ * @template TUrl - The type of URL used to load resources
1502
+ */
1503
+ class LoaderBaseNode extends webgpu.Loader {
1504
+ /**
1505
+ * @private
1506
+ * @param responseType
1507
+ */
1508
+ createFileLoader(responseType) {
1509
+ const loader = new webgpu.FileLoader(this.manager);
1510
+ if (responseType)
1511
+ loader.setResponseType(responseType);
1512
+ loader.setRequestHeader(this.requestHeader);
1513
+ loader.setPath(this.path);
1514
+ loader.setWithCredentials(this.withCredentials);
1515
+ return loader;
1516
+ }
1517
+ /**
1518
+ * Decodes the images and feeds them to the node, together with the metadata
1519
+ *
1520
+ * @private
1521
+ * @param node
1522
+ * @param metadata
1523
+ * @param sdrBuffer
1524
+ * @param gainMapBuffer
1525
+ */
1526
+ async fillNode(node, metadata, sdrBuffer, gainMapBuffer) {
1527
+ // flipY like any other three.js texture, so the node can be sampled with regular uvs
1528
+ const { sdrImage, gainMapImage } = await processImages(sdrBuffer, gainMapBuffer, 'from-image');
1529
+ const { sdr, gainMap } = createTextures(sdrImage, gainMapImage, true);
1530
+ node.setTextures(sdr, gainMap).setMetadata(metadata);
1531
+ }
1532
+ }
1533
+
1534
+ /**
1535
+ * A Three.js Loader for the gain map format stored as separate files (sdr image, gain map image, metadata json),
1536
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1537
+ *
1538
+ * No renderer is needed: `load` returns the node synchronously, it can be assigned to materials right away
1539
+ * and it is decoded on the GPU once loaded.
1540
+ *
1541
+ * @category Loaders
1542
+ * @group Loaders
1543
+ *
1544
+ * @example
1545
+ * import { GainMapNodeLoader } from '@monogrid/gainmap-js/webgpu'
1546
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1547
+ *
1548
+ * const hdr = new GainMapNodeLoader().load([
1549
+ * 'sdr.webp',
1550
+ * 'gainmap.webp',
1551
+ * 'metadata.json'
1552
+ * ])
1553
+ *
1554
+ * const material = new MeshBasicNodeMaterial()
1555
+ * material.colorNode = hdr
1556
+ */
1557
+ class GainMapNodeLoader extends LoaderBaseNode {
1558
+ /**
1559
+ * Loads a gainmap using separate data
1560
+ * * sdr image
1561
+ * * gain map image
1562
+ * * metadata json
1563
+ *
1564
+ * useful for webp gain maps
1565
+ *
1566
+ * @param urls An array in the form of [sdr.jpg, gainmap.jpg, metadata.json]
1567
+ * @param onLoad Load complete callback, will receive the node
1568
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1569
+ * @param onError Error callback
1570
+ * @returns a node which can be used immediately, it will hold the image once loaded
1571
+ */
1572
+ load(urls, onLoad, onProgress, onError) {
1573
+ const node = new GainMapNode();
1574
+ const progress = urls.map(() => ({ lengthComputable: true, loaded: 0, total: 0 }));
1575
+ const loadFile = (url, index, responseType) => new Promise((resolve, reject) => {
1576
+ this.manager.itemStart(url);
1577
+ this.createFileLoader(responseType).load(url, resolve, (e) => {
1578
+ progress[index] = { lengthComputable: e.lengthComputable, loaded: e.loaded, total: e.total };
1579
+ if (typeof onProgress === 'function') {
1580
+ onProgress(new ProgressEvent('progress', {
1581
+ lengthComputable: progress.every(p => p.lengthComputable),
1582
+ loaded: progress.reduce((sum, p) => sum + p.loaded, 0),
1583
+ total: progress.reduce((sum, p) => sum + p.total, 0)
1584
+ }));
1585
+ }
1586
+ }, reject);
1587
+ });
1588
+ const [sdrUrl, gainMapUrl, metadataUrl] = urls;
1589
+ Promise.all([
1590
+ loadFile(sdrUrl, 0, 'arraybuffer'),
1591
+ loadFile(gainMapUrl, 1, 'arraybuffer'),
1592
+ loadFile(metadataUrl, 2)
1593
+ ]).then(async ([sdr, gainMap, json]) => {
1594
+ /* istanbul ignore if
1595
+ this condition exists only because of three.js types + strict mode
1596
+ */
1597
+ if (typeof sdr === 'string' || typeof gainMap === 'string' || typeof json !== 'string')
1598
+ throw new Error('Invalid response types');
1599
+ // TODO: implement check on JSON file
1600
+ const metadata = JSON.parse(json);
1601
+ await this.fillNode(node, metadata, sdr, gainMap);
1602
+ }).then(() => {
1603
+ if (typeof onLoad === 'function')
1604
+ onLoad(node);
1605
+ urls.forEach(url => this.manager.itemEnd(url));
1606
+ }, (error) => {
1607
+ urls.forEach(url => this.manager.itemError(url));
1608
+ if (typeof onError === 'function')
1609
+ onError(error);
1610
+ });
1611
+ return node;
1612
+ }
1613
+ }
1614
+
1215
1615
  /**
1216
1616
  * A Three.js Loader for a JPEG with embedded gainmap metadata (WebGPU version).
1217
1617
  *
1618
+ * @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).
1218
1619
  * @category Loaders
1219
1620
  * @group Loaders
1220
1621
  *
@@ -1261,6 +1662,10 @@
1261
1662
  *
1262
1663
  */
1263
1664
  class HDRJPGLoader extends LoaderBaseWebGPU {
1665
+ constructor(renderer, manager) {
1666
+ super(renderer, manager);
1667
+ warnDeprecated('HDRJPGLoader', '@monogrid/gainmap-js/webgpu', 'HDRJPGNodeLoader');
1668
+ }
1264
1669
  /**
1265
1670
  * Loads a JPEG containing gain map metadata
1266
1671
  * Renders a normal SDR image if gainmap data is not found
@@ -1339,19 +1744,121 @@
1339
1744
  }
1340
1745
  }
1341
1746
 
1747
+ /**
1748
+ * A Three.js Loader for a JPEG with embedded gain map metadata,
1749
+ * returning a {@link GainMapNode} (a TSL texture node holding the decoded HDR image).
1750
+ *
1751
+ * No renderer is needed: `load` returns the node synchronously
1752
+ * (like `TextureLoader` returns a `Texture`), it can be assigned to materials right away
1753
+ * and it is decoded on the GPU once loaded.
1754
+ *
1755
+ * @category Loaders
1756
+ * @group Loaders
1757
+ *
1758
+ * @example
1759
+ * import { HDRJPGNodeLoader } from '@monogrid/gainmap-js/webgpu'
1760
+ * import { equirectUV } from 'three/tsl'
1761
+ * import { MeshBasicNodeMaterial } from 'three/webgpu'
1762
+ *
1763
+ * const hdr = new HDRJPGNodeLoader().load('gainmap.jpeg')
1764
+ *
1765
+ * const material = new MeshBasicNodeMaterial()
1766
+ * material.colorNode = hdr
1767
+ *
1768
+ * scene.backgroundNode = hdr.sample(equirectUV())
1769
+ *
1770
+ * // all parameters are uniforms, changing them re-decodes the image once
1771
+ * hdr.maxDisplayBoost.value = 2
1772
+ */
1773
+ class HDRJPGNodeLoader extends LoaderBaseNode {
1774
+ /**
1775
+ * Loads a JPEG containing gain map metadata
1776
+ * Renders a normal SDR image if gainmap data is not found
1777
+ *
1778
+ * @param url Path to a JPEG file containing embedded gain map metadata
1779
+ * @param onLoad Load complete callback, will receive the node
1780
+ * @param onProgress Progress callback, will receive a `ProgressEvent`
1781
+ * @param onError Error callback
1782
+ * @returns a node which can be used immediately, it will hold the image once loaded
1783
+ */
1784
+ load(url, onLoad, onProgress, onError) {
1785
+ const node = new GainMapNode();
1786
+ this.manager.itemStart(url);
1787
+ this.createFileLoader('arraybuffer').load(url, async (jpeg) => {
1788
+ try {
1789
+ /* istanbul ignore if
1790
+ this condition exists only because of three.js types + strict mode
1791
+ */
1792
+ if (typeof jpeg === 'string')
1793
+ throw new Error('Invalid buffer, received [string], was expecting [ArrayBuffer]');
1794
+ const jpegBuffer = new Uint8Array(jpeg);
1795
+ let sdrJPEG;
1796
+ let gainMapJPEG;
1797
+ let metadata;
1798
+ try {
1799
+ const extractionResult = await extractGainmapFromJPEG(jpegBuffer);
1800
+ sdrJPEG = extractionResult.sdr;
1801
+ gainMapJPEG = extractionResult.gainMap;
1802
+ metadata = extractionResult.metadata;
1803
+ }
1804
+ catch (e) {
1805
+ // render the SDR version if this is not a gainmap
1806
+ if (e instanceof XMPMetadataNotFoundError || e instanceof GainMapNotFoundError) {
1807
+ console.warn(`Failure to reconstruct an HDR image from ${url}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`);
1808
+ metadata = {
1809
+ gainMapMin: [0, 0, 0],
1810
+ gainMapMax: [1, 1, 1],
1811
+ gamma: [1, 1, 1],
1812
+ hdrCapacityMin: 0,
1813
+ hdrCapacityMax: 1,
1814
+ offsetHdr: [0, 0, 0],
1815
+ offsetSdr: [0, 0, 0]
1816
+ };
1817
+ sdrJPEG = jpegBuffer;
1818
+ }
1819
+ else {
1820
+ throw e;
1821
+ }
1822
+ }
1823
+ await this.fillNode(node, metadata, sdrJPEG.buffer, gainMapJPEG?.buffer);
1824
+ }
1825
+ catch (error) {
1826
+ this.manager.itemError(url);
1827
+ if (typeof onError === 'function')
1828
+ onError(error);
1829
+ return;
1830
+ }
1831
+ if (typeof onLoad === 'function')
1832
+ onLoad(node);
1833
+ this.manager.itemEnd(url);
1834
+ }, onProgress, (error) => {
1835
+ this.manager.itemError(url);
1836
+ if (typeof onError === 'function')
1837
+ onError(error);
1838
+ });
1839
+ return node;
1840
+ }
1841
+ }
1842
+
1342
1843
  exports.GainMapDecoderMaterial = GainMapDecoderMaterial;
1343
1844
  exports.GainMapLoader = GainMapLoader;
1845
+ exports.GainMapNode = GainMapNode;
1846
+ exports.GainMapNodeLoader = GainMapNodeLoader;
1344
1847
  exports.GainMapNotFoundError = GainMapNotFoundError;
1345
1848
  exports.HDRJPGLoader = HDRJPGLoader;
1849
+ exports.HDRJPGNodeLoader = HDRJPGNodeLoader;
1346
1850
  exports.JPEGRLoader = HDRJPGLoader;
1347
1851
  exports.LoaderBaseShared = LoaderBaseShared;
1348
1852
  exports.MPFExtractor = MPFExtractor;
1349
1853
  exports.QuadRenderer = QuadRenderer;
1350
1854
  exports.XMPMetadataNotFoundError = XMPMetadataNotFoundError;
1351
1855
  exports.createDecodeFunction = createDecodeFunction;
1856
+ exports.createTextures = createTextures;
1352
1857
  exports.decode = decode;
1353
1858
  exports.extractGainmapFromJPEG = extractGainmapFromJPEG;
1354
1859
  exports.extractISO = extractISO;
1355
1860
  exports.extractXMP = extractXMP;
1861
+ exports.gainMapNode = gainMapNode;
1862
+ exports.processImages = processImages;
1356
1863
 
1357
1864
  }));