@monogrid/gainmap-js 1.1.0 → 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 (51) hide show
  1. package/CHANGELOG.md +22 -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/{utils → core}/QuadRenderer.d.ts +6 -0
  8. package/dist/core/types.d.ts +64 -0
  9. package/dist/decode/decode.d.ts +56 -0
  10. package/dist/decode/extract.d.ts +10 -0
  11. package/dist/decode/index.d.ts +8 -0
  12. package/dist/{loaders → decode/loaders}/GainMapLoader.d.ts +4 -4
  13. package/dist/{loaders → decode/loaders}/JPEGRLoader.d.ts +5 -5
  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 +737 -0
  20. package/dist/decode.umd.js +917 -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 +4 -5
  26. package/dist/encode/index.d.ts +10 -0
  27. package/dist/encode/types.d.ts +172 -0
  28. package/dist/encode.d.ts +1 -117
  29. package/dist/{index.js → encode.js} +42 -230
  30. package/dist/encode.umd.js +972 -0
  31. package/dist/libultrahdr/decode-jpeg-metadata.d.ts +31 -0
  32. package/dist/libultrahdr/encode-jpeg-metadata.d.ts +84 -0
  33. package/dist/libultrahdr/library.d.ts +9 -0
  34. package/dist/libultrahdr.d.ts +3 -123
  35. package/dist/libultrahdr.js +92 -167
  36. package/dist/libultrahdr.umd.js +91 -530
  37. package/dist/worker-interface.js +2 -2
  38. package/dist/worker-interface.umd.js +1 -3
  39. package/dist/worker-types.d.ts +2 -2
  40. package/dist/worker.js +3 -3
  41. package/dist/worker.umd.js +1 -1
  42. package/package.json +36 -29
  43. package/dist/LoaderBase-aa4842c4.js +0 -373
  44. package/dist/index.d.ts +0 -11
  45. package/dist/index.umd.js +0 -1360
  46. package/dist/materials/index.d.ts +0 -3
  47. package/dist/types.d.ts +0 -262
  48. /package/dist/{utils → core}/get-data-texture.d.ts +0 -0
  49. /package/dist/{encode-utils → encode}/find-texture-min-max.d.ts +0 -0
  50. /package/dist/{materials → encode/materials}/GainMapEncoderMaterial.d.ts +0 -0
  51. /package/dist/{materials → encode/materials}/SDRMaterial.d.ts +0 -0
package/dist/index.umd.js DELETED
@@ -1,1360 +0,0 @@
1
- /**
2
- * @monogrid/gainmap-js v1.0.2
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().fromArray(offsetHdr) },
62
- offsetSdr: { value: new three.Vector3().fromArray(offsetSdr) },
63
- gainMapMin: { value: new three.Vector3().fromArray(gainMapMin) },
64
- gainMapMax: { value: new three.Vector3().fromArray(gainMapMax) },
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
- get sdr() { return this.uniforms.sdr.value; }
80
- set sdr(value) { this.uniforms.sdr.value = value; }
81
- get gainMap() { return this.uniforms.gainMap.value; }
82
- set gainMap(value) { this.uniforms.gainMap.value = value; }
83
- /**
84
- * @see {@link GainMapMetadata.offsetHdr}
85
- */
86
- get offsetHdr() { return this.uniforms.offsetHdr.value.toArray(); }
87
- set offsetHdr(value) { this.uniforms.offsetHdr.value.fromArray(value); }
88
- /**
89
- * @see {@link GainMapMetadata.offsetSdr}
90
- */
91
- get offsetSdr() { return this.uniforms.offsetSdr.value.toArray(); }
92
- set offsetSdr(value) { this.uniforms.offsetSdr.value.fromArray(value); }
93
- /**
94
- * @see {@link GainMapMetadata.gainMapMin}
95
- */
96
- get gainMapMin() { return this.uniforms.gainMapMin.value.toArray(); }
97
- set gainMapMin(value) { this.uniforms.gainMapMin.value.fromArray(value); }
98
- /**
99
- * @see {@link GainMapMetadata.gainMapMax}
100
- */
101
- get gainMapMax() { return this.uniforms.gainMapMax.value.toArray(); }
102
- set gainMapMax(value) { this.uniforms.gainMapMax.value.fromArray(value); }
103
- /**
104
- * @see {@link GainmapEncodingParameters.gamma}
105
- */
106
- get gamma() {
107
- const g = this.uniforms.gamma.value;
108
- return [1 / g.x, 1 / g.y, 1 / g.z];
109
- }
110
- set gamma(value) {
111
- const g = this.uniforms.gamma.value;
112
- g.x = 1.0 / value[0];
113
- g.y = 1.0 / value[1];
114
- g.z = 1.0 / value[2];
115
- }
116
- /**
117
- * @see {@link GainMapMetadata.hdrCapacityMin}
118
- * @remarks Logarithmic space
119
- */
120
- get hdrCapacityMin() { return this._hdrCapacityMin; }
121
- set hdrCapacityMin(value) {
122
- this._hdrCapacityMin = value;
123
- this.calculateWeight();
124
- }
125
- /**
126
- * @see {@link GainMapMetadata.hdrCapacityMin}
127
- * @remarks Logarithmic space
128
- */
129
- get hdrCapacityMax() { return this._hdrCapacityMax; }
130
- set hdrCapacityMax(value) {
131
- this._hdrCapacityMax = value;
132
- this.calculateWeight();
133
- }
134
- /**
135
- * @see {@link GainmapDecodingParameters.maxDisplayBoost}
136
- * @remarks Non Logarithmic space
137
- */
138
- get maxDisplayBoost() { return this._maxDisplayBoost; }
139
- set maxDisplayBoost(value) {
140
- this._maxDisplayBoost = value;
141
- this.calculateWeight();
142
- }
143
- calculateWeight() {
144
- this.uniforms.weightFactor.value = (Math.log2(this._maxDisplayBoost) - this._hdrCapacityMin) / (this._hdrCapacityMax - this._hdrCapacityMin);
145
- }
146
- }
147
-
148
- /**
149
- * Utility structure used for rendering a texture with a material
150
- *
151
- * @category General
152
- * @group General
153
- */
154
- class QuadRenderer {
155
- /**
156
- *
157
- * @param sourceTexture
158
- * @param renderer
159
- */
160
- constructor(width, height, type, colorSpace, material, renderer) {
161
- this._rendererIsDisposable = false;
162
- /**
163
- * Renders the input texture using the specified material
164
- */
165
- this.render = () => {
166
- this._renderer.setRenderTarget(this._renderTarget);
167
- try {
168
- this._renderer.render(this._scene, this._camera);
169
- }
170
- catch (e) {
171
- this._renderer.setRenderTarget(null);
172
- throw e;
173
- }
174
- this._renderer.setRenderTarget(null);
175
- };
176
- this._width = width;
177
- this._height = height;
178
- this._type = type;
179
- this._material = material;
180
- if (renderer) {
181
- this._renderer = renderer;
182
- }
183
- else {
184
- this._renderer = QuadRenderer.instantiateRenderer();
185
- this._rendererIsDisposable = true;
186
- }
187
- this._scene = new three.Scene();
188
- this._camera = new three.OrthographicCamera();
189
- this._camera.position.set(0, 0, 10);
190
- this._camera.left = -0.5;
191
- this._camera.right = 0.5;
192
- this._camera.top = 0.5;
193
- this._camera.bottom = -0.5;
194
- this._camera.updateProjectionMatrix();
195
- this._quad = new three.Mesh(new three.PlaneGeometry(), this._material);
196
- this._quad.geometry.computeBoundingBox();
197
- this._scene.add(this._quad);
198
- this._renderTarget = new three.WebGLRenderTarget(width, height, {
199
- type,
200
- colorSpace,
201
- format: three.RGBAFormat,
202
- magFilter: three.LinearFilter,
203
- minFilter: three.LinearMipMapLinearFilter,
204
- wrapS: three.RepeatWrapping,
205
- wrapT: three.RepeatWrapping,
206
- depthBuffer: false,
207
- stencilBuffer: false,
208
- generateMipmaps: true
209
- });
210
- }
211
- /**
212
- * Instantiates a temporary renderer
213
- *
214
- * @returns
215
- */
216
- static instantiateRenderer() {
217
- const renderer = new three.WebGLRenderer();
218
- renderer.setSize(128, 128);
219
- // renderer.outputColorSpace = SRGBColorSpace
220
- // renderer.toneMapping = LinearToneMapping
221
- // renderer.debug.checkShaderErrors = false
222
- // this._rendererIsDisposable = true
223
- return renderer;
224
- }
225
- /**
226
- * Obtains a Buffer containing the rendered texture.
227
- *
228
- * @returns
229
- */
230
- toArray() {
231
- let out;
232
- switch (this._type) {
233
- case three.UnsignedByteType:
234
- out = new Uint8ClampedArray(this._width * this._height * 4);
235
- break;
236
- case three.HalfFloatType:
237
- out = new Uint16Array(this._width * this._height * 4);
238
- break;
239
- case three.UnsignedIntType:
240
- out = new Uint32Array(this._width * this._height * 4);
241
- break;
242
- case three.ByteType:
243
- out = new Int8Array(this._width * this._height * 4);
244
- break;
245
- case three.ShortType:
246
- out = new Int16Array(this._width * this._height * 4);
247
- break;
248
- case three.IntType:
249
- out = new Int32Array(this._width * this._height * 4);
250
- break;
251
- case three.FloatType:
252
- out = new Float32Array(this._width * this._height * 4);
253
- break;
254
- default:
255
- throw new Error('Unsupported data type');
256
- }
257
- this._renderer.readRenderTargetPixels(this._renderTarget, 0, 0, this._width, this._height, out);
258
- return out;
259
- }
260
- toDataTexture() {
261
- return new three.DataTexture(this.toArray(), this.width, this.height, three.RGBAFormat, three.HalfFloatType, three.UVMapping, three.RepeatWrapping, three.RepeatWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, 1, three.NoColorSpace);
262
- }
263
- /**
264
- * If using a disposable renderer, it will dispose it.
265
- */
266
- dispose() {
267
- this._renderer.setRenderTarget(null);
268
- if (this._rendererIsDisposable) {
269
- this._renderer.dispose();
270
- this._renderer.forceContextLoss();
271
- }
272
- }
273
- /**
274
- * Width of the texture
275
- */
276
- get width() { return this._width; }
277
- set width(value) {
278
- this._width = value;
279
- this._renderTarget.setSize(this._width, this._height);
280
- }
281
- /**
282
- * Height of the texture
283
- */
284
- get height() { return this._height; }
285
- set height(value) {
286
- this._height = value;
287
- this._renderTarget.setSize(this._width, this._height);
288
- }
289
- /**
290
- * The renderer used
291
- */
292
- get renderer() { return this._renderer; }
293
- /**
294
- * The `WebGLRenderTarget` used.
295
- */
296
- get renderTarget() { return this._renderTarget; }
297
- set renderTarget(value) {
298
- this._renderTarget = value;
299
- this._width = value.width;
300
- this._height = value.height;
301
- // this._type = value.texture.type
302
- }
303
- /**
304
- * The `Material` used.
305
- */
306
- get material() { return this._material; }
307
- }
308
-
309
- /**
310
- * Decodes a gain map using a WebGLRenderTarget
311
- *
312
- * @category Decoding
313
- * @group Decoding
314
- * @example
315
- * import { decode } from '@monogrid/gainmap-js'
316
- * import {
317
- * Mesh,
318
- * MeshBasicMaterial,
319
- * PerspectiveCamera,
320
- * PlaneGeometry,
321
- * Scene,
322
- * TextureLoader,
323
- * WebGLRenderer
324
- * } from 'three'
325
- *
326
- * const renderer = new WebGLRenderer()
327
- *
328
- * const textureLoader = new TextureLoader()
329
- *
330
- * // load SDR Representation
331
- * const sdr = await textureLoader.loadAsync('sdr.jpg')
332
- * // load Gain map recovery image
333
- * const gainMap = await textureLoader.loadAsync('gainmap.jpg')
334
- * // load metadata
335
- * const metadata = await (await fetch('metadata.json')).json()
336
- *
337
- * const result = await decode({
338
- * sdr,
339
- * gainMap,
340
- * // this allows to use `result.renderTarget.texture` directly
341
- * renderer,
342
- * // this will restore the full HDR range
343
- * maxDisplayBoost: Math.pow(2, metadata.hdrCapacityMax),
344
- * ...metadata
345
- * })
346
- *
347
- * const scene = new Scene()
348
- * // `result` can be used to populate a Texture
349
- * const mesh = new Mesh(
350
- * new PlaneGeometry(),
351
- * new MeshBasicMaterial({ map: result.renderTarget.texture })
352
- * )
353
- * scene.add(mesh)
354
- * renderer.render(scene, new PerspectiveCamera())
355
- *
356
- *
357
- * @param params
358
- * @returns
359
- * @throws {Error} if the WebGLRenderer fails to render the gain map
360
- */
361
- const decode = (params) => {
362
- const { sdr, gainMap, renderer } = params;
363
- if (sdr.colorSpace !== three.SRGBColorSpace) {
364
- console.warn('SDR Colorspace needs to be *SRGBColorSpace*, setting it automatically');
365
- sdr.colorSpace = three.SRGBColorSpace;
366
- }
367
- sdr.needsUpdate = true;
368
- if (gainMap.colorSpace !== three.NoColorSpace) {
369
- console.warn('Gainmap Colorspace needs to be *NoColorSpace*');
370
- gainMap.colorSpace = three.NoColorSpace;
371
- }
372
- gainMap.needsUpdate = true;
373
- const material = new GainMapDecoderMaterial(Object.assign(Object.assign({}, params), { sdr,
374
- gainMap }));
375
- const quadRenderer = new QuadRenderer(sdr.image.width, sdr.image.height, three.HalfFloatType, three.NoColorSpace, material, renderer);
376
- try {
377
- quadRenderer.render();
378
- }
379
- catch (e) {
380
- quadRenderer.dispose();
381
- throw e;
382
- }
383
- return quadRenderer;
384
- };
385
-
386
- /**
387
- * Used internally
388
- *
389
- * @internal
390
- * @param canvas
391
- * @param mimeType
392
- * @param quality
393
- * @returns
394
- */
395
- const canvasToBlob = async (canvas, mimeType, quality) => {
396
- if (canvas instanceof OffscreenCanvas) {
397
- return canvas.convertToBlob({ type: mimeType, quality: quality || 0.9 });
398
- }
399
- return new Promise((resolve, reject) => {
400
- canvas.toBlob((res) => {
401
- if (res)
402
- resolve(res);
403
- else
404
- reject('Failed to convert canvas to blob');
405
- }, mimeType, quality || 0.9);
406
- });
407
- };
408
- /**
409
- * Converts a RAW RGBA image buffer into the provided `mimeType` using the provided `quality`
410
- *
411
- * @category Compression
412
- * @group Compression
413
- * @param params
414
- * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
415
- * @throws {Error} if the provided source image cannot be decoded
416
- * @throws {Error} if the function fails to create a canvas context
417
- */
418
- const compress = async (params) => {
419
- if (typeof createImageBitmap === 'undefined')
420
- throw new Error('createImageBitmap() not supported.');
421
- const { source, mimeType, quality, flipY } = params;
422
- // eslint-disable-next-line no-undef
423
- let imageBitmapSource;
424
- if ((source instanceof Uint8Array || source instanceof Uint8ClampedArray) && 'sourceMimeType' in params) {
425
- imageBitmapSource = new Blob([source], { type: params.sourceMimeType });
426
- }
427
- else if (source instanceof ImageData) {
428
- imageBitmapSource = source;
429
- }
430
- else {
431
- throw new Error('Invalid source image');
432
- }
433
- const img = await createImageBitmap(imageBitmapSource);
434
- const width = img.width;
435
- const height = img.height;
436
- let canvas;
437
- if (typeof OffscreenCanvas !== 'undefined') {
438
- canvas = new OffscreenCanvas(width, height);
439
- }
440
- else {
441
- canvas = document.createElement('canvas');
442
- }
443
- const ctx = canvas.getContext('2d');
444
- if (!ctx)
445
- throw new Error('Failed to create canvas Context');
446
- // flip Y
447
- if (flipY === true) {
448
- ctx.translate(0, height);
449
- ctx.scale(1, -1);
450
- }
451
- ctx.drawImage(img, 0, 0, width, height);
452
- const blob = await canvasToBlob(canvas, mimeType, quality || 0.9);
453
- const data = new Uint8Array(await blob.arrayBuffer());
454
- return {
455
- data,
456
- mimeType,
457
- width,
458
- height
459
- };
460
- };
461
-
462
- const vertexShader$2 = /* glsl */ `
463
- varying vec2 vUv;
464
-
465
- void main() {
466
- vUv = uv;
467
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
468
- }
469
- `;
470
- const fragmentShader$2 = /* glsl */ `
471
- #ifndef saturate
472
- #define saturate( a ) clamp( a, 0.0, 1.0 )
473
- #endif
474
- uniform sampler2D sdr;
475
- uniform sampler2D hdr;
476
- uniform vec3 gamma;
477
- uniform vec3 offsetSdr;
478
- uniform vec3 offsetHdr;
479
- uniform float minLog2;
480
- uniform float maxLog2;
481
-
482
- varying vec2 vUv;
483
-
484
- void main() {
485
- vec3 sdrColor = texture2D(sdr, vUv).rgb;
486
- vec3 hdrColor = texture2D(hdr, vUv).rgb;
487
-
488
- vec3 pixelGain = (hdrColor + offsetHdr) / (sdrColor + offsetSdr);
489
- vec3 logRecovery = (log2(pixelGain) - minLog2) / (maxLog2 - minLog2);
490
- vec3 clampedRecovery = saturate(logRecovery);
491
- gl_FragColor = vec4(pow(clampedRecovery, gamma), 1.0);
492
- }
493
- `;
494
- /**
495
- * A Material which is able to encode a gainmap
496
- *
497
- * @category Materials
498
- * @group Materials
499
- */
500
- class GainMapEncoderMaterial extends three.ShaderMaterial {
501
- /**
502
- *
503
- * @param params
504
- */
505
- constructor({ sdr, hdr, offsetSdr, offsetHdr, maxContentBoost, minContentBoost, gamma }) {
506
- if (!maxContentBoost)
507
- throw new Error('maxContentBoost is required');
508
- if (!sdr)
509
- throw new Error('sdr is required');
510
- if (!hdr)
511
- throw new Error('hdr is required');
512
- const _gamma = gamma || [1, 1, 1];
513
- const _offsetSdr = offsetSdr || [1 / 64, 1 / 64, 1 / 64];
514
- const _offsetHdr = offsetHdr || [1 / 64, 1 / 64, 1 / 64];
515
- const _minContentBoost = minContentBoost || 1;
516
- const _maxContentBoost = Math.max(maxContentBoost, 1.0001);
517
- super({
518
- name: 'GainMapEncoderMaterial',
519
- vertexShader: vertexShader$2,
520
- fragmentShader: fragmentShader$2,
521
- uniforms: {
522
- sdr: { value: sdr },
523
- hdr: { value: hdr },
524
- gamma: { value: new three.Vector3().fromArray(_gamma) },
525
- offsetSdr: { value: new three.Vector3().fromArray(_offsetSdr) },
526
- offsetHdr: { value: new three.Vector3().fromArray(_offsetHdr) },
527
- minLog2: { value: Math.log2(_minContentBoost) },
528
- maxLog2: { value: Math.log2(_maxContentBoost) }
529
- },
530
- blending: three.NoBlending,
531
- depthTest: false,
532
- depthWrite: false
533
- });
534
- this._minContentBoost = _minContentBoost;
535
- this._maxContentBoost = _maxContentBoost;
536
- this._offsetSdr = _offsetSdr;
537
- this._offsetHdr = _offsetHdr;
538
- this._gamma = _gamma;
539
- this.needsUpdate = true;
540
- this.uniformsNeedUpdate = true;
541
- }
542
- /**
543
- * @see {@link GainmapEncodingParameters.gamma}
544
- */
545
- get gamma() { return this._gamma; }
546
- set gamma(value) {
547
- this._gamma = value;
548
- this.uniforms.gamma.value = new three.Vector3().fromArray(value);
549
- }
550
- /**
551
- * @see {@link GainmapEncodingParameters.offsetHdr}
552
- */
553
- get offsetHdr() { return this._offsetHdr; }
554
- set offsetHdr(value) {
555
- this._offsetHdr = value;
556
- this.uniforms.offsetHdr.value = new three.Vector3().fromArray(value);
557
- }
558
- /**
559
- * @see {@link GainmapEncodingParameters.offsetSdr}
560
- */
561
- get offsetSdr() { return this._offsetSdr; }
562
- set offsetSdr(value) {
563
- this._offsetSdr = value;
564
- this.uniforms.offsetSdr.value = new three.Vector3().fromArray(value);
565
- }
566
- /**
567
- * @see {@link GainmapEncodingParameters.minContentBoost}
568
- * @remarks Non logarithmic space
569
- */
570
- get minContentBoost() { return this._minContentBoost; }
571
- set minContentBoost(value) {
572
- this._minContentBoost = value;
573
- this.uniforms.minLog2.value = Math.log2(value);
574
- }
575
- /**
576
- * @see {@link GainmapEncodingParameters.maxContentBoost}
577
- * @remarks Non logarithmic space
578
- */
579
- get maxContentBoost() { return this._maxContentBoost; }
580
- set maxContentBoost(value) {
581
- this._maxContentBoost = value;
582
- this.uniforms.maxLog2.value = Math.log2(value);
583
- }
584
- /**
585
- * @see {@link GainMapMetadata.gainMapMin}
586
- * @remarks Logarithmic space
587
- */
588
- get gainMapMin() { return [Math.log2(this._minContentBoost), Math.log2(this._minContentBoost), Math.log2(this._minContentBoost)]; }
589
- /**
590
- * @see {@link GainMapMetadata.gainMapMax}
591
- * @remarks Logarithmic space
592
- */
593
- get gainMapMax() { return [Math.log2(this._maxContentBoost), Math.log2(this._maxContentBoost), Math.log2(this._maxContentBoost)]; }
594
- /**
595
- * @see {@link GainMapMetadata.hdrCapacityMin}
596
- * @remarks Logarithmic space
597
- */
598
- get hdrCapacityMin() { return Math.min(Math.max(0, this.gainMapMin[0]), Math.max(0, this.gainMapMin[1]), Math.max(0, this.gainMapMin[2])); }
599
- /**
600
- * @see {@link GainMapMetadata.hdrCapacityMax}
601
- * @remarks Logarithmic space
602
- */
603
- get hdrCapacityMax() { return Math.min(Math.max(0, this.gainMapMax[0]), Math.max(0, this.gainMapMax[1]), Math.max(0, this.gainMapMax[2])); }
604
- }
605
-
606
- /**
607
- * Utility function to obtain a `DataTexture` from various input formats
608
- *
609
- * @category General
610
- * @group General
611
- *
612
- * @param image
613
- * @returns
614
- */
615
- const getDataTexture = (image) => {
616
- let dataTexture;
617
- if (image instanceof three.DataTexture) {
618
- if (!(image.image.data instanceof Uint16Array) && !(image.image.data instanceof Float32Array)) {
619
- throw new Error('Provided image is not HDR');
620
- }
621
- dataTexture = image;
622
- }
623
- else {
624
- 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);
625
- // TODO: This tries to detect a raw RGBE and applies flipY
626
- // see if there's a better way to detect it?
627
- if ('header' in image && 'gamma' in image) {
628
- dataTexture.flipY = true;
629
- }
630
- dataTexture.needsUpdate = true;
631
- }
632
- return dataTexture;
633
- };
634
-
635
- /**
636
- *
637
- * @param params
638
- * @returns
639
- * @category Encoding Functions
640
- * @group Encoding Functions
641
- */
642
- const getGainMap = (params) => {
643
- const { image, sdr, renderer } = params;
644
- const dataTexture = getDataTexture(image);
645
- const material = new GainMapEncoderMaterial(Object.assign(Object.assign({}, params), { sdr: sdr.renderTarget.texture, hdr: dataTexture }));
646
- const quadRenderer = new QuadRenderer(dataTexture.image.width, dataTexture.image.height, three.UnsignedByteType, three.NoColorSpace, material, renderer);
647
- try {
648
- quadRenderer.render();
649
- }
650
- catch (e) {
651
- quadRenderer.dispose();
652
- throw e;
653
- }
654
- return quadRenderer;
655
- };
656
-
657
- const vertexShader$1 = /* glsl */ `
658
- varying vec2 vUv;
659
-
660
- void main() {
661
- vUv = uv;
662
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
663
- }
664
- `;
665
- const fragmentShader$1 = /* glsl */ `
666
- #ifndef saturate
667
- #define saturate( a ) clamp( a, 0.0, 1.0 )
668
- #endif
669
-
670
- uniform sampler2D map;
671
- uniform float brightness;
672
- uniform float contrast;
673
- uniform float saturation;
674
- uniform float exposure;
675
-
676
- varying vec2 vUv;
677
-
678
- mat4 brightnessMatrix( float brightness ) {
679
- return mat4(
680
- 1, 0, 0, 0,
681
- 0, 1, 0, 0,
682
- 0, 0, 1, 0,
683
- brightness, brightness, brightness, 1
684
- );
685
- }
686
-
687
- mat4 contrastMatrix( float contrast ) {
688
- float t = ( 1.0 - contrast ) / 2.0;
689
- return mat4(
690
- contrast, 0, 0, 0,
691
- 0, contrast, 0, 0,
692
- 0, 0, contrast, 0,
693
- t, t, t, 1
694
- );
695
- }
696
-
697
- mat4 saturationMatrix( float saturation ) {
698
- vec3 luminance = vec3( 0.3086, 0.6094, 0.0820 );
699
- float oneMinusSat = 1.0 - saturation;
700
- vec3 red = vec3( luminance.x * oneMinusSat );
701
- red+= vec3( saturation, 0, 0 );
702
- vec3 green = vec3( luminance.y * oneMinusSat );
703
- green += vec3( 0, saturation, 0 );
704
- vec3 blue = vec3( luminance.z * oneMinusSat );
705
- blue += vec3( 0, 0, saturation );
706
- return mat4(
707
- red, 0,
708
- green, 0,
709
- blue, 0,
710
- 0, 0, 0, 1
711
- );
712
- }
713
-
714
- vec3 RRTAndODTFit( vec3 v ) {
715
- vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
716
- vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
717
- return a / b;
718
- }
719
-
720
- vec3 ACESFilmicToneMapping( vec3 color ) {
721
- // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
722
- const mat3 ACESInputMat = mat3(
723
- vec3( 0.59719, 0.07600, 0.02840 ), // transposed from source
724
- vec3( 0.35458, 0.90834, 0.13383 ),
725
- vec3( 0.04823, 0.01566, 0.83777 )
726
- );
727
- // ODT_SAT => XYZ => D60_2_D65 => sRGB
728
- const mat3 ACESOutputMat = mat3(
729
- vec3( 1.60475, -0.10208, -0.00327 ), // transposed from source
730
- vec3( -0.53108, 1.10813, -0.07276 ),
731
- vec3( -0.07367, -0.00605, 1.07602 )
732
- );
733
- color = ACESInputMat * color;
734
- // Apply RRT and ODT
735
- color = RRTAndODTFit( color );
736
- color = ACESOutputMat * color;
737
- // Clamp to [0, 1]
738
- return saturate( color );
739
- }
740
-
741
- // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
742
- vec3 ReinhardToneMapping( vec3 color ) {
743
- return saturate( color / ( vec3( 1.0 ) + color ) );
744
- }
745
-
746
- // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
747
- vec3 CineonToneMapping( vec3 color ) {
748
- // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
749
- color = max( vec3( 0.0 ), color - 0.004 );
750
- return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
751
- }
752
-
753
- // nothing
754
- vec3 LinearToneMapping ( vec3 color ) {
755
- return color;
756
- }
757
-
758
-
759
- void main() {
760
- vec4 color = texture2D(map, vUv);
761
-
762
- vec4 exposed = vec4(exposure * color.rgb, color.a);
763
-
764
- vec4 tonemapped = vec4(TONEMAPPING_FUNCTION(exposed.rgb), color.a);
765
-
766
- vec4 adjusted =
767
- brightnessMatrix( brightness ) *
768
- contrastMatrix( contrast ) *
769
- saturationMatrix( saturation ) *
770
- tonemapped;
771
-
772
- gl_FragColor = adjusted;
773
- }
774
- `;
775
- /**
776
- * A Material used to adjust the SDR representation of an HDR image
777
- *
778
- * @category Materials
779
- * @group Materials
780
- */
781
- class SDRMaterial extends three.ShaderMaterial {
782
- /**
783
- *
784
- * @param params
785
- */
786
- constructor({ map, toneMapping }) {
787
- super({
788
- name: 'SDRMaterial',
789
- vertexShader: vertexShader$1,
790
- fragmentShader: fragmentShader$1,
791
- uniforms: {
792
- map: { value: map },
793
- brightness: { value: 0 },
794
- contrast: { value: 1 },
795
- saturation: { value: 1 },
796
- exposure: { value: 1 }
797
- },
798
- blending: three.NoBlending,
799
- depthTest: false,
800
- depthWrite: false
801
- });
802
- this._brightness = 0;
803
- this._contrast = 1;
804
- this._saturation = 1;
805
- this._exposure = 1;
806
- this._map = map;
807
- this.toneMapping = this._toneMapping = toneMapping || three.ACESFilmicToneMapping;
808
- this.needsUpdate = true;
809
- this.uniformsNeedUpdate = true;
810
- }
811
- get toneMapping() { return this._toneMapping; }
812
- set toneMapping(value) {
813
- switch (value) {
814
- case three.ACESFilmicToneMapping:
815
- this.defines.TONEMAPPING_FUNCTION = 'ACESFilmicToneMapping';
816
- break;
817
- case three.ReinhardToneMapping:
818
- this.defines.TONEMAPPING_FUNCTION = 'ReinhardToneMapping';
819
- break;
820
- case three.CineonToneMapping:
821
- this.defines.TONEMAPPING_FUNCTION = 'CineonToneMapping';
822
- break;
823
- case three.LinearToneMapping:
824
- this.defines.TONEMAPPING_FUNCTION = 'LinearToneMapping';
825
- break;
826
- default:
827
- console.error('Unsupported toneMapping');
828
- return;
829
- }
830
- this._toneMapping = value;
831
- this.needsUpdate = true;
832
- }
833
- get brightness() { return this._brightness; }
834
- set brightness(value) {
835
- this._brightness = value;
836
- this.uniforms.brightness.value = value;
837
- }
838
- get contrast() { return this._contrast; }
839
- set contrast(value) {
840
- this._contrast = value;
841
- this.uniforms.contrast.value = value;
842
- }
843
- get saturation() { return this._saturation; }
844
- set saturation(value) {
845
- this._saturation = value;
846
- this.uniforms.saturation.value = value;
847
- }
848
- get exposure() { return this._exposure; }
849
- set exposure(value) {
850
- this._exposure = value;
851
- this.uniforms.exposure.value = value;
852
- }
853
- get map() { return this._map; }
854
- set map(value) {
855
- this._map = value;
856
- this.uniforms.map.value = value;
857
- }
858
- }
859
-
860
- /**
861
- * Renders an SDR Representation of an HDR Image
862
- *
863
- * @category Encoding Functions
864
- * @group Encoding Functions
865
- *
866
- * @param hdrTexture The HDR image to be rendered
867
- * @param renderer (optional) WebGLRenderer to use diring the rendering, a disposable renderer will be create and destroyed if this is not provided.
868
- * @param toneMapping (optional) Tonemapping to be applied to the SDR Rendition
869
- * @throws {Error} if the WebGLRenderer fails to render the SDR image
870
- */
871
- const getSDRRendition = (hdrTexture, renderer, toneMapping) => {
872
- hdrTexture.needsUpdate = true;
873
- const quadRenderer = new QuadRenderer(hdrTexture.image.width, hdrTexture.image.height, three.UnsignedByteType, three.SRGBColorSpace, new SDRMaterial({ map: hdrTexture, toneMapping }), renderer);
874
- try {
875
- quadRenderer.render();
876
- }
877
- catch (e) {
878
- quadRenderer.dispose();
879
- throw e;
880
- }
881
- return quadRenderer;
882
- };
883
-
884
- /**
885
- * Encodes a Gainmap starting from an HDR file.
886
- *
887
- * @remarks
888
- * if you do not pass a `renderer` parameter
889
- * you must manually dispose the result
890
- * ```js
891
- * const encodingResult = await encode({ ... })
892
- * // do something with the buffers
893
- * const sdr = encodingResult.sdr.getArray()
894
- * const gainMap = encodingResult.gainMap.getArray()
895
- * // after that
896
- * encodingResult.sdr.dispose()
897
- * encodingResult.gainMap.dispose()
898
- * ```
899
- *
900
- * @category Encoding Functions
901
- * @group Encoding Functions
902
- *
903
- * @example
904
- * import { encode, findTextureMinMax } from '@monogrid/gainmap-js'
905
- * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
906
- *
907
- * // load an HDR file
908
- * const loader = new EXRLoader()
909
- * const image = await loader.loadAsync('image.exr')
910
- *
911
- * // find RAW RGB Max value of a texture
912
- * const textureMax = await findTextureMinMax(image)
913
- *
914
- * // Encode the gainmap
915
- * const encodingResult = encode({
916
- * image,
917
- * // this will encode the full HDR range
918
- * maxContentBoost: Math.max.apply(this, textureMax)
919
- * })
920
- * // can be re-encoded after changing parameters
921
- * encodingResult.sdr.material.exposure = 0.9
922
- * encodingResult.sdr.render()
923
- * // or
924
- * encodingResult.gainMap.material.gamma = [1.1, 1.1, 1.1]
925
- * encodingResult.gainMap.render()
926
- *
927
- * // must be manually disposed
928
- * encodingResult.sdr.dispose()
929
- * encodingResult.gainMap.dispose()
930
- *
931
- * @param params Encoding Paramaters
932
- * @returns
933
- */
934
- const encode = (params) => {
935
- const { image, renderer } = params;
936
- const dataTexture = getDataTexture(image);
937
- const sdr = getSDRRendition(dataTexture, renderer, params.toneMapping);
938
- const gainMapRenderer = getGainMap(Object.assign(Object.assign({}, params), { image: dataTexture, sdr, renderer: sdr.renderer // reuse the same (maybe disposable?) renderer
939
- }));
940
- return {
941
- sdr,
942
- gainMap: gainMapRenderer,
943
- hdr: dataTexture,
944
- getMetadata: () => {
945
- const meta = {
946
- gainMapMax: gainMapRenderer.material.gainMapMax,
947
- gainMapMin: gainMapRenderer.material.gainMapMin,
948
- gamma: gainMapRenderer.material.gamma,
949
- hdrCapacityMax: gainMapRenderer.material.hdrCapacityMax,
950
- hdrCapacityMin: gainMapRenderer.material.hdrCapacityMin,
951
- offsetHdr: gainMapRenderer.material.offsetHdr,
952
- offsetSdr: gainMapRenderer.material.offsetSdr
953
- };
954
- return meta;
955
- }
956
- };
957
- };
958
- /**
959
- * Encodes a Gainmap starting from an HDR file into compressed file formats (`image/jpeg`, `image/webp` or `image/png`).
960
- *
961
- * Uses {@link encode} internally, then pipes the results to {@link compress}.
962
- *
963
- * @remarks
964
- * if a `renderer` parameter is not provided
965
- * This function will automatically dispose its "disposable"
966
- * renderer, no need to disapose it manually later
967
- *
968
- * @category Encoding Functions
969
- * @group Encoding Functions
970
- * @example
971
- * import { encodeAndCompress, findTextureMinMax } from '@monogrid/gainmap-js'
972
- * import { encodeJPEGMetadata } from '@monogrid/gainmap-js/libultrahdr'
973
- * import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js'
974
- *
975
- * // load an HDR file
976
- * const loader = new EXRLoader()
977
- * const image = await loader.loadAsync('image.exr')
978
- *
979
- * // find RAW RGB Max value of a texture
980
- * const textureMax = await findTextureMinMax(image)
981
- *
982
- * // Encode the gainmap
983
- * const encodingResult = await encodeAndCompress({
984
- * image,
985
- * maxContentBoost: Math.max.apply(this, textureMax),
986
- * mimeType: 'image/jpeg'
987
- * })
988
- *
989
- * // embed the compressed images + metadata into a single
990
- * // JPEG file
991
- * const jpeg = await encodeJPEGMetadata({
992
- * ...encodingResult,
993
- * sdr: encodingResult.sdr,
994
- * gainMap: encodingResult.gainMap
995
- * })
996
- *
997
- * // `jpeg` will be an `Uint8Array` which can be saved somewhere
998
- *
999
- *
1000
- * @param params Encoding Paramaters
1001
- * @throws {Error} if the browser does not support [createImageBitmap](https://caniuse.com/createimagebitmap)
1002
- */
1003
- const encodeAndCompress = async (params) => {
1004
- const encodingResult = encode(params);
1005
- const { mimeType, quality, flipY, withWorker } = params;
1006
- let compressResult;
1007
- let rawSDR;
1008
- let rawGainMap;
1009
- const sdrImageData = new ImageData(encodingResult.sdr.toArray(), encodingResult.sdr.width, encodingResult.sdr.height);
1010
- const gainMapImageData = new ImageData(encodingResult.gainMap.toArray(), encodingResult.gainMap.width, encodingResult.gainMap.height);
1011
- if (withWorker) {
1012
- const workerResult = await Promise.all([
1013
- withWorker.compress({
1014
- source: sdrImageData,
1015
- mimeType,
1016
- quality,
1017
- flipY
1018
- }),
1019
- withWorker.compress({
1020
- source: gainMapImageData,
1021
- mimeType,
1022
- quality,
1023
- flipY
1024
- })
1025
- ]);
1026
- compressResult = workerResult;
1027
- rawSDR = workerResult[0].source;
1028
- rawGainMap = workerResult[1].source;
1029
- }
1030
- else {
1031
- compressResult = await Promise.all([
1032
- compress({
1033
- source: sdrImageData,
1034
- mimeType,
1035
- quality,
1036
- flipY
1037
- }),
1038
- compress({
1039
- source: gainMapImageData,
1040
- mimeType,
1041
- quality,
1042
- flipY
1043
- })
1044
- ]);
1045
- rawSDR = sdrImageData.data;
1046
- rawGainMap = gainMapImageData.data;
1047
- }
1048
- encodingResult.sdr.dispose();
1049
- encodingResult.gainMap.dispose();
1050
- return Object.assign(Object.assign(Object.assign({}, encodingResult), encodingResult.getMetadata()), { sdr: compressResult[0], gainMap: compressResult[1], rawSDR,
1051
- rawGainMap });
1052
- };
1053
-
1054
- const vertexShader = /* glsl */ `
1055
- varying vec2 vUv;
1056
- void main() {
1057
- vUv = uv;
1058
- gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
1059
- }
1060
- `;
1061
- const fragmentShader = /* glsl */ `
1062
- precision mediump float;
1063
-
1064
- #ifndef CELL_SIZE
1065
- #define CELL_SIZE 2
1066
- #endif
1067
-
1068
- #ifndef COMPARE_FUNCTION
1069
- #define COMPARE_FUNCTION max
1070
- #endif
1071
-
1072
- uniform sampler2D map;
1073
- uniform vec2 u_srcResolution;
1074
-
1075
- varying vec2 vUv;
1076
-
1077
- void main() {
1078
- // compute the first pixel the source cell
1079
- vec2 srcPixel = floor(gl_FragCoord.xy) * float(CELL_SIZE);
1080
-
1081
- // one pixel in source
1082
- vec2 onePixel = vec2(1) / u_srcResolution;
1083
-
1084
- // uv for first pixel in cell. +0.5 for center of pixel
1085
- vec2 uv = (srcPixel + 0.5) * onePixel;
1086
-
1087
- vec4 resultColor = vec4(0);
1088
- for (int y = 0; y < CELL_SIZE; ++y) {
1089
- for (int x = 0; x < CELL_SIZE; ++x) {
1090
- resultColor = COMPARE_FUNCTION(resultColor, texture2D(map, uv + vec2(x, y) * onePixel));
1091
- }
1092
- }
1093
-
1094
- gl_FragColor = resultColor;
1095
- }
1096
- `;
1097
- /**
1098
- *
1099
- * @category Encoding Functions
1100
- * @group Encoding Functions
1101
- *
1102
- * @param srcTex
1103
- * @param mode
1104
- * @param renderer
1105
- * @returns
1106
- */
1107
- const findTextureMinMax = (image, mode = 'max', renderer) => {
1108
- const srcTex = getDataTexture(image);
1109
- const cellSize = 2;
1110
- const mat = new three.ShaderMaterial({
1111
- vertexShader,
1112
- fragmentShader,
1113
- uniforms: {
1114
- u_srcResolution: { value: new three.Vector2(srcTex.image.width, srcTex.image.height) },
1115
- map: { value: srcTex }
1116
- },
1117
- defines: {
1118
- CELL_SIZE: cellSize,
1119
- COMPARE_FUNCTION: mode
1120
- }
1121
- });
1122
- srcTex.needsUpdate = true;
1123
- mat.needsUpdate = true;
1124
- let w = srcTex.image.width;
1125
- let h = srcTex.image.height;
1126
- const quadRenderer = new QuadRenderer(w, h, srcTex.type, srcTex.colorSpace, mat, renderer);
1127
- const framebuffers = [];
1128
- while (w > 1 || h > 1) {
1129
- w = Math.max(1, (w + cellSize - 1) / cellSize | 0);
1130
- h = Math.max(1, (h + cellSize - 1) / cellSize | 0);
1131
- const fb = new three.WebGLRenderTarget(w, h, {
1132
- type: srcTex.type,
1133
- format: srcTex.format,
1134
- colorSpace: srcTex.colorSpace,
1135
- minFilter: three.NearestFilter,
1136
- magFilter: three.NearestFilter,
1137
- wrapS: three.ClampToEdgeWrapping,
1138
- wrapT: three.ClampToEdgeWrapping,
1139
- generateMipmaps: false,
1140
- depthBuffer: false,
1141
- stencilBuffer: false
1142
- });
1143
- framebuffers.push(fb);
1144
- }
1145
- w = srcTex.image.width;
1146
- h = srcTex.image.height;
1147
- framebuffers.forEach((fbi) => {
1148
- w = Math.max(1, (w + cellSize - 1) / cellSize | 0);
1149
- h = Math.max(1, (h + cellSize - 1) / cellSize | 0);
1150
- quadRenderer.renderTarget = fbi;
1151
- quadRenderer.render();
1152
- mat.uniforms.map.value = fbi.texture;
1153
- mat.uniforms.u_srcResolution.value.x = w;
1154
- mat.uniforms.u_srcResolution.value.y = h;
1155
- });
1156
- const out = quadRenderer.toArray();
1157
- quadRenderer.dispose();
1158
- framebuffers.forEach(fb => fb.dispose());
1159
- return [three.DataUtils.fromHalfFloat(out[0]), three.DataUtils.fromHalfFloat(out[1]), three.DataUtils.fromHalfFloat(out[2])];
1160
- };
1161
-
1162
- class LoaderBase extends three.Loader {
1163
- /**
1164
- *
1165
- * @param renderer
1166
- * @param manager
1167
- */
1168
- constructor(renderer, manager) {
1169
- super(manager);
1170
- this.renderer = renderer;
1171
- }
1172
- /**
1173
- * @private
1174
- * @returns
1175
- */
1176
- prepareQuadRenderer() {
1177
- // temporary values
1178
- const material = new GainMapDecoderMaterial({
1179
- gainMapMax: [1, 1, 1],
1180
- gainMapMin: [0, 0, 0],
1181
- gamma: [1, 1, 1],
1182
- offsetHdr: [1, 1, 1],
1183
- offsetSdr: [1, 1, 1],
1184
- hdrCapacityMax: 1,
1185
- hdrCapacityMin: 0,
1186
- maxDisplayBoost: 1,
1187
- gainMap: new three.Texture(),
1188
- sdr: new three.Texture()
1189
- });
1190
- return new QuadRenderer(16, 16, three.HalfFloatType, three.NoColorSpace, material, this.renderer);
1191
- }
1192
- /**
1193
- *
1194
- * @private
1195
- * @param quadRenderer
1196
- * @param gainMapBuffer
1197
- * @param sdrBuffer
1198
- * @param metadata
1199
- */
1200
- async render(quadRenderer, gainMapBuffer, sdrBuffer, metadata) {
1201
- const gainMapBlob = new Blob([gainMapBuffer], { type: 'image/jpeg' });
1202
- // TODO: figure out why result.sdr is not usable here, problem is in the libultrahdr-wasm repo
1203
- // we use the original image buffer instead
1204
- const sdrBlob = new Blob([sdrBuffer], { type: 'image/jpeg' });
1205
- const [gainMapImageBitmap, sdrImageBitmap] = await Promise.all([
1206
- createImageBitmap(gainMapBlob, { imageOrientation: 'flipY' }),
1207
- createImageBitmap(sdrBlob, { imageOrientation: 'flipY' })
1208
- ]);
1209
- const gainMap = new three.Texture(gainMapImageBitmap, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.NoColorSpace);
1210
- gainMap.needsUpdate = true;
1211
- const sdr = new three.Texture(sdrImageBitmap, three.UVMapping, three.ClampToEdgeWrapping, three.ClampToEdgeWrapping, three.LinearFilter, three.LinearMipMapLinearFilter, three.RGBAFormat, three.UnsignedByteType, 1, three.SRGBColorSpace);
1212
- sdr.needsUpdate = true;
1213
- quadRenderer.width = sdrImageBitmap.width;
1214
- quadRenderer.height = sdrImageBitmap.height;
1215
- quadRenderer.material.gainMap = gainMap;
1216
- quadRenderer.material.sdr = sdr;
1217
- quadRenderer.material.gainMapMin = metadata.gainMapMin;
1218
- quadRenderer.material.gainMapMax = metadata.gainMapMax;
1219
- quadRenderer.material.offsetHdr = metadata.offsetHdr;
1220
- quadRenderer.material.offsetSdr = metadata.offsetSdr;
1221
- quadRenderer.material.gamma = metadata.gamma;
1222
- quadRenderer.material.hdrCapacityMin = metadata.hdrCapacityMin;
1223
- quadRenderer.material.hdrCapacityMax = metadata.hdrCapacityMax;
1224
- quadRenderer.material.maxDisplayBoost = Math.pow(2, metadata.hdrCapacityMax);
1225
- quadRenderer.material.needsUpdate = true;
1226
- quadRenderer.render();
1227
- }
1228
- }
1229
-
1230
- /**
1231
- * A Three.js Loader for the gain map format.
1232
- *
1233
- * @category Loaders
1234
- * @group Loaders
1235
- *
1236
- * @example
1237
- * import { GainMapLoader } from '@monogrid/gainmap-js'
1238
- * import {
1239
- * EquirectangularReflectionMapping,
1240
- * LinearFilter,
1241
- * Mesh,
1242
- * MeshBasicMaterial,
1243
- * PerspectiveCamera,
1244
- * PlaneGeometry,
1245
- * Scene,
1246
- * WebGLRenderer
1247
- * } from 'three'
1248
- *
1249
- * const renderer = new WebGLRenderer()
1250
- *
1251
- * const loader = new GainMapLoader(renderer)
1252
- *
1253
- * const result = loader.load(['sdr.jpeg', 'gainmap.jpeg', 'metadata.json'])
1254
- * // `result` can be used to populate a Texture
1255
- *
1256
- * const scene = new Scene()
1257
- * const mesh = new Mesh(
1258
- * new PlaneGeometry(),
1259
- * new MeshBasicMaterial({ map: result.renderTarget.texture })
1260
- * )
1261
- * scene.add(mesh)
1262
- * renderer.render(scene, new PerspectiveCamera())
1263
- *
1264
- * // `result.renderTarget.texture` must be
1265
- * // converted to `DataTexture` in order
1266
- * // to use it as Equirectanmgular scene background
1267
- * // if needed
1268
- *
1269
- * scene.background = result.toDataTexture()
1270
- * scene.background.mapping = EquirectangularReflectionMapping
1271
- * scene.background.minFilter = LinearFilter
1272
- *
1273
- *
1274
- */
1275
- class GainMapLoader extends LoaderBase {
1276
- /**
1277
- * Loads a gainmap using separate data
1278
- * * sdr image
1279
- * * gain map image
1280
- * * metadata json
1281
- *
1282
- * useful for webp gainmaps
1283
- *
1284
- * @param sdrUrl
1285
- * @param gainMapUrl
1286
- * @param metadataUrl
1287
- * @param onLoad
1288
- * @param onProgress
1289
- * @param onError
1290
- * @returns
1291
- */
1292
- load([sdrUrl, gainMapUrl, metadataUrl], onLoad, onProgress, onError) {
1293
- const quadRenderer = this.prepareQuadRenderer();
1294
- let sdr;
1295
- let gainMap;
1296
- let metadata;
1297
- const loadCheck = async () => {
1298
- if (sdr && gainMap && metadata) {
1299
- await this.render(quadRenderer, gainMap, sdr, metadata);
1300
- if (typeof onLoad === 'function')
1301
- onLoad(quadRenderer);
1302
- quadRenderer.dispose();
1303
- }
1304
- };
1305
- const progressHandler = (e) => {
1306
- };
1307
- const sdrLoader = new three.FileLoader(this.manager);
1308
- sdrLoader.setResponseType('arraybuffer');
1309
- sdrLoader.setRequestHeader(this.requestHeader);
1310
- sdrLoader.setPath(this.path);
1311
- sdrLoader.setWithCredentials(this.withCredentials);
1312
- sdrLoader.load(sdrUrl, async (buffer) => {
1313
- if (typeof buffer === 'string')
1314
- throw new Error('Invalid sdr buffer');
1315
- sdr = buffer;
1316
- loadCheck();
1317
- }, progressHandler, onError);
1318
- const gainMapLoader = new three.FileLoader(this.manager);
1319
- gainMapLoader.setResponseType('arraybuffer');
1320
- gainMapLoader.setRequestHeader(this.requestHeader);
1321
- gainMapLoader.setPath(this.path);
1322
- gainMapLoader.setWithCredentials(this.withCredentials);
1323
- gainMapLoader.load(gainMapUrl, async (buffer) => {
1324
- if (typeof buffer === 'string')
1325
- throw new Error('Invalid gainmap buffer');
1326
- gainMap = buffer;
1327
- loadCheck();
1328
- }, progressHandler, onError);
1329
- const metadataLoader = new three.FileLoader(this.manager);
1330
- // metadataLoader.setResponseType('json')
1331
- metadataLoader.setRequestHeader(this.requestHeader);
1332
- metadataLoader.setPath(this.path);
1333
- metadataLoader.setWithCredentials(this.withCredentials);
1334
- metadataLoader.load(metadataUrl, async (json) => {
1335
- if (typeof json !== 'string')
1336
- throw new Error('Invalid metadata string');
1337
- metadata = JSON.parse(json);
1338
- loadCheck();
1339
- }, progressHandler, onError);
1340
- return quadRenderer;
1341
- }
1342
- }
1343
-
1344
- exports.GainMapDecoderMaterial = GainMapDecoderMaterial;
1345
- exports.GainMapEncoderMaterial = GainMapEncoderMaterial;
1346
- exports.GainMapLoader = GainMapLoader;
1347
- exports.QuadRenderer = QuadRenderer;
1348
- exports.SDRMaterial = SDRMaterial;
1349
- exports.compress = compress;
1350
- exports.decode = decode;
1351
- exports.encode = encode;
1352
- exports.encodeAndCompress = encodeAndCompress;
1353
- exports.findTextureMinMax = findTextureMinMax;
1354
- exports.getDataTexture = getDataTexture;
1355
- exports.getGainMap = getGainMap;
1356
- exports.getSDRRendition = getSDRRendition;
1357
-
1358
- Object.defineProperty(exports, '__esModule', { value: true });
1359
-
1360
- }));