@monogrid/gainmap-js 1.0.2

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