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