@monogrid/gainmap-js 3.6.0 → 3.7.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 (59) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +86 -13
  3. package/dist/GainMapNode-CntuYSg-.js +338 -0
  4. package/dist/GainMapNode-DtVNqKtN.js +5 -0
  5. package/dist/{warn-deprecated-Bk17fVbj.js → Loader-D82gF-Rq.js} +3 -19
  6. package/dist/{warn-deprecated-D0kPpXtA.js → Loader-EFF6JZel.js} +2 -2
  7. package/dist/{QuadRenderer-CXtNzoCY.js → QuadRenderer-DD6leG7y.js} +1 -1
  8. package/dist/{QuadRenderer-DcBTBLz6.js → QuadRenderer-DoK2pW5M.js} +1 -1
  9. package/dist/{_commonjsHelpers-CnYhShyx.js → _commonjsHelpers-C0JuzTK_.js} +1 -1
  10. package/dist/{_commonjsHelpers-Cdw2adc2.js → _commonjsHelpers-p2JmW4Hh.js} +1 -1
  11. package/dist/{compress-C42bpk6O.js → compress-BTsSIi_B.js} +1 -1
  12. package/dist/{compress-CzMz2bpX.js → compress-PmebyFxR.js} +1 -1
  13. package/dist/core/webgpu/RenderTargetNode.d.ts +79 -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/nodes/GainMapNode.d.ts +17 -18
  21. package/dist/decode.js +5 -18
  22. package/dist/decode.min.js +2 -2
  23. package/dist/decode.umd.cjs +1 -30
  24. package/dist/decode.umd.min.cjs +2 -2
  25. package/dist/decode.webgpu.js +41 -228
  26. package/dist/decode.webgpu.min.js +2 -2
  27. package/dist/decode.webgpu.umd.cjs +186 -62
  28. package/dist/decode.webgpu.umd.min.cjs +2 -2
  29. package/dist/encode/webgpu/GainMapEncoder.d.ts +142 -0
  30. package/dist/encode/webgpu/find-texture-min-max.d.ts +27 -0
  31. package/dist/encode/webgpu/index.d.ts +8 -0
  32. package/dist/encode/webgpu/nodes/GainMapEncoderNode.d.ts +92 -0
  33. package/dist/encode/webgpu/nodes/SDRRenditionNode.d.ts +120 -0
  34. package/dist/encode/webgpu/read-render-target-pixels.d.ts +11 -0
  35. package/dist/encode.js +5 -36
  36. package/dist/encode.min.js +2 -2
  37. package/dist/encode.umd.cjs +1 -1
  38. package/dist/encode.umd.min.cjs +1 -1
  39. package/dist/encode.webgpu.js +635 -0
  40. package/dist/encode.webgpu.min.js +5 -0
  41. package/dist/encode.webgpu.umd.cjs +1081 -0
  42. package/dist/encode.webgpu.umd.min.cjs +5 -0
  43. package/dist/get-data-texture-CkaFVcv-.js +5 -0
  44. package/dist/get-data-texture-DkHkbczN.js +40 -0
  45. package/dist/{iso-gainmap-metadata-CEaaU7RT.js → iso-gainmap-metadata-BJxZGPtk.js} +1 -1
  46. package/dist/{iso-gainmap-metadata-ByNqnUPn.js → iso-gainmap-metadata-Bx6ha9th.js} +1 -1
  47. package/dist/libultrahdr.js +2 -2
  48. package/dist/libultrahdr.min.js +2 -2
  49. package/dist/libultrahdr.umd.cjs +1 -1
  50. package/dist/libultrahdr.umd.min.cjs +1 -1
  51. package/dist/worker-interface.js +2 -2
  52. package/dist/worker-interface.min.js +2 -2
  53. package/dist/worker-interface.umd.cjs +1 -1
  54. package/dist/worker-interface.umd.min.cjs +1 -1
  55. package/dist/worker.js +3 -3
  56. package/dist/worker.min.js +2 -2
  57. package/dist/worker.umd.cjs +1 -1
  58. package/dist/worker.umd.min.cjs +1 -1
  59. package/package.json +10 -2
@@ -0,0 +1,92 @@
1
+ import { type Node, type UniformNode, Vector3 } from 'three/webgpu';
2
+ import { type GainMapMetadata } from '../../../core/types';
3
+ import { RenderTargetNode } from '../../../core/webgpu/RenderTargetNode';
4
+ import { type GainmapEncodingParameters } from '../../types';
5
+ import { SDRRenditionNode } from './SDRRenditionNode';
6
+ /**
7
+ * Uniforms driving a {@link GainMapEncoderNode}
8
+ */
9
+ export type GainMapEncoderNodeUniforms = {
10
+ gamma: UniformNode<'vec3', Vector3>;
11
+ offsetSdr: UniformNode<'vec3', Vector3>;
12
+ offsetHdr: UniformNode<'vec3', Vector3>;
13
+ minContentBoost: UniformNode<'float', number>;
14
+ maxContentBoost: UniformNode<'float', number>;
15
+ };
16
+ /**
17
+ * A TSL texture node holding the gain map (recovery map) of an HDR image: the second step of gain map encoding.
18
+ *
19
+ * The gain map is computed from the HDR input of a {@link SDRRenditionNode} and its SDR rendition,
20
+ * into an 8 bit linear render target. The result is identical to the one of the WebGL `GainMapEncoderMaterial`.
21
+ *
22
+ * It renders only when something changed (the SDR rendition or any uniform value),
23
+ * the SDR rendition is rendered first when needed.
24
+ *
25
+ * @category Nodes
26
+ * @group Nodes
27
+ *
28
+ * @example
29
+ * import { GainMapEncoderNode, SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
30
+ *
31
+ * const sdr = new SDRRenditionNode(hdrTexture)
32
+ * const gainMap = new GainMapEncoderNode(sdr, { maxContentBoost: 8 })
33
+ *
34
+ * material.colorNode = gainMap
35
+ * gainMap.gamma.value.setScalar(1.2) // renders again once, on the next frame
36
+ * const metadata = gainMap.metadata
37
+ */
38
+ export declare class GainMapEncoderNode extends RenderTargetNode {
39
+ static get type(): string;
40
+ /**
41
+ * The SDR rendition this gain map is computed from
42
+ */
43
+ readonly sdr: SDRRenditionNode;
44
+ /**
45
+ * Shared uniforms
46
+ */
47
+ readonly uniforms: GainMapEncoderNodeUniforms;
48
+ private _warned;
49
+ /**
50
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
51
+ * @param params encoding parameters, all of them can be changed later through the uniforms
52
+ */
53
+ constructor(sdr: SDRRenditionNode, params?: Partial<GainmapEncodingParameters>);
54
+ /** @see {@link GainmapEncodingParameters.gamma} */
55
+ get gamma(): UniformNode<"vec3", Vector3>;
56
+ /** @see {@link GainmapEncodingParameters.offsetSdr} */
57
+ get offsetSdr(): UniformNode<"vec3", Vector3>;
58
+ /** @see {@link GainmapEncodingParameters.offsetHdr} */
59
+ get offsetHdr(): UniformNode<"vec3", Vector3>;
60
+ /**
61
+ * @see {@link GainmapEncodingParameters.minContentBoost}
62
+ * @remarks Non logarithmic space
63
+ */
64
+ get minContentBoost(): UniformNode<"float", number>;
65
+ /**
66
+ * @see {@link GainmapEncodingParameters.maxContentBoost}
67
+ * @remarks Non logarithmic space, values <= 1 are clamped to 1.0001 since a gain map can't encode an empty boost range
68
+ */
69
+ get maxContentBoost(): UniformNode<"float", number>;
70
+ /** Same size as the SDR rendition */
71
+ get width(): number;
72
+ /** Same size as the SDR rendition */
73
+ get height(): number;
74
+ /** The min content boost actually encoded */
75
+ private get metadataMinContentBoost();
76
+ /** The max content boost actually encoded, clamped to a valid range */
77
+ private get metadataMaxContentBoost();
78
+ /**
79
+ * The gain map metadata matching the current uniform values
80
+ */
81
+ get metadata(): GainMapMetadata;
82
+ protected _getState(): number[];
83
+ protected _getDependencies(): SDRRenditionNode[];
84
+ protected _onRender(): void;
85
+ }
86
+ /**
87
+ * TSL function creating a {@link GainMapEncoderNode}
88
+ *
89
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
90
+ * @param params encoding parameters
91
+ */
92
+ export declare const gainMapEncoder: (sdr: SDRRenditionNode, params?: Partial<GainmapEncodingParameters>) => GainMapEncoderNode & Node;
@@ -0,0 +1,120 @@
1
+ import { type Node, Texture, type ToneMapping, type UniformNode } from 'three/webgpu';
2
+ import { RenderTargetNode } from '../../../core/webgpu/RenderTargetNode';
3
+ /**
4
+ * HDR input of the encoder: a texture or any TSL node returning a linear HDR color (vec3 or vec4)
5
+ *
6
+ * Nodes are evaluated on a full screen quad, `uv()` spans the whole output image.
7
+ *
8
+ * @category Encoding Parameters
9
+ * @group Encoding Parameters
10
+ */
11
+ export type HDRInput = Texture | Node;
12
+ /**
13
+ * Options of a {@link SDRRenditionNode}
14
+ *
15
+ * @category Encoding Parameters
16
+ * @group Encoding Parameters
17
+ */
18
+ export type SDRRenditionNodeOptions = {
19
+ /**
20
+ * Tone mapping applied to the SDR rendition
21
+ * @defaultValue `ACESFilmicToneMapping`
22
+ */
23
+ toneMapping?: ToneMapping;
24
+ /**
25
+ * Width of the output, required when the HDR input is a generic node
26
+ * (textures and texture nodes provide their own size)
27
+ */
28
+ width?: number;
29
+ /**
30
+ * Height of the output, required when the HDR input is a generic node
31
+ * (textures and texture nodes provide their own size)
32
+ */
33
+ height?: number;
34
+ };
35
+ /**
36
+ * Uniforms driving a {@link SDRRenditionNode}
37
+ */
38
+ export type SDRRenditionNodeUniforms = {
39
+ exposure: UniformNode<'float', number>;
40
+ brightness: UniformNode<'float', number>;
41
+ contrast: UniformNode<'float', number>;
42
+ saturation: UniformNode<'float', number>;
43
+ };
44
+ /**
45
+ * A TSL texture node holding the SDR rendition of an HDR image: the first step of gain map encoding.
46
+ *
47
+ * The HDR input is exposed, tone mapped (with the three.js TSL tone mapping functions)
48
+ * and adjusted (brightness, contrast, saturation) into an 8 bit sRGB render target.
49
+ *
50
+ * It renders only when something changed (input, tone mapping or any uniform value):
51
+ * sampling the node costs a single texture read, like any other texture.
52
+ *
53
+ * @category Nodes
54
+ * @group Nodes
55
+ *
56
+ * @example
57
+ * import { SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
58
+ * import { AgXToneMapping, LinearToneMapping } from 'three/webgpu'
59
+ *
60
+ * const sdr = new SDRRenditionNode(hdrTexture, { toneMapping: AgXToneMapping })
61
+ * material.colorNode = sdr
62
+ * sdr.exposure.value = 0.8 // renders again once, on the next frame
63
+ * sdr.setToneMapping(LinearToneMapping)
64
+ */
65
+ export declare class SDRRenditionNode extends RenderTargetNode {
66
+ static get type(): string;
67
+ /**
68
+ * The HDR input, as a node
69
+ */
70
+ readonly hdr: Node;
71
+ /**
72
+ * Shared uniforms
73
+ */
74
+ readonly uniforms: SDRRenditionNodeUniforms;
75
+ private _hdrTexture;
76
+ private _hdrSource;
77
+ private _width;
78
+ private _height;
79
+ private _toneMapping;
80
+ /**
81
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
82
+ * @param options
83
+ * @throws {Error} if the input is a generic node and `width` or `height` are not provided
84
+ */
85
+ constructor(hdr: HDRInput, options?: SDRRenditionNodeOptions);
86
+ /** Exposure applied to the HDR input before tone mapping */
87
+ get exposure(): UniformNode<"float", number>;
88
+ /** Brightness offset applied after tone mapping */
89
+ get brightness(): UniformNode<"float", number>;
90
+ /** Contrast applied after tone mapping */
91
+ get contrast(): UniformNode<"float", number>;
92
+ /** Saturation applied after tone mapping */
93
+ get saturation(): UniformNode<"float", number>;
94
+ /**
95
+ * The tone mapping applied to the SDR rendition
96
+ */
97
+ getToneMapping(): ToneMapping;
98
+ /**
99
+ * Sets the tone mapping applied to the SDR rendition
100
+ * (`toneMapping` can't be used as a property name: it's a TSL method of every node)
101
+ *
102
+ * @param value any three.js tone mapping, e.g. `ACESFilmicToneMapping`, `AgXToneMapping`, `NeutralToneMapping`
103
+ * or `LinearToneMapping` (which keeps the SDR rendition closest to the HDR input)
104
+ */
105
+ setToneMapping(value: ToneMapping): this;
106
+ /** Width of the output, 0 while the input texture is not loaded */
107
+ get width(): number;
108
+ /** Height of the output, 0 while the input texture is not loaded */
109
+ get height(): number;
110
+ private _buildOutput;
111
+ protected _getState(): (number | undefined)[];
112
+ protected _getDependencies(): RenderTargetNode[];
113
+ }
114
+ /**
115
+ * TSL function creating a {@link SDRRenditionNode}
116
+ *
117
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
118
+ * @param options
119
+ */
120
+ export declare const sdrRendition: (hdr: HDRInput, options?: SDRRenditionNodeOptions) => SDRRenditionNode & Node;
@@ -0,0 +1,11 @@
1
+ import { type RenderTarget, type WebGPURenderer } from 'three/webgpu';
2
+ /**
3
+ * Reads the pixels of a render target, rows are returned top to bottom
4
+ * (like `ImageData`, regardless of the backend) and tightly packed
5
+ * (WebGPU pads each row to 256 bytes).
6
+ *
7
+ * @internal
8
+ * @param renderer
9
+ * @param renderTarget
10
+ */
11
+ export declare const readRenderTargetPixels: (renderer: WebGPURenderer, renderTarget: RenderTarget) => Promise<import("three").TypedArray>;
package/dist/encode.js CHANGED
@@ -1,43 +1,12 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.0
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
6
- import { c as compress } from './compress-CzMz2bpX.js';
7
- import { DataTexture, RGBAFormat, UVMapping, RepeatWrapping, LinearFilter, LinearSRGBColorSpace, ShaderMaterial, NoBlending, Vector3, UnsignedByteType, ACESFilmicToneMapping, LinearToneMapping, NeutralToneMapping, AgXToneMapping, CineonToneMapping, ReinhardToneMapping, SRGBColorSpace, AlphaFormat, RGBFormat, DepthFormat, DepthStencilFormat, RedFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, Vector2, WebGLRenderTarget, ClampToEdgeWrapping, NearestFilter, FloatType, DataUtils } from 'three';
8
- import { Q as QuadRenderer } from './QuadRenderer-CXtNzoCY.js';
9
-
10
- /**
11
- * Utility function to obtain a `DataTexture` from various input formats
12
- *
13
- * @category Utility
14
- * @group Utility
15
- *
16
- * @param image
17
- * @returns
18
- */
19
- const getDataTexture = (image) => {
20
- let dataTexture;
21
- if (image instanceof DataTexture) {
22
- if (!(image.image.data instanceof Uint16Array) && !(image.image.data instanceof Float32Array)) {
23
- throw new Error('Provided image is not HDR');
24
- }
25
- dataTexture = image;
26
- }
27
- else {
28
- if (!image.data || !image.width || !image.height) {
29
- throw new Error('Provided image has no data or size');
30
- }
31
- dataTexture = new DataTexture(image.data, image.width, image.height, image.format ?? RGBAFormat, image.type, UVMapping, RepeatWrapping, RepeatWrapping, LinearFilter, LinearFilter, 1, 'colorSpace' in image && image.colorSpace === 'srgb' ? image.colorSpace : LinearSRGBColorSpace);
32
- // TODO: This tries to detect a raw RGBE and applies flipY
33
- // see if there's a better way to detect it?
34
- if ('header' in image && 'gamma' in image) {
35
- dataTexture.flipY = true;
36
- }
37
- dataTexture.needsUpdate = true;
38
- }
39
- return dataTexture;
40
- };
6
+ import { c as compress } from './compress-PmebyFxR.js';
7
+ import { g as getDataTexture } from './get-data-texture-DkHkbczN.js';
8
+ import { ShaderMaterial, NoBlending, Vector3, LinearSRGBColorSpace, UnsignedByteType, ACESFilmicToneMapping, LinearToneMapping, NeutralToneMapping, AgXToneMapping, CineonToneMapping, ReinhardToneMapping, SRGBColorSpace, AlphaFormat, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, RedFormat, RedIntegerFormat, RGFormat, RGIntegerFormat, RGBIntegerFormat, RGBAIntegerFormat, Vector2, WebGLRenderTarget, ClampToEdgeWrapping, NearestFilter, FloatType, DataUtils } from 'three';
9
+ import { Q as QuadRenderer } from './QuadRenderer-DD6leG7y.js';
41
10
 
42
11
  const vertexShader$2 = /* glsl */ `
43
12
  varying vec2 vUv;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.0
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
- import{c as n}from"./compress-C42bpk6O.js";import{DataTexture as e,RGBAFormat as t,UVMapping as o,RepeatWrapping as a,LinearFilter as r,LinearSRGBColorSpace as i,ShaderMaterial as s,NoBlending as m,Vector3 as c,UnsignedByteType as l,ACESFilmicToneMapping as p,LinearToneMapping as d,NeutralToneMapping as g,AgXToneMapping as u,CineonToneMapping as f,ReinhardToneMapping as h,SRGBColorSpace as v,AlphaFormat as x,RGBFormat as M,DepthFormat as _,DepthStencilFormat as C,RedFormat as w,RedIntegerFormat as A,RGFormat as T,RGIntegerFormat as E,RGBIntegerFormat as y,RGBAIntegerFormat as I,Vector2 as S,WebGLRenderTarget as N,ClampToEdgeWrapping as R,NearestFilter as L,FloatType as b,DataUtils as O}from"three";import{Q as U}from"./QuadRenderer-DcBTBLz6.js";const B=n=>{let s;if(n instanceof e){if(!(n.image.data instanceof Uint16Array||n.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");s=n}else{if(!n.data||!n.width||!n.height)throw new Error("Provided image has no data or size");s=new e(n.data,n.width,n.height,n.format??t,n.type,o,a,a,r,r,1,"colorSpace"in n&&"srgb"===n.colorSpace?n.colorSpace:i),"header"in n&&"gamma"in n&&(s.flipY=!0),s.needsUpdate=!0}return s},P=1.0001,D=n=>{console.warn(`gainmap-js: maxContentBoost is ${n} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},F=(n,e)=>{console.warn(`gainmap-js: minContentBoost (${n}) must be lower than maxContentBoost (${e}), the resulting gain map will be invalid.`)};class G extends s{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:o,maxContentBoost:a,minContentBoost:r,gamma:i}){if(!a)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const s=i||[1,1,1],l=t||[1/64,1/64,1/64],p=o||[1/64,1/64,1/64];a<=1&&D(a);const d=r||1,g=Math.max(a,P);d>=g&&F(d,g),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new c).fromArray(s)},offsetSdr:{value:(new c).fromArray(l)},offsetHdr:{value:(new c).fromArray(p)},minLog2:{value:Math.log2(d)},maxLog2:{value:Math.log2(g)}},blending:m,depthTest:!1,depthWrite:!1}),this._minContentBoost=d,this._maxContentBoost=g,this._offsetSdr=l,this._offsetHdr=p,this._gamma=s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new c).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new c).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new c).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){n>=this._maxContentBoost&&F(n,this._maxContentBoost),this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){n<=1&&D(n);const e=Math.max(n,P);this._minContentBoost>=e&&F(this._minContentBoost,e),this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const k=n=>{const{image:e,sdr:t,renderer:o}=n,a=B(e),r=new G({...n,sdr:t.renderTarget.texture,hdr:a}),s=new U({width:a.image.width,height:a.image.height,type:l,colorSpace:i,material:r,renderer:o,renderTargetOptions:n.renderTargetOptions});try{s.render()}catch(n){throw s.disposeOnDemandRenderer(),n}return s};class H extends s{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:m,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||p,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case p:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case h:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case f:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case d:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case g:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=d}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const X=(n,e,t,o)=>{n.needsUpdate=!0;const a=new U({width:n.image.width,height:n.image.height,type:l,colorSpace:v,material:new H({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{a.render()}catch(n){throw a.disposeOnDemandRenderer(),n}return a},j=n=>{const{image:e,renderer:t}=n,o=B(e),a=X(o,t,n.toneMapping,n.renderTargetOptions),r=k({...n,image:o,sdr:a,renderer:a.renderer});return{sdr:a,gainMap:r,hdr:o,getMetadata:()=>({gainMapMax:r.material.gainMapMax,gainMapMin:r.material.gainMapMin,gamma:r.material.gamma,hdrCapacityMax:r.material.hdrCapacityMax,hdrCapacityMin:r.material.hdrCapacityMin,offsetHdr:r.material.offsetHdr,offsetSdr:r.material.offsetSdr})}},Y=async e=>{const t=j(e),{mimeType:o,quality:a,flipY:r,withWorker:i}=e;let s,m,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:a,flipY:r}),i.compress({source:p,mimeType:o,quality:a,flipY:r})]);s=n,m=n[0].source,c=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:a,flipY:r}),n({source:p,mimeType:o,quality:a,flipY:r})]),m=l.data,c=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},q=(n,e="max",o)=>{const a=B(n);if(a.format!==x&&a.format!==M&&a.format!==t&&a.format!==_&&a.format!==C&&a.format!==w&&a.format!==A&&a.format!==T&&a.format!==E&&a.format!==y&&a.format!==I)throw new Error("Unsupported texture format");const r=new s({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new S(a.image.width,a.image.height)},map:{value:a}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:e,INITIAL_VALUE:"max"===e?0:65504}});a.needsUpdate=!0,r.needsUpdate=!0;let i=a.image.width,m=a.image.height;const c=new U({width:i,height:m,type:a.type,colorSpace:a.colorSpace,material:r,renderer:o}),l=[];for(;i>1||m>1;){i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const n=new N(i,m,{type:c.type,format:a.format,colorSpace:c.colorSpace,minFilter:L,magFilter:L,wrapS:R,wrapT:R,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}i=a.image.width,m=a.image.height,l.forEach(n=>{i=Math.max(1,(i+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=n,c.render(),r.uniforms.map.value=n.texture,r.uniforms.u_srcResolution.value.x=i,r.uniforms.u_srcResolution.value.y=m});const p=c.toArray();return c.dispose(),l.forEach(n=>n.dispose()),[c.type===b?p[0]:O.fromHalfFloat(p[0]),c.type===b?p[1]:O.fromHalfFloat(p[1]),c.type===b?p[2]:O.fromHalfFloat(p[2])]};export{G as GainMapEncoderMaterial,H as SDRMaterial,n as compress,j as encode,Y as encodeAndCompress,q as findTextureMinMax,k as getGainMap,X as getSDRRendition};
5
+ import{c as n}from"./compress-BTsSIi_B.js";import{g as e}from"./get-data-texture-CkaFVcv-.js";import{ShaderMaterial as t,NoBlending as o,Vector3 as a,LinearSRGBColorSpace as r,UnsignedByteType as i,ACESFilmicToneMapping as s,LinearToneMapping as m,NeutralToneMapping as c,AgXToneMapping as l,CineonToneMapping as p,ReinhardToneMapping as u,SRGBColorSpace as g,AlphaFormat as d,RGBFormat as f,RGBAFormat as h,DepthFormat as v,DepthStencilFormat as x,RedFormat as M,RedIntegerFormat as _,RGFormat as C,RGIntegerFormat as w,RGBIntegerFormat as A,RGBAIntegerFormat as T,Vector2 as E,WebGLRenderTarget as I,ClampToEdgeWrapping as y,NearestFilter as N,FloatType as S,DataUtils as R}from"three";import{Q as L}from"./QuadRenderer-DoK2pW5M.js";const O=1.0001,b=n=>{console.warn(`gainmap-js: maxContentBoost is ${n} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},U=(n,e)=>{console.warn(`gainmap-js: minContentBoost (${n}) must be lower than maxContentBoost (${e}), the resulting gain map will be invalid.`)};class B extends t{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:n,hdr:e,offsetSdr:t,offsetHdr:r,maxContentBoost:i,minContentBoost:s,gamma:m}){if(!i)throw new Error("maxContentBoost is required");if(!n)throw new Error("sdr is required");if(!e)throw new Error("hdr is required");const c=m||[1,1,1],l=t||[1/64,1/64,1/64],p=r||[1/64,1/64,1/64];i<=1&&b(i);const u=s||1,g=Math.max(i,O);u>=g&&U(u,g),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:n},hdr:{value:e},gamma:{value:(new a).fromArray(c)},offsetSdr:{value:(new a).fromArray(l)},offsetHdr:{value:(new a).fromArray(p)},minLog2:{value:Math.log2(u)},maxLog2:{value:Math.log2(g)}},blending:o,depthTest:!1,depthWrite:!1}),this._minContentBoost=u,this._maxContentBoost=g,this._offsetSdr=l,this._offsetHdr=p,this._gamma=c,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(n){this._gamma=n,this.uniforms.gamma.value=(new a).fromArray(n)}get offsetHdr(){return this._offsetHdr}set offsetHdr(n){this._offsetHdr=n,this.uniforms.offsetHdr.value=(new a).fromArray(n)}get offsetSdr(){return this._offsetSdr}set offsetSdr(n){this._offsetSdr=n,this.uniforms.offsetSdr.value=(new a).fromArray(n)}get minContentBoost(){return this._minContentBoost}set minContentBoost(n){n>=this._maxContentBoost&&U(n,this._maxContentBoost),this._minContentBoost=n,this.uniforms.minLog2.value=Math.log2(n)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(n){n<=1&&b(n);const e=Math.max(n,O);this._minContentBoost>=e&&U(this._minContentBoost,e),this._maxContentBoost=e,this.uniforms.maxLog2.value=Math.log2(e)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const P=n=>{const{image:t,sdr:o,renderer:a}=n,s=e(t),m=new B({...n,sdr:o.renderTarget.texture,hdr:s}),c=new L({width:s.image.width,height:s.image.height,type:i,colorSpace:r,material:m,renderer:a,renderTargetOptions:n.renderTargetOptions});try{c.render()}catch(n){throw c.disposeOnDemandRenderer(),n}return c};class D extends t{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:n,toneMapping:e}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:n},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:o,depthTest:!1,depthWrite:!1}),this._map=n,this.toneMapping=this._toneMapping=e||s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(n){let e=!1;switch(n){case s:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",e=!0;break;case u:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",e=!0;break;case p:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",e=!0;break;case m:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",e=!0;break;case l:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",e=!0;break;case c:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",e=!0;break;default:console.error(`Unsupported toneMapping: ${n}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=m}e&&(this._toneMapping=n),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(n){this._brightness=n,this.uniforms.brightness.value=n}get contrast(){return this._contrast}set contrast(n){this._contrast=n,this.uniforms.contrast.value=n}get saturation(){return this._saturation}set saturation(n){this._saturation=n,this.uniforms.saturation.value=n}get exposure(){return this._exposure}set exposure(n){this._exposure=n,this.uniforms.exposure.value=n}get map(){return this._map}set map(n){this._map=n,this.uniforms.map.value=n}}const F=(n,e,t,o)=>{n.needsUpdate=!0;const a=new L({width:n.image.width,height:n.image.height,type:i,colorSpace:g,material:new D({map:n,toneMapping:t}),renderer:e,renderTargetOptions:o});try{a.render()}catch(n){throw a.disposeOnDemandRenderer(),n}return a},G=n=>{const{image:t,renderer:o}=n,a=e(t),r=F(a,o,n.toneMapping,n.renderTargetOptions),i=P({...n,image:a,sdr:r,renderer:r.renderer});return{sdr:r,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}},k=async e=>{const t=G(e),{mimeType:o,quality:a,flipY:r,withWorker:i}=e;let s,m,c;const l=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),p=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const n=await Promise.all([i.compress({source:l,mimeType:o,quality:a,flipY:r}),i.compress({source:p,mimeType:o,quality:a,flipY:r})]);s=n,m=n[0].source,c=n[1].source}else s=await Promise.all([n({source:l,mimeType:o,quality:a,flipY:r}),n({source:p,mimeType:o,quality:a,flipY:r})]),m=l.data,c=p.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:m,rawGainMap:c}},H=(n,o="max",a)=>{const r=e(n);if(r.format!==d&&r.format!==f&&r.format!==h&&r.format!==v&&r.format!==x&&r.format!==M&&r.format!==_&&r.format!==C&&r.format!==w&&r.format!==A&&r.format!==T)throw new Error("Unsupported texture format");const i=new t({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new E(r.image.width,r.image.height)},map:{value:r}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:o,INITIAL_VALUE:"max"===o?0:65504}});r.needsUpdate=!0,i.needsUpdate=!0;let s=r.image.width,m=r.image.height;const c=new L({width:s,height:m,type:r.type,colorSpace:r.colorSpace,material:i,renderer:a}),l=[];for(;s>1||m>1;){s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0);const n=new I(s,m,{type:c.type,format:r.format,colorSpace:c.colorSpace,minFilter:N,magFilter:N,wrapS:y,wrapT:y,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});l.push(n)}s=r.image.width,m=r.image.height,l.forEach(n=>{s=Math.max(1,(s+2-1)/2|0),m=Math.max(1,(m+2-1)/2|0),c.renderTarget=n,c.render(),i.uniforms.map.value=n.texture,i.uniforms.u_srcResolution.value.x=s,i.uniforms.u_srcResolution.value.y=m});const p=c.toArray();return c.dispose(),l.forEach(n=>n.dispose()),[c.type===S?p[0]:R.fromHalfFloat(p[0]),c.type===S?p[1]:R.fromHalfFloat(p[1]),c.type===S?p[2]:R.fromHalfFloat(p[2])]};export{B as GainMapEncoderMaterial,D as SDRMaterial,n as compress,G as encode,k as encodeAndCompress,H as findTextureMinMax,P as getGainMap,F as getSDRRendition};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.0
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @monogrid/gainmap-js v3.6.0
2
+ * @monogrid/gainmap-js v3.7.0
3
3
  * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
4
  */
5
5
  !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("three")):"function"==typeof define&&define.amd?define(["exports","three"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).encode={},e.three)}(this,function(e,t){"use strict";const n=async e=>{if("undefined"==typeof createImageBitmap)throw new Error("createImageBitmap() not supported.");const{source:t,mimeType:n,quality:r,flipY:a}=e;let o;if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&"sourceMimeType"in e)o=new Blob([t],{type:e.sourceMimeType});else{if(!(t instanceof ImageData))throw new Error("Invalid source image");o=t}const i=await createImageBitmap(o),s=i.width,p=i.height;let l;"undefined"!=typeof OffscreenCanvas?l=new OffscreenCanvas(s,p):(l=document.createElement("canvas"),l.width=s,l.height=p);const c=l.getContext("2d");if(!c)throw new Error("Failed to create canvas Context");!0===a&&(c.translate(0,p),c.scale(1,-1)),c.drawImage(i,0,0,s,p);const d=await(async(e,t,n)=>{if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return e.convertToBlob({type:t,quality:n});if(e instanceof HTMLCanvasElement)return new Promise((r,a)=>{e.toBlob(e=>{e?r(e):a(new Error("Failed to convert canvas to blob"))},t,n)});throw new Error("Unsupported canvas element")})(l,n,r||.9);return{data:new Uint8Array(await d.arrayBuffer()),mimeType:n,width:s,height:p}},r=e=>{let n;if(e instanceof t.DataTexture){if(!(e.image.data instanceof Uint16Array||e.image.data instanceof Float32Array))throw new Error("Provided image is not HDR");n=e}else{if(!e.data||!e.width||!e.height)throw new Error("Provided image has no data or size");n=new t.DataTexture(e.data,e.width,e.height,e.format??t.RGBAFormat,e.type,t.UVMapping,t.RepeatWrapping,t.RepeatWrapping,t.LinearFilter,t.LinearFilter,1,"colorSpace"in e&&"srgb"===e.colorSpace?e.colorSpace:t.LinearSRGBColorSpace),"header"in e&&"gamma"in e&&(n.flipY=!0),n.needsUpdate=!0}return n},a=(e,n,r)=>{let a;switch(e){case t.UnsignedByteType:a=new Uint8ClampedArray(n*r*4);break;case t.HalfFloatType:a=new Uint16Array(n*r*4);break;case t.UnsignedIntType:a=new Uint32Array(n*r*4);break;case t.ByteType:a=new Int8Array(n*r*4);break;case t.ShortType:a=new Int16Array(n*r*4);break;case t.IntType:a=new Int32Array(n*r*4);break;case t.FloatType:a=new Float32Array(n*r*4);break;default:throw new Error("Unsupported data type")}return a};let o;class i{_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 n={format:t.RGBAFormat,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:t.LinearFilter,minFilter:void 0!==e.renderTargetOptions?.minFilter?e.renderTargetOptions?.minFilter:t.LinearFilter,samples:void 0!==e.renderTargetOptions?.samples?e.renderTargetOptions?.samples:void 0,wrapS:void 0!==e.renderTargetOptions?.wrapS?e.renderTargetOptions?.wrapS:t.ClampToEdgeWrapping,wrapT:void 0!==e.renderTargetOptions?.wrapT?e.renderTargetOptions?.wrapT:t.ClampToEdgeWrapping};if(this._material=e.material,e.renderer?this._renderer=e.renderer:(this._renderer=i.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new t.Scene,this._camera=new t.OrthographicCamera,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(),!((e,n,r,i)=>{if(void 0!==o)return o;const s=new t.WebGLRenderTarget(1,1,i);n.setRenderTarget(s);const p=new t.Mesh(new t.PlaneGeometry,new t.MeshBasicMaterial({color:16777215}));n.render(p,r),n.setRenderTarget(null);const l=a(e,s.width,s.height);return n.readRenderTargetPixels(s,0,0,s.width,s.height,l),s.dispose(),p.geometry.dispose(),p.material.dispose(),o=0!==l[0],o})(this._type,this._renderer,this._camera,n)){let e;if(this._type===t.HalfFloatType)e=this._renderer.extensions.has("EXT_color_buffer_float")?t.FloatType:void 0;void 0!==e?(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${t.FloatType}`),this._type=e):(this._supportsReadPixels=!1,console.warn("This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown"))}this._quad=new t.Mesh(new t.PlaneGeometry,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new t.WebGLRenderTarget(this.width,this.height,n),this._renderTarget.texture.mapping=void 0!==e.renderTargetOptions?.mapping?e.renderTargetOptions?.mapping:t.UVMapping}static instantiateRenderer(){const e=new t.WebGLRenderer;return e.setSize(128,128),e}render=()=>{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)};toArray(){if(!this._supportsReadPixels)throw new Error("Can't read pixels in this browser");const e=a(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){const n=new t.DataTexture(this.toArray(),this.width,this.height,t.RGBAFormat,this._type,e?.mapping||t.UVMapping,e?.wrapS||t.ClampToEdgeWrapping,e?.wrapT||t.ClampToEdgeWrapping,e?.magFilter||t.LinearFilter,e?.minFilter||t.LinearFilter,e?.anisotropy||1,t.LinearSRGBColorSpace);return n.generateMipmaps=void 0!==e?.generateMipmaps&&e?.generateMipmaps,n}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof t.ShaderMaterial&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof t.Texture&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof t.Texture&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}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 s=1.0001,p=e=>{console.warn(`gainmap-js: maxContentBoost is ${e} (<= 1), the source image has no HDR content. It will be clamped to 1.0001 and the result will be equivalent to an SDR image.`)},l=(e,t)=>{console.warn(`gainmap-js: minContentBoost (${e}) must be lower than maxContentBoost (${t}), the resulting gain map will be invalid.`)};class c extends t.ShaderMaterial{_minContentBoost;_maxContentBoost;_offsetSdr;_offsetHdr;_gamma;constructor({sdr:e,hdr:n,offsetSdr:r,offsetHdr:a,maxContentBoost:o,minContentBoost:i,gamma:c}){if(!o)throw new Error("maxContentBoost is required");if(!e)throw new Error("sdr is required");if(!n)throw new Error("hdr is required");const d=c||[1,1,1],m=r||[1/64,1/64,1/64],h=a||[1/64,1/64,1/64];o<=1&&p(o);const g=i||1,u=Math.max(o,s);g>=u&&l(g,u),super({name:"GainMapEncoderMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform sampler2D sdr;\nuniform sampler2D hdr;\nuniform vec3 gamma;\nuniform vec3 offsetSdr;\nuniform vec3 offsetHdr;\nuniform float minLog2;\nuniform float maxLog2;\n\nvarying vec2 vUv;\n\nvoid main() {\n vec3 sdrColor = texture2D(sdr, vUv).rgb;\n vec3 hdrColor = texture2D(hdr, vUv).rgb;\n\n vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);\n vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);\n vec3 clampedRecovery = saturate(logRecovery);\n gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);\n}\n",uniforms:{sdr:{value:e},hdr:{value:n},gamma:{value:(new t.Vector3).fromArray(d)},offsetSdr:{value:(new t.Vector3).fromArray(m)},offsetHdr:{value:(new t.Vector3).fromArray(h)},minLog2:{value:Math.log2(g)},maxLog2:{value:Math.log2(u)}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._minContentBoost=g,this._maxContentBoost=u,this._offsetSdr=m,this._offsetHdr=h,this._gamma=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get gamma(){return this._gamma}set gamma(e){this._gamma=e,this.uniforms.gamma.value=(new t.Vector3).fromArray(e)}get offsetHdr(){return this._offsetHdr}set offsetHdr(e){this._offsetHdr=e,this.uniforms.offsetHdr.value=(new t.Vector3).fromArray(e)}get offsetSdr(){return this._offsetSdr}set offsetSdr(e){this._offsetSdr=e,this.uniforms.offsetSdr.value=(new t.Vector3).fromArray(e)}get minContentBoost(){return this._minContentBoost}set minContentBoost(e){e>=this._maxContentBoost&&l(e,this._maxContentBoost),this._minContentBoost=e,this.uniforms.minLog2.value=Math.log2(e)}get maxContentBoost(){return this._maxContentBoost}set maxContentBoost(e){e<=1&&p(e);const t=Math.max(e,s);this._minContentBoost>=t&&l(this._minContentBoost,t),this._maxContentBoost=t,this.uniforms.maxLog2.value=Math.log2(t)}get gainMapMin(){return[Math.log2(this._minContentBoost),Math.log2(this._minContentBoost),Math.log2(this._minContentBoost)]}get gainMapMax(){return[Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost),Math.log2(this._maxContentBoost)]}get hdrCapacityMin(){return Math.min(Math.max(0,this.gainMapMin[0]),Math.max(0,this.gainMapMin[1]),Math.max(0,this.gainMapMin[2]))}get hdrCapacityMax(){return Math.max(Math.max(0,this.gainMapMax[0]),Math.max(0,this.gainMapMax[1]),Math.max(0,this.gainMapMax[2]))}}const d=e=>{const{image:n,sdr:a,renderer:o}=e,s=r(n),p=new c({...e,sdr:a.renderTarget.texture,hdr:s}),l=new i({width:s.image.width,height:s.image.height,type:t.UnsignedByteType,colorSpace:t.LinearSRGBColorSpace,material:p,renderer:o,renderTargetOptions:e.renderTargetOptions});try{l.render()}catch(e){throw l.disposeOnDemandRenderer(),e}return l};class m extends t.ShaderMaterial{_brightness=0;_contrast=1;_saturation=1;_exposure=1;_toneMapping;_map;constructor({map:e,toneMapping:n}){super({name:"SDRMaterial",vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n\nuniform sampler2D map;\nuniform float brightness;\nuniform float contrast;\nuniform float saturation;\nuniform float exposure;\n\nvarying vec2 vUv;\n\nmat4 brightnessMatrix( float brightness ) {\n return mat4(\n 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n brightness, brightness, brightness, 1\n );\n}\n\nmat4 contrastMatrix( float contrast ) {\n float t = ( 1.0 - contrast ) / 2.0;\n return mat4(\n contrast, 0, 0, 0,\n 0, contrast, 0, 0,\n 0, 0, contrast, 0,\n t, t, t, 1\n );\n}\n\nmat4 saturationMatrix( float saturation ) {\n vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );\n float oneMinusSat = 1.0 - saturation;\n vec3 red = vec3( luminance.x * oneMinusSat );\n red+= vec3( saturation, 0, 0 );\n vec3 green = vec3( luminance.y * oneMinusSat );\n green += vec3( 0, saturation, 0 );\n vec3 blue = vec3( luminance.z * oneMinusSat );\n blue += vec3( 0, 0, saturation );\n return mat4(\n red, 0,\n green, 0,\n blue, 0,\n 0, 0, 0, 1\n );\n}\n\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\n\nvec3 ACESFilmicToneMapping( vec3 color ) {\n // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source\n vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n // ODT_SAT => XYZ => D60_2_D65 => sRGB\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source\n vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color = ACESInputMat * color;\n // Apply RRT and ODT\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n // Clamp to [0, 1]\n return saturate( color );\n}\n\n// source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf\nvec3 ReinhardToneMapping( vec3 color ) {\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n\n// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/\nvec3 CineonToneMapping( vec3 color ) {\n // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n\n// nothing\nvec3 LinearToneMapping ( vec3 color ) {\n return color;\n}\n\n// Matrices for rec 2020 <> rec 709 color space conversion\n// matrix provided in row-major order so it has been transposed\n// https://www.itu.int/pub/R-REP-BT.2407-2017\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\n\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\n\n// https://iolite-engine.com/blog_posts/minimal_agx_implementation\n// Mean error^2: 3.6705141e-06\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\n\n// AgX Tone Mapping implementation based on Filament, which in turn is based\n// on Blender's implementation using rec 2020 primaries\n// https://github.com/google/filament/pull/7236\n// Inputs and outputs are encoded as Linear-sRGB.\n\nvec3 AgXToneMapping( vec3 color ) {\n\n // AgX constants\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n\n // explicit AgXOutsetMatrix generated from Filaments AgXOutsetMatrixInv\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n\n // LOG2_MIN = -10.0\n // LOG2_MAX = +6.5\n // MIDDLE_GRAY = 0.18\n const float AgxMinEv = - 12.47393; // log2( pow( 2, LOG2_MIN ) * MIDDLE_GRAY )\n const float AgxMaxEv = 4.026069; // log2( pow( 2, LOG2_MAX ) * MIDDLE_GRAY )\n\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\n color = AgXInsetMatrix * color;\n\n // Log2 encoding\n color = max( color, 1e-10 ); // avoid 0 or negative numbers for log2\n color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\n color = clamp( color, 0.0, 1.0 );\n\n // Apply sigmoid\n color = agxDefaultContrastApprox( color );\n\n // Apply AgX look\n // v = agxLook(v, look);\n\n color = AgXOutsetMatrix * color;\n\n // Linearize\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\n // Gamut mapping. Simple clamp for now.\n color = clamp( color, 0.0, 1.0 );\n\n return color;\n\n}\n\n// https://modelviewer.dev/examples/tone-mapping\n\nvec3 NeutralToneMapping( vec3 color ) {\n\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n\n float x = min( color.r, min( color.g, color.b ) );\n\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\n color -= offset;\n\n float peak = max( color.r, max( color.g, color.b ) );\n\n if ( peak < StartCompression ) return color;\n\n float d = 1. - StartCompression;\n\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n\n color *= newPeak / peak;\n\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\n return mix( color, vec3( newPeak ), g );\n\n}\n\n\n\nvoid main() {\n vec4 color = texture2D(map, vUv);\n\n vec4 exposed = vec4(exposure * color.rgb, color.a);\n\n vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);\n\n vec4 adjusted =\n brightnessMatrix( brightness ) *\n contrastMatrix( contrast ) *\n saturationMatrix( saturation ) *\n tonemapped;\n\n gl_FragColor = adjusted;\n}\n",uniforms:{map:{value:e},brightness:{value:0},contrast:{value:1},saturation:{value:1},exposure:{value:1}},blending:t.NoBlending,depthTest:!1,depthWrite:!1}),this._map=e,this.toneMapping=this._toneMapping=n||t.ACESFilmicToneMapping,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get toneMapping(){return this._toneMapping}set toneMapping(e){let n=!1;switch(e){case t.ACESFilmicToneMapping:this.defines.TONEMAPPING_FUNCTION="ACESFilmicToneMapping",n=!0;break;case t.ReinhardToneMapping:this.defines.TONEMAPPING_FUNCTION="ReinhardToneMapping",n=!0;break;case t.CineonToneMapping:this.defines.TONEMAPPING_FUNCTION="CineonToneMapping",n=!0;break;case t.LinearToneMapping:this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",n=!0;break;case t.AgXToneMapping:this.defines.TONEMAPPING_FUNCTION="AgXToneMapping",n=!0;break;case t.NeutralToneMapping:this.defines.TONEMAPPING_FUNCTION="NeutralToneMapping",n=!0;break;default:console.error(`Unsupported toneMapping: ${e}. Using LinearToneMapping.`),this.defines.TONEMAPPING_FUNCTION="LinearToneMapping",this._toneMapping=t.LinearToneMapping}n&&(this._toneMapping=e),this.needsUpdate=!0}get brightness(){return this._brightness}set brightness(e){this._brightness=e,this.uniforms.brightness.value=e}get contrast(){return this._contrast}set contrast(e){this._contrast=e,this.uniforms.contrast.value=e}get saturation(){return this._saturation}set saturation(e){this._saturation=e,this.uniforms.saturation.value=e}get exposure(){return this._exposure}set exposure(e){this._exposure=e,this.uniforms.exposure.value=e}get map(){return this._map}set map(e){this._map=e,this.uniforms.map.value=e}}const h=(e,n,r,a)=>{e.needsUpdate=!0;const o=new i({width:e.image.width,height:e.image.height,type:t.UnsignedByteType,colorSpace:t.SRGBColorSpace,material:new m({map:e,toneMapping:r}),renderer:n,renderTargetOptions:a});try{o.render()}catch(e){throw o.disposeOnDemandRenderer(),e}return o},g=e=>{const{image:t,renderer:n}=e,a=r(t),o=h(a,n,e.toneMapping,e.renderTargetOptions),i=d({...e,image:a,sdr:o,renderer:o.renderer});return{sdr:o,gainMap:i,hdr:a,getMetadata:()=>({gainMapMax:i.material.gainMapMax,gainMapMin:i.material.gainMapMin,gamma:i.material.gamma,hdrCapacityMax:i.material.hdrCapacityMax,hdrCapacityMin:i.material.hdrCapacityMin,offsetHdr:i.material.offsetHdr,offsetSdr:i.material.offsetSdr})}};e.GainMapEncoderMaterial=c,e.SDRMaterial=m,e.compress=n,e.encode=g,e.encodeAndCompress=async e=>{const t=g(e),{mimeType:r,quality:a,flipY:o,withWorker:i}=e;let s,p,l;const c=new ImageData(t.sdr.toArray(),t.sdr.width,t.sdr.height),d=new ImageData(t.gainMap.toArray(),t.gainMap.width,t.gainMap.height);if(i){const e=await Promise.all([i.compress({source:c,mimeType:r,quality:a,flipY:o}),i.compress({source:d,mimeType:r,quality:a,flipY:o})]);s=e,p=e[0].source,l=e[1].source}else s=await Promise.all([n({source:c,mimeType:r,quality:a,flipY:o}),n({source:d,mimeType:r,quality:a,flipY:o})]),p=c.data,l=d.data;return t.sdr.dispose(),t.gainMap.dispose(),{...t,...t.getMetadata(),sdr:s[0],gainMap:s[1],rawSDR:p,rawGainMap:l}},e.findTextureMinMax=(e,n="max",a)=>{const o=r(e);if(o.format!==t.AlphaFormat&&o.format!==t.RGBFormat&&o.format!==t.RGBAFormat&&o.format!==t.DepthFormat&&o.format!==t.DepthStencilFormat&&o.format!==t.RedFormat&&o.format!==t.RedIntegerFormat&&o.format!==t.RGFormat&&o.format!==t.RGIntegerFormat&&o.format!==t.RGBIntegerFormat&&o.format!==t.RGBAIntegerFormat)throw new Error("Unsupported texture format");const s=new t.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n",fragmentShader:"\nprecision mediump float;\n\n#ifndef CELL_SIZE\n #define CELL_SIZE 2\n#endif\n\n#ifndef COMPARE_FUNCTION\n #define COMPARE_FUNCTION max\n#endif\n\n#ifndef INITIAL_VALUE\n #define INITIAL_VALUE 0\n#endif\n\nuniform sampler2D map;\nuniform vec2 u_srcResolution;\n\nvarying vec2 vUv;\n\nvoid main() {\n // compute the first pixel the source cell\n vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);\n\n // one pixel in source\n vec2 onePixel = vec2(1) / u_srcResolution;\n\n // uv for first pixel in cell. +0.5 for center of pixel\n vec2 uv = (srcPixel + 0.5) * onePixel;\n\n vec4 resultColor = vec4(INITIAL_VALUE);\n\n for (int y = 0; y < CELL_SIZE; ++y) {\n for (int x = 0; x < CELL_SIZE; ++x) {\n resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));\n }\n }\n\n gl_FragColor = resultColor;\n}\n",uniforms:{u_srcResolution:{value:new t.Vector2(o.image.width,o.image.height)},map:{value:o}},defines:{CELL_SIZE:2,COMPARE_FUNCTION:n,INITIAL_VALUE:"max"===n?0:65504}});o.needsUpdate=!0,s.needsUpdate=!0;let p=o.image.width,l=o.image.height;const c=new i({width:p,height:l,type:o.type,colorSpace:o.colorSpace,material:s,renderer:a}),d=[];for(;p>1||l>1;){p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0);const e=new t.WebGLRenderTarget(p,l,{type:c.type,format:o.format,colorSpace:c.colorSpace,minFilter:t.NearestFilter,magFilter:t.NearestFilter,wrapS:t.ClampToEdgeWrapping,wrapT:t.ClampToEdgeWrapping,generateMipmaps:!1,depthBuffer:!1,stencilBuffer:!1});d.push(e)}p=o.image.width,l=o.image.height,d.forEach(e=>{p=Math.max(1,(p+2-1)/2|0),l=Math.max(1,(l+2-1)/2|0),c.renderTarget=e,c.render(),s.uniforms.map.value=e.texture,s.uniforms.u_srcResolution.value.x=p,s.uniforms.u_srcResolution.value.y=l});const m=c.toArray();return c.dispose(),d.forEach(e=>e.dispose()),[c.type===t.FloatType?m[0]:t.DataUtils.fromHalfFloat(m[0]),c.type===t.FloatType?m[1]:t.DataUtils.fromHalfFloat(m[1]),c.type===t.FloatType?m[2]:t.DataUtils.fromHalfFloat(m[2])]},e.getGainMap=d,e.getSDRRendition=h});