@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
@@ -0,0 +1,1086 @@
1
+ /**
2
+ * @monogrid/gainmap-js v3.7.1
3
+ * With ❤️, by MONOGRID <gainmap@monogrid.com>
4
+ */
5
+
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three/webgpu'), require('three/tsl'), require('three')) :
8
+ typeof define === 'function' && define.amd ? define(['exports', 'three/webgpu', 'three/tsl', 'three'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.encode = {}, global["three/webgpu"], global["three/tsl"], global.three));
10
+ })(this, (function (exports, webgpu, tsl, three) { 'use strict';
11
+
12
+ /**
13
+ * Base class for TSL texture nodes whose texture is a render target, filled by rendering a full screen quad.
14
+ *
15
+ * The quad is rendered only when something changed since the last render:
16
+ * subclasses list what the result depends on in {@link RenderTargetNode._getState}
17
+ * and the other render target nodes they read from in {@link RenderTargetNode._getDependencies}.
18
+ * Sampling the node costs a single texture read, like any other texture.
19
+ *
20
+ * The node renders itself before rendering whenever it is part of a rendered node graph
21
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`)
22
+ * call {@link RenderTargetNode.render} yourself.
23
+ *
24
+ * @category Nodes
25
+ * @group Nodes
26
+ */
27
+ class RenderTargetNode extends webgpu.TextureNode {
28
+ /**
29
+ * The render target holding the result
30
+ */
31
+ renderTarget;
32
+ /**
33
+ * Incremented every time the render target is rendered,
34
+ * nodes depending on this one use it to know when to render again
35
+ */
36
+ revision = 0;
37
+ _quadMesh;
38
+ _material;
39
+ // filled by RendererUtils.resetRendererState
40
+ _rendererState = {};
41
+ _state = [];
42
+ /**
43
+ * @param material the material rendered on the full screen quad
44
+ * @param renderTargetOptions options of the render target, it is created with a 1x1 size
45
+ * and resized to {@link RenderTargetNode.width} x {@link RenderTargetNode.height} before rendering
46
+ */
47
+ constructor(material, renderTargetOptions) {
48
+ const renderTarget = new webgpu.RenderTarget(1, 1, { depthBuffer: false, ...renderTargetOptions });
49
+ super(renderTarget.texture);
50
+ this.renderTarget = renderTarget;
51
+ this.updateBeforeType = webgpu.NodeUpdateType.RENDER;
52
+ this._material = material;
53
+ this._quadMesh = new webgpu.QuadMesh(material);
54
+ }
55
+ /**
56
+ * Render target nodes read by this node, rendered (if needed) before this one
57
+ */
58
+ _getDependencies() { return []; }
59
+ /**
60
+ * Called after the render target has been rendered
61
+ */
62
+ _onRender() { }
63
+ /**
64
+ * Forces a render the next time {@link RenderTargetNode.render} is called,
65
+ * use it when something the node can't track changed (e.g. a custom input node)
66
+ */
67
+ invalidate() {
68
+ this._state = [];
69
+ return this;
70
+ }
71
+ /**
72
+ * Renders into {@link RenderTargetNode.renderTarget}, only if something changed since the last render.
73
+ *
74
+ * Called automatically when the node is part of a rendered node graph.
75
+ *
76
+ * @param renderer
77
+ * @returns `true` if the render target was rendered
78
+ */
79
+ render(renderer) {
80
+ const dependencies = this._getDependencies();
81
+ for (const dependency of dependencies)
82
+ dependency.render(renderer);
83
+ const { width, height } = this;
84
+ // not ready yet
85
+ if (width === 0 || height === 0)
86
+ return false;
87
+ const state = [width, height, ...dependencies.map(d => d.revision), ...this._getState()];
88
+ if (state.length === this._state.length && state.every((v, i) => v === this._state[i]))
89
+ return false;
90
+ this._state = state;
91
+ if (this.renderTarget.width !== width || this.renderTarget.height !== height)
92
+ this.renderTarget.setSize(width, height);
93
+ webgpu.RendererUtils.resetRendererState(renderer, this._rendererState);
94
+ renderer.setRenderTarget(this.renderTarget);
95
+ this._quadMesh.render(renderer);
96
+ webgpu.RendererUtils.restoreRendererState(renderer, this._rendererState);
97
+ this.revision++;
98
+ this._onRender();
99
+ return true;
100
+ }
101
+ /**
102
+ * Called by three.js before rendering, renders the node when needed
103
+ * @internal
104
+ */
105
+ updateBefore(frame) {
106
+ if (frame.renderer)
107
+ this.render(frame.renderer);
108
+ return undefined;
109
+ }
110
+ set value(value) {
111
+ if (this.renderTarget && value !== this.renderTarget.texture) {
112
+ throw new Error(`${this.constructor.name}: the value of this node is its render target texture and can't be replaced`);
113
+ }
114
+ }
115
+ get value() {
116
+ return this.renderTarget?.texture;
117
+ }
118
+ /**
119
+ * Clones created by `sample()` & co. are plain TextureNodes reading this node's texture,
120
+ * they keep it updated before rendering as well
121
+ */
122
+ clone() {
123
+ const node = new webgpu.TextureNode(this.value, this.uvNode, this.levelNode, this.biasNode);
124
+ node.sampler = this.sampler;
125
+ node.updateBeforeType = webgpu.NodeUpdateType.RENDER;
126
+ node.updateBefore = (frame) => this.updateBefore(frame);
127
+ return node;
128
+ }
129
+ /**
130
+ * Disposes the render target and the material
131
+ */
132
+ dispose() {
133
+ this.renderTarget.dispose();
134
+ this._material.dispose();
135
+ super.dispose();
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Used internally
141
+ *
142
+ * @internal
143
+ * @param canvas
144
+ * @param mimeType
145
+ * @param quality
146
+ * @returns
147
+ */
148
+ const canvasToBlob = async (canvas, mimeType, quality) => {
149
+ if (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas) {
150
+ return canvas.convertToBlob({ type: mimeType, quality: quality });
151
+ }
152
+ else if (canvas instanceof HTMLCanvasElement) {
153
+ return new Promise((resolve, reject) => {
154
+ canvas.toBlob((res) => {
155
+ if (res)
156
+ resolve(res);
157
+ else
158
+ reject(new Error('Failed to convert canvas to blob'));
159
+ }, mimeType, quality);
160
+ });
161
+ }
162
+ /* istanbul ignore next
163
+ as long as this function is not exported this is only here
164
+ to satisfy TS strict mode internally
165
+ */
166
+ throw new Error('Unsupported canvas element');
167
+ };
168
+ /**
169
+ * Converts a RAW RGBA image buffer into the provided `mimeType` using the provided `quality`
170
+ *
171
+ * @category Compression
172
+ * @group Compression
173
+ * @param params
174
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
175
+ * @throws {Error} if the provided source image cannot be decoded
176
+ * @throws {Error} if the function fails to create a canvas context
177
+ */
178
+ const compress = async (params) => {
179
+ if (typeof createImageBitmap === 'undefined')
180
+ throw new Error('createImageBitmap() not supported.');
181
+ const { source, mimeType, quality, flipY } = params;
182
+ let imageBitmapSource;
183
+ if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
184
+ imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
185
+ }
186
+ else if (source instanceof ImageData) {
187
+ imageBitmapSource = source;
188
+ }
189
+ else {
190
+ throw new Error('Invalid source image');
191
+ }
192
+ const img = await createImageBitmap(imageBitmapSource);
193
+ const width = img.width;
194
+ const height = img.height;
195
+ let canvas;
196
+ if (typeof OffscreenCanvas !== 'undefined') {
197
+ canvas = new OffscreenCanvas(width, height);
198
+ }
199
+ else {
200
+ canvas = document.createElement('canvas');
201
+ canvas.width = width;
202
+ canvas.height = height;
203
+ }
204
+ // apparently we do need to assert the type here for npx tsc to be happy
205
+ const ctx = canvas.getContext('2d');
206
+ if (!ctx)
207
+ throw new Error('Failed to create canvas Context');
208
+ // flip Y
209
+ if (flipY === true) {
210
+ ctx.translate(0, height);
211
+ ctx.scale(1, -1);
212
+ }
213
+ ctx.drawImage(img, 0, 0, width, height);
214
+ const blob = await canvasToBlob(canvas, mimeType, quality || 0.9);
215
+ const data = new Uint8Array(await blob.arrayBuffer());
216
+ return {
217
+ data,
218
+ mimeType,
219
+ width,
220
+ height
221
+ };
222
+ };
223
+
224
+ /**
225
+ * Utility function to obtain a `DataTexture` from various input formats
226
+ *
227
+ * @category Utility
228
+ * @group Utility
229
+ *
230
+ * @param image
231
+ * @returns
232
+ */
233
+ const getDataTexture = (image) => {
234
+ let dataTexture;
235
+ if (image instanceof three.DataTexture) {
236
+ if (!(image.image.data instanceof Uint16Array) && !(image.image.data instanceof Float32Array)) {
237
+ throw new Error('Provided image is not HDR');
238
+ }
239
+ dataTexture = image;
240
+ }
241
+ else {
242
+ if (!image.data || !image.width || !image.height) {
243
+ throw new Error('Provided image has no data or size');
244
+ }
245
+ dataTexture = new three.DataTexture(image.data, image.width, image.height, image.format ?? three.RGBAFormat, image.type, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearFilter, 1, 'colorSpace' in image && image.colorSpace === 'srgb' ? image.colorSpace : three.LinearSRGBColorSpace);
246
+ // TODO: This tries to detect a raw RGBE and applies flipY
247
+ // see if there's a better way to detect it?
248
+ if ('header' in image && 'gamma' in image) {
249
+ dataTexture.flipY = true;
250
+ }
251
+ dataTexture.needsUpdate = true;
252
+ }
253
+ return dataTexture;
254
+ };
255
+
256
+ /**
257
+ * Reads the pixels of a render target, rows are returned top to bottom
258
+ * (like `ImageData`, regardless of the backend) and tightly packed
259
+ * (WebGPU pads each row to 256 bytes).
260
+ *
261
+ * @internal
262
+ * @param renderer
263
+ * @param renderTarget
264
+ */
265
+ const readRenderTargetPixels = async (renderer, renderTarget) => {
266
+ const { width, height } = renderTarget;
267
+ const data = await renderer.readRenderTargetPixelsAsync(renderTarget, 0, 0, width, height);
268
+ const rowLength = width * 4;
269
+ const rowStride = height > 1 ? (data.length - rowLength) / (height - 1) : rowLength;
270
+ // the WebGPU backend reads rows bottom to top (render targets are sampled with flipped uvs),
271
+ // the WebGL backend top to bottom
272
+ const flip = renderer.backend.isWebGLBackend !== true;
273
+ if (rowStride === rowLength && !flip)
274
+ return data.length === rowLength * height ? data : data.subarray(0, rowLength * height);
275
+ const out = new data.constructor(rowLength * height);
276
+ for (let y = 0; y < height; y++) {
277
+ const sourceRow = flip ? height - 1 - y : y;
278
+ out.set(data.subarray(sourceRow * rowStride, sourceRow * rowStride + rowLength), y * rowLength);
279
+ }
280
+ return out;
281
+ };
282
+
283
+ // max half float value
284
+ const HALF_FLOAT_MAX$1 = 65504;
285
+ const CELL_SIZE = 2;
286
+ const isTextureData = (image) => typeof image === 'object' && image !== null && 'data' in image && 'width' in image && 'height' in image && !(image instanceof webgpu.Texture);
287
+ /**
288
+ * Finds the min or max value of each RGB channel of an HDR image, on the GPU.
289
+ *
290
+ * The image is reduced by 2x2 cells until it's 1x1, then the single remaining pixel is read back.
291
+ * Negative values are ignored when looking for the max, values above 65504 (max half float) when looking for the min.
292
+ *
293
+ * @category Utility
294
+ * @group Utility
295
+ *
296
+ * @example
297
+ * import { findTextureMinMax } from '@monogrid/gainmap-js/encode/webgpu'
298
+ *
299
+ * const [r, g, b] = await findTextureMinMax(exrTexture, 'max', renderer)
300
+ * const maxContentBoost = Math.max(r, g, b)
301
+ *
302
+ * @param image the HDR image: a texture, raw texture data or a TSL node (which requires `size`)
303
+ * @param mode
304
+ * @param renderer
305
+ * @param size size of the image, required when the image is a generic node
306
+ * @throws {Error} if the image is a generic node and `size` is not provided
307
+ */
308
+ const findTextureMinMax = async (image, mode, renderer, size) => {
309
+ const rendererState = webgpu.RendererUtils.resetRendererState(renderer, {});
310
+ const renderTargets = [];
311
+ const quad = new webgpu.QuadMesh(new webgpu.NodeMaterial());
312
+ const createRenderTarget = (width, height) => {
313
+ const renderTarget = new webgpu.RenderTarget(width, height, {
314
+ type: webgpu.FloatType,
315
+ minFilter: webgpu.NearestFilter,
316
+ magFilter: webgpu.NearestFilter,
317
+ generateMipmaps: false,
318
+ depthBuffer: false
319
+ });
320
+ renderTargets.push(renderTarget);
321
+ return renderTarget;
322
+ };
323
+ const renderQuad = (material, renderTarget) => {
324
+ material.blending = webgpu.NoBlending;
325
+ material.depthTest = false;
326
+ material.depthWrite = false;
327
+ quad.material = material;
328
+ renderer.setRenderTarget(renderTarget);
329
+ quad.render(renderer);
330
+ };
331
+ try {
332
+ let source;
333
+ let width;
334
+ let height;
335
+ if (image instanceof webgpu.Texture || isTextureData(image)) {
336
+ source = image instanceof webgpu.Texture ? image : getDataTexture(image);
337
+ const sourceImage = source.image;
338
+ width = sourceImage.width;
339
+ height = sourceImage.height;
340
+ }
341
+ else {
342
+ // generic nodes are rendered at full resolution first
343
+ if (!size)
344
+ throw new Error('findTextureMinMax: size is required when the image is a node');
345
+ width = size.width;
346
+ height = size.height;
347
+ const material = new webgpu.NodeMaterial();
348
+ material.fragmentNode = tsl.vec4(image);
349
+ const renderTarget = createRenderTarget(width, height);
350
+ renderQuad(material, renderTarget);
351
+ material.dispose();
352
+ source = renderTarget.texture;
353
+ }
354
+ // creates a material reducing 2x2 cells of a texture into 1 pixel
355
+ const createReduceMaterial = (texture, width, height) => {
356
+ const sourceSize = tsl.uniform(new webgpu.Vector2(width, height));
357
+ const sourceTexture = tsl.textureLoad(texture);
358
+ const reduce = tsl.Fn(() => {
359
+ // the first pixel of the source cell
360
+ const sourcePixel = tsl.screenCoordinate.xy.floor().mul(CELL_SIZE);
361
+ const last = sourceSize.sub(1);
362
+ const result = tsl.vec4(tsl.float(mode === 'max' ? 0 : HALF_FLOAT_MAX$1)).toVar();
363
+ for (let y = 0; y < CELL_SIZE; y++) {
364
+ for (let x = 0; x < CELL_SIZE; x++) {
365
+ // pixels outside the source repeat the edge ones
366
+ const texel = sourceTexture.load(tsl.ivec2(tsl.min(sourcePixel.add(tsl.vec2(x, y)), last)));
367
+ result.assign(mode === 'max' ? tsl.max(result, texel) : tsl.min(result, texel));
368
+ }
369
+ }
370
+ return result;
371
+ });
372
+ const material = new webgpu.NodeMaterial();
373
+ material.fragmentNode = reduce();
374
+ return { material, sourceTexture, sourceSize };
375
+ };
376
+ // the source may have a different format from the intermediate (float) render targets,
377
+ // it is reduced by its own material
378
+ let reducer = createReduceMaterial(source, width, height);
379
+ let renderTarget;
380
+ while (width > 1 || height > 1 || !renderTarget) {
381
+ width = Math.max(1, Math.ceil(width / CELL_SIZE));
382
+ height = Math.max(1, Math.ceil(height / CELL_SIZE));
383
+ const sourceRenderTarget = renderTarget;
384
+ renderTarget = createRenderTarget(width, height);
385
+ if (sourceRenderTarget) {
386
+ if (reducer.sourceTexture.value === source) {
387
+ reducer.material.dispose();
388
+ reducer = createReduceMaterial(sourceRenderTarget.texture, sourceRenderTarget.width, sourceRenderTarget.height);
389
+ }
390
+ else {
391
+ reducer.sourceTexture.value = sourceRenderTarget.texture;
392
+ reducer.sourceSize.value.set(sourceRenderTarget.width, sourceRenderTarget.height);
393
+ }
394
+ }
395
+ renderQuad(reducer.material, renderTarget);
396
+ }
397
+ reducer.material.dispose();
398
+ const out = await readRenderTargetPixels(renderer, renderTarget);
399
+ return [out[0], out[1], out[2]];
400
+ }
401
+ finally {
402
+ webgpu.RendererUtils.restoreRendererState(renderer, rendererState);
403
+ renderTargets.forEach(renderTarget => renderTarget.dispose());
404
+ }
405
+ };
406
+
407
+ // max half float value
408
+ const HALF_FLOAT_MAX = 65504;
409
+ /**
410
+ * A TSL texture node holding the HDR image decoded from an SDR image + gain map.
411
+ *
412
+ * The decode runs on the GPU into a HalfFloat render target, and only when something changed
413
+ * (textures loaded/swapped or any uniform value changed): sampling the node costs a single
414
+ * texture read, like any other texture.
415
+ *
416
+ * The node updates itself before rendering whenever it is part of a rendered node graph
417
+ * (material, `scene.backgroundNode`, ...). When only its texture is used (`node.value`,
418
+ * e.g. `scene.environment = node.value`) call {@link GainMapNode.decode} yourself.
419
+ *
420
+ * Re-decoding also flags the texture for PMREM regeneration,
421
+ * so environment maps are recomputed only when the image actually changes.
422
+ *
423
+ * `node.value` gets its final size once loaded: three.js PMREMs don't follow texture resizes,
424
+ * so assign it to `scene.environment` (or `pmremTexture()`) after load.
425
+ *
426
+ * @category Nodes
427
+ * @group Nodes
428
+ *
429
+ * @example
430
+ * import { GainMapNode } from '@monogrid/gainmap-js/webgpu'
431
+ * import { equirectUV } from 'three/tsl'
432
+ *
433
+ * const hdr = new GainMapNode()
434
+ * .setTextures(sdrTexture, gainMapTexture)
435
+ * .setMetadata(metadata)
436
+ *
437
+ * material.colorNode = hdr
438
+ * scene.backgroundNode = hdr.sample(equirectUV())
439
+ * hdr.maxDisplayBoost.value = 2 // re-decodes once, on the next frame
440
+ */
441
+ class GainMapNode extends RenderTargetNode {
442
+ static get type() { return 'GainMapNode'; }
443
+ /**
444
+ * Shared textures and uniforms
445
+ */
446
+ uniforms;
447
+ // set when the textures are produced by other render target nodes (e.g. a gain map encoder)
448
+ _sdrSource = null;
449
+ _gainMapSource = null;
450
+ constructor() {
451
+ const material = new webgpu.MeshBasicNodeMaterial();
452
+ material.name = 'GainMapDecoder';
453
+ super(material, {
454
+ type: webgpu.HalfFloatType,
455
+ colorSpace: webgpu.LinearSRGBColorSpace,
456
+ generateMipmaps: true,
457
+ minFilter: webgpu.LinearMipmapLinearFilter,
458
+ magFilter: webgpu.LinearFilter
459
+ });
460
+ const u = this.uniforms = {
461
+ sdr: tsl.texture(new webgpu.Texture()),
462
+ gainMap: tsl.texture(new webgpu.Texture()),
463
+ gamma: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
464
+ offsetSdr: tsl.uniform(new webgpu.Vector3()),
465
+ offsetHdr: tsl.uniform(new webgpu.Vector3()),
466
+ gainMapMin: tsl.uniform(new webgpu.Vector3()),
467
+ gainMapMax: tsl.uniform(new webgpu.Vector3(1, 1, 1)),
468
+ hdrCapacityMin: tsl.uniform(0),
469
+ hdrCapacityMax: tsl.uniform(1),
470
+ maxDisplayBoost: tsl.uniform(1)
471
+ };
472
+ const logRecovery = u.gainMap.rgb.pow(tsl.vec3(1).div(u.gamma));
473
+ const logBoost = tsl.mix(u.gainMapMin, u.gainMapMax, logRecovery);
474
+ const weight = tsl.saturate(tsl.log2(u.maxDisplayBoost).sub(u.hdrCapacityMin).div(u.hdrCapacityMax.sub(u.hdrCapacityMin)));
475
+ const hdr = u.sdr.rgb.add(u.offsetSdr).mul(tsl.exp2(logBoost.mul(weight))).sub(u.offsetHdr);
476
+ material.colorNode = tsl.vec4(hdr.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX), 1);
477
+ }
478
+ /** The SDR rendition texture (sRGB) */
479
+ get sdr() { return this.uniforms.sdr.value; }
480
+ /** The gain map recovery texture (linear) */
481
+ get gainMap() { return this.uniforms.gainMap.value; }
482
+ /** @see {@link GainMapMetadata.gamma} */
483
+ get gamma() { return this.uniforms.gamma; }
484
+ /** @see {@link GainMapMetadata.offsetSdr} */
485
+ get offsetSdr() { return this.uniforms.offsetSdr; }
486
+ /** @see {@link GainMapMetadata.offsetHdr} */
487
+ get offsetHdr() { return this.uniforms.offsetHdr; }
488
+ /** @see {@link GainMapMetadata.gainMapMin} */
489
+ get gainMapMin() { return this.uniforms.gainMapMin; }
490
+ /** @see {@link GainMapMetadata.gainMapMax} */
491
+ get gainMapMax() { return this.uniforms.gainMapMax; }
492
+ /** @see {@link GainMapMetadata.hdrCapacityMin} */
493
+ get hdrCapacityMin() { return this.uniforms.hdrCapacityMin; }
494
+ /** @see {@link GainMapMetadata.hdrCapacityMax} */
495
+ get hdrCapacityMax() { return this.uniforms.hdrCapacityMax; }
496
+ /**
497
+ * @see {@link GainmapDecodingParameters.maxDisplayBoost}
498
+ * @remarks Non Logarithmic space
499
+ */
500
+ get maxDisplayBoost() { return this.uniforms.maxDisplayBoost; }
501
+ /** Width of the SDR image, 0 until loaded */
502
+ get width() {
503
+ if (this._sdrSource)
504
+ return this._sdrSource.width;
505
+ return this.sdr.image?.width ?? 0;
506
+ }
507
+ /** Height of the SDR image, 0 until loaded */
508
+ get height() {
509
+ if (this._sdrSource)
510
+ return this._sdrSource.height;
511
+ return this.sdr.image?.height ?? 0;
512
+ }
513
+ /**
514
+ * Sets the SDR and gain map textures.
515
+ * The SDR texture is expected in sRGB color space, the gain map in linear.
516
+ *
517
+ * Render target nodes (e.g. the `sdr` and `gainMap` nodes of a `GainMapEncoder`) are accepted as well:
518
+ * they are rendered before decoding and the image is decoded again whenever they change.
519
+ *
520
+ * @param sdr
521
+ * @param gainMap
522
+ */
523
+ setTextures(sdr, gainMap) {
524
+ this._sdrSource = sdr instanceof RenderTargetNode ? sdr : null;
525
+ this._gainMapSource = gainMap instanceof RenderTargetNode ? gainMap : null;
526
+ this.uniforms.sdr.value = sdr instanceof RenderTargetNode ? sdr.value : sdr;
527
+ this.uniforms.gainMap.value = gainMap instanceof RenderTargetNode ? gainMap.value : gainMap;
528
+ // size the render target right away, so `value` has its final size before the first decode
529
+ if (this.width > 0 && this.height > 0)
530
+ this.renderTarget.setSize(this.width, this.height);
531
+ return this;
532
+ }
533
+ /**
534
+ * Copies the gain map metadata into the uniforms.
535
+ * Also sets `maxDisplayBoost` to fully restore the HDR range.
536
+ *
537
+ * @param metadata
538
+ */
539
+ setMetadata(metadata) {
540
+ const u = this.uniforms;
541
+ u.gamma.value.fromArray(metadata.gamma);
542
+ u.offsetSdr.value.fromArray(metadata.offsetSdr);
543
+ u.offsetHdr.value.fromArray(metadata.offsetHdr);
544
+ u.gainMapMin.value.fromArray(metadata.gainMapMin);
545
+ u.gainMapMax.value.fromArray(metadata.gainMapMax);
546
+ u.hdrCapacityMin.value = metadata.hdrCapacityMin;
547
+ u.hdrCapacityMax.value = metadata.hdrCapacityMax;
548
+ u.maxDisplayBoost.value = Math.pow(2, metadata.hdrCapacityMax);
549
+ return this;
550
+ }
551
+ _getState() {
552
+ const u = this.uniforms;
553
+ return [
554
+ this.sdr.id, this.sdr.version, this.gainMap.id, this.gainMap.version,
555
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
556
+ ...u.gainMapMin.value.toArray(), ...u.gainMapMax.value.toArray(),
557
+ u.hdrCapacityMin.value, u.hdrCapacityMax.value, u.maxDisplayBoost.value
558
+ ];
559
+ }
560
+ _getDependencies() {
561
+ const dependencies = [];
562
+ if (this._sdrSource)
563
+ dependencies.push(this._sdrSource);
564
+ if (this._gainMapSource)
565
+ dependencies.push(this._gainMapSource);
566
+ return dependencies;
567
+ }
568
+ _onRender() {
569
+ this.value.needsPMREMUpdate = true;
570
+ }
571
+ /**
572
+ * Decodes the image into {@link GainMapNode.renderTarget}, only if something changed since the last decode.
573
+ *
574
+ * Called automatically when the node is part of a rendered node graph.
575
+ *
576
+ * @param renderer
577
+ * @returns `true` if the image was decoded
578
+ */
579
+ decode(renderer) {
580
+ return this.render(renderer);
581
+ }
582
+ /**
583
+ * Calls {@link GainMapNode.decode} once per render, before the node is evaluated.
584
+ *
585
+ * @param frame
586
+ */
587
+ updateBefore(frame) {
588
+ if (frame.renderer)
589
+ this.decode(frame.renderer);
590
+ return undefined;
591
+ }
592
+ /**
593
+ * Disposes the render target, the SDR and gain map textures
594
+ * (unless they belong to other render target nodes)
595
+ */
596
+ dispose() {
597
+ if (!this._sdrSource)
598
+ this.sdr.dispose();
599
+ if (!this._gainMapSource)
600
+ this.gainMap.dispose();
601
+ super.dispose();
602
+ }
603
+ }
604
+
605
+ // maxContentBoost must be > 1, a gain map can't encode an empty boost range
606
+ const MIN_MAX_CONTENT_BOOST = 1.0001;
607
+ /**
608
+ * A TSL texture node holding the gain map (recovery map) of an HDR image: the second step of gain map encoding.
609
+ *
610
+ * The gain map is computed from the HDR input of a {@link SDRRenditionNode} and its SDR rendition,
611
+ * into an 8 bit linear render target. The result is identical to the one of the WebGL `GainMapEncoderMaterial`.
612
+ *
613
+ * It renders only when something changed (the SDR rendition or any uniform value),
614
+ * the SDR rendition is rendered first when needed.
615
+ *
616
+ * @category Nodes
617
+ * @group Nodes
618
+ *
619
+ * @example
620
+ * import { GainMapEncoderNode, SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
621
+ *
622
+ * const sdr = new SDRRenditionNode(hdrTexture)
623
+ * const gainMap = new GainMapEncoderNode(sdr, { maxContentBoost: 8 })
624
+ *
625
+ * material.colorNode = gainMap
626
+ * gainMap.gamma.value.setScalar(1.2) // renders again once, on the next frame
627
+ * const metadata = gainMap.metadata
628
+ */
629
+ class GainMapEncoderNode extends RenderTargetNode {
630
+ static get type() { return 'GainMapEncoderNode'; }
631
+ /**
632
+ * The SDR rendition this gain map is computed from
633
+ */
634
+ sdr;
635
+ /**
636
+ * Shared uniforms
637
+ */
638
+ uniforms;
639
+ _warned = [];
640
+ /**
641
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
642
+ * @param params encoding parameters, all of them can be changed later through the uniforms
643
+ */
644
+ constructor(sdr, params = {}) {
645
+ super(new webgpu.NodeMaterial(), {
646
+ type: webgpu.UnsignedByteType,
647
+ colorSpace: webgpu.LinearSRGBColorSpace,
648
+ minFilter: webgpu.LinearFilter,
649
+ magFilter: webgpu.LinearFilter
650
+ });
651
+ this.sdr = sdr;
652
+ const u = this.uniforms = {
653
+ gamma: tsl.uniform(new webgpu.Vector3().fromArray(params.gamma ?? [1, 1, 1])),
654
+ offsetSdr: tsl.uniform(new webgpu.Vector3().fromArray(params.offsetSdr ?? [1 / 64, 1 / 64, 1 / 64])),
655
+ offsetHdr: tsl.uniform(new webgpu.Vector3().fromArray(params.offsetHdr ?? [1 / 64, 1 / 64, 1 / 64])),
656
+ // 0 is not a valid min content boost
657
+ minContentBoost: tsl.uniform(params.minContentBoost || 1),
658
+ maxContentBoost: tsl.uniform(params.maxContentBoost ?? MIN_MAX_CONTENT_BOOST)
659
+ };
660
+ // logarithms are computed on the CPU (in double precision), like the WebGL encoder does
661
+ const minLog2 = tsl.uniform(0).onRenderUpdate(() => Math.log2(this.metadataMinContentBoost));
662
+ const maxLog2 = tsl.uniform(0).onRenderUpdate(() => Math.log2(this.metadataMaxContentBoost));
663
+ const sdrColor = tsl.texture(sdr.value).rgb;
664
+ const hdrColor = tsl.vec4(sdr.hdr).rgb;
665
+ const pixelGain = hdrColor.add(u.offsetHdr).div(sdrColor.add(u.offsetSdr));
666
+ const logRecovery = tsl.log2(pixelGain).sub(minLog2).div(maxLog2.sub(minLog2));
667
+ const clampedRecovery = tsl.saturate(logRecovery);
668
+ this._material.name = 'GainMapEncoder';
669
+ this._material.blending = webgpu.NoBlending;
670
+ this._material.depthTest = false;
671
+ this._material.depthWrite = false;
672
+ this._material.fragmentNode = tsl.vec4(tsl.pow(clampedRecovery, u.gamma), 1.0);
673
+ }
674
+ /** @see {@link GainmapEncodingParameters.gamma} */
675
+ get gamma() { return this.uniforms.gamma; }
676
+ /** @see {@link GainmapEncodingParameters.offsetSdr} */
677
+ get offsetSdr() { return this.uniforms.offsetSdr; }
678
+ /** @see {@link GainmapEncodingParameters.offsetHdr} */
679
+ get offsetHdr() { return this.uniforms.offsetHdr; }
680
+ /**
681
+ * @see {@link GainmapEncodingParameters.minContentBoost}
682
+ * @remarks Non logarithmic space
683
+ */
684
+ get minContentBoost() { return this.uniforms.minContentBoost; }
685
+ /**
686
+ * @see {@link GainmapEncodingParameters.maxContentBoost}
687
+ * @remarks Non logarithmic space, values <= 1 are clamped to 1.0001 since a gain map can't encode an empty boost range
688
+ */
689
+ get maxContentBoost() { return this.uniforms.maxContentBoost; }
690
+ /** Same size as the SDR rendition */
691
+ get width() { return this.sdr.width; }
692
+ /** Same size as the SDR rendition */
693
+ get height() { return this.sdr.height; }
694
+ /** The min content boost actually encoded */
695
+ get metadataMinContentBoost() { return this.uniforms.minContentBoost.value; }
696
+ /** The max content boost actually encoded, clamped to a valid range */
697
+ get metadataMaxContentBoost() { return Math.max(this.uniforms.maxContentBoost.value, MIN_MAX_CONTENT_BOOST); }
698
+ /**
699
+ * The gain map metadata matching the current uniform values
700
+ */
701
+ get metadata() {
702
+ const u = this.uniforms;
703
+ const gainMapMin = Math.log2(this.metadataMinContentBoost);
704
+ const gainMapMax = Math.log2(this.metadataMaxContentBoost);
705
+ return {
706
+ gamma: u.gamma.value.toArray(),
707
+ offsetSdr: u.offsetSdr.value.toArray(),
708
+ offsetHdr: u.offsetHdr.value.toArray(),
709
+ gainMapMin: [gainMapMin, gainMapMin, gainMapMin],
710
+ gainMapMax: [gainMapMax, gainMapMax, gainMapMax],
711
+ hdrCapacityMin: Math.max(0, gainMapMin),
712
+ hdrCapacityMax: Math.max(0, gainMapMax)
713
+ };
714
+ }
715
+ _getState() {
716
+ const u = this.uniforms;
717
+ return [
718
+ ...u.gamma.value.toArray(), ...u.offsetSdr.value.toArray(), ...u.offsetHdr.value.toArray(),
719
+ u.minContentBoost.value, u.maxContentBoost.value
720
+ ];
721
+ }
722
+ _getDependencies() {
723
+ return [this.sdr];
724
+ }
725
+ _onRender() {
726
+ // warn once per invalid combination of parameters
727
+ const { minContentBoost, maxContentBoost } = this.uniforms;
728
+ const state = [minContentBoost.value, maxContentBoost.value];
729
+ if (state.every((v, i) => v === this._warned[i]))
730
+ return;
731
+ this._warned = state;
732
+ if (maxContentBoost.value <= 1) {
733
+ console.warn(`gainmap-js: maxContentBoost is ${maxContentBoost.value} (<= 1), the source image has no HDR content. It will be clamped to ${MIN_MAX_CONTENT_BOOST} and the result will be equivalent to an SDR image.`);
734
+ }
735
+ if (this.metadataMinContentBoost >= this.metadataMaxContentBoost) {
736
+ console.warn(`gainmap-js: minContentBoost (${this.metadataMinContentBoost}) must be lower than maxContentBoost (${this.metadataMaxContentBoost}), the resulting gain map will be invalid.`);
737
+ }
738
+ }
739
+ }
740
+ /**
741
+ * TSL function creating a {@link GainMapEncoderNode}
742
+ *
743
+ * @param sdr the SDR rendition, its HDR input is the HDR input of the gain map
744
+ * @param params encoding parameters
745
+ */
746
+ const gainMapEncoder = (sdr, params) => new GainMapEncoderNode(sdr, params);
747
+
748
+ const textureSize = (texture) => {
749
+ const image = texture.image;
750
+ return { width: image?.width ?? 0, height: image?.height ?? 0 };
751
+ };
752
+ /**
753
+ * A TSL texture node holding the SDR rendition of an HDR image: the first step of gain map encoding.
754
+ *
755
+ * The HDR input is exposed, tone mapped (with the three.js TSL tone mapping functions)
756
+ * and adjusted (brightness, contrast, saturation) into an 8 bit sRGB render target.
757
+ *
758
+ * It renders only when something changed (input, tone mapping or any uniform value):
759
+ * sampling the node costs a single texture read, like any other texture.
760
+ *
761
+ * @category Nodes
762
+ * @group Nodes
763
+ *
764
+ * @example
765
+ * import { SDRRenditionNode } from '@monogrid/gainmap-js/encode/webgpu'
766
+ * import { AgXToneMapping, LinearToneMapping } from 'three/webgpu'
767
+ *
768
+ * const sdr = new SDRRenditionNode(hdrTexture, { toneMapping: AgXToneMapping })
769
+ * material.colorNode = sdr
770
+ * sdr.exposure.value = 0.8 // renders again once, on the next frame
771
+ * sdr.setToneMapping(LinearToneMapping)
772
+ */
773
+ class SDRRenditionNode extends RenderTargetNode {
774
+ static get type() { return 'SDRRenditionNode'; }
775
+ /**
776
+ * The HDR input, as a node
777
+ */
778
+ hdr;
779
+ /**
780
+ * Shared uniforms
781
+ */
782
+ uniforms;
783
+ _hdrTexture;
784
+ _hdrSource;
785
+ _width;
786
+ _height;
787
+ _toneMapping = webgpu.ACESFilmicToneMapping;
788
+ /**
789
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
790
+ * @param options
791
+ * @throws {Error} if the input is a generic node and `width` or `height` are not provided
792
+ */
793
+ constructor(hdr, options = {}) {
794
+ super(new webgpu.NodeMaterial(), {
795
+ type: webgpu.UnsignedByteType,
796
+ colorSpace: webgpu.SRGBColorSpace,
797
+ minFilter: webgpu.LinearFilter,
798
+ magFilter: webgpu.LinearFilter
799
+ });
800
+ this._hdrTexture = hdr instanceof webgpu.Texture ? hdr : hdr instanceof webgpu.TextureNode ? hdr.value : null;
801
+ this._hdrSource = hdr instanceof RenderTargetNode ? hdr : null;
802
+ this.hdr = hdr instanceof webgpu.Texture ? tsl.texture(hdr) : hdr;
803
+ this._width = options.width;
804
+ this._height = options.height;
805
+ if (!this._hdrTexture && (!this._width || !this._height)) {
806
+ throw new Error('SDRRenditionNode: width and height are required when the HDR input is not a texture');
807
+ }
808
+ this.uniforms = {
809
+ exposure: tsl.uniform(1),
810
+ brightness: tsl.uniform(0),
811
+ contrast: tsl.uniform(1),
812
+ saturation: tsl.uniform(1)
813
+ };
814
+ this._material.name = 'SDRRendition';
815
+ this._material.blending = webgpu.NoBlending;
816
+ this._material.depthTest = false;
817
+ this._material.depthWrite = false;
818
+ this.setToneMapping(options.toneMapping ?? webgpu.ACESFilmicToneMapping);
819
+ }
820
+ /** Exposure applied to the HDR input before tone mapping */
821
+ get exposure() { return this.uniforms.exposure; }
822
+ /** Brightness offset applied after tone mapping */
823
+ get brightness() { return this.uniforms.brightness; }
824
+ /** Contrast applied after tone mapping */
825
+ get contrast() { return this.uniforms.contrast; }
826
+ /** Saturation applied after tone mapping */
827
+ get saturation() { return this.uniforms.saturation; }
828
+ /**
829
+ * The tone mapping applied to the SDR rendition
830
+ */
831
+ getToneMapping() { return this._toneMapping; }
832
+ /**
833
+ * Sets the tone mapping applied to the SDR rendition
834
+ * (`toneMapping` can't be used as a property name: it's a TSL method of every node)
835
+ *
836
+ * @param value any three.js tone mapping, e.g. `ACESFilmicToneMapping`, `AgXToneMapping`, `NeutralToneMapping`
837
+ * or `LinearToneMapping` (which keeps the SDR rendition closest to the HDR input)
838
+ */
839
+ setToneMapping(value) {
840
+ this._toneMapping = value;
841
+ this._material.fragmentNode = this._buildOutput();
842
+ this._material.needsUpdate = true;
843
+ return this;
844
+ }
845
+ /** Width of the output, 0 while the input texture is not loaded */
846
+ get width() {
847
+ if (this._width)
848
+ return this._width;
849
+ if (this._hdrSource)
850
+ return this._hdrSource.width;
851
+ return this._hdrTexture ? textureSize(this._hdrTexture).width : 0;
852
+ }
853
+ /** Height of the output, 0 while the input texture is not loaded */
854
+ get height() {
855
+ if (this._height)
856
+ return this._height;
857
+ if (this._hdrSource)
858
+ return this._hdrSource.height;
859
+ return this._hdrTexture ? textureSize(this._hdrTexture).height : 0;
860
+ }
861
+ _buildOutput() {
862
+ const u = this.uniforms;
863
+ const color = tsl.vec4(this.hdr);
864
+ // exposure is applied here rather than by the tone mapping function, so it works with `NoToneMapping` too
865
+ // `.rgb` because ToneMappingNode declares a vec3 but its setup returns a vec4 (colour + alpha) when a tone mapping is set
866
+ const toneMapped = tsl.vec4(tsl.toneMapping(this._toneMapping, tsl.float(1), color.rgb.mul(u.exposure)).rgb, color.a);
867
+ const b = u.brightness;
868
+ const brightnessMatrix = tsl.mat4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, b, b, b, 1);
869
+ const c = u.contrast;
870
+ const t = tsl.float(1.0).sub(c).div(2.0);
871
+ const contrastMatrix = tsl.mat4(c, 0, 0, 0, 0, c, 0, 0, 0, 0, c, 0, t, t, t, 1);
872
+ const luminance = tsl.vec3(0.3086, 0.6094, 0.0820);
873
+ const oneMinusSat = tsl.float(1.0).sub(u.saturation);
874
+ const red = tsl.vec3(luminance.x.mul(oneMinusSat)).add(tsl.vec3(u.saturation, 0, 0));
875
+ const green = tsl.vec3(luminance.y.mul(oneMinusSat)).add(tsl.vec3(0, u.saturation, 0));
876
+ const blue = tsl.vec3(luminance.z.mul(oneMinusSat)).add(tsl.vec3(0, 0, u.saturation));
877
+ const saturationMatrix = tsl.mat4(tsl.vec4(red, 0), tsl.vec4(green, 0), tsl.vec4(blue, 0), tsl.vec4(0, 0, 0, 1));
878
+ return brightnessMatrix.mul(contrastMatrix).mul(saturationMatrix).mul(toneMapped);
879
+ }
880
+ _getState() {
881
+ const u = this.uniforms;
882
+ return [
883
+ this._hdrTexture?.id, this._hdrTexture?.version, this._toneMapping,
884
+ u.exposure.value, u.brightness.value, u.contrast.value, u.saturation.value
885
+ ];
886
+ }
887
+ _getDependencies() {
888
+ return this._hdrSource ? [this._hdrSource] : [];
889
+ }
890
+ }
891
+ /**
892
+ * TSL function creating a {@link SDRRenditionNode}
893
+ *
894
+ * @param hdr HDR input, a texture or a TSL node returning a linear HDR color
895
+ * @param options
896
+ */
897
+ const sdrRendition = (hdr, options) => new SDRRenditionNode(hdr, options);
898
+
899
+ /**
900
+ * A gain map preview: a {@link GainMapNode} decoding the encoder output, following its metadata
901
+ */
902
+ class EncoderPreviewNode extends GainMapNode {
903
+ _encoder;
904
+ constructor(encoder) {
905
+ super();
906
+ this._encoder = encoder;
907
+ this.setTextures(encoder.sdr, encoder.gainMap).setMetadata(encoder.metadata);
908
+ }
909
+ _getState() {
910
+ // follow the encoder metadata, except the display boost which belongs to the viewer
911
+ const { gamma, offsetSdr, offsetHdr, gainMapMin, gainMapMax, hdrCapacityMin, hdrCapacityMax } = this._encoder.metadata;
912
+ const u = this.uniforms;
913
+ u.gamma.value.fromArray(gamma);
914
+ u.offsetSdr.value.fromArray(offsetSdr);
915
+ u.offsetHdr.value.fromArray(offsetHdr);
916
+ u.gainMapMin.value.fromArray(gainMapMin);
917
+ u.gainMapMax.value.fromArray(gainMapMax);
918
+ u.hdrCapacityMin.value = hdrCapacityMin;
919
+ u.hdrCapacityMax.value = hdrCapacityMax;
920
+ return super._getState();
921
+ }
922
+ }
923
+ /**
924
+ * Encodes an HDR image into an SDR rendition + a gain map, on the GPU, with TSL nodes.
925
+ *
926
+ * {@link GainMapEncoder.sdr} and {@link GainMapEncoder.gainMap} are live texture nodes:
927
+ * every encoding parameter is a uniform, changing one re-renders the affected nodes once, when they're next used.
928
+ * No renderer is needed until the result is read back with {@link GainMapEncoder.read} or {@link GainMapEncoder.compress}.
929
+ *
930
+ * Read back images are oriented top to bottom (like `ImageData`), no `flipY` is needed when compressing them.
931
+ *
932
+ * @category Encoding Functions
933
+ * @group Encoding Functions
934
+ *
935
+ * @example
936
+ * import { GainMapEncoder } from '@monogrid/gainmap-js/encode/webgpu'
937
+ * import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
938
+ * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
939
+ * import { AgXToneMapping, MeshBasicNodeMaterial, WebGPURenderer } from 'three/webgpu'
940
+ *
941
+ * const renderer = new WebGPURenderer()
942
+ * await renderer.init()
943
+ *
944
+ * const image = await new EXRLoader().loadAsync('image.exr')
945
+ * const encoder = new GainMapEncoder(image, { toneMapping: AgXToneMapping })
946
+ * // encode the full HDR range
947
+ * await encoder.fitMaxContentBoost(renderer)
948
+ *
949
+ * // live previews, they follow any parameter change
950
+ * sdrMaterial.colorNode = encoder.sdr
951
+ * gainMapMaterial.colorNode = encoder.gainMap
952
+ * hdrMaterial.colorNode = encoder.createPreviewNode() // decodes the encoded result
953
+ *
954
+ * encoder.sdr.exposure.value = 0.9
955
+ * encoder.gainMap.gamma.value.setScalar(1.1)
956
+ *
957
+ * // compress and embed into a single JPEG file
958
+ * const result = await encoder.compress(renderer, { mimeType: 'image/jpeg', quality: 0.9 })
959
+ * const jpeg = encodeJPEGMetadata(result)
960
+ */
961
+ class GainMapEncoder {
962
+ /**
963
+ * The SDR rendition node
964
+ */
965
+ sdr;
966
+ /**
967
+ * The gain map node
968
+ */
969
+ gainMap;
970
+ _ownedTexture;
971
+ /**
972
+ * @param image the HDR image: a texture, raw texture data (e.g. from a worker) or a TSL node (which requires `width` and `height`)
973
+ * @param options encoding parameters, all of them can be changed later through the node uniforms
974
+ */
975
+ constructor(image, options = {}) {
976
+ let input;
977
+ if (image instanceof webgpu.Texture || !('data' in image)) {
978
+ input = image;
979
+ this._ownedTexture = null;
980
+ }
981
+ else {
982
+ input = this._ownedTexture = getDataTexture(image);
983
+ }
984
+ this.sdr = new SDRRenditionNode(input, options);
985
+ this.gainMap = new GainMapEncoderNode(this.sdr, options);
986
+ }
987
+ /** Width of the encoded images */
988
+ get width() { return this.sdr.width; }
989
+ /** Height of the encoded images */
990
+ get height() { return this.sdr.height; }
991
+ /**
992
+ * The gain map metadata matching the current parameters
993
+ */
994
+ get metadata() {
995
+ return this.gainMap.metadata;
996
+ }
997
+ /**
998
+ * Finds the max value of the HDR image and uses it as `maxContentBoost`,
999
+ * so the full HDR range is encoded.
1000
+ *
1001
+ * @param renderer
1002
+ * @returns the new `maxContentBoost`
1003
+ */
1004
+ async fitMaxContentBoost(renderer) {
1005
+ const max = Math.max(...await findTextureMinMax(this.sdr.hdr, 'max', renderer, this));
1006
+ this.gainMap.maxContentBoost.value = max;
1007
+ return max;
1008
+ }
1009
+ /**
1010
+ * Creates a {@link GainMapNode} decoding the encoded result on the fly,
1011
+ * it follows any change to the encoding parameters.
1012
+ * Its `maxDisplayBoost` is initialized to restore the full HDR range, and is not changed afterwards.
1013
+ */
1014
+ createPreviewNode() {
1015
+ return new EncoderPreviewNode(this);
1016
+ }
1017
+ /**
1018
+ * Renders the SDR rendition and the gain map, only if something changed since the last render
1019
+ *
1020
+ * @param renderer
1021
+ */
1022
+ render(renderer) {
1023
+ // renders the SDR rendition first
1024
+ this.gainMap.render(renderer);
1025
+ }
1026
+ /**
1027
+ * Renders (if needed) and reads back the raw SDR rendition and gain map
1028
+ *
1029
+ * @param renderer
1030
+ */
1031
+ async read(renderer) {
1032
+ this.render(renderer);
1033
+ const metadata = this.metadata;
1034
+ const [sdr, gainMap] = await Promise.all([
1035
+ readRenderTargetPixels(renderer, this.sdr.renderTarget),
1036
+ readRenderTargetPixels(renderer, this.gainMap.renderTarget)
1037
+ ]);
1038
+ return {
1039
+ sdr: new ImageData(new Uint8ClampedArray(sdr), this.width, this.height),
1040
+ gainMap: new ImageData(new Uint8ClampedArray(gainMap), this.width, this.height),
1041
+ metadata
1042
+ };
1043
+ }
1044
+ /**
1045
+ * Renders (if needed), reads back and compresses the SDR rendition and gain map
1046
+ *
1047
+ * @param renderer
1048
+ * @param options compression options, `flipY` is not needed
1049
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
1050
+ */
1051
+ async compress(renderer, options) {
1052
+ const { sdr, gainMap, metadata } = await this.read(renderer);
1053
+ const { withWorker, ...compressOptions } = options;
1054
+ if (withWorker) {
1055
+ const [compressedSDR, compressedGainMap] = await Promise.all([
1056
+ withWorker.compress({ ...compressOptions, source: sdr }),
1057
+ withWorker.compress({ ...compressOptions, source: gainMap })
1058
+ ]);
1059
+ return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: compressedSDR.source, rawGainMap: compressedGainMap.source };
1060
+ }
1061
+ const [compressedSDR, compressedGainMap] = await Promise.all([
1062
+ compress({ ...compressOptions, source: sdr }),
1063
+ compress({ ...compressOptions, source: gainMap })
1064
+ ]);
1065
+ return { ...metadata, sdr: compressedSDR, gainMap: compressedGainMap, rawSDR: sdr.data, rawGainMap: gainMap.data };
1066
+ }
1067
+ /**
1068
+ * Disposes the nodes, and the HDR texture if it was created by the encoder from raw data
1069
+ */
1070
+ dispose() {
1071
+ this.sdr.dispose();
1072
+ this.gainMap.dispose();
1073
+ this._ownedTexture?.dispose();
1074
+ }
1075
+ }
1076
+
1077
+ exports.GainMapEncoder = GainMapEncoder;
1078
+ exports.GainMapEncoderNode = GainMapEncoderNode;
1079
+ exports.RenderTargetNode = RenderTargetNode;
1080
+ exports.SDRRenditionNode = SDRRenditionNode;
1081
+ exports.compress = compress;
1082
+ exports.findTextureMinMax = findTextureMinMax;
1083
+ exports.gainMapEncoder = gainMapEncoder;
1084
+ exports.sdrRendition = sdrRendition;
1085
+
1086
+ }));