@monogrid/gainmap-js 1.1.1 → 2.0.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 (49) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +21 -8
  3. package/dist/QuadRenderer-IDZuHqZM.js +178 -0
  4. package/dist/{_commonjsHelpers-1789f0cf.js → _commonjsHelpers-G_2thcKl.js} +1 -1
  5. package/dist/{compress-a4b59cab.js → compress-Cw5IwRTb.js} +1 -1
  6. package/dist/{loaders → core}/LoaderBase.d.ts +3 -3
  7. package/dist/core/types.d.ts +64 -0
  8. package/dist/decode/decode.d.ts +56 -0
  9. package/dist/decode/extract.d.ts +10 -0
  10. package/dist/decode/index.d.ts +8 -0
  11. package/dist/{loaders → decode/loaders}/GainMapLoader.d.ts +2 -2
  12. package/dist/{loaders → decode/loaders}/JPEGRLoader.d.ts +4 -4
  13. package/dist/{materials → decode/materials}/GainMapDecoderMaterial.d.ts +3 -2
  14. package/dist/decode/types.d.ts +38 -0
  15. package/dist/decode/utils/MPFExtractor.d.ts +22 -0
  16. package/dist/decode/utils/extract-metadata-from-jpeg.d.ts +7 -0
  17. package/dist/decode.d.ts +1 -56
  18. package/dist/decode.js +737 -0
  19. package/dist/decode.umd.js +917 -0
  20. package/dist/{encode-utils → encode}/compress.d.ts +1 -1
  21. package/dist/encode/encode-and-compress.d.ts +61 -0
  22. package/dist/encode/encode.d.ts +58 -0
  23. package/dist/{encode-utils → encode}/get-gainmap.d.ts +3 -3
  24. package/dist/{encode-utils → encode}/get-sdr-rendition.d.ts +2 -3
  25. package/dist/encode/index.d.ts +10 -0
  26. package/dist/{types.d.ts → encode/types.d.ts} +2 -102
  27. package/dist/encode.d.ts +1 -117
  28. package/dist/{index.js → encode.js} +26 -218
  29. package/dist/encode.umd.js +972 -0
  30. package/dist/libultrahdr/decode-jpeg-metadata.d.ts +2 -2
  31. package/dist/libultrahdr/encode-jpeg-metadata.d.ts +2 -1
  32. package/dist/libultrahdr.d.ts +0 -1
  33. package/dist/libultrahdr.js +2 -79
  34. package/dist/libultrahdr.umd.js +10 -460
  35. package/dist/worker-interface.js +2 -2
  36. package/dist/worker-interface.umd.js +1 -3
  37. package/dist/worker-types.d.ts +1 -1
  38. package/dist/worker.js +3 -3
  39. package/dist/worker.umd.js +1 -1
  40. package/package.json +36 -29
  41. package/dist/LoaderBase-eee19701.js +0 -382
  42. package/dist/index.d.ts +0 -11
  43. package/dist/index.umd.js +0 -1373
  44. package/dist/materials/index.d.ts +0 -3
  45. /package/dist/{utils → core}/QuadRenderer.d.ts +0 -0
  46. /package/dist/{utils → core}/get-data-texture.d.ts +0 -0
  47. /package/dist/{encode-utils → encode}/find-texture-min-max.d.ts +0 -0
  48. /package/dist/{materials → encode/materials}/GainMapEncoderMaterial.d.ts +0 -0
  49. /package/dist/{materials → encode/materials}/SDRMaterial.d.ts +0 -0
@@ -0,0 +1,972 @@
1
+ /**
2
+ * @monogrid/gainmap-js v1.1.1
3
+ * With ❤️, by MONOGRID <hello@mono-grid.com>
4
+ */
5
+
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
8
+ typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@monogrid/gainmap-js"] = {}, global.three));
10
+ })(this, (function (exports, three) { 'use strict';
11
+
12
+ /**
13
+ * Used internally
14
+ *
15
+ * @internal
16
+ * @param canvas
17
+ * @param mimeType
18
+ * @param quality
19
+ * @returns
20
+ */
21
+ const canvasToBlob = async (canvas, mimeType, quality) => {
22
+ if (canvas instanceof OffscreenCanvas) {
23
+ return canvas.convertToBlob({ type: mimeType, quality: quality || 0.9 });
24
+ }
25
+ return new Promise((resolve, reject) => {
26
+ canvas.toBlob((res) => {
27
+ if (res)
28
+ resolve(res);
29
+ else
30
+ reject('Failed to convert canvas to blob');
31
+ }, mimeType, quality || 0.9);
32
+ });
33
+ };
34
+ /**
35
+ * Converts a RAW RGBA image buffer into the provided `mimeType` using the provided `quality`
36
+ *
37
+ * @category Compression
38
+ * @group Compression
39
+ * @param params
40
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
41
+ * @throws {Error} if the provided source image cannot be decoded
42
+ * @throws {Error} if the function fails to create a canvas context
43
+ */
44
+ const compress = async (params) => {
45
+ if (typeof createImageBitmap === 'undefined')
46
+ throw new Error('createImageBitmap() not supported.');
47
+ const { source, mimeType, quality, flipY } = params;
48
+ // eslint-disable-next-line no-undef
49
+ let imageBitmapSource;
50
+ if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
51
+ imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
52
+ }
53
+ else if (source instanceof ImageData) {
54
+ imageBitmapSource = source;
55
+ }
56
+ else {
57
+ throw new Error('Invalid source image');
58
+ }
59
+ const img = await createImageBitmap(imageBitmapSource);
60
+ const width = img.width;
61
+ const height = img.height;
62
+ let canvas;
63
+ if (typeof OffscreenCanvas !== 'undefined') {
64
+ canvas = new OffscreenCanvas(width, height);
65
+ }
66
+ else {
67
+ canvas = document.createElement('canvas');
68
+ }
69
+ const ctx = canvas.getContext('2d');
70
+ if (!ctx)
71
+ throw new Error('Failed to create canvas Context');
72
+ // flip Y
73
+ if (flipY === true) {
74
+ ctx.translate(0, height);
75
+ ctx.scale(1, -1);
76
+ }
77
+ ctx.drawImage(img, 0, 0, width, height);
78
+ const blob = await canvasToBlob(canvas, mimeType, quality || 0.9);
79
+ const data = new Uint8Array(await blob.arrayBuffer());
80
+ return {
81
+ data,
82
+ mimeType,
83
+ width,
84
+ height
85
+ };
86
+ };
87
+
88
+ /**
89
+ * Utility function to obtain a `DataTexture` from various input formats
90
+ *
91
+ * @category General
92
+ * @group General
93
+ *
94
+ * @param image
95
+ * @returns
96
+ */
97
+ const getDataTexture = (image) => {
98
+ let dataTexture;
99
+ if (image instanceof three.DataTexture) {
100
+ if (!(image.image.data instanceof Uint16Array) && !(image.image.data instanceof Float32Array)) {
101
+ throw new Error('Provided image is not HDR');
102
+ }
103
+ dataTexture = image;
104
+ }
105
+ else {
106
+ dataTexture = new three.DataTexture(image.data, image.width, image.height, 'format' in image ? 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.NoColorSpace);
107
+ // TODO: This tries to detect a raw RGBE and applies flipY
108
+ // see if there's a better way to detect it?
109
+ if ('header' in image && 'gamma' in image) {
110
+ dataTexture.flipY = true;
111
+ }
112
+ dataTexture.needsUpdate = true;
113
+ }
114
+ return dataTexture;
115
+ };
116
+
117
+ /**
118
+ * Utility structure used for rendering a texture with a material
119
+ *
120
+ * @category General
121
+ * @group General
122
+ */
123
+ class QuadRenderer {
124
+ /**
125
+ *
126
+ * @param sourceTexture
127
+ * @param renderer
128
+ */
129
+ constructor(width, height, type, colorSpace, material, renderer) {
130
+ this._rendererIsDisposable = false;
131
+ /**
132
+ * Renders the input texture using the specified material
133
+ */
134
+ this.render = () => {
135
+ this._renderer.setRenderTarget(this._renderTarget);
136
+ try {
137
+ this._renderer.render(this._scene, this._camera);
138
+ }
139
+ catch (e) {
140
+ this._renderer.setRenderTarget(null);
141
+ throw e;
142
+ }
143
+ this._renderer.setRenderTarget(null);
144
+ };
145
+ this._width = width;
146
+ this._height = height;
147
+ this._type = type;
148
+ this._colorSpace = colorSpace;
149
+ if (type === three.HalfFloatType && navigator.userAgent.toLowerCase().includes('firefox')) {
150
+ this._type = three.FloatType;
151
+ }
152
+ this._material = material;
153
+ if (renderer) {
154
+ this._renderer = renderer;
155
+ }
156
+ else {
157
+ this._renderer = QuadRenderer.instantiateRenderer();
158
+ this._rendererIsDisposable = true;
159
+ }
160
+ this._scene = new three.Scene();
161
+ this._camera = new three.OrthographicCamera();
162
+ this._camera.position.set(0, 0, 10);
163
+ this._camera.left = -0.5;
164
+ this._camera.right = 0.5;
165
+ this._camera.top = 0.5;
166
+ this._camera.bottom = -0.5;
167
+ this._camera.updateProjectionMatrix();
168
+ this._quad = new three.Mesh(new three.PlaneGeometry(), this._material);
169
+ this._quad.geometry.computeBoundingBox();
170
+ this._scene.add(this._quad);
171
+ this._renderTarget = new three.WebGLRenderTarget(width, height, {
172
+ type: this._type,
173
+ colorSpace,
174
+ format: three.RGBAFormat,
175
+ magFilter: three.LinearFilter,
176
+ minFilter: three.LinearMipMapLinearFilter,
177
+ wrapS: three.RepeatWrapping,
178
+ wrapT: three.RepeatWrapping,
179
+ depthBuffer: false,
180
+ stencilBuffer: false,
181
+ generateMipmaps: true
182
+ });
183
+ }
184
+ /**
185
+ * Instantiates a temporary renderer
186
+ *
187
+ * @returns
188
+ */
189
+ static instantiateRenderer() {
190
+ const renderer = new three.WebGLRenderer();
191
+ renderer.setSize(128, 128);
192
+ // renderer.outputColorSpace = SRGBColorSpace
193
+ // renderer.toneMapping = LinearToneMapping
194
+ // renderer.debug.checkShaderErrors = false
195
+ // this._rendererIsDisposable = true
196
+ return renderer;
197
+ }
198
+ /**
199
+ * Obtains a Buffer containing the rendered texture.
200
+ *
201
+ * @returns
202
+ */
203
+ toArray() {
204
+ let out;
205
+ switch (this._type) {
206
+ case three.UnsignedByteType:
207
+ out = new Uint8ClampedArray(this._width * this._height * 4);
208
+ break;
209
+ case three.HalfFloatType:
210
+ out = new Uint16Array(this._width * this._height * 4);
211
+ break;
212
+ case three.UnsignedIntType:
213
+ out = new Uint32Array(this._width * this._height * 4);
214
+ break;
215
+ case three.ByteType:
216
+ out = new Int8Array(this._width * this._height * 4);
217
+ break;
218
+ case three.ShortType:
219
+ out = new Int16Array(this._width * this._height * 4);
220
+ break;
221
+ case three.IntType:
222
+ out = new Int32Array(this._width * this._height * 4);
223
+ break;
224
+ case three.FloatType:
225
+ out = new Float32Array(this._width * this._height * 4);
226
+ break;
227
+ default:
228
+ throw new Error('Unsupported data type');
229
+ }
230
+ this._renderer.readRenderTargetPixels(this._renderTarget, 0, 0, this._width, this._height, out);
231
+ return out;
232
+ }
233
+ toDataTexture() {
234
+ return new three.DataTexture(this.toArray(), this.width, this.height, three.RGBAFormat, this._type, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, 1, three.NoColorSpace);
235
+ }
236
+ /**
237
+ * If using a disposable renderer, it will dispose it.
238
+ */
239
+ dispose() {
240
+ this._renderer.setRenderTarget(null);
241
+ if (this._rendererIsDisposable) {
242
+ this._renderer.dispose();
243
+ this._renderer.forceContextLoss();
244
+ }
245
+ }
246
+ /**
247
+ * Width of the texture
248
+ */
249
+ get width() { return this._width; }
250
+ set width(value) {
251
+ this._width = value;
252
+ this._renderTarget.setSize(this._width, this._height);
253
+ }
254
+ /**
255
+ * Height of the texture
256
+ */
257
+ get height() { return this._height; }
258
+ set height(value) {
259
+ this._height = value;
260
+ this._renderTarget.setSize(this._width, this._height);
261
+ }
262
+ /**
263
+ * The renderer used
264
+ */
265
+ get renderer() { return this._renderer; }
266
+ /**
267
+ * The `WebGLRenderTarget` used.
268
+ */
269
+ get renderTarget() { return this._renderTarget; }
270
+ set renderTarget(value) {
271
+ this._renderTarget = value;
272
+ this._width = value.width;
273
+ this._height = value.height;
274
+ // this._type = value.texture.type
275
+ }
276
+ /**
277
+ * The `Material` used.
278
+ */
279
+ get material() { return this._material; }
280
+ /**
281
+ *
282
+ */
283
+ get type() { return this._type; }
284
+ get colorSpace() { return this._colorSpace; }
285
+ }
286
+
287
+ const vertexShader$2 = /* glsl */ `
288
+ varying vec2 vUv;
289
+
290
+ void main() {
291
+ vUv = uv;
292
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
293
+ }
294
+ `;
295
+ const fragmentShader$2 = /* glsl */ `
296
+ #ifndef saturate
297
+ #define saturate( a ) clamp( a, 0.0, 1.0 )
298
+ #endif
299
+ uniform sampler2D sdr;
300
+ uniform sampler2D hdr;
301
+ uniform vec3 gamma;
302
+ uniform vec3 offsetSdr;
303
+ uniform vec3 offsetHdr;
304
+ uniform float minLog2;
305
+ uniform float maxLog2;
306
+
307
+ varying vec2 vUv;
308
+
309
+ void main() {
310
+ vec3 sdrColor = texture2D(sdr, vUv).rgb;
311
+ vec3 hdrColor = texture2D(hdr, vUv).rgb;
312
+
313
+ vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);
314
+ vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);
315
+ vec3 clampedRecovery = saturate(logRecovery);
316
+ gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);
317
+ }
318
+ `;
319
+ /**
320
+ * A Material which is able to encode a gainmap
321
+ *
322
+ * @category Materials
323
+ * @group Materials
324
+ */
325
+ class GainMapEncoderMaterial extends three.ShaderMaterial {
326
+ /**
327
+ *
328
+ * @param params
329
+ */
330
+ constructor({ sdr, hdr, offsetSdr, offsetHdr, maxContentBoost, minContentBoost, gamma }) {
331
+ if (!maxContentBoost)
332
+ throw new Error('maxContentBoost is required');
333
+ if (!sdr)
334
+ throw new Error('sdr is required');
335
+ if (!hdr)
336
+ throw new Error('hdr is required');
337
+ const _gamma = gamma || [1, 1, 1];
338
+ const _offsetSdr = offsetSdr || [1 / 64, 1 / 64, 1 / 64];
339
+ const _offsetHdr = offsetHdr || [1 / 64, 1 / 64, 1 / 64];
340
+ const _minContentBoost = minContentBoost || 1;
341
+ const _maxContentBoost = Math.max(maxContentBoost, 1.0001);
342
+ super({
343
+ name: 'GainMapEncoderMaterial',
344
+ vertexShader: vertexShader$2,
345
+ fragmentShader: fragmentShader$2,
346
+ uniforms: {
347
+ sdr: { value: sdr },
348
+ hdr: { value: hdr },
349
+ gamma: { value: new three.Vector3().fromArray(_gamma) },
350
+ offsetSdr: { value: new three.Vector3().fromArray(_offsetSdr) },
351
+ offsetHdr: { value: new three.Vector3().fromArray(_offsetHdr) },
352
+ minLog2: { value: Math.log2(_minContentBoost) },
353
+ maxLog2: { value: Math.log2(_maxContentBoost) }
354
+ },
355
+ blending: three.NoBlending,
356
+ depthTest: false,
357
+ depthWrite: false
358
+ });
359
+ this._minContentBoost = _minContentBoost;
360
+ this._maxContentBoost = _maxContentBoost;
361
+ this._offsetSdr = _offsetSdr;
362
+ this._offsetHdr = _offsetHdr;
363
+ this._gamma = _gamma;
364
+ this.needsUpdate = true;
365
+ this.uniformsNeedUpdate = true;
366
+ }
367
+ /**
368
+ * @see {@link GainmapEncodingParameters.gamma}
369
+ */
370
+ get gamma() { return this._gamma; }
371
+ set gamma(value) {
372
+ this._gamma = value;
373
+ this.uniforms.gamma.value = new three.Vector3().fromArray(value);
374
+ }
375
+ /**
376
+ * @see {@link GainmapEncodingParameters.offsetHdr}
377
+ */
378
+ get offsetHdr() { return this._offsetHdr; }
379
+ set offsetHdr(value) {
380
+ this._offsetHdr = value;
381
+ this.uniforms.offsetHdr.value = new three.Vector3().fromArray(value);
382
+ }
383
+ /**
384
+ * @see {@link GainmapEncodingParameters.offsetSdr}
385
+ */
386
+ get offsetSdr() { return this._offsetSdr; }
387
+ set offsetSdr(value) {
388
+ this._offsetSdr = value;
389
+ this.uniforms.offsetSdr.value = new three.Vector3().fromArray(value);
390
+ }
391
+ /**
392
+ * @see {@link GainmapEncodingParameters.minContentBoost}
393
+ * @remarks Non logarithmic space
394
+ */
395
+ get minContentBoost() { return this._minContentBoost; }
396
+ set minContentBoost(value) {
397
+ this._minContentBoost = value;
398
+ this.uniforms.minLog2.value = Math.log2(value);
399
+ }
400
+ /**
401
+ * @see {@link GainmapEncodingParameters.maxContentBoost}
402
+ * @remarks Non logarithmic space
403
+ */
404
+ get maxContentBoost() { return this._maxContentBoost; }
405
+ set maxContentBoost(value) {
406
+ this._maxContentBoost = value;
407
+ this.uniforms.maxLog2.value = Math.log2(value);
408
+ }
409
+ /**
410
+ * @see {@link GainMapMetadata.gainMapMin}
411
+ * @remarks Logarithmic space
412
+ */
413
+ get gainMapMin() { return [Math.log2(this._minContentBoost), Math.log2(this._minContentBoost), Math.log2(this._minContentBoost)]; }
414
+ /**
415
+ * @see {@link GainMapMetadata.gainMapMax}
416
+ * @remarks Logarithmic space
417
+ */
418
+ get gainMapMax() { return [Math.log2(this._maxContentBoost), Math.log2(this._maxContentBoost), Math.log2(this._maxContentBoost)]; }
419
+ /**
420
+ * @see {@link GainMapMetadata.hdrCapacityMin}
421
+ * @remarks Logarithmic space
422
+ */
423
+ get hdrCapacityMin() { return Math.min(Math.max(0, this.gainMapMin[0]), Math.max(0, this.gainMapMin[1]), Math.max(0, this.gainMapMin[2])); }
424
+ /**
425
+ * @see {@link GainMapMetadata.hdrCapacityMax}
426
+ * @remarks Logarithmic space
427
+ */
428
+ get hdrCapacityMax() { return Math.min(Math.max(0, this.gainMapMax[0]), Math.max(0, this.gainMapMax[1]), Math.max(0, this.gainMapMax[2])); }
429
+ }
430
+
431
+ /**
432
+ *
433
+ * @param params
434
+ * @returns
435
+ * @category Encoding Functions
436
+ * @group Encoding Functions
437
+ */
438
+ const getGainMap = (params) => {
439
+ const { image, sdr, renderer } = params;
440
+ const dataTexture = getDataTexture(image);
441
+ const material = new GainMapEncoderMaterial(Object.assign(Object.assign({}, params), { sdr: sdr.renderTarget.texture, hdr: dataTexture }));
442
+ const quadRenderer = new QuadRenderer(dataTexture.image.width, dataTexture.image.height, three.UnsignedByteType, three.NoColorSpace, material, renderer);
443
+ try {
444
+ quadRenderer.render();
445
+ }
446
+ catch (e) {
447
+ quadRenderer.dispose();
448
+ throw e;
449
+ }
450
+ return quadRenderer;
451
+ };
452
+
453
+ const vertexShader$1 = /* glsl */ `
454
+ varying vec2 vUv;
455
+
456
+ void main() {
457
+ vUv = uv;
458
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
459
+ }
460
+ `;
461
+ const fragmentShader$1 = /* glsl */ `
462
+ #ifndef saturate
463
+ #define saturate( a ) clamp( a, 0.0, 1.0 )
464
+ #endif
465
+
466
+ uniform sampler2D map;
467
+ uniform float brightness;
468
+ uniform float contrast;
469
+ uniform float saturation;
470
+ uniform float exposure;
471
+
472
+ varying vec2 vUv;
473
+
474
+ mat4 brightnessMatrix( float brightness ) {
475
+ return mat4(
476
+ 1, 0, 0, 0,
477
+ 0, 1, 0, 0,
478
+ 0, 0, 1, 0,
479
+ brightness, brightness, brightness, 1
480
+ );
481
+ }
482
+
483
+ mat4 contrastMatrix( float contrast ) {
484
+ float t = ( 1.0 - contrast ) / 2.0;
485
+ return mat4(
486
+ contrast, 0, 0, 0,
487
+ 0, contrast, 0, 0,
488
+ 0, 0, contrast, 0,
489
+ t, t, t, 1
490
+ );
491
+ }
492
+
493
+ mat4 saturationMatrix( float saturation ) {
494
+ vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );
495
+ float oneMinusSat = 1.0 - saturation;
496
+ vec3 red = vec3( luminance.x * oneMinusSat );
497
+ red+= vec3( saturation, 0, 0 );
498
+ vec3 green = vec3( luminance.y * oneMinusSat );
499
+ green += vec3( 0, saturation, 0 );
500
+ vec3 blue = vec3( luminance.z * oneMinusSat );
501
+ blue += vec3( 0, 0, saturation );
502
+ return mat4(
503
+ red, 0,
504
+ green, 0,
505
+ blue, 0,
506
+ 0, 0, 0, 1
507
+ );
508
+ }
509
+
510
+ vec3 RRTAndODTFit( vec3 v ) {
511
+ vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
512
+ vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
513
+ return a / b;
514
+ }
515
+
516
+ vec3 ACESFilmicToneMapping( vec3 color ) {
517
+ // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
518
+ const mat3 ACESInputMat = mat3(
519
+ vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source
520
+ vec3( 0.35458, 0.90834, 0.13383 ),
521
+ vec3( 0.04823, 0.01566, 0.83777 )
522
+ );
523
+ // ODT_SAT => XYZ => D60_2_D65 => sRGB
524
+ const mat3 ACESOutputMat = mat3(
525
+ vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source
526
+ vec3( -0.53108, 1.10813, -0.07276 ),
527
+ vec3( -0.07367, -0.00605, 1.07602 )
528
+ );
529
+ color = ACESInputMat * color;
530
+ // Apply RRT and ODT
531
+ color = RRTAndODTFit( color );
532
+ color = ACESOutputMat * color;
533
+ // Clamp to [0, 1]
534
+ return saturate( color );
535
+ }
536
+
537
+ // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
538
+ vec3 ReinhardToneMapping( vec3 color ) {
539
+ return saturate( color / ( vec3( 1.0 ) + color ) );
540
+ }
541
+
542
+ // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
543
+ vec3 CineonToneMapping( vec3 color ) {
544
+ // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
545
+ color = max( vec3( 0.0 ), color - 0.004 );
546
+ return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
547
+ }
548
+
549
+ // nothing
550
+ vec3 LinearToneMapping ( vec3 color ) {
551
+ return color;
552
+ }
553
+
554
+
555
+ void main() {
556
+ vec4 color = texture2D(map, vUv);
557
+
558
+ vec4 exposed = vec4(exposure * color.rgb, color.a);
559
+
560
+ vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);
561
+
562
+ vec4 adjusted =
563
+ brightnessMatrix( brightness ) *
564
+ contrastMatrix( contrast ) *
565
+ saturationMatrix( saturation ) *
566
+ tonemapped;
567
+
568
+ gl_FragColor = adjusted;
569
+ }
570
+ `;
571
+ /**
572
+ * A Material used to adjust the SDR representation of an HDR image
573
+ *
574
+ * @category Materials
575
+ * @group Materials
576
+ */
577
+ class SDRMaterial extends three.ShaderMaterial {
578
+ /**
579
+ *
580
+ * @param params
581
+ */
582
+ constructor({ map, toneMapping }) {
583
+ super({
584
+ name: 'SDRMaterial',
585
+ vertexShader: vertexShader$1,
586
+ fragmentShader: fragmentShader$1,
587
+ uniforms: {
588
+ map: { value: map },
589
+ brightness: { value: 0 },
590
+ contrast: { value: 1 },
591
+ saturation: { value: 1 },
592
+ exposure: { value: 1 }
593
+ },
594
+ blending: three.NoBlending,
595
+ depthTest: false,
596
+ depthWrite: false
597
+ });
598
+ this._brightness = 0;
599
+ this._contrast = 1;
600
+ this._saturation = 1;
601
+ this._exposure = 1;
602
+ this._map = map;
603
+ this.toneMapping = this._toneMapping = toneMapping || three.ACESFilmicToneMapping;
604
+ this.needsUpdate = true;
605
+ this.uniformsNeedUpdate = true;
606
+ }
607
+ get toneMapping() { return this._toneMapping; }
608
+ set toneMapping(value) {
609
+ switch (value) {
610
+ case three.ACESFilmicToneMapping:
611
+ this.defines.TONEMAPPING_FUNCTION = 'ACESFilmicToneMapping';
612
+ break;
613
+ case three.ReinhardToneMapping:
614
+ this.defines.TONEMAPPING_FUNCTION = 'ReinhardToneMapping';
615
+ break;
616
+ case three.CineonToneMapping:
617
+ this.defines.TONEMAPPING_FUNCTION = 'CineonToneMapping';
618
+ break;
619
+ case three.LinearToneMapping:
620
+ this.defines.TONEMAPPING_FUNCTION = 'LinearToneMapping';
621
+ break;
622
+ default:
623
+ console.error('Unsupported toneMapping');
624
+ return;
625
+ }
626
+ this._toneMapping = value;
627
+ this.needsUpdate = true;
628
+ }
629
+ get brightness() { return this._brightness; }
630
+ set brightness(value) {
631
+ this._brightness = value;
632
+ this.uniforms.brightness.value = value;
633
+ }
634
+ get contrast() { return this._contrast; }
635
+ set contrast(value) {
636
+ this._contrast = value;
637
+ this.uniforms.contrast.value = value;
638
+ }
639
+ get saturation() { return this._saturation; }
640
+ set saturation(value) {
641
+ this._saturation = value;
642
+ this.uniforms.saturation.value = value;
643
+ }
644
+ get exposure() { return this._exposure; }
645
+ set exposure(value) {
646
+ this._exposure = value;
647
+ this.uniforms.exposure.value = value;
648
+ }
649
+ get map() { return this._map; }
650
+ set map(value) {
651
+ this._map = value;
652
+ this.uniforms.map.value = value;
653
+ }
654
+ }
655
+
656
+ /**
657
+ * Renders an SDR Representation of an HDR Image
658
+ *
659
+ * @category Encoding Functions
660
+ * @group Encoding Functions
661
+ *
662
+ * @param hdrTexture The HDR image to be rendered
663
+ * @param renderer (optional) WebGLRenderer to use during the rendering, a disposable renderer will be create and destroyed if this is not provided.
664
+ * @param toneMapping (optional) Tone mapping to be applied to the SDR Rendition
665
+ * @throws {Error} if the WebGLRenderer fails to render the SDR image
666
+ */
667
+ const getSDRRendition = (hdrTexture, renderer, toneMapping) => {
668
+ hdrTexture.needsUpdate = true;
669
+ const quadRenderer = new QuadRenderer(hdrTexture.image.width, hdrTexture.image.height, three.UnsignedByteType, three.SRGBColorSpace, new SDRMaterial({ map: hdrTexture, toneMapping }), renderer);
670
+ try {
671
+ quadRenderer.render();
672
+ }
673
+ catch (e) {
674
+ quadRenderer.dispose();
675
+ throw e;
676
+ }
677
+ return quadRenderer;
678
+ };
679
+
680
+ /**
681
+ * Encodes a Gainmap starting from an HDR file.
682
+ *
683
+ * @remarks
684
+ * if you do not pass a `renderer` parameter
685
+ * you must manually dispose the result
686
+ * ```js
687
+ * const encodingResult = await encode({ ... })
688
+ * // do something with the buffers
689
+ * const sdr = encodingResult.sdr.getArray()
690
+ * const gainMap = encodingResult.gainMap.getArray()
691
+ * // after that
692
+ * encodingResult.sdr.dispose()
693
+ * encodingResult.gainMap.dispose()
694
+ * ```
695
+ *
696
+ * @category Encoding Functions
697
+ * @group Encoding Functions
698
+ *
699
+ * @example
700
+ * import { encode, findTextureMinMax } from '@monogrid/gainmap-js'
701
+ * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
702
+ *
703
+ * // load an HDR file
704
+ * const loader = new EXRLoader()
705
+ * const image = await loader.loadAsync('image.exr')
706
+ *
707
+ * // find RAW RGB Max value of a texture
708
+ * const textureMax = await findTextureMinMax(image)
709
+ *
710
+ * // Encode the gainmap
711
+ * const encodingResult = encode({
712
+ * image,
713
+ * // this will encode the full HDR range
714
+ * maxContentBoost: Math.max.apply(this, textureMax)
715
+ * })
716
+ * // can be re-encoded after changing parameters
717
+ * encodingResult.sdr.material.exposure = 0.9
718
+ * encodingResult.sdr.render()
719
+ * // or
720
+ * encodingResult.gainMap.material.gamma = [1.1, 1.1, 1.1]
721
+ * encodingResult.gainMap.render()
722
+ *
723
+ * // must be manually disposed
724
+ * encodingResult.sdr.dispose()
725
+ * encodingResult.gainMap.dispose()
726
+ *
727
+ * @param params Encoding Parameters
728
+ * @returns
729
+ */
730
+ const encode = (params) => {
731
+ const { image, renderer } = params;
732
+ const dataTexture = getDataTexture(image);
733
+ const sdr = getSDRRendition(dataTexture, renderer, params.toneMapping);
734
+ const gainMapRenderer = getGainMap(Object.assign(Object.assign({}, params), { image: dataTexture, sdr, renderer: sdr.renderer // reuse the same (maybe disposable?) renderer
735
+ }));
736
+ return {
737
+ sdr,
738
+ gainMap: gainMapRenderer,
739
+ hdr: dataTexture,
740
+ getMetadata: () => {
741
+ const meta = {
742
+ gainMapMax: gainMapRenderer.material.gainMapMax,
743
+ gainMapMin: gainMapRenderer.material.gainMapMin,
744
+ gamma: gainMapRenderer.material.gamma,
745
+ hdrCapacityMax: gainMapRenderer.material.hdrCapacityMax,
746
+ hdrCapacityMin: gainMapRenderer.material.hdrCapacityMin,
747
+ offsetHdr: gainMapRenderer.material.offsetHdr,
748
+ offsetSdr: gainMapRenderer.material.offsetSdr
749
+ };
750
+ return meta;
751
+ }
752
+ };
753
+ };
754
+
755
+ /**
756
+ * Encodes a Gainmap starting from an HDR file into compressed file formats (`image/jpeg`, `image/webp` or `image/png`).
757
+ *
758
+ * Uses {@link encode} internally, then pipes the results to {@link compress}.
759
+ *
760
+ * @remarks
761
+ * if a `renderer` parameter is not provided
762
+ * This function will automatically dispose its "disposable"
763
+ * renderer, no need to dispose it manually later
764
+ *
765
+ * @category Encoding Functions
766
+ * @group Encoding Functions
767
+ * @example
768
+ * import { encodeAndCompress, findTextureMinMax } from '@monogrid/gainmap-js'
769
+ * import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
770
+ * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
771
+ *
772
+ * // load an HDR file
773
+ * const loader = new EXRLoader()
774
+ * const image = await loader.loadAsync('image.exr')
775
+ *
776
+ * // find RAW RGB Max value of a texture
777
+ * const textureMax = await findTextureMinMax(image)
778
+ *
779
+ * // Encode the gainmap
780
+ * const encodingResult = await encodeAndCompress({
781
+ * image,
782
+ * maxContentBoost: Math.max.apply(this, textureMax),
783
+ * mimeType: 'image/jpeg'
784
+ * })
785
+ *
786
+ * // embed the compressed images + metadata into a single
787
+ * // JPEG file
788
+ * const jpeg = await encodeJPEGMetadata({
789
+ * ...encodingResult,
790
+ * sdr: encodingResult.sdr,
791
+ * gainMap: encodingResult.gainMap
792
+ * })
793
+ *
794
+ * // `jpeg` will be an `Uint8Array` which can be saved somewhere
795
+ *
796
+ *
797
+ * @param params Encoding Parameters
798
+ * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
799
+ */
800
+ const encodeAndCompress = async (params) => {
801
+ const encodingResult = encode(params);
802
+ const { mimeType, quality, flipY, withWorker } = params;
803
+ let compressResult;
804
+ let rawSDR;
805
+ let rawGainMap;
806
+ const sdrImageData = new ImageData(encodingResult.sdr.toArray(), encodingResult.sdr.width, encodingResult.sdr.height);
807
+ const gainMapImageData = new ImageData(encodingResult.gainMap.toArray(), encodingResult.gainMap.width, encodingResult.gainMap.height);
808
+ if (withWorker) {
809
+ const workerResult = await Promise.all([
810
+ withWorker.compress({
811
+ source: sdrImageData,
812
+ mimeType,
813
+ quality,
814
+ flipY
815
+ }),
816
+ withWorker.compress({
817
+ source: gainMapImageData,
818
+ mimeType,
819
+ quality,
820
+ flipY
821
+ })
822
+ ]);
823
+ compressResult = workerResult;
824
+ rawSDR = workerResult[0].source;
825
+ rawGainMap = workerResult[1].source;
826
+ }
827
+ else {
828
+ compressResult = await Promise.all([
829
+ compress({
830
+ source: sdrImageData,
831
+ mimeType,
832
+ quality,
833
+ flipY
834
+ }),
835
+ compress({
836
+ source: gainMapImageData,
837
+ mimeType,
838
+ quality,
839
+ flipY
840
+ })
841
+ ]);
842
+ rawSDR = sdrImageData.data;
843
+ rawGainMap = gainMapImageData.data;
844
+ }
845
+ encodingResult.sdr.dispose();
846
+ encodingResult.gainMap.dispose();
847
+ return Object.assign(Object.assign(Object.assign({}, encodingResult), encodingResult.getMetadata()), { sdr: compressResult[0], gainMap: compressResult[1], rawSDR,
848
+ rawGainMap });
849
+ };
850
+
851
+ const vertexShader = /* glsl */ `
852
+ varying vec2 vUv;
853
+ void main() {
854
+ vUv = uv;
855
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
856
+ }
857
+ `;
858
+ const fragmentShader = /* glsl */ `
859
+ precision mediump float;
860
+
861
+ #ifndef CELL_SIZE
862
+ #define CELL_SIZE 2
863
+ #endif
864
+
865
+ #ifndef COMPARE_FUNCTION
866
+ #define COMPARE_FUNCTION max
867
+ #endif
868
+
869
+ uniform sampler2D map;
870
+ uniform vec2 u_srcResolution;
871
+
872
+ varying vec2 vUv;
873
+
874
+ void main() {
875
+ // compute the first pixel the source cell
876
+ vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);
877
+
878
+ // one pixel in source
879
+ vec2 onePixel = vec2(1) / u_srcResolution;
880
+
881
+ // uv for first pixel in cell. +0.5 for center of pixel
882
+ vec2 uv = (srcPixel + 0.5) * onePixel;
883
+
884
+ vec4 resultColor = vec4(0);
885
+ for (int y = 0; y < CELL_SIZE; ++y) {
886
+ for (int x = 0; x < CELL_SIZE; ++x) {
887
+ resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));
888
+ }
889
+ }
890
+
891
+ gl_FragColor = resultColor;
892
+ }
893
+ `;
894
+ /**
895
+ *
896
+ * @category Encoding Functions
897
+ * @group Encoding Functions
898
+ *
899
+ * @param srcTex
900
+ * @param mode
901
+ * @param renderer
902
+ * @returns
903
+ */
904
+ const findTextureMinMax = (image, mode = 'max', renderer) => {
905
+ const srcTex = getDataTexture(image);
906
+ const cellSize = 2;
907
+ const mat = new three.ShaderMaterial({
908
+ vertexShader,
909
+ fragmentShader,
910
+ uniforms: {
911
+ u_srcResolution: { value: new three.Vector2(srcTex.image.width, srcTex.image.height) },
912
+ map: { value: srcTex }
913
+ },
914
+ defines: {
915
+ CELL_SIZE: cellSize,
916
+ COMPARE_FUNCTION: mode
917
+ }
918
+ });
919
+ srcTex.needsUpdate = true;
920
+ mat.needsUpdate = true;
921
+ let w = srcTex.image.width;
922
+ let h = srcTex.image.height;
923
+ const quadRenderer = new QuadRenderer(w, h, srcTex.type, srcTex.colorSpace, mat, renderer);
924
+ const frameBuffers = [];
925
+ while (w > 1 || h > 1) {
926
+ w = Math.max(1, (w + cellSize - 1) / cellSize | 0);
927
+ h = Math.max(1, (h + cellSize - 1) / cellSize | 0);
928
+ const fb = new three.WebGLRenderTarget(w, h, {
929
+ type: quadRenderer.type,
930
+ format: srcTex.format,
931
+ colorSpace: quadRenderer.colorSpace,
932
+ minFilter: three.NearestFilter,
933
+ magFilter: three.NearestFilter,
934
+ wrapS: three.ClampToEdgeWrapping,
935
+ wrapT: three.ClampToEdgeWrapping,
936
+ generateMipmaps: false,
937
+ depthBuffer: false,
938
+ stencilBuffer: false
939
+ });
940
+ frameBuffers.push(fb);
941
+ }
942
+ w = srcTex.image.width;
943
+ h = srcTex.image.height;
944
+ frameBuffers.forEach((fbi) => {
945
+ w = Math.max(1, (w + cellSize - 1) / cellSize | 0);
946
+ h = Math.max(1, (h + cellSize - 1) / cellSize | 0);
947
+ quadRenderer.renderTarget = fbi;
948
+ quadRenderer.render();
949
+ mat.uniforms.map.value = fbi.texture;
950
+ mat.uniforms.u_srcResolution.value.x = w;
951
+ mat.uniforms.u_srcResolution.value.y = h;
952
+ });
953
+ const out = quadRenderer.toArray();
954
+ quadRenderer.dispose();
955
+ frameBuffers.forEach(fb => fb.dispose());
956
+ return [
957
+ quadRenderer.type === three.FloatType ? out[0] : three.DataUtils.fromHalfFloat(out[0]),
958
+ quadRenderer.type === three.FloatType ? out[1] : three.DataUtils.fromHalfFloat(out[1]),
959
+ quadRenderer.type === three.FloatType ? out[2] : three.DataUtils.fromHalfFloat(out[2])
960
+ ];
961
+ };
962
+
963
+ exports.GainMapEncoderMaterial = GainMapEncoderMaterial;
964
+ exports.SDRMaterial = SDRMaterial;
965
+ exports.compress = compress;
966
+ exports.encode = encode;
967
+ exports.encodeAndCompress = encodeAndCompress;
968
+ exports.findTextureMinMax = findTextureMinMax;
969
+ exports.getGainMap = getGainMap;
970
+ exports.getSDRRendition = getSDRRendition;
971
+
972
+ }));