@monogrid/gainmap-js 3.6.1 → 3.7.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 (60) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +86 -13
  3. package/dist/GainMapNode-Cz4_NIGH.js +5 -0
  4. package/dist/GainMapNode-Dl8yqSVg.js +342 -0
  5. package/dist/{warn-deprecated-DtCQWGKi.js → Loader-BNe3xn0l.js} +3 -19
  6. package/dist/{warn-deprecated-gLZfP_DV.js → Loader-DcZ7MyM7.js} +2 -2
  7. package/dist/{QuadRenderer-DMno-Vj6.js → QuadRenderer-BOS9Aas1.js} +1 -1
  8. package/dist/{QuadRenderer-Bhn3yOPC.js → QuadRenderer-BqD-oQ7D.js} +1 -1
  9. package/dist/{_commonjsHelpers-DFuDJEaJ.js → _commonjsHelpers-DrNnMDE-.js} +1 -1
  10. package/dist/{_commonjsHelpers-C8qmDUO8.js → _commonjsHelpers-pGJUN9hi.js} +1 -1
  11. package/dist/{compress-oIjJuPa8.js → compress-DA31yhmz.js} +1 -1
  12. package/dist/{compress-TBp7MS8D.js → compress-goZ8TdVo.js} +1 -1
  13. package/dist/core/webgpu/RenderTargetNode.d.ts +83 -0
  14. package/dist/decode/shared/utils/warn-deprecated.d.ts +1 -1
  15. package/dist/decode/webgl/decode.d.ts +0 -1
  16. package/dist/decode/webgl/index.d.ts +0 -1
  17. package/dist/decode/webgl/loaders/GainMapLoader.d.ts +1 -3
  18. package/dist/decode/webgl/loaders/HDRJPGLoader.d.ts +1 -3
  19. package/dist/decode/webgl/materials/GainMapDecoderMaterial.d.ts +0 -1
  20. package/dist/decode/webgpu/index.d.ts +1 -0
  21. package/dist/decode/webgpu/nodes/GainMapNode.d.ts +13 -19
  22. package/dist/decode.js +5 -18
  23. package/dist/decode.min.js +2 -2
  24. package/dist/decode.umd.cjs +1 -30
  25. package/dist/decode.umd.min.cjs +2 -2
  26. package/dist/decode.webgpu.js +27 -232
  27. package/dist/decode.webgpu.min.js +2 -2
  28. package/dist/decode.webgpu.umd.cjs +176 -65
  29. package/dist/decode.webgpu.umd.min.cjs +2 -2
  30. package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
  31. package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
  32. package/dist/encode/webgpu/index.d.ts +8 -0
  33. package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
  34. package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
  35. package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
  36. package/dist/encode.js +5 -36
  37. package/dist/encode.min.js +2 -2
  38. package/dist/encode.umd.cjs +1 -1
  39. package/dist/encode.umd.min.cjs +1 -1
  40. package/dist/encode.webgpu.js +636 -0
  41. package/dist/encode.webgpu.min.js +5 -0
  42. package/dist/encode.webgpu.umd.cjs +1086 -0
  43. package/dist/encode.webgpu.umd.min.cjs +5 -0
  44. package/dist/get-data-texture-CpszSMzv.js +40 -0
  45. package/dist/get-data-texture-Dlg6zKSG.js +5 -0
  46. package/dist/{iso-gainmap-metadata-C1io5isX.js → iso-gainmap-metadata-BwLnWVQ-.js} +1 -1
  47. package/dist/{iso-gainmap-metadata-Oi7gAKNC.js → iso-gainmap-metadata-CuDCCi9d.js} +1 -1
  48. package/dist/libultrahdr.js +2 -2
  49. package/dist/libultrahdr.min.js +2 -2
  50. package/dist/libultrahdr.umd.cjs +1 -1
  51. package/dist/libultrahdr.umd.min.cjs +1 -1
  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 -1
  59. package/dist/worker.umd.min.cjs +1 -1
  60. package/package.json +9 -1
@@ -1,14 +1,16 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
- import { w as warnDeprecated, c as createDecodeFunction, L as LoaderBaseShared, p as processImages, a as createTextures, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './warn-deprecated-DtCQWGKi.js';
7
- export { M as MPFExtractor, b as extractISO, d as extractXMP } from './warn-deprecated-DtCQWGKi.js';
8
- import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader, TextureNode, LinearMipmapLinearFilter, HalfFloatType, NodeUpdateType, QuadMesh, RendererUtils, Loader } from 'three/webgpu';
6
+ import { G as GainMapNode } from './GainMapNode-Dl8yqSVg.js';
7
+ export { R as RenderTargetNode, g as gainMapNode } from './GainMapNode-Dl8yqSVg.js';
8
+ import { c as createDecodeFunction, L as LoaderBaseShared, p as processImages, a as createTextures, e as extractGainmapFromJPEG, X as XMPMetadataNotFoundError, G as GainMapNotFoundError } from './Loader-BNe3xn0l.js';
9
+ export { M as MPFExtractor, b as extractISO, d as extractXMP } from './Loader-BNe3xn0l.js';
10
+ import { ClampToEdgeWrapping, LinearFilter, Scene, OrthographicCamera, Mesh, PlaneGeometry, RenderTarget, RGBAFormat, UVMapping, WebGPURenderer, DataTexture, LinearSRGBColorSpace, ShaderMaterial, Texture, MeshBasicNodeMaterial, NoBlending, Vector3, FileLoader, Loader } from 'three/webgpu';
9
11
  import 'three';
10
- import { vec3, texture, uniform, mix, saturate, log2, exp2, vec4 } from 'three/tsl';
11
- import './iso-gainmap-metadata-C1io5isX.js';
12
+ import { vec3, texture, uniform } from 'three/tsl';
13
+ import './iso-gainmap-metadata-BwLnWVQ-.js';
12
14
 
13
15
  /**
14
16
  * Utility class used for rendering a texture with a material (WebGPU version)
@@ -249,10 +251,26 @@ class QuadRenderer {
249
251
  get colorSpace() { return this._colorSpace; }
250
252
  }
251
253
 
254
+ const warned = new Set();
255
+ /**
256
+ * Warns once per API that a render target based decode API is going away in v4.0.0
257
+ *
258
+ * @param name deprecated API
259
+ * @param entry entry point exposing the deprecated API
260
+ * @param replacement node based API replacing it, from `@monogrid/gainmap-js/webgpu`
261
+ */
262
+ const warnDeprecated = (name, entry, replacement) => {
263
+ const key = `${entry}:${name}`;
264
+ if (warned.has(key))
265
+ return;
266
+ warned.add(key);
267
+ 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`);
268
+ };
269
+
252
270
  // min half float value
253
271
  const HALF_FLOAT_MIN = vec3(-65504, -65504, -65504);
254
272
  // max half float value
255
- const HALF_FLOAT_MAX$1 = vec3(65504, 65504, 65504);
273
+ const HALF_FLOAT_MAX = vec3(65504, 65504, 65504);
256
274
  /**
257
275
  * A Material which is able to decode the Gainmap into a full HDR Representation using TSL (Three.js Shading Language)
258
276
  *
@@ -307,7 +325,7 @@ class GainMapDecoderMaterial extends MeshBasicNodeMaterial {
307
325
  // the mathematically equivalent pow(2, x) which has proper vec3 typings.
308
326
  const gain = vec3(2).pow(logBoost.mul(this._weightFactorUniform));
309
327
  const hdrColor = rgb.add(this._offsetSdrUniform).mul(gain).sub(this._offsetHdrUniform);
310
- const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX$1).max(HALF_FLOAT_MIN);
328
+ const clampedHdrColor = hdrColor.min(HALF_FLOAT_MAX).max(HALF_FLOAT_MIN);
311
329
  this.colorNode = clampedHdrColor;
312
330
  }
313
331
  get sdr() { return this._sdrTexture.value; }
@@ -703,229 +721,6 @@ class GainMapLoader extends LoaderBaseWebGPU {
703
721
  }
704
722
  }
705
723
 
706
- // max half float value
707
- const HALF_FLOAT_MAX = 65504;
708
- /**
709
- * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
710
- *
711
- * The decode runs on the GPU into a HalfFloat render target, and only when something changed
712
- * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
713
- * texture read, like any other texture.
714
- *
715
- * The node updates itself before rendering whenever it is part of a rendered node graph
716
- * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
717
- * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
718
- *
719
- * Re-decoding also flags the texture for PMREM regeneration,
720
- * so environment maps are recomputed only when the image actually changes.
721
- *
722
- * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
723
- * so assign it to `scene.environment` (or `pmremTexture()`) after load.
724
- *
725
- * @category Nodes
726
- * @group Nodes
727
- *
728
- * @example
729
- * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
730
- * import { equirectUV } from 'three/tsl'
731
- *
732
- * const hdr = new GainMapNode()
733
- * .setTextures(sdrTexture, gainMapTexture)
734
- * .setMetadata(metadata)
735
- *
736
- * material.colorNode = hdr
737
- * scene.backgroundNode = hdr.sample(equirectUV())
738
- * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
739
- */
740
- class GainMapNode extends TextureNode {
741
- static get type() { return 'GainMapNode'; }
742
- /**
743
- * Shared textures and uniforms
744
- */
745
- uniforms;
746
- /**
747
- * The render target holding the decoded HDR image
748
- */
749
- renderTarget;
750
- _quadMesh;
751
- _material;
752
- // filled by RendererUtils.resetRendererState
753
- _rendererState = {};
754
- _state = [];
755
- constructor() {
756
- const renderTarget = new RenderTarget(1, 1, {
757
- type: HalfFloatType,
758
- colorSpace: LinearSRGBColorSpace,
759
- depthBuffer: false,
760
- generateMipmaps: true,
761
- minFilter: LinearMipmapLinearFilter,
762
- magFilter: LinearFilter
763
- });
764
- super(renderTarget.texture);
765
- this.renderTarget = renderTarget;
766
- this.updateBeforeType = NodeUpdateType.RENDER;
767
- const u = this.uniforms = {
768
- sdr: texture(new Texture()),
769
- gainMap: texture(new Texture()),
770
- gamma: uniform(new Vector3(1, 1, 1)),
771
- offsetSdr: uniform(new Vector3()),
772
- offsetHdr: uniform(new Vector3()),
773
- gainMapMin: uniform(new Vector3()),
774
- gainMapMax: uniform(new Vector3(1, 1, 1)),
775
- hdrCapacityMin: uniform(0),
776
- hdrCapacityMax: uniform(1),
777
- maxDisplayBoost: uniform(1)
778
- };
779
- const logRecovery = u.gainMap.rgb.pow(vec3(1).div(u.gamma));
780
- const logBoost = mix(u.gainMapMin, u.gainMapMax, logRecovery);
781
- const weight = saturate(log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
782
- const hdr = u.sdr.rgb.add(u.offsetSdr).mul(exp2(logBoost.mul(weight))).sub(u.offsetHdr);
783
- this._material = new MeshBasicNodeMaterial();
784
- this._material.name = 'GainMapDecoder';
785
- this._material.colorNode = vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
786
- this._quadMesh = new QuadMesh(this._material);
787
- }
788
- /** The SDR rendition texture (sRGB) */
789
- get sdr() { return this.uniforms.sdr.value; }
790
- /** The gain map recovery texture (linear) */
791
- get gainMap() { return this.uniforms.gainMap.value; }
792
- /** @see {@link GainMapMetadata.gamma} */
793
- get gamma() { return this.uniforms.gamma; }
794
- /** @see {@link GainMapMetadata.offsetSdr} */
795
- get offsetSdr() { return this.uniforms.offsetSdr; }
796
- /** @see {@link GainMapMetadata.offsetHdr} */
797
- get offsetHdr() { return this.uniforms.offsetHdr; }
798
- /** @see {@link GainMapMetadata.gainMapMin} */
799
- get gainMapMin() { return this.uniforms.gainMapMin; }
800
- /** @see {@link GainMapMetadata.gainMapMax} */
801
- get gainMapMax() { return this.uniforms.gainMapMax; }
802
- /** @see {@link GainMapMetadata.hdrCapacityMin} */
803
- get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
804
- /** @see {@link GainMapMetadata.hdrCapacityMax} */
805
- get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
806
- /**
807
- * @see {@link GainmapDecodingParameters.maxDisplayBoost}
808
- * @remarks Non Logarithmic space
809
- */
810
- get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
811
- /** Width of the SDR image, 0 until loaded */
812
- get width() { return this.sdr.image?.width ?? 0; }
813
- /** Height of the SDR image, 0 until loaded */
814
- get height() { return this.sdr.image?.height ?? 0; }
815
- /**
816
- * Sets the SDR and gain map textures.
817
- * The SDR texture is expected in sRGB color space, the gain map in linear.
818
- *
819
- * @param sdr
820
- * @param gainMap
821
- */
822
- setTextures(sdr, gainMap) {
823
- this.uniforms.sdr.value = sdr;
824
- this.uniforms.gainMap.value = gainMap;
825
- // size the render target right away, so `value` has its final size before the first decode
826
- if (this.width > 0 && this.height > 0)
827
- this.renderTarget.setSize(this.width, this.height);
828
- return this;
829
- }
830
- /**
831
- * Copies the gain map metadata into the uniforms.
832
- * Also sets `maxDisplayBoost` to fully restore the HDR range.
833
- *
834
- * @param metadata
835
- */
836
- setMetadata(metadata) {
837
- const u = this.uniforms;
838
- u.gamma.value.fromArray(metadata.gamma);
839
- u.offsetSdr.value.fromArray(metadata.offsetSdr);
840
- u.offsetHdr.value.fromArray(metadata.offsetHdr);
841
- u.gainMapMin.value.fromArray(metadata.gainMapMin);
842
- u.gainMapMax.value.fromArray(metadata.gainMapMax);
843
- u.hdrCapacityMin.value = metadata.hdrCapacityMin;
844
- u.hdrCapacityMax.value = metadata.hdrCapacityMax;
845
- u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
846
- return this;
847
- }
848
- _currentState() {
849
- const u = this.uniforms;
850
- return [
851
- this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
852
- ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
853
- ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
854
- u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
855
- ];
856
- }
857
- /**
858
- * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
859
- *
860
- * Called automatically when the node is part of a rendered node graph.
861
- *
862
- * @param renderer
863
- * @returns `true` if the image was decoded
864
- */
865
- decode(renderer) {
866
- // not loaded yet
867
- if (this.width === 0 || this.height === 0)
868
- return false;
869
- const state = this._currentState();
870
- if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
871
- return false;
872
- this._state = state;
873
- RendererUtils.resetRendererState(renderer, this._rendererState);
874
- renderer.setRenderTarget(this.renderTarget);
875
- this._quadMesh.render(renderer);
876
- RendererUtils.restoreRendererState(renderer, this._rendererState);
877
- this.value.needsPMREMUpdate = true;
878
- return true;
879
- }
880
- /**
881
- * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
882
- *
883
- * @param frame
884
- */
885
- updateBefore(frame) {
886
- if (frame.renderer)
887
- this.decode(frame.renderer);
888
- return undefined;
889
- }
890
- set value(value) {
891
- if (this.renderTarget && value !== this.renderTarget.texture) {
892
- throw new Error('GainMapNode: the value of this node is its render target texture and can\'t be replaced');
893
- }
894
- }
895
- get value() {
896
- return this.renderTarget?.texture;
897
- }
898
- /**
899
- * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
900
- * they keep it updated before rendering as well
901
- */
902
- clone() {
903
- const node = new TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
904
- node.sampler = this.sampler;
905
- node.updateBeforeType = NodeUpdateType.RENDER;
906
- node.updateBefore = (frame) => this.updateBefore(frame);
907
- return node;
908
- }
909
- /**
910
- * Disposes the render target, the SDR and gain map textures
911
- */
912
- dispose() {
913
- this.renderTarget.dispose();
914
- this._material.dispose();
915
- this.sdr.dispose();
916
- this.gainMap.dispose();
917
- super.dispose();
918
- }
919
- }
920
- /**
921
- * TSL function creating a {@link GainMapNode} from an SDR texture, a gain map texture and its metadata
922
- *
923
- * @param sdr
924
- * @param gainMap
925
- * @param metadata
926
- */
927
- const gainMapNode = (sdr, gainMap, metadata) => new GainMapNode().setTextures(sdr, gainMap).setMetadata(metadata);
928
-
929
724
  /**
930
725
  * Base class for loaders returning a {@link GainMapNode}
931
726
  * @template TUrl - The type of URL used to load resources
@@ -1270,4 +1065,4 @@ class HDRJPGNodeLoader extends LoaderBaseNode {
1270
1065
  }
1271
1066
  }
1272
1067
 
1273
- export { GainMapDecoderMaterial, GainMapLoader, GainMapNode, GainMapNodeLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGNodeLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, createTextures, decode, extractGainmapFromJPEG, gainMapNode, processImages };
1068
+ export { GainMapDecoderMaterial, GainMapLoader, GainMapNode, GainMapNodeLoader, GainMapNotFoundError, HDRJPGLoader, HDRJPGNodeLoader, HDRJPGLoader as JPEGRLoader, LoaderBaseShared, QuadRenderer, XMPMetadataNotFoundError, createDecodeFunction, createTextures, decode, extractGainmapFromJPEG, processImages };
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.1
2
+ * @monogrid/gainmap-js v3.7.1
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- import{w as e,c as t,L as r,p as a,a as i,e as s,X as n,G as o}from"./warn-deprecated-gLZfP_DV.js";export{M as MPFExtractor,b as extractISO,d as extractXMP}from"./warn-deprecated-gLZfP_DV.js";import{ClampToEdgeWrapping as h,LinearFilter as p,Scene as m,OrthographicCamera as g,Mesh as f,PlaneGeometry as u,RenderTarget as l,RGBAFormat as c,UVMapping as _,WebGPURenderer as y,DataTexture as w,LinearSRGBColorSpace as x,ShaderMaterial as v,Texture as T,MeshBasicNodeMaterial as C,NoBlending as S,Vector3 as U,FileLoader as R,TextureNode as E,LinearMipmapLinearFilter as D,HalfFloatType as H,NodeUpdateType as B,QuadMesh as O,RendererUtils as P,Loader as F}from"three/webgpu";import"three";import{vec3 as N,texture as q,uniform as A,mix as L,saturate as I,log2 as z,exp2 as G,vec4 as j}from"three/tsl";import"./iso-gainmap-metadata-Oi7gAKNC.js";class W{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const t={format:c,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:p,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:p,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:h,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:h};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=W.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new m,this._camera=new g,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),this._quad=new f(new u,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new l(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:_}static instantiateRenderer(){const e=new y;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const s=(this._height-1-i)*r;a.set(e.subarray(s,s+t),i*t)}return a}async toDataTexture(e){const t=new w(await this.toArray(),this.width,this.height,c,this._type,e?.mapping||_,e?.wrapS||h,e?.wrapT||h,e?.magFilter||p,e?.minFilter||p,e?.anisotropy||1,x);return t.flipY=void 0===e?.flipY||e?.flipY,t.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof v&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof T&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof T&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const J=N(-65504,-65504,-65504),Q=N(65504,65504,65504);class Y extends C{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:r,gainMapMin:a,gainMapMax:i,maxDisplayBoost:s,hdrCapacityMin:n,hdrCapacityMax:o,sdr:h,gainMap:d}){super(),this.name="GainMapDecoderMaterial",this.blending=S,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=q(h),this._gainMapTexture=q(d),this._gammaUniform=A(new U(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=A(new U(t[0],t[1],t[2])),this._offsetSdrUniform=A(new U(r[0],r[1],r[2])),this._gainMapMinUniform=A(new U(a[0],a[1],a[2])),this._gainMapMaxUniform=A(new U(i[0],i[1],i[2]));const p=(Math.log2(s)-n)/(o-n);this._weightFactorUniform=A(p,"float"),this._maxDisplayBoost=s,this._hdrCapacityMin=n,this._hdrCapacityMax=o;const m=this._sdrTexture.rgb,g=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(g.oneMinus()).add(this._gainMapMaxUniform.mul(g)),u=N(2).pow(f.mul(this._weightFactorUniform)),l=m.add(this._offsetSdrUniform).mul(u).sub(this._offsetHdrUniform).min(Q).max(J);this.colorNode=l}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const k=t({renderer:y,createMaterial:e=>new Y(e),createQuadRenderer:e=>new W(e)}),X=async t=>{if(e("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!t.renderer)throw new Error("Renderer is required for decode function");const r=k({...t,renderer:t.renderer});try{await r.render()}catch(e){throw r.disposeOnDemandRenderer(),e}return r};class $ extends r{constructor(e,t){super({renderer:e,createMaterial:e=>new Y(e),createQuadRenderer:e=>new W(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:s,needsFlip:n}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:h}=this.createTextures(i,s,n);this.updateQuadRenderer(e,i,o,h,t),await e.render()}}class K extends ${constructor(t,r){super(t,r),e("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,t,r],a,i,s){const n=this.prepareQuadRenderer();let o,h,d;const p=async()=>{if(o&&h&&d){try{await this.render(n,d,o,h)}catch(a){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(r),"function"==typeof s&&s(a),void n.disposeOnDemandRenderer()}"function"==typeof a&&a(n),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(r),n.disposeOnDemandRenderer()}};let m=!0,g=0,f=0,u=!0,l=0,c=0,M=!0,_=0,y=0;const w=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:m&&u&&M,loaded:f+c+y,total:g+l+_}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(r);const x=new R(this._internalLoadingManager);x.setResponseType("arraybuffer"),x.setRequestHeader(this.requestHeader),x.setPath(this.path),x.setWithCredentials(this.withCredentials),x.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");o=e,await p()},e=>{m=e.lengthComputable,f=e.loaded,g=e.total,w()},t=>{this.manager.itemError(e),"function"==typeof s&&s(t)});const v=new R(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await p()},e=>{u=e.lengthComputable,c=e.loaded,l=e.total,w()},e=>{this.manager.itemError(t),"function"==typeof s&&s(e)});const T=new R(this._internalLoadingManager);return T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");d=JSON.parse(e),await p()},e=>{M=e.lengthComputable,y=e.loaded,_=e.total,w()},e=>{this.manager.itemError(r),"function"==typeof s&&s(e)}),n}}class V extends E{static get type(){return"GainMapNode"}uniforms;renderTarget;_quadMesh;_material;_rendererState={};_state=[];constructor(){const e=new l(1,1,{type:H,colorSpace:x,depthBuffer:!1,generateMipmaps:!0,minFilter:D,magFilter:p});super(e.texture),this.renderTarget=e,this.updateBeforeType=B.RENDER;const t=this.uniforms={sdr:q(new T),gainMap:q(new T),gamma:A(new U(1,1,1)),offsetSdr:A(new U),offsetHdr:A(new U),gainMapMin:A(new U),gainMapMax:A(new U(1,1,1)),hdrCapacityMin:A(0),hdrCapacityMax:A(1),maxDisplayBoost:A(1)},r=t.gainMap.rgb.pow(N(1).div(t.gamma)),a=L(t.gainMapMin,t.gainMapMax,r),i=I(z(t.maxDisplayBoost).sub(t.hdrCapacityMin).div(t.hdrCapacityMax.sub(t.hdrCapacityMin))),s=t.sdr.rgb.add(t.offsetSdr).mul(G(a.mul(i))).sub(t.offsetHdr);this._material=new C,this._material.name="GainMapDecoder",this._material.colorNode=j(s.clamp(-65504,65504),1),this._quadMesh=new O(this._material)}get sdr(){return this.uniforms.sdr.value}get gainMap(){return this.uniforms.gainMap.value}get gamma(){return this.uniforms.gamma}get offsetSdr(){return this.uniforms.offsetSdr}get offsetHdr(){return this.uniforms.offsetHdr}get gainMapMin(){return this.uniforms.gainMapMin}get gainMapMax(){return this.uniforms.gainMapMax}get hdrCapacityMin(){return this.uniforms.hdrCapacityMin}get hdrCapacityMax(){return this.uniforms.hdrCapacityMax}get maxDisplayBoost(){return this.uniforms.maxDisplayBoost}get width(){return this.sdr.image?.width??0}get height(){return this.sdr.image?.height??0}setTextures(e,t){return this.uniforms.sdr.value=e,this.uniforms.gainMap.value=t,this.width>0&&this.height>0&&this.renderTarget.setSize(this.width,this.height),this}setMetadata(e){const t=this.uniforms;return t.gamma.value.fromArray(e.gamma),t.offsetSdr.value.fromArray(e.offsetSdr),t.offsetHdr.value.fromArray(e.offsetHdr),t.gainMapMin.value.fromArray(e.gainMapMin),t.gainMapMax.value.fromArray(e.gainMapMax),t.hdrCapacityMin.value=e.hdrCapacityMin,t.hdrCapacityMax.value=e.hdrCapacityMax,t.maxDisplayBoost.value=Math.pow(2,e.hdrCapacityMax),this}_currentState(){const e=this.uniforms;return[this.sdr.id,this.sdr.version,this.gainMap.id,this.gainMap.version,...e.gamma.value.toArray(),...e.offsetSdr.value.toArray(),...e.offsetHdr.value.toArray(),...e.gainMapMin.value.toArray(),...e.gainMapMax.value.toArray(),e.hdrCapacityMin.value,e.hdrCapacityMax.value,e.maxDisplayBoost.value]}decode(e){if(0===this.width||0===this.height)return!1;const t=this._currentState();return(t.length!==this._state.length||!t.every((e,t)=>e===this._state[t]))&&(this._state=t,P.resetRendererState(e,this._rendererState),e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),P.restoreRendererState(e,this._rendererState),this.value.needsPMREMUpdate=!0,!0)}updateBefore(e){e.renderer&&this.decode(e.renderer)}set value(e){if(this.renderTarget&&e!==this.renderTarget.texture)throw new Error("GainMapNode: the value of this node is its render target texture and can't be replaced")}get value(){return this.renderTarget?.texture}clone(){const e=new E(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.updateBeforeType=B.RENDER,e.updateBefore=e=>this.updateBefore(e),e}dispose(){this.renderTarget.dispose(),this._material.dispose(),this.sdr.dispose(),this.gainMap.dispose(),super.dispose()}}const Z=(e,t,r)=>(new V).setTextures(e,t).setMetadata(r);class ee extends F{createFileLoader(e){const t=new R(this.manager);return e&&t.setResponseType(e),t.setRequestHeader(this.requestHeader),t.setPath(this.path),t.setWithCredentials(this.withCredentials),t}async fillNode(e,t,r,s){const{sdrImage:n,gainMapImage:o}=await a(r,s,"from-image"),{sdr:h,gainMap:d}=i(n,o,!0);e.setTextures(h,d).setMetadata(t)}}class te extends ee{load(e,t,r,a){const i=new V,s=e.map(()=>({lengthComputable:!0,loaded:0,total:0})),n=(e,t,a)=>new Promise((i,n)=>{this.manager.itemStart(e),this.createFileLoader(a).load(e,i,e=>{s[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof r&&r(new ProgressEvent("progress",{lengthComputable:s.every(e=>e.lengthComputable),loaded:s.reduce((e,t)=>e+t.loaded,0),total:s.reduce((e,t)=>e+t.total,0)}))},n)}),[o,h,d]=e;return Promise.all([n(o,0,"arraybuffer"),n(h,1,"arraybuffer"),n(d,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(i,a,e,t)}).then(()=>{"function"==typeof t&&t(i),e.forEach(e=>this.manager.itemEnd(e))},t=>{e.forEach(e=>this.manager.itemError(e)),"function"==typeof a&&a(t)}),i}}class re extends ${constructor(t,r){super(t,r),e("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,t,r,a){const i=this.prepareQuadRenderer(),h=new R(this._internalLoadingManager);return h.setResponseType("arraybuffer"),h.setRequestHeader(this.requestHeader),h.setPath(this.path),h.setWithCredentials(this.withCredentials),this.manager.itemStart(e),h.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const h=new Uint8Array(r);let d,p,m;try{const e=await s(h);d=e.sdr,p=e.gainMap,m=e.metadata}catch(t){if(!(t instanceof n||t instanceof o))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),m={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=h}try{await this.render(i,m,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof a&&a(t),void i.disposeOnDemandRenderer()}"function"==typeof t&&t(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}}class ae extends ee{load(e,t,r,a){const i=new V;return this.manager.itemStart(e),this.createFileLoader("arraybuffer").load(e,async r=>{try{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const t=new Uint8Array(r);let a,h,d;try{const e=await s(t);a=e.sdr,h=e.gainMap,d=e.metadata}catch(r){if(!(r instanceof n||r instanceof o))throw r;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=t}await this.fillNode(i,d,a.buffer,h?.buffer)}catch(t){return this.manager.itemError(e),void("function"==typeof a&&a(t))}"function"==typeof t&&t(i),this.manager.itemEnd(e)},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}}export{Y as GainMapDecoderMaterial,K as GainMapLoader,V as GainMapNode,te as GainMapNodeLoader,o as GainMapNotFoundError,re as HDRJPGLoader,ae as HDRJPGNodeLoader,re as JPEGRLoader,r as LoaderBaseShared,W as QuadRenderer,n as XMPMetadataNotFoundError,t as createDecodeFunction,i as createTextures,X as decode,s as extractGainmapFromJPEG,Z as gainMapNode,a as processImages};
5
+ import{G as e}from"./GainMapNode-Cz4_NIGH.js";export{R as RenderTargetNode,g as gainMapNode}from"./GainMapNode-Cz4_NIGH.js";import{c as t,L as r,p as a,a as i,e as n,X as s,G as o}from"./Loader-DcZ7MyM7.js";export{M as MPFExtractor,b as extractISO,d as extractXMP}from"./Loader-DcZ7MyM7.js";import{ClampToEdgeWrapping as h,LinearFilter as p,Scene as m,OrthographicCamera as f,Mesh as l,PlaneGeometry as c,RenderTarget as u,RGBAFormat as _,UVMapping as w,WebGPURenderer as y,DataTexture as x,LinearSRGBColorSpace as v,ShaderMaterial as T,Texture as U,MeshBasicNodeMaterial as E,NoBlending as S,Vector3 as C,FileLoader as H,Loader as O}from"three/webgpu";import"three";import{vec3 as D,texture as P,uniform as L}from"three/tsl";import"./iso-gainmap-metadata-CuDCCi9d.js";class F{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(e){this._width=e.width,this._height=e.height,this._type=e.type,this._colorSpace=e.colorSpace;const t={format:_,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:void 0!==e.renderTargetOptions?.anisotropy?e.renderTargetOptions?.anisotropy:1,generateMipmaps:void 0!==e.renderTargetOptions?.generateMipmaps&&e.renderTargetOptions?.generateMipmaps,magFilter:void 0!==e.renderTargetOptions?.magFilter?e.renderTargetOptions?.magFilter:p,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:p,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:h,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:h};this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=F.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new m,this._camera=new f,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),this._quad=new l(new c,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new u(this.width,this.height,t),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:w}static instantiateRenderer(){const e=new y;return e.setSize(128,128),e}render=async()=>{this._renderer.hasInitialized()||await this._renderer.init(),this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};async toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=await this._renderer.readRenderTargetPixelsAsync(this._renderTarget,0,0,this._width,this._height);if(!this._renderer.backend.isWebGPUBackend)return e;const t=4*this._width,r=256*Math.ceil(t*e.BYTES_PER_ELEMENT/256)/e.BYTES_PER_ELEMENT,a=new e.constructor(t*this._height);for(let i=0;i<this._height;i++){const n=(this._height-1-i)*r;a.set(e.subarray(n,n+t),i*t)}return a}async toDataTexture(e){const t=new x(await this.toArray(),this.width,this.height,_,this._type,e?.mapping||w,e?.wrapS||h,e?.wrapT||h,e?.magFilter||p,e?.minFilter||p,e?.anisotropy||1,v);return t.flipY=void 0===e?.flipY||e?.flipY,t.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&this._renderer.dispose().catch(console.error)}dispose(e){e&&this.renderTarget.dispose(),this.material instanceof T&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof U&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof U&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose(),this.disposeOnDemandRenderer()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}}const G=new Set,I=(e,t,r)=>{const a=`${t}:${e}`;G.has(a)||(G.add(a),console.warn(`gainmap-js: ${e} from '${t}' is deprecated and will be removed in v4.0.0. Use ${r} 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`))},N=D(-65504,-65504,-65504),B=D(65504,65504,65504);class j extends E{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;_gammaUniform;_offsetHdrUniform;_offsetSdrUniform;_gainMapMinUniform;_gainMapMaxUniform;_weightFactorUniform;_sdrTexture;_gainMapTexture;constructor({gamma:e,offsetHdr:t,offsetSdr:r,gainMapMin:a,gainMapMax:i,maxDisplayBoost:n,hdrCapacityMin:s,hdrCapacityMax:o,sdr:h,gainMap:d}){super(),this.name="GainMapDecoderMaterial",this.blending=S,this.depthTest=!1,this.depthWrite=!1,this._sdrTexture=P(h),this._gainMapTexture=P(d),this._gammaUniform=L(new C(1/e[0],1/e[1],1/e[2])),this._offsetHdrUniform=L(new C(t[0],t[1],t[2])),this._offsetSdrUniform=L(new C(r[0],r[1],r[2])),this._gainMapMinUniform=L(new C(a[0],a[1],a[2])),this._gainMapMaxUniform=L(new C(i[0],i[1],i[2]));const p=(Math.log2(n)-s)/(o-s);this._weightFactorUniform=L(p,"float"),this._maxDisplayBoost=n,this._hdrCapacityMin=s,this._hdrCapacityMax=o;const m=this._sdrTexture.rgb,g=this._gainMapTexture.rgb.pow(this._gammaUniform),f=this._gainMapMinUniform.mul(g.oneMinus()).add(this._gainMapMaxUniform.mul(g)),l=D(2).pow(f.mul(this._weightFactorUniform)),c=m.add(this._offsetSdrUniform).mul(l).sub(this._offsetHdrUniform).min(B).max(N);this.colorNode=c}get sdr(){return this._sdrTexture.value}set sdr(e){this._sdrTexture.value=e}get gainMap(){return this._gainMapTexture.value}set gainMap(e){this._gainMapTexture.value=e}get offsetHdr(){return[this._offsetHdrUniform.value.x,this._offsetHdrUniform.value.y,this._offsetHdrUniform.value.z]}set offsetHdr(e){this._offsetHdrUniform.value.x=e[0],this._offsetHdrUniform.value.y=e[1],this._offsetHdrUniform.value.z=e[2]}get offsetSdr(){return[this._offsetSdrUniform.value.x,this._offsetSdrUniform.value.y,this._offsetSdrUniform.value.z]}set offsetSdr(e){this._offsetSdrUniform.value.x=e[0],this._offsetSdrUniform.value.y=e[1],this._offsetSdrUniform.value.z=e[2]}get gainMapMin(){return[this._gainMapMinUniform.value.x,this._gainMapMinUniform.value.y,this._gainMapMinUniform.value.z]}set gainMapMin(e){this._gainMapMinUniform.value.x=e[0],this._gainMapMinUniform.value.y=e[1],this._gainMapMinUniform.value.z=e[2]}get gainMapMax(){return[this._gainMapMaxUniform.value.x,this._gainMapMaxUniform.value.y,this._gainMapMaxUniform.value.z]}set gainMapMax(e){this._gainMapMaxUniform.value.x=e[0],this._gainMapMaxUniform.value.y=e[1],this._gainMapMaxUniform.value.z=e[2]}get gamma(){return[1/this._gammaUniform.value.x,1/this._gammaUniform.value.y,1/this._gammaUniform.value.z]}set gamma(e){this._gammaUniform.value.x=1/e[0],this._gammaUniform.value.y=1/e[1],this._gammaUniform.value.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this._weightFactorUniform.value=Math.max(0,Math.min(1,e))}}const q=t({renderer:y,createMaterial:e=>new j(e),createQuadRenderer:e=>new F(e)}),z=async e=>{if(I("decode()","@monogrid/gainmap-js/webgpu","gainMapNode()"),!e.renderer)throw new Error("Renderer is required for decode function");const t=q({...e,renderer:e.renderer});try{await t.render()}catch(e){throw t.disposeOnDemandRenderer(),e}return t};class W extends r{constructor(e,t){super({renderer:e,createMaterial:e=>new j(e),createQuadRenderer:e=>new F(e)},t)}async render(e,t,r,a){const{sdrImage:i,gainMapImage:n,needsFlip:s}=await this.processImages(r,a,"from-image"),{gainMap:o,sdr:h}=this.createTextures(i,n,s);this.updateQuadRenderer(e,i,o,h,t),await e.render()}}class A extends W{constructor(e,t){super(e,t),I("GainMapLoader","@monogrid/gainmap-js/webgpu","GainMapNodeLoader")}load([e,t,r],a,i,n){const s=this.prepareQuadRenderer();let o,h,d;const p=async()=>{if(o&&h&&d){try{await this.render(s,d,o,h)}catch(a){return this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(r),"function"==typeof n&&n(a),void s.disposeOnDemandRenderer()}"function"==typeof a&&a(s),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(r),s.disposeOnDemandRenderer()}};let m=!0,g=0,f=0,l=!0,c=0,u=0,_=!0,M=0,w=0;const y=()=>{if("function"==typeof i){i(new ProgressEvent("progress",{lengthComputable:m&&l&&_,loaded:f+u+w,total:g+c+M}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(r);const x=new H(this._internalLoadingManager);x.setResponseType("arraybuffer"),x.setRequestHeader(this.requestHeader),x.setPath(this.path),x.setWithCredentials(this.withCredentials),x.load(e,async e=>{if("string"==typeof e)throw new Error("Invalid sdr buffer");o=e,await p()},e=>{m=e.lengthComputable,f=e.loaded,g=e.total,y()},t=>{this.manager.itemError(e),"function"==typeof n&&n(t)});const v=new H(this._internalLoadingManager);v.setResponseType("arraybuffer"),v.setRequestHeader(this.requestHeader),v.setPath(this.path),v.setWithCredentials(this.withCredentials),v.load(t,async e=>{if("string"==typeof e)throw new Error("Invalid gainmap buffer");h=e,await p()},e=>{l=e.lengthComputable,u=e.loaded,c=e.total,y()},e=>{this.manager.itemError(t),"function"==typeof n&&n(e)});const T=new H(this._internalLoadingManager);return T.setRequestHeader(this.requestHeader),T.setPath(this.path),T.setWithCredentials(this.withCredentials),T.load(r,async e=>{if("string"!=typeof e)throw new Error("Invalid metadata string");d=JSON.parse(e),await p()},e=>{_=e.lengthComputable,w=e.loaded,M=e.total,y()},e=>{this.manager.itemError(r),"function"==typeof n&&n(e)}),s}}class J extends O{createFileLoader(e){const t=new H(this.manager);return e&&t.setResponseType(e),t.setRequestHeader(this.requestHeader),t.setPath(this.path),t.setWithCredentials(this.withCredentials),t}async fillNode(e,t,r,n){const{sdrImage:s,gainMapImage:o}=await a(r,n,"from-image"),{sdr:h,gainMap:d}=i(s,o,!0);e.setTextures(h,d).setMetadata(t)}}class $ extends J{load(t,r,a,i){const n=new e,s=t.map(()=>({lengthComputable:!0,loaded:0,total:0})),o=(e,t,r)=>new Promise((i,n)=>{this.manager.itemStart(e),this.createFileLoader(r).load(e,i,e=>{s[t]={lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total},"function"==typeof a&&a(new ProgressEvent("progress",{lengthComputable:s.every(e=>e.lengthComputable),loaded:s.reduce((e,t)=>e+t.loaded,0),total:s.reduce((e,t)=>e+t.total,0)}))},n)}),[h,d,p]=t;return Promise.all([o(h,0,"arraybuffer"),o(d,1,"arraybuffer"),o(p,2)]).then(async([e,t,r])=>{if("string"==typeof e||"string"==typeof t||"string"!=typeof r)throw new Error("Invalid response types");const a=JSON.parse(r);await this.fillNode(n,a,e,t)}).then(()=>{"function"==typeof r&&r(n),t.forEach(e=>this.manager.itemEnd(e))},e=>{t.forEach(e=>this.manager.itemError(e)),"function"==typeof i&&i(e)}),n}}class Q extends W{constructor(e,t){super(e,t),I("HDRJPGLoader","@monogrid/gainmap-js/webgpu","HDRJPGNodeLoader")}load(e,t,r,a){const i=this.prepareQuadRenderer(),h=new H(this._internalLoadingManager);return h.setResponseType("arraybuffer"),h.setRequestHeader(this.requestHeader),h.setPath(this.path),h.setWithCredentials(this.withCredentials),this.manager.itemStart(e),h.load(e,async r=>{if("string"==typeof r)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const h=new Uint8Array(r);let d,p,m;try{const e=await n(h);d=e.sdr,p=e.gainMap,m=e.metadata}catch(t){if(!(t instanceof s||t instanceof o))throw t;console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),m={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},d=h}try{await this.render(i,m,d.buffer,p?.buffer)}catch(t){return this.manager.itemError(e),"function"==typeof a&&a(t),void i.disposeOnDemandRenderer()}"function"==typeof t&&t(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},r,t=>{this.manager.itemError(e),"function"==typeof a&&a(t)}),i}}class Y extends J{load(t,r,a,i){const h=new e;return this.manager.itemStart(t),this.createFileLoader("arraybuffer").load(t,async e=>{try{if("string"==typeof e)throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const r=new Uint8Array(e);let a,i,d;try{const e=await n(r);a=e.sdr,i=e.gainMap,d=e.metadata}catch(e){if(!(e instanceof s||e instanceof o))throw e;console.warn(`Failure to reconstruct an HDR image from ${t}: Gain map metadata not found in the file, HDRJPGNodeLoader will render the SDR jpeg`),d={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},a=r}await this.fillNode(h,d,a.buffer,i?.buffer)}catch(e){return this.manager.itemError(t),void("function"==typeof i&&i(e))}"function"==typeof r&&r(h),this.manager.itemEnd(t)},a,e=>{this.manager.itemError(t),"function"==typeof i&&i(e)}),h}}export{j as GainMapDecoderMaterial,A as GainMapLoader,e as GainMapNode,$ as GainMapNodeLoader,o as GainMapNotFoundError,Q as HDRJPGLoader,Y as HDRJPGNodeLoader,Q as JPEGRLoader,r as LoaderBaseShared,F as QuadRenderer,s as XMPMetadataNotFoundError,t as createDecodeFunction,i as createTextures,z as decode,n as extractGainmapFromJPEG,a as processImages};